Build tool
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.

catch.hpp 636KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825
  1. /*
  2. * Catch v2.13.2
  3. * Generated: 2020-10-07 11:32:53.302017
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 13
  16. #define CATCH_VERSION_PATCH 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. // We have to avoid both ICC and Clang, because they try to mask themselves
  111. // as gcc, and we want only GCC in this block
  112. #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__)
  113. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
  114. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
  115. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
  116. #endif
  117. #if defined(__clang__)
  118. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
  119. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
  120. // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
  121. // which results in calls to destructors being emitted for each temporary,
  122. // without a matching initialization. In practice, this can result in something
  123. // like `std::string::~string` being called on an uninitialized value.
  124. //
  125. // For example, this code will likely segfault under IBM XL:
  126. // ```
  127. // REQUIRE(std::string("12") + "34" == "1234")
  128. // ```
  129. //
  130. // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
  131. # if !defined(__ibmxl__) && !defined(__CUDACC__)
  132. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
  133. # endif
  134. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  135. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  136. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  137. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  138. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  139. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  140. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  141. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  142. _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
  143. # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  144. _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
  145. #endif // __clang__
  146. ////////////////////////////////////////////////////////////////////////////////
  147. // Assume that non-Windows platforms support posix signals by default
  148. #if !defined(CATCH_PLATFORM_WINDOWS)
  149. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  150. #endif
  151. ////////////////////////////////////////////////////////////////////////////////
  152. // We know some environments not to support full POSIX signals
  153. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  154. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  155. #endif
  156. #ifdef __OS400__
  157. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  158. # define CATCH_CONFIG_COLOUR_NONE
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // Android somehow still does not support std::to_string
  162. #if defined(__ANDROID__)
  163. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  164. # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
  165. #endif
  166. ////////////////////////////////////////////////////////////////////////////////
  167. // Not all Windows environments support SEH properly
  168. #if defined(__MINGW32__)
  169. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  170. #endif
  171. ////////////////////////////////////////////////////////////////////////////////
  172. // PS4
  173. #if defined(__ORBIS__)
  174. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  175. #endif
  176. ////////////////////////////////////////////////////////////////////////////////
  177. // Cygwin
  178. #ifdef __CYGWIN__
  179. // Required for some versions of Cygwin to declare gettimeofday
  180. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  181. # define _BSD_SOURCE
  182. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  183. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  184. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  185. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  186. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  187. # endif
  188. #endif // __CYGWIN__
  189. ////////////////////////////////////////////////////////////////////////////////
  190. // Visual C++
  191. #if defined(_MSC_VER)
  192. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
  193. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
  194. // Universal Windows platform does not support SEH
  195. // Or console colours (or console at all...)
  196. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  197. # define CATCH_CONFIG_COLOUR_NONE
  198. # else
  199. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  200. # endif
  201. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  202. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  203. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  204. # if !defined(__clang__) // Handle Clang masquerading for msvc
  205. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  206. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  207. # endif // MSVC_TRADITIONAL
  208. # endif // __clang__
  209. #endif // _MSC_VER
  210. #if defined(_REENTRANT) || defined(_MSC_VER)
  211. // Enable async processing, as -pthread is specified or no additional linking is required
  212. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  213. #endif // _MSC_VER
  214. ////////////////////////////////////////////////////////////////////////////////
  215. // Check if we are compiled with -fno-exceptions or equivalent
  216. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  217. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  218. #endif
  219. ////////////////////////////////////////////////////////////////////////////////
  220. // DJGPP
  221. #ifdef __DJGPP__
  222. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  223. #endif // __DJGPP__
  224. ////////////////////////////////////////////////////////////////////////////////
  225. // Embarcadero C++Build
  226. #if defined(__BORLANDC__)
  227. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  228. #endif
  229. ////////////////////////////////////////////////////////////////////////////////
  230. // Use of __COUNTER__ is suppressed during code analysis in
  231. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  232. // handled by it.
  233. // Otherwise all supported compilers support COUNTER macro,
  234. // but user still might want to turn it off
  235. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  236. #define CATCH_INTERNAL_CONFIG_COUNTER
  237. #endif
  238. ////////////////////////////////////////////////////////////////////////////////
  239. // RTX is a special version of Windows that is real time.
  240. // This means that it is detected as Windows, but does not provide
  241. // the same set of capabilities as real Windows does.
  242. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  243. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  244. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  245. #define CATCH_CONFIG_COLOUR_NONE
  246. #endif
  247. #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
  248. #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
  249. #endif
  250. // Various stdlib support checks that require __has_include
  251. #if defined(__has_include)
  252. // Check if string_view is available and usable
  253. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  254. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  255. #endif
  256. // Check if optional is available and usable
  257. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  258. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  259. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  260. // Check if byte is available and usable
  261. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  262. # include <cstddef>
  263. # if __cpp_lib_byte > 0
  264. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  265. # endif
  266. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  267. // Check if variant is available and usable
  268. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  269. # if defined(__clang__) && (__clang_major__ < 8)
  270. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  271. // fix should be in clang 8, workaround in libstdc++ 8.2
  272. # include <ciso646>
  273. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  274. # define CATCH_CONFIG_NO_CPP17_VARIANT
  275. # else
  276. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  277. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  278. # else
  279. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  280. # endif // defined(__clang__) && (__clang_major__ < 8)
  281. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  282. #endif // defined(__has_include)
  283. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  284. # define CATCH_CONFIG_COUNTER
  285. #endif
  286. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  287. # define CATCH_CONFIG_WINDOWS_SEH
  288. #endif
  289. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  290. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  291. # define CATCH_CONFIG_POSIX_SIGNALS
  292. #endif
  293. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  294. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  295. # define CATCH_CONFIG_WCHAR
  296. #endif
  297. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  298. # define CATCH_CONFIG_CPP11_TO_STRING
  299. #endif
  300. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  301. # define CATCH_CONFIG_CPP17_OPTIONAL
  302. #endif
  303. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  304. # define CATCH_CONFIG_CPP17_STRING_VIEW
  305. #endif
  306. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  307. # define CATCH_CONFIG_CPP17_VARIANT
  308. #endif
  309. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  310. # define CATCH_CONFIG_CPP17_BYTE
  311. #endif
  312. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  313. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  314. #endif
  315. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  316. # define CATCH_CONFIG_NEW_CAPTURE
  317. #endif
  318. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  319. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  320. #endif
  321. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  322. # define CATCH_CONFIG_POLYFILL_ISNAN
  323. #endif
  324. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  325. # define CATCH_CONFIG_USE_ASYNC
  326. #endif
  327. #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  328. # define CATCH_CONFIG_ANDROID_LOGWRITE
  329. #endif
  330. #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  331. # define CATCH_CONFIG_GLOBAL_NEXTAFTER
  332. #endif
  333. // Even if we do not think the compiler has that warning, we still have
  334. // to provide a macro that can be used by the code.
  335. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
  336. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  337. #endif
  338. #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
  339. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  340. #endif
  341. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  342. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  343. #endif
  344. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  345. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  346. #endif
  347. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  348. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  349. #endif
  350. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  351. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  352. #endif
  353. // The goal of this macro is to avoid evaluation of the arguments, but
  354. // still have the compiler warn on problems inside...
  355. #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
  356. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
  357. #endif
  358. #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
  359. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  360. #elif defined(__clang__) && (__clang_major__ < 5)
  361. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  362. #endif
  363. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
  364. # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  365. #endif
  366. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  367. #define CATCH_TRY if ((true))
  368. #define CATCH_CATCH_ALL if ((false))
  369. #define CATCH_CATCH_ANON(type) if ((false))
  370. #else
  371. #define CATCH_TRY try
  372. #define CATCH_CATCH_ALL catch (...)
  373. #define CATCH_CATCH_ANON(type) catch (type)
  374. #endif
  375. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  376. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  377. #endif
  378. // end catch_compiler_capabilities.h
  379. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  380. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  381. #ifdef CATCH_CONFIG_COUNTER
  382. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  383. #else
  384. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  385. #endif
  386. #include <iosfwd>
  387. #include <string>
  388. #include <cstdint>
  389. // We need a dummy global operator<< so we can bring it into Catch namespace later
  390. struct Catch_global_namespace_dummy {};
  391. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  392. namespace Catch {
  393. struct CaseSensitive { enum Choice {
  394. Yes,
  395. No
  396. }; };
  397. class NonCopyable {
  398. NonCopyable( NonCopyable const& ) = delete;
  399. NonCopyable( NonCopyable && ) = delete;
  400. NonCopyable& operator = ( NonCopyable const& ) = delete;
  401. NonCopyable& operator = ( NonCopyable && ) = delete;
  402. protected:
  403. NonCopyable();
  404. virtual ~NonCopyable();
  405. };
  406. struct SourceLineInfo {
  407. SourceLineInfo() = delete;
  408. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  409. : file( _file ),
  410. line( _line )
  411. {}
  412. SourceLineInfo( SourceLineInfo const& other ) = default;
  413. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  414. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  415. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  416. bool empty() const noexcept { return file[0] == '\0'; }
  417. bool operator == ( SourceLineInfo const& other ) const noexcept;
  418. bool operator < ( SourceLineInfo const& other ) const noexcept;
  419. char const* file;
  420. std::size_t line;
  421. };
  422. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  423. // Bring in operator<< from global namespace into Catch namespace
  424. // This is necessary because the overload of operator<< above makes
  425. // lookup stop at namespace Catch
  426. using ::operator<<;
  427. // Use this in variadic streaming macros to allow
  428. // >> +StreamEndStop
  429. // as well as
  430. // >> stuff +StreamEndStop
  431. struct StreamEndStop {
  432. std::string operator+() const;
  433. };
  434. template<typename T>
  435. T const& operator + ( T const& value, StreamEndStop ) {
  436. return value;
  437. }
  438. }
  439. #define CATCH_INTERNAL_LINEINFO \
  440. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  441. // end catch_common.h
  442. namespace Catch {
  443. struct RegistrarForTagAliases {
  444. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  445. };
  446. } // end namespace Catch
  447. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  448. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  449. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  450. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  451. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  452. // end catch_tag_alias_autoregistrar.h
  453. // start catch_test_registry.h
  454. // start catch_interfaces_testcase.h
  455. #include <vector>
  456. namespace Catch {
  457. class TestSpec;
  458. struct ITestInvoker {
  459. virtual void invoke () const = 0;
  460. virtual ~ITestInvoker();
  461. };
  462. class TestCase;
  463. struct IConfig;
  464. struct ITestCaseRegistry {
  465. virtual ~ITestCaseRegistry();
  466. virtual std::vector<TestCase> const& getAllTests() const = 0;
  467. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  468. };
  469. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  470. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  471. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  472. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  473. }
  474. // end catch_interfaces_testcase.h
  475. // start catch_stringref.h
  476. #include <cstddef>
  477. #include <string>
  478. #include <iosfwd>
  479. #include <cassert>
  480. namespace Catch {
  481. /// A non-owning string class (similar to the forthcoming std::string_view)
  482. /// Note that, because a StringRef may be a substring of another string,
  483. /// it may not be null terminated.
  484. class StringRef {
  485. public:
  486. using size_type = std::size_t;
  487. using const_iterator = const char*;
  488. private:
  489. static constexpr char const* const s_empty = "";
  490. char const* m_start = s_empty;
  491. size_type m_size = 0;
  492. public: // construction
  493. constexpr StringRef() noexcept = default;
  494. StringRef( char const* rawChars ) noexcept;
  495. constexpr StringRef( char const* rawChars, size_type size ) noexcept
  496. : m_start( rawChars ),
  497. m_size( size )
  498. {}
  499. StringRef( std::string const& stdString ) noexcept
  500. : m_start( stdString.c_str() ),
  501. m_size( stdString.size() )
  502. {}
  503. explicit operator std::string() const {
  504. return std::string(m_start, m_size);
  505. }
  506. public: // operators
  507. auto operator == ( StringRef const& other ) const noexcept -> bool;
  508. auto operator != (StringRef const& other) const noexcept -> bool {
  509. return !(*this == other);
  510. }
  511. auto operator[] ( size_type index ) const noexcept -> char {
  512. assert(index < m_size);
  513. return m_start[index];
  514. }
  515. public: // named queries
  516. constexpr auto empty() const noexcept -> bool {
  517. return m_size == 0;
  518. }
  519. constexpr auto size() const noexcept -> size_type {
  520. return m_size;
  521. }
  522. // Returns the current start pointer. If the StringRef is not
  523. // null-terminated, throws std::domain_exception
  524. auto c_str() const -> char const*;
  525. public: // substrings and searches
  526. // Returns a substring of [start, start + length).
  527. // If start + length > size(), then the substring is [start, size()).
  528. // If start > size(), then the substring is empty.
  529. auto substr( size_type start, size_type length ) const noexcept -> StringRef;
  530. // Returns the current start pointer. May not be null-terminated.
  531. auto data() const noexcept -> char const*;
  532. constexpr auto isNullTerminated() const noexcept -> bool {
  533. return m_start[m_size] == '\0';
  534. }
  535. public: // iterators
  536. constexpr const_iterator begin() const { return m_start; }
  537. constexpr const_iterator end() const { return m_start + m_size; }
  538. };
  539. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  540. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  541. constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  542. return StringRef( rawChars, size );
  543. }
  544. } // namespace Catch
  545. constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  546. return Catch::StringRef( rawChars, size );
  547. }
  548. // end catch_stringref.h
  549. // start catch_preprocessor.hpp
  550. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  551. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  552. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  553. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  554. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  555. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  556. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  557. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  558. // MSVC needs more evaluations
  559. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  560. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  561. #else
  562. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  563. #endif
  564. #define CATCH_REC_END(...)
  565. #define CATCH_REC_OUT
  566. #define CATCH_EMPTY()
  567. #define CATCH_DEFER(id) id CATCH_EMPTY()
  568. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  569. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  570. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  571. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  572. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  573. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  574. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  575. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  576. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  577. #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  578. #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  579. #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  580. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  581. // and passes userdata as the first parameter to each invocation,
  582. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  583. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  584. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  585. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  586. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  587. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  588. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  589. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  590. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  591. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  592. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  593. #else
  594. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  595. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  596. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  597. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  598. #endif
  599. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  600. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  601. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  602. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  603. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  604. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  605. #else
  606. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  607. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  608. #endif
  609. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  610. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  611. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  612. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  613. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  614. #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
  615. #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
  616. #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
  617. #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
  618. #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
  619. #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
  620. #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
  621. #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
  622. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  623. #define INTERNAL_CATCH_TYPE_GEN\
  624. template<typename...> struct TypeList {};\
  625. template<typename...Ts>\
  626. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  627. template<template<typename...> class...> struct TemplateTypeList{};\
  628. template<template<typename...> class...Cs>\
  629. constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
  630. template<typename...>\
  631. struct append;\
  632. template<typename...>\
  633. struct rewrap;\
  634. template<template<typename...> class, typename...>\
  635. struct create;\
  636. template<template<typename...> class, typename>\
  637. struct convert;\
  638. \
  639. template<typename T> \
  640. struct append<T> { using type = T; };\
  641. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  642. struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
  643. template< template<typename...> class L1, typename...E1, typename...Rest>\
  644. struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
  645. \
  646. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  647. struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
  648. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  649. struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
  650. \
  651. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  652. struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
  653. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  654. struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
  655. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  656. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  657. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  658. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  659. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
  660. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
  661. constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
  662. \
  663. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  664. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
  665. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  666. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
  667. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  668. struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
  669. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  670. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  671. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  672. static void TestName()
  673. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  674. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  675. static void TestName()
  676. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  677. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  678. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  679. static void TestName()
  680. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  681. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  682. static void TestName()
  683. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  684. template<typename Type>\
  685. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  686. {\
  687. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  688. }
  689. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  690. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  691. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  692. {\
  693. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  694. }
  695. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  696. template<typename Type>\
  697. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  698. {\
  699. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  700. }
  701. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  702. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  703. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  704. {\
  705. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  706. }
  707. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  708. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  709. template<typename TestType> \
  710. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  711. void test();\
  712. }
  713. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  714. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  715. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  716. void test();\
  717. }
  718. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  719. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  720. template<typename TestType> \
  721. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  722. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  723. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  724. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  725. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  726. #define INTERNAL_CATCH_NTTP_0
  727. #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
  728. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
  729. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
  730. #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
  731. #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
  732. #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
  733. #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
  734. #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
  735. #else
  736. #define INTERNAL_CATCH_NTTP_0(signature)
  737. #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
  738. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
  739. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
  740. #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
  741. #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
  742. #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
  743. #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
  744. #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
  745. #endif
  746. // end catch_preprocessor.hpp
  747. // start catch_meta.hpp
  748. #include <type_traits>
  749. namespace Catch {
  750. template<typename T>
  751. struct always_false : std::false_type {};
  752. template <typename> struct true_given : std::true_type {};
  753. struct is_callable_tester {
  754. template <typename Fun, typename... Args>
  755. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  756. template <typename...>
  757. std::false_type static test(...);
  758. };
  759. template <typename T>
  760. struct is_callable;
  761. template <typename Fun, typename... Args>
  762. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  763. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  764. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  765. // replaced with std::invoke_result here.
  766. template <typename Func, typename... U>
  767. using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
  768. #else
  769. // Keep ::type here because we still support C++11
  770. template <typename Func, typename... U>
  771. using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
  772. #endif
  773. } // namespace Catch
  774. namespace mpl_{
  775. struct na;
  776. }
  777. // end catch_meta.hpp
  778. namespace Catch {
  779. template<typename C>
  780. class TestInvokerAsMethod : public ITestInvoker {
  781. void (C::*m_testAsMethod)();
  782. public:
  783. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  784. void invoke() const override {
  785. C obj;
  786. (obj.*m_testAsMethod)();
  787. }
  788. };
  789. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  790. template<typename C>
  791. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  792. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  793. }
  794. struct NameAndTags {
  795. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  796. StringRef name;
  797. StringRef tags;
  798. };
  799. struct AutoReg : NonCopyable {
  800. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  801. ~AutoReg();
  802. };
  803. } // end namespace Catch
  804. #if defined(CATCH_CONFIG_DISABLE)
  805. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  806. static void TestName()
  807. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  808. namespace{ \
  809. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  810. void test(); \
  811. }; \
  812. } \
  813. void TestName::test()
  814. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  815. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  816. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  817. namespace{ \
  818. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  819. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  820. } \
  821. } \
  822. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  823. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  824. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  825. INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
  826. #else
  827. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  828. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
  829. #endif
  830. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  831. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  832. INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
  833. #else
  834. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  835. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
  836. #endif
  837. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  838. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  839. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
  840. #else
  841. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  842. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
  843. #endif
  844. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  845. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  846. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
  847. #else
  848. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  849. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
  850. #endif
  851. #endif
  852. ///////////////////////////////////////////////////////////////////////////////
  853. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  854. static void TestName(); \
  855. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  856. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  857. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  858. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  859. static void TestName()
  860. #define INTERNAL_CATCH_TESTCASE( ... ) \
  861. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  862. ///////////////////////////////////////////////////////////////////////////////
  863. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  864. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  865. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  866. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  867. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  868. ///////////////////////////////////////////////////////////////////////////////
  869. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  870. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  871. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  872. namespace{ \
  873. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  874. void test(); \
  875. }; \
  876. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  877. } \
  878. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  879. void TestName::test()
  880. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  881. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  882. ///////////////////////////////////////////////////////////////////////////////
  883. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  884. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  885. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  886. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  887. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  888. ///////////////////////////////////////////////////////////////////////////////
  889. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  890. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  891. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  892. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  893. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  894. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  895. namespace {\
  896. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  897. INTERNAL_CATCH_TYPE_GEN\
  898. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  899. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  900. template<typename...Types> \
  901. struct TestName{\
  902. TestName(){\
  903. int index = 0; \
  904. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  905. using expander = int[];\
  906. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  907. }\
  908. };\
  909. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  910. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  911. return 0;\
  912. }();\
  913. }\
  914. }\
  915. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  916. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  917. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  918. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  919. INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
  920. #else
  921. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  922. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
  923. #endif
  924. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  925. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  926. INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
  927. #else
  928. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  929. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
  930. #endif
  931. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  932. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  933. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  934. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  935. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  936. template<typename TestType> static void TestFuncName(); \
  937. namespace {\
  938. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  939. INTERNAL_CATCH_TYPE_GEN \
  940. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  941. template<typename... Types> \
  942. struct TestName { \
  943. void reg_tests() { \
  944. int index = 0; \
  945. using expander = int[]; \
  946. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  947. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  948. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  949. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
  950. } \
  951. }; \
  952. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  953. using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
  954. TestInit t; \
  955. t.reg_tests(); \
  956. return 0; \
  957. }(); \
  958. } \
  959. } \
  960. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  961. template<typename TestType> \
  962. static void TestFuncName()
  963. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  964. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  965. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
  966. #else
  967. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  968. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
  969. #endif
  970. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  971. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  972. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
  973. #else
  974. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  975. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
  976. #endif
  977. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  978. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  979. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  980. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  981. template<typename TestType> static void TestFunc(); \
  982. namespace {\
  983. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  984. INTERNAL_CATCH_TYPE_GEN\
  985. template<typename... Types> \
  986. struct TestName { \
  987. void reg_tests() { \
  988. int index = 0; \
  989. using expander = int[]; \
  990. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
  991. } \
  992. };\
  993. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  994. using TestInit = typename convert<TestName, TmplList>::type; \
  995. TestInit t; \
  996. t.reg_tests(); \
  997. return 0; \
  998. }(); \
  999. }}\
  1000. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1001. template<typename TestType> \
  1002. static void TestFunc()
  1003. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  1004. INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
  1005. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  1006. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1007. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1008. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1009. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1010. namespace {\
  1011. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1012. INTERNAL_CATCH_TYPE_GEN\
  1013. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1014. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  1015. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1016. template<typename...Types> \
  1017. struct TestNameClass{\
  1018. TestNameClass(){\
  1019. int index = 0; \
  1020. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1021. using expander = int[];\
  1022. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  1023. }\
  1024. };\
  1025. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1026. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1027. return 0;\
  1028. }();\
  1029. }\
  1030. }\
  1031. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1032. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1033. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1034. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1035. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
  1036. #else
  1037. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1038. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
  1039. #endif
  1040. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1041. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1042. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
  1043. #else
  1044. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1045. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
  1046. #endif
  1047. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1048. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1049. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1050. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1051. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1052. template<typename TestType> \
  1053. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1054. void test();\
  1055. };\
  1056. namespace {\
  1057. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1058. INTERNAL_CATCH_TYPE_GEN \
  1059. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1060. template<typename...Types>\
  1061. struct TestNameClass{\
  1062. void reg_tests(){\
  1063. int index = 0;\
  1064. using expander = int[];\
  1065. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1066. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1067. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1068. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
  1069. }\
  1070. };\
  1071. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1072. using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
  1073. TestInit t;\
  1074. t.reg_tests();\
  1075. return 0;\
  1076. }(); \
  1077. }\
  1078. }\
  1079. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1080. template<typename TestType> \
  1081. void TestName<TestType>::test()
  1082. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1083. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1084. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
  1085. #else
  1086. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1087. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
  1088. #endif
  1089. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1090. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1091. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
  1092. #else
  1093. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1094. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
  1095. #endif
  1096. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1097. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1098. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1099. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1100. template<typename TestType> \
  1101. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1102. void test();\
  1103. };\
  1104. namespace {\
  1105. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1106. INTERNAL_CATCH_TYPE_GEN\
  1107. template<typename...Types>\
  1108. struct TestNameClass{\
  1109. void reg_tests(){\
  1110. int index = 0;\
  1111. using expander = int[];\
  1112. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
  1113. }\
  1114. };\
  1115. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1116. using TestInit = typename convert<TestNameClass, TmplList>::type;\
  1117. TestInit t;\
  1118. t.reg_tests();\
  1119. return 0;\
  1120. }(); \
  1121. }}\
  1122. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1123. template<typename TestType> \
  1124. void TestName<TestType>::test()
  1125. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1126. INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
  1127. // end catch_test_registry.h
  1128. // start catch_capture.hpp
  1129. // start catch_assertionhandler.h
  1130. // start catch_assertioninfo.h
  1131. // start catch_result_type.h
  1132. namespace Catch {
  1133. // ResultWas::OfType enum
  1134. struct ResultWas { enum OfType {
  1135. Unknown = -1,
  1136. Ok = 0,
  1137. Info = 1,
  1138. Warning = 2,
  1139. FailureBit = 0x10,
  1140. ExpressionFailed = FailureBit | 1,
  1141. ExplicitFailure = FailureBit | 2,
  1142. Exception = 0x100 | FailureBit,
  1143. ThrewException = Exception | 1,
  1144. DidntThrowException = Exception | 2,
  1145. FatalErrorCondition = 0x200 | FailureBit
  1146. }; };
  1147. bool isOk( ResultWas::OfType resultType );
  1148. bool isJustInfo( int flags );
  1149. // ResultDisposition::Flags enum
  1150. struct ResultDisposition { enum Flags {
  1151. Normal = 0x01,
  1152. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1153. FalseTest = 0x04, // Prefix expression with !
  1154. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1155. }; };
  1156. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1157. bool shouldContinueOnFailure( int flags );
  1158. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1159. bool shouldSuppressFailure( int flags );
  1160. } // end namespace Catch
  1161. // end catch_result_type.h
  1162. namespace Catch {
  1163. struct AssertionInfo
  1164. {
  1165. StringRef macroName;
  1166. SourceLineInfo lineInfo;
  1167. StringRef capturedExpression;
  1168. ResultDisposition::Flags resultDisposition;
  1169. // We want to delete this constructor but a compiler bug in 4.8 means
  1170. // the struct is then treated as non-aggregate
  1171. //AssertionInfo() = delete;
  1172. };
  1173. } // end namespace Catch
  1174. // end catch_assertioninfo.h
  1175. // start catch_decomposer.h
  1176. // start catch_tostring.h
  1177. #include <vector>
  1178. #include <cstddef>
  1179. #include <type_traits>
  1180. #include <string>
  1181. // start catch_stream.h
  1182. #include <iosfwd>
  1183. #include <cstddef>
  1184. #include <ostream>
  1185. namespace Catch {
  1186. std::ostream& cout();
  1187. std::ostream& cerr();
  1188. std::ostream& clog();
  1189. class StringRef;
  1190. struct IStream {
  1191. virtual ~IStream();
  1192. virtual std::ostream& stream() const = 0;
  1193. };
  1194. auto makeStream( StringRef const &filename ) -> IStream const*;
  1195. class ReusableStringStream : NonCopyable {
  1196. std::size_t m_index;
  1197. std::ostream* m_oss;
  1198. public:
  1199. ReusableStringStream();
  1200. ~ReusableStringStream();
  1201. auto str() const -> std::string;
  1202. template<typename T>
  1203. auto operator << ( T const& value ) -> ReusableStringStream& {
  1204. *m_oss << value;
  1205. return *this;
  1206. }
  1207. auto get() -> std::ostream& { return *m_oss; }
  1208. };
  1209. }
  1210. // end catch_stream.h
  1211. // start catch_interfaces_enum_values_registry.h
  1212. #include <vector>
  1213. namespace Catch {
  1214. namespace Detail {
  1215. struct EnumInfo {
  1216. StringRef m_name;
  1217. std::vector<std::pair<int, StringRef>> m_values;
  1218. ~EnumInfo();
  1219. StringRef lookup( int value ) const;
  1220. };
  1221. } // namespace Detail
  1222. struct IMutableEnumValuesRegistry {
  1223. virtual ~IMutableEnumValuesRegistry();
  1224. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1225. template<typename E>
  1226. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1227. static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
  1228. std::vector<int> intValues;
  1229. intValues.reserve( values.size() );
  1230. for( auto enumValue : values )
  1231. intValues.push_back( static_cast<int>( enumValue ) );
  1232. return registerEnum( enumName, allEnums, intValues );
  1233. }
  1234. };
  1235. } // Catch
  1236. // end catch_interfaces_enum_values_registry.h
  1237. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1238. #include <string_view>
  1239. #endif
  1240. #ifdef __OBJC__
  1241. // start catch_objc_arc.hpp
  1242. #import <Foundation/Foundation.h>
  1243. #ifdef __has_feature
  1244. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1245. #else
  1246. #define CATCH_ARC_ENABLED 0
  1247. #endif
  1248. void arcSafeRelease( NSObject* obj );
  1249. id performOptionalSelector( id obj, SEL sel );
  1250. #if !CATCH_ARC_ENABLED
  1251. inline void arcSafeRelease( NSObject* obj ) {
  1252. [obj release];
  1253. }
  1254. inline id performOptionalSelector( id obj, SEL sel ) {
  1255. if( [obj respondsToSelector: sel] )
  1256. return [obj performSelector: sel];
  1257. return nil;
  1258. }
  1259. #define CATCH_UNSAFE_UNRETAINED
  1260. #define CATCH_ARC_STRONG
  1261. #else
  1262. inline void arcSafeRelease( NSObject* ){}
  1263. inline id performOptionalSelector( id obj, SEL sel ) {
  1264. #ifdef __clang__
  1265. #pragma clang diagnostic push
  1266. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1267. #endif
  1268. if( [obj respondsToSelector: sel] )
  1269. return [obj performSelector: sel];
  1270. #ifdef __clang__
  1271. #pragma clang diagnostic pop
  1272. #endif
  1273. return nil;
  1274. }
  1275. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1276. #define CATCH_ARC_STRONG __strong
  1277. #endif
  1278. // end catch_objc_arc.hpp
  1279. #endif
  1280. #ifdef _MSC_VER
  1281. #pragma warning(push)
  1282. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1283. #endif
  1284. namespace Catch {
  1285. namespace Detail {
  1286. extern const std::string unprintableString;
  1287. std::string rawMemoryToString( const void *object, std::size_t size );
  1288. template<typename T>
  1289. std::string rawMemoryToString( const T& object ) {
  1290. return rawMemoryToString( &object, sizeof(object) );
  1291. }
  1292. template<typename T>
  1293. class IsStreamInsertable {
  1294. template<typename Stream, typename U>
  1295. static auto test(int)
  1296. -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
  1297. template<typename, typename>
  1298. static auto test(...)->std::false_type;
  1299. public:
  1300. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1301. };
  1302. template<typename E>
  1303. std::string convertUnknownEnumToString( E e );
  1304. template<typename T>
  1305. typename std::enable_if<
  1306. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1307. std::string>::type convertUnstreamable( T const& ) {
  1308. return Detail::unprintableString;
  1309. }
  1310. template<typename T>
  1311. typename std::enable_if<
  1312. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1313. std::string>::type convertUnstreamable(T const& ex) {
  1314. return ex.what();
  1315. }
  1316. template<typename T>
  1317. typename std::enable_if<
  1318. std::is_enum<T>::value
  1319. , std::string>::type convertUnstreamable( T const& value ) {
  1320. return convertUnknownEnumToString( value );
  1321. }
  1322. #if defined(_MANAGED)
  1323. //! Convert a CLR string to a utf8 std::string
  1324. template<typename T>
  1325. std::string clrReferenceToString( T^ ref ) {
  1326. if (ref == nullptr)
  1327. return std::string("null");
  1328. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1329. cli::pin_ptr<System::Byte> p = &bytes[0];
  1330. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1331. }
  1332. #endif
  1333. } // namespace Detail
  1334. // If we decide for C++14, change these to enable_if_ts
  1335. template <typename T, typename = void>
  1336. struct StringMaker {
  1337. template <typename Fake = T>
  1338. static
  1339. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1340. convert(const Fake& value) {
  1341. ReusableStringStream rss;
  1342. // NB: call using the function-like syntax to avoid ambiguity with
  1343. // user-defined templated operator<< under clang.
  1344. rss.operator<<(value);
  1345. return rss.str();
  1346. }
  1347. template <typename Fake = T>
  1348. static
  1349. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1350. convert( const Fake& value ) {
  1351. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1352. return Detail::convertUnstreamable(value);
  1353. #else
  1354. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1355. #endif
  1356. }
  1357. };
  1358. namespace Detail {
  1359. // This function dispatches all stringification requests inside of Catch.
  1360. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1361. template <typename T>
  1362. std::string stringify(const T& e) {
  1363. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1364. }
  1365. template<typename E>
  1366. std::string convertUnknownEnumToString( E e ) {
  1367. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1368. }
  1369. #if defined(_MANAGED)
  1370. template <typename T>
  1371. std::string stringify( T^ e ) {
  1372. return ::Catch::StringMaker<T^>::convert(e);
  1373. }
  1374. #endif
  1375. } // namespace Detail
  1376. // Some predefined specializations
  1377. template<>
  1378. struct StringMaker<std::string> {
  1379. static std::string convert(const std::string& str);
  1380. };
  1381. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1382. template<>
  1383. struct StringMaker<std::string_view> {
  1384. static std::string convert(std::string_view str);
  1385. };
  1386. #endif
  1387. template<>
  1388. struct StringMaker<char const *> {
  1389. static std::string convert(char const * str);
  1390. };
  1391. template<>
  1392. struct StringMaker<char *> {
  1393. static std::string convert(char * str);
  1394. };
  1395. #ifdef CATCH_CONFIG_WCHAR
  1396. template<>
  1397. struct StringMaker<std::wstring> {
  1398. static std::string convert(const std::wstring& wstr);
  1399. };
  1400. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1401. template<>
  1402. struct StringMaker<std::wstring_view> {
  1403. static std::string convert(std::wstring_view str);
  1404. };
  1405. # endif
  1406. template<>
  1407. struct StringMaker<wchar_t const *> {
  1408. static std::string convert(wchar_t const * str);
  1409. };
  1410. template<>
  1411. struct StringMaker<wchar_t *> {
  1412. static std::string convert(wchar_t * str);
  1413. };
  1414. #endif
  1415. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1416. // while keeping string semantics?
  1417. template<int SZ>
  1418. struct StringMaker<char[SZ]> {
  1419. static std::string convert(char const* str) {
  1420. return ::Catch::Detail::stringify(std::string{ str });
  1421. }
  1422. };
  1423. template<int SZ>
  1424. struct StringMaker<signed char[SZ]> {
  1425. static std::string convert(signed char const* str) {
  1426. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1427. }
  1428. };
  1429. template<int SZ>
  1430. struct StringMaker<unsigned char[SZ]> {
  1431. static std::string convert(unsigned char const* str) {
  1432. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1433. }
  1434. };
  1435. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1436. template<>
  1437. struct StringMaker<std::byte> {
  1438. static std::string convert(std::byte value);
  1439. };
  1440. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1441. template<>
  1442. struct StringMaker<int> {
  1443. static std::string convert(int value);
  1444. };
  1445. template<>
  1446. struct StringMaker<long> {
  1447. static std::string convert(long value);
  1448. };
  1449. template<>
  1450. struct StringMaker<long long> {
  1451. static std::string convert(long long value);
  1452. };
  1453. template<>
  1454. struct StringMaker<unsigned int> {
  1455. static std::string convert(unsigned int value);
  1456. };
  1457. template<>
  1458. struct StringMaker<unsigned long> {
  1459. static std::string convert(unsigned long value);
  1460. };
  1461. template<>
  1462. struct StringMaker<unsigned long long> {
  1463. static std::string convert(unsigned long long value);
  1464. };
  1465. template<>
  1466. struct StringMaker<bool> {
  1467. static std::string convert(bool b);
  1468. };
  1469. template<>
  1470. struct StringMaker<char> {
  1471. static std::string convert(char c);
  1472. };
  1473. template<>
  1474. struct StringMaker<signed char> {
  1475. static std::string convert(signed char c);
  1476. };
  1477. template<>
  1478. struct StringMaker<unsigned char> {
  1479. static std::string convert(unsigned char c);
  1480. };
  1481. template<>
  1482. struct StringMaker<std::nullptr_t> {
  1483. static std::string convert(std::nullptr_t);
  1484. };
  1485. template<>
  1486. struct StringMaker<float> {
  1487. static std::string convert(float value);
  1488. static int precision;
  1489. };
  1490. template<>
  1491. struct StringMaker<double> {
  1492. static std::string convert(double value);
  1493. static int precision;
  1494. };
  1495. template <typename T>
  1496. struct StringMaker<T*> {
  1497. template <typename U>
  1498. static std::string convert(U* p) {
  1499. if (p) {
  1500. return ::Catch::Detail::rawMemoryToString(p);
  1501. } else {
  1502. return "nullptr";
  1503. }
  1504. }
  1505. };
  1506. template <typename R, typename C>
  1507. struct StringMaker<R C::*> {
  1508. static std::string convert(R C::* p) {
  1509. if (p) {
  1510. return ::Catch::Detail::rawMemoryToString(p);
  1511. } else {
  1512. return "nullptr";
  1513. }
  1514. }
  1515. };
  1516. #if defined(_MANAGED)
  1517. template <typename T>
  1518. struct StringMaker<T^> {
  1519. static std::string convert( T^ ref ) {
  1520. return ::Catch::Detail::clrReferenceToString(ref);
  1521. }
  1522. };
  1523. #endif
  1524. namespace Detail {
  1525. template<typename InputIterator, typename Sentinel = InputIterator>
  1526. std::string rangeToString(InputIterator first, Sentinel last) {
  1527. ReusableStringStream rss;
  1528. rss << "{ ";
  1529. if (first != last) {
  1530. rss << ::Catch::Detail::stringify(*first);
  1531. for (++first; first != last; ++first)
  1532. rss << ", " << ::Catch::Detail::stringify(*first);
  1533. }
  1534. rss << " }";
  1535. return rss.str();
  1536. }
  1537. }
  1538. #ifdef __OBJC__
  1539. template<>
  1540. struct StringMaker<NSString*> {
  1541. static std::string convert(NSString * nsstring) {
  1542. if (!nsstring)
  1543. return "nil";
  1544. return std::string("@") + [nsstring UTF8String];
  1545. }
  1546. };
  1547. template<>
  1548. struct StringMaker<NSObject*> {
  1549. static std::string convert(NSObject* nsObject) {
  1550. return ::Catch::Detail::stringify([nsObject description]);
  1551. }
  1552. };
  1553. namespace Detail {
  1554. inline std::string stringify( NSString* nsstring ) {
  1555. return StringMaker<NSString*>::convert( nsstring );
  1556. }
  1557. } // namespace Detail
  1558. #endif // __OBJC__
  1559. } // namespace Catch
  1560. //////////////////////////////////////////////////////
  1561. // Separate std-lib types stringification, so it can be selectively enabled
  1562. // This means that we do not bring in
  1563. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1564. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1565. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1566. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1567. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1568. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1569. #endif
  1570. // Separate std::pair specialization
  1571. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1572. #include <utility>
  1573. namespace Catch {
  1574. template<typename T1, typename T2>
  1575. struct StringMaker<std::pair<T1, T2> > {
  1576. static std::string convert(const std::pair<T1, T2>& pair) {
  1577. ReusableStringStream rss;
  1578. rss << "{ "
  1579. << ::Catch::Detail::stringify(pair.first)
  1580. << ", "
  1581. << ::Catch::Detail::stringify(pair.second)
  1582. << " }";
  1583. return rss.str();
  1584. }
  1585. };
  1586. }
  1587. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1588. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1589. #include <optional>
  1590. namespace Catch {
  1591. template<typename T>
  1592. struct StringMaker<std::optional<T> > {
  1593. static std::string convert(const std::optional<T>& optional) {
  1594. ReusableStringStream rss;
  1595. if (optional.has_value()) {
  1596. rss << ::Catch::Detail::stringify(*optional);
  1597. } else {
  1598. rss << "{ }";
  1599. }
  1600. return rss.str();
  1601. }
  1602. };
  1603. }
  1604. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1605. // Separate std::tuple specialization
  1606. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1607. #include <tuple>
  1608. namespace Catch {
  1609. namespace Detail {
  1610. template<
  1611. typename Tuple,
  1612. std::size_t N = 0,
  1613. bool = (N < std::tuple_size<Tuple>::value)
  1614. >
  1615. struct TupleElementPrinter {
  1616. static void print(const Tuple& tuple, std::ostream& os) {
  1617. os << (N ? ", " : " ")
  1618. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1619. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1620. }
  1621. };
  1622. template<
  1623. typename Tuple,
  1624. std::size_t N
  1625. >
  1626. struct TupleElementPrinter<Tuple, N, false> {
  1627. static void print(const Tuple&, std::ostream&) {}
  1628. };
  1629. }
  1630. template<typename ...Types>
  1631. struct StringMaker<std::tuple<Types...>> {
  1632. static std::string convert(const std::tuple<Types...>& tuple) {
  1633. ReusableStringStream rss;
  1634. rss << '{';
  1635. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1636. rss << " }";
  1637. return rss.str();
  1638. }
  1639. };
  1640. }
  1641. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1642. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1643. #include <variant>
  1644. namespace Catch {
  1645. template<>
  1646. struct StringMaker<std::monostate> {
  1647. static std::string convert(const std::monostate&) {
  1648. return "{ }";
  1649. }
  1650. };
  1651. template<typename... Elements>
  1652. struct StringMaker<std::variant<Elements...>> {
  1653. static std::string convert(const std::variant<Elements...>& variant) {
  1654. if (variant.valueless_by_exception()) {
  1655. return "{valueless variant}";
  1656. } else {
  1657. return std::visit(
  1658. [](const auto& value) {
  1659. return ::Catch::Detail::stringify(value);
  1660. },
  1661. variant
  1662. );
  1663. }
  1664. }
  1665. };
  1666. }
  1667. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1668. namespace Catch {
  1669. // Import begin/ end from std here
  1670. using std::begin;
  1671. using std::end;
  1672. namespace detail {
  1673. template <typename...>
  1674. struct void_type {
  1675. using type = void;
  1676. };
  1677. template <typename T, typename = void>
  1678. struct is_range_impl : std::false_type {
  1679. };
  1680. template <typename T>
  1681. struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
  1682. };
  1683. } // namespace detail
  1684. template <typename T>
  1685. struct is_range : detail::is_range_impl<T> {
  1686. };
  1687. #if defined(_MANAGED) // Managed types are never ranges
  1688. template <typename T>
  1689. struct is_range<T^> {
  1690. static const bool value = false;
  1691. };
  1692. #endif
  1693. template<typename Range>
  1694. std::string rangeToString( Range const& range ) {
  1695. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1696. }
  1697. // Handle vector<bool> specially
  1698. template<typename Allocator>
  1699. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1700. ReusableStringStream rss;
  1701. rss << "{ ";
  1702. bool first = true;
  1703. for( bool b : v ) {
  1704. if( first )
  1705. first = false;
  1706. else
  1707. rss << ", ";
  1708. rss << ::Catch::Detail::stringify( b );
  1709. }
  1710. rss << " }";
  1711. return rss.str();
  1712. }
  1713. template<typename R>
  1714. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1715. static std::string convert( R const& range ) {
  1716. return rangeToString( range );
  1717. }
  1718. };
  1719. template <typename T, int SZ>
  1720. struct StringMaker<T[SZ]> {
  1721. static std::string convert(T const(&arr)[SZ]) {
  1722. return rangeToString(arr);
  1723. }
  1724. };
  1725. } // namespace Catch
  1726. // Separate std::chrono::duration specialization
  1727. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1728. #include <ctime>
  1729. #include <ratio>
  1730. #include <chrono>
  1731. namespace Catch {
  1732. template <class Ratio>
  1733. struct ratio_string {
  1734. static std::string symbol();
  1735. };
  1736. template <class Ratio>
  1737. std::string ratio_string<Ratio>::symbol() {
  1738. Catch::ReusableStringStream rss;
  1739. rss << '[' << Ratio::num << '/'
  1740. << Ratio::den << ']';
  1741. return rss.str();
  1742. }
  1743. template <>
  1744. struct ratio_string<std::atto> {
  1745. static std::string symbol();
  1746. };
  1747. template <>
  1748. struct ratio_string<std::femto> {
  1749. static std::string symbol();
  1750. };
  1751. template <>
  1752. struct ratio_string<std::pico> {
  1753. static std::string symbol();
  1754. };
  1755. template <>
  1756. struct ratio_string<std::nano> {
  1757. static std::string symbol();
  1758. };
  1759. template <>
  1760. struct ratio_string<std::micro> {
  1761. static std::string symbol();
  1762. };
  1763. template <>
  1764. struct ratio_string<std::milli> {
  1765. static std::string symbol();
  1766. };
  1767. ////////////
  1768. // std::chrono::duration specializations
  1769. template<typename Value, typename Ratio>
  1770. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1771. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1772. ReusableStringStream rss;
  1773. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1774. return rss.str();
  1775. }
  1776. };
  1777. template<typename Value>
  1778. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1779. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1780. ReusableStringStream rss;
  1781. rss << duration.count() << " s";
  1782. return rss.str();
  1783. }
  1784. };
  1785. template<typename Value>
  1786. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1787. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1788. ReusableStringStream rss;
  1789. rss << duration.count() << " m";
  1790. return rss.str();
  1791. }
  1792. };
  1793. template<typename Value>
  1794. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1795. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1796. ReusableStringStream rss;
  1797. rss << duration.count() << " h";
  1798. return rss.str();
  1799. }
  1800. };
  1801. ////////////
  1802. // std::chrono::time_point specialization
  1803. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1804. template<typename Clock, typename Duration>
  1805. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1806. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1807. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1808. }
  1809. };
  1810. // std::chrono::time_point<system_clock> specialization
  1811. template<typename Duration>
  1812. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1813. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1814. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1815. #ifdef _MSC_VER
  1816. std::tm timeInfo = {};
  1817. gmtime_s(&timeInfo, &converted);
  1818. #else
  1819. std::tm* timeInfo = std::gmtime(&converted);
  1820. #endif
  1821. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1822. char timeStamp[timeStampSize];
  1823. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1824. #ifdef _MSC_VER
  1825. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1826. #else
  1827. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1828. #endif
  1829. return std::string(timeStamp);
  1830. }
  1831. };
  1832. }
  1833. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1834. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1835. namespace Catch { \
  1836. template<> struct StringMaker<enumName> { \
  1837. static std::string convert( enumName value ) { \
  1838. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1839. return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
  1840. } \
  1841. }; \
  1842. }
  1843. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1844. #ifdef _MSC_VER
  1845. #pragma warning(pop)
  1846. #endif
  1847. // end catch_tostring.h
  1848. #include <iosfwd>
  1849. #ifdef _MSC_VER
  1850. #pragma warning(push)
  1851. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1852. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1853. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1854. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1855. #pragma warning(disable:4800) // Forcing result to true or false
  1856. #endif
  1857. namespace Catch {
  1858. struct ITransientExpression {
  1859. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1860. auto getResult() const -> bool { return m_result; }
  1861. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1862. ITransientExpression( bool isBinaryExpression, bool result )
  1863. : m_isBinaryExpression( isBinaryExpression ),
  1864. m_result( result )
  1865. {}
  1866. // We don't actually need a virtual destructor, but many static analysers
  1867. // complain if it's not here :-(
  1868. virtual ~ITransientExpression();
  1869. bool m_isBinaryExpression;
  1870. bool m_result;
  1871. };
  1872. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1873. template<typename LhsT, typename RhsT>
  1874. class BinaryExpr : public ITransientExpression {
  1875. LhsT m_lhs;
  1876. StringRef m_op;
  1877. RhsT m_rhs;
  1878. void streamReconstructedExpression( std::ostream &os ) const override {
  1879. formatReconstructedExpression
  1880. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1881. }
  1882. public:
  1883. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1884. : ITransientExpression{ true, comparisonResult },
  1885. m_lhs( lhs ),
  1886. m_op( op ),
  1887. m_rhs( rhs )
  1888. {}
  1889. template<typename T>
  1890. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1891. static_assert(always_false<T>::value,
  1892. "chained comparisons are not supported inside assertions, "
  1893. "wrap the expression inside parentheses, or decompose it");
  1894. }
  1895. template<typename T>
  1896. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1897. static_assert(always_false<T>::value,
  1898. "chained comparisons are not supported inside assertions, "
  1899. "wrap the expression inside parentheses, or decompose it");
  1900. }
  1901. template<typename T>
  1902. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1903. static_assert(always_false<T>::value,
  1904. "chained comparisons are not supported inside assertions, "
  1905. "wrap the expression inside parentheses, or decompose it");
  1906. }
  1907. template<typename T>
  1908. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1909. static_assert(always_false<T>::value,
  1910. "chained comparisons are not supported inside assertions, "
  1911. "wrap the expression inside parentheses, or decompose it");
  1912. }
  1913. template<typename T>
  1914. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1915. static_assert(always_false<T>::value,
  1916. "chained comparisons are not supported inside assertions, "
  1917. "wrap the expression inside parentheses, or decompose it");
  1918. }
  1919. template<typename T>
  1920. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1921. static_assert(always_false<T>::value,
  1922. "chained comparisons are not supported inside assertions, "
  1923. "wrap the expression inside parentheses, or decompose it");
  1924. }
  1925. template<typename T>
  1926. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1927. static_assert(always_false<T>::value,
  1928. "chained comparisons are not supported inside assertions, "
  1929. "wrap the expression inside parentheses, or decompose it");
  1930. }
  1931. template<typename T>
  1932. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1933. static_assert(always_false<T>::value,
  1934. "chained comparisons are not supported inside assertions, "
  1935. "wrap the expression inside parentheses, or decompose it");
  1936. }
  1937. };
  1938. template<typename LhsT>
  1939. class UnaryExpr : public ITransientExpression {
  1940. LhsT m_lhs;
  1941. void streamReconstructedExpression( std::ostream &os ) const override {
  1942. os << Catch::Detail::stringify( m_lhs );
  1943. }
  1944. public:
  1945. explicit UnaryExpr( LhsT lhs )
  1946. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1947. m_lhs( lhs )
  1948. {}
  1949. };
  1950. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1951. template<typename LhsT, typename RhsT>
  1952. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1953. template<typename T>
  1954. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1955. template<typename T>
  1956. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1957. template<typename T>
  1958. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1959. template<typename T>
  1960. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1961. template<typename LhsT, typename RhsT>
  1962. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1963. template<typename T>
  1964. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1965. template<typename T>
  1966. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1967. template<typename T>
  1968. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1969. template<typename T>
  1970. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1971. template<typename LhsT>
  1972. class ExprLhs {
  1973. LhsT m_lhs;
  1974. public:
  1975. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1976. template<typename RhsT>
  1977. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1978. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1979. }
  1980. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1981. return { m_lhs == rhs, m_lhs, "==", rhs };
  1982. }
  1983. template<typename RhsT>
  1984. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1985. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1986. }
  1987. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1988. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1989. }
  1990. template<typename RhsT>
  1991. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1992. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1993. }
  1994. template<typename RhsT>
  1995. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1996. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1997. }
  1998. template<typename RhsT>
  1999. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2000. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  2001. }
  2002. template<typename RhsT>
  2003. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2004. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  2005. }
  2006. template <typename RhsT>
  2007. auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2008. return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
  2009. }
  2010. template <typename RhsT>
  2011. auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2012. return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
  2013. }
  2014. template <typename RhsT>
  2015. auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2016. return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
  2017. }
  2018. template<typename RhsT>
  2019. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2020. static_assert(always_false<RhsT>::value,
  2021. "operator&& is not supported inside assertions, "
  2022. "wrap the expression inside parentheses, or decompose it");
  2023. }
  2024. template<typename RhsT>
  2025. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2026. static_assert(always_false<RhsT>::value,
  2027. "operator|| is not supported inside assertions, "
  2028. "wrap the expression inside parentheses, or decompose it");
  2029. }
  2030. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  2031. return UnaryExpr<LhsT>{ m_lhs };
  2032. }
  2033. };
  2034. void handleExpression( ITransientExpression const& expr );
  2035. template<typename T>
  2036. void handleExpression( ExprLhs<T> const& expr ) {
  2037. handleExpression( expr.makeUnaryExpr() );
  2038. }
  2039. struct Decomposer {
  2040. template<typename T>
  2041. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  2042. return ExprLhs<T const&>{ lhs };
  2043. }
  2044. auto operator <=( bool value ) -> ExprLhs<bool> {
  2045. return ExprLhs<bool>{ value };
  2046. }
  2047. };
  2048. } // end namespace Catch
  2049. #ifdef _MSC_VER
  2050. #pragma warning(pop)
  2051. #endif
  2052. // end catch_decomposer.h
  2053. // start catch_interfaces_capture.h
  2054. #include <string>
  2055. #include <chrono>
  2056. namespace Catch {
  2057. class AssertionResult;
  2058. struct AssertionInfo;
  2059. struct SectionInfo;
  2060. struct SectionEndInfo;
  2061. struct MessageInfo;
  2062. struct MessageBuilder;
  2063. struct Counts;
  2064. struct AssertionReaction;
  2065. struct SourceLineInfo;
  2066. struct ITransientExpression;
  2067. struct IGeneratorTracker;
  2068. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2069. struct BenchmarkInfo;
  2070. template <typename Duration = std::chrono::duration<double, std::nano>>
  2071. struct BenchmarkStats;
  2072. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2073. struct IResultCapture {
  2074. virtual ~IResultCapture();
  2075. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2076. Counts& assertions ) = 0;
  2077. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2078. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2079. virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2080. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2081. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2082. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2083. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2084. virtual void benchmarkFailed( std::string const& error ) = 0;
  2085. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2086. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2087. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2088. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2089. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2090. virtual void handleExpr
  2091. ( AssertionInfo const& info,
  2092. ITransientExpression const& expr,
  2093. AssertionReaction& reaction ) = 0;
  2094. virtual void handleMessage
  2095. ( AssertionInfo const& info,
  2096. ResultWas::OfType resultType,
  2097. StringRef const& message,
  2098. AssertionReaction& reaction ) = 0;
  2099. virtual void handleUnexpectedExceptionNotThrown
  2100. ( AssertionInfo const& info,
  2101. AssertionReaction& reaction ) = 0;
  2102. virtual void handleUnexpectedInflightException
  2103. ( AssertionInfo const& info,
  2104. std::string const& message,
  2105. AssertionReaction& reaction ) = 0;
  2106. virtual void handleIncomplete
  2107. ( AssertionInfo const& info ) = 0;
  2108. virtual void handleNonExpr
  2109. ( AssertionInfo const &info,
  2110. ResultWas::OfType resultType,
  2111. AssertionReaction &reaction ) = 0;
  2112. virtual bool lastAssertionPassed() = 0;
  2113. virtual void assertionPassed() = 0;
  2114. // Deprecated, do not use:
  2115. virtual std::string getCurrentTestName() const = 0;
  2116. virtual const AssertionResult* getLastResult() const = 0;
  2117. virtual void exceptionEarlyReported() = 0;
  2118. };
  2119. IResultCapture& getResultCapture();
  2120. }
  2121. // end catch_interfaces_capture.h
  2122. namespace Catch {
  2123. struct TestFailureException{};
  2124. struct AssertionResultData;
  2125. struct IResultCapture;
  2126. class RunContext;
  2127. class LazyExpression {
  2128. friend class AssertionHandler;
  2129. friend struct AssertionStats;
  2130. friend class RunContext;
  2131. ITransientExpression const* m_transientExpression = nullptr;
  2132. bool m_isNegated;
  2133. public:
  2134. LazyExpression( bool isNegated );
  2135. LazyExpression( LazyExpression const& other );
  2136. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2137. explicit operator bool() const;
  2138. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2139. };
  2140. struct AssertionReaction {
  2141. bool shouldDebugBreak = false;
  2142. bool shouldThrow = false;
  2143. };
  2144. class AssertionHandler {
  2145. AssertionInfo m_assertionInfo;
  2146. AssertionReaction m_reaction;
  2147. bool m_completed = false;
  2148. IResultCapture& m_resultCapture;
  2149. public:
  2150. AssertionHandler
  2151. ( StringRef const& macroName,
  2152. SourceLineInfo const& lineInfo,
  2153. StringRef capturedExpression,
  2154. ResultDisposition::Flags resultDisposition );
  2155. ~AssertionHandler() {
  2156. if ( !m_completed ) {
  2157. m_resultCapture.handleIncomplete( m_assertionInfo );
  2158. }
  2159. }
  2160. template<typename T>
  2161. void handleExpr( ExprLhs<T> const& expr ) {
  2162. handleExpr( expr.makeUnaryExpr() );
  2163. }
  2164. void handleExpr( ITransientExpression const& expr );
  2165. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2166. void handleExceptionThrownAsExpected();
  2167. void handleUnexpectedExceptionNotThrown();
  2168. void handleExceptionNotThrownAsExpected();
  2169. void handleThrowingCallSkipped();
  2170. void handleUnexpectedInflightException();
  2171. void complete();
  2172. void setCompleted();
  2173. // query
  2174. auto allowThrows() const -> bool;
  2175. };
  2176. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2177. } // namespace Catch
  2178. // end catch_assertionhandler.h
  2179. // start catch_message.h
  2180. #include <string>
  2181. #include <vector>
  2182. namespace Catch {
  2183. struct MessageInfo {
  2184. MessageInfo( StringRef const& _macroName,
  2185. SourceLineInfo const& _lineInfo,
  2186. ResultWas::OfType _type );
  2187. StringRef macroName;
  2188. std::string message;
  2189. SourceLineInfo lineInfo;
  2190. ResultWas::OfType type;
  2191. unsigned int sequence;
  2192. bool operator == ( MessageInfo const& other ) const;
  2193. bool operator < ( MessageInfo const& other ) const;
  2194. private:
  2195. static unsigned int globalCount;
  2196. };
  2197. struct MessageStream {
  2198. template<typename T>
  2199. MessageStream& operator << ( T const& value ) {
  2200. m_stream << value;
  2201. return *this;
  2202. }
  2203. ReusableStringStream m_stream;
  2204. };
  2205. struct MessageBuilder : MessageStream {
  2206. MessageBuilder( StringRef const& macroName,
  2207. SourceLineInfo const& lineInfo,
  2208. ResultWas::OfType type );
  2209. template<typename T>
  2210. MessageBuilder& operator << ( T const& value ) {
  2211. m_stream << value;
  2212. return *this;
  2213. }
  2214. MessageInfo m_info;
  2215. };
  2216. class ScopedMessage {
  2217. public:
  2218. explicit ScopedMessage( MessageBuilder const& builder );
  2219. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2220. ScopedMessage( ScopedMessage&& old );
  2221. ~ScopedMessage();
  2222. MessageInfo m_info;
  2223. bool m_moved;
  2224. };
  2225. class Capturer {
  2226. std::vector<MessageInfo> m_messages;
  2227. IResultCapture& m_resultCapture = getResultCapture();
  2228. size_t m_captured = 0;
  2229. public:
  2230. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2231. ~Capturer();
  2232. void captureValue( size_t index, std::string const& value );
  2233. template<typename T>
  2234. void captureValues( size_t index, T const& value ) {
  2235. captureValue( index, Catch::Detail::stringify( value ) );
  2236. }
  2237. template<typename T, typename... Ts>
  2238. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2239. captureValue( index, Catch::Detail::stringify(value) );
  2240. captureValues( index+1, values... );
  2241. }
  2242. };
  2243. } // end namespace Catch
  2244. // end catch_message.h
  2245. #if !defined(CATCH_CONFIG_DISABLE)
  2246. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2247. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2248. #else
  2249. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2250. #endif
  2251. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2252. ///////////////////////////////////////////////////////////////////////////////
  2253. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2254. // macros.
  2255. #define INTERNAL_CATCH_TRY
  2256. #define INTERNAL_CATCH_CATCH( capturer )
  2257. #else // CATCH_CONFIG_FAST_COMPILE
  2258. #define INTERNAL_CATCH_TRY try
  2259. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2260. #endif
  2261. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2262. ///////////////////////////////////////////////////////////////////////////////
  2263. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2264. do { \
  2265. CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
  2266. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2267. INTERNAL_CATCH_TRY { \
  2268. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2269. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2270. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2271. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2272. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2273. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2274. } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
  2275. ///////////////////////////////////////////////////////////////////////////////
  2276. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2277. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2278. if( Catch::getResultCapture().lastAssertionPassed() )
  2279. ///////////////////////////////////////////////////////////////////////////////
  2280. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2281. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2282. if( !Catch::getResultCapture().lastAssertionPassed() )
  2283. ///////////////////////////////////////////////////////////////////////////////
  2284. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2285. do { \
  2286. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2287. try { \
  2288. static_cast<void>(__VA_ARGS__); \
  2289. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2290. } \
  2291. catch( ... ) { \
  2292. catchAssertionHandler.handleUnexpectedInflightException(); \
  2293. } \
  2294. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2295. } while( false )
  2296. ///////////////////////////////////////////////////////////////////////////////
  2297. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2298. do { \
  2299. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2300. if( catchAssertionHandler.allowThrows() ) \
  2301. try { \
  2302. static_cast<void>(__VA_ARGS__); \
  2303. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2304. } \
  2305. catch( ... ) { \
  2306. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2307. } \
  2308. else \
  2309. catchAssertionHandler.handleThrowingCallSkipped(); \
  2310. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2311. } while( false )
  2312. ///////////////////////////////////////////////////////////////////////////////
  2313. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2314. do { \
  2315. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2316. if( catchAssertionHandler.allowThrows() ) \
  2317. try { \
  2318. static_cast<void>(expr); \
  2319. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2320. } \
  2321. catch( exceptionType const& ) { \
  2322. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2323. } \
  2324. catch( ... ) { \
  2325. catchAssertionHandler.handleUnexpectedInflightException(); \
  2326. } \
  2327. else \
  2328. catchAssertionHandler.handleThrowingCallSkipped(); \
  2329. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2330. } while( false )
  2331. ///////////////////////////////////////////////////////////////////////////////
  2332. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2333. do { \
  2334. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2335. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2336. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2337. } while( false )
  2338. ///////////////////////////////////////////////////////////////////////////////
  2339. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2340. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2341. varName.captureValues( 0, __VA_ARGS__ )
  2342. ///////////////////////////////////////////////////////////////////////////////
  2343. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2344. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2345. ///////////////////////////////////////////////////////////////////////////////
  2346. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2347. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2348. ///////////////////////////////////////////////////////////////////////////////
  2349. // Although this is matcher-based, it can be used with just a string
  2350. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2351. do { \
  2352. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2353. if( catchAssertionHandler.allowThrows() ) \
  2354. try { \
  2355. static_cast<void>(__VA_ARGS__); \
  2356. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2357. } \
  2358. catch( ... ) { \
  2359. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2360. } \
  2361. else \
  2362. catchAssertionHandler.handleThrowingCallSkipped(); \
  2363. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2364. } while( false )
  2365. #endif // CATCH_CONFIG_DISABLE
  2366. // end catch_capture.hpp
  2367. // start catch_section.h
  2368. // start catch_section_info.h
  2369. // start catch_totals.h
  2370. #include <cstddef>
  2371. namespace Catch {
  2372. struct Counts {
  2373. Counts operator - ( Counts const& other ) const;
  2374. Counts& operator += ( Counts const& other );
  2375. std::size_t total() const;
  2376. bool allPassed() const;
  2377. bool allOk() const;
  2378. std::size_t passed = 0;
  2379. std::size_t failed = 0;
  2380. std::size_t failedButOk = 0;
  2381. };
  2382. struct Totals {
  2383. Totals operator - ( Totals const& other ) const;
  2384. Totals& operator += ( Totals const& other );
  2385. Totals delta( Totals const& prevTotals ) const;
  2386. int error = 0;
  2387. Counts assertions;
  2388. Counts testCases;
  2389. };
  2390. }
  2391. // end catch_totals.h
  2392. #include <string>
  2393. namespace Catch {
  2394. struct SectionInfo {
  2395. SectionInfo
  2396. ( SourceLineInfo const& _lineInfo,
  2397. std::string const& _name );
  2398. // Deprecated
  2399. SectionInfo
  2400. ( SourceLineInfo const& _lineInfo,
  2401. std::string const& _name,
  2402. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2403. std::string name;
  2404. std::string description; // !Deprecated: this will always be empty
  2405. SourceLineInfo lineInfo;
  2406. };
  2407. struct SectionEndInfo {
  2408. SectionInfo sectionInfo;
  2409. Counts prevAssertions;
  2410. double durationInSeconds;
  2411. };
  2412. } // end namespace Catch
  2413. // end catch_section_info.h
  2414. // start catch_timer.h
  2415. #include <cstdint>
  2416. namespace Catch {
  2417. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2418. auto getEstimatedClockResolution() -> uint64_t;
  2419. class Timer {
  2420. uint64_t m_nanoseconds = 0;
  2421. public:
  2422. void start();
  2423. auto getElapsedNanoseconds() const -> uint64_t;
  2424. auto getElapsedMicroseconds() const -> uint64_t;
  2425. auto getElapsedMilliseconds() const -> unsigned int;
  2426. auto getElapsedSeconds() const -> double;
  2427. };
  2428. } // namespace Catch
  2429. // end catch_timer.h
  2430. #include <string>
  2431. namespace Catch {
  2432. class Section : NonCopyable {
  2433. public:
  2434. Section( SectionInfo const& info );
  2435. ~Section();
  2436. // This indicates whether the section should be executed or not
  2437. explicit operator bool() const;
  2438. private:
  2439. SectionInfo m_info;
  2440. std::string m_name;
  2441. Counts m_assertions;
  2442. bool m_sectionIncluded;
  2443. Timer m_timer;
  2444. };
  2445. } // end namespace Catch
  2446. #define INTERNAL_CATCH_SECTION( ... ) \
  2447. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2448. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2449. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2450. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2451. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2452. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2453. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2454. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2455. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2456. // end catch_section.h
  2457. // start catch_interfaces_exception.h
  2458. // start catch_interfaces_registry_hub.h
  2459. #include <string>
  2460. #include <memory>
  2461. namespace Catch {
  2462. class TestCase;
  2463. struct ITestCaseRegistry;
  2464. struct IExceptionTranslatorRegistry;
  2465. struct IExceptionTranslator;
  2466. struct IReporterRegistry;
  2467. struct IReporterFactory;
  2468. struct ITagAliasRegistry;
  2469. struct IMutableEnumValuesRegistry;
  2470. class StartupExceptionRegistry;
  2471. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2472. struct IRegistryHub {
  2473. virtual ~IRegistryHub();
  2474. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2475. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2476. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2477. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2478. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2479. };
  2480. struct IMutableRegistryHub {
  2481. virtual ~IMutableRegistryHub();
  2482. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2483. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2484. virtual void registerTest( TestCase const& testInfo ) = 0;
  2485. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2486. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2487. virtual void registerStartupException() noexcept = 0;
  2488. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2489. };
  2490. IRegistryHub const& getRegistryHub();
  2491. IMutableRegistryHub& getMutableRegistryHub();
  2492. void cleanUp();
  2493. std::string translateActiveException();
  2494. }
  2495. // end catch_interfaces_registry_hub.h
  2496. #if defined(CATCH_CONFIG_DISABLE)
  2497. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2498. static std::string translatorName( signature )
  2499. #endif
  2500. #include <exception>
  2501. #include <string>
  2502. #include <vector>
  2503. namespace Catch {
  2504. using exceptionTranslateFunction = std::string(*)();
  2505. struct IExceptionTranslator;
  2506. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2507. struct IExceptionTranslator {
  2508. virtual ~IExceptionTranslator();
  2509. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2510. };
  2511. struct IExceptionTranslatorRegistry {
  2512. virtual ~IExceptionTranslatorRegistry();
  2513. virtual std::string translateActiveException() const = 0;
  2514. };
  2515. class ExceptionTranslatorRegistrar {
  2516. template<typename T>
  2517. class ExceptionTranslator : public IExceptionTranslator {
  2518. public:
  2519. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2520. : m_translateFunction( translateFunction )
  2521. {}
  2522. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2523. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2524. return "";
  2525. #else
  2526. try {
  2527. if( it == itEnd )
  2528. std::rethrow_exception(std::current_exception());
  2529. else
  2530. return (*it)->translate( it+1, itEnd );
  2531. }
  2532. catch( T& ex ) {
  2533. return m_translateFunction( ex );
  2534. }
  2535. #endif
  2536. }
  2537. protected:
  2538. std::string(*m_translateFunction)( T& );
  2539. };
  2540. public:
  2541. template<typename T>
  2542. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2543. getMutableRegistryHub().registerTranslator
  2544. ( new ExceptionTranslator<T>( translateFunction ) );
  2545. }
  2546. };
  2547. }
  2548. ///////////////////////////////////////////////////////////////////////////////
  2549. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2550. static std::string translatorName( signature ); \
  2551. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2552. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2553. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2554. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2555. static std::string translatorName( signature )
  2556. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2557. // end catch_interfaces_exception.h
  2558. // start catch_approx.h
  2559. #include <type_traits>
  2560. namespace Catch {
  2561. namespace Detail {
  2562. class Approx {
  2563. private:
  2564. bool equalityComparisonImpl(double other) const;
  2565. // Validates the new margin (margin >= 0)
  2566. // out-of-line to avoid including stdexcept in the header
  2567. void setMargin(double margin);
  2568. // Validates the new epsilon (0 < epsilon < 1)
  2569. // out-of-line to avoid including stdexcept in the header
  2570. void setEpsilon(double epsilon);
  2571. public:
  2572. explicit Approx ( double value );
  2573. static Approx custom();
  2574. Approx operator-() const;
  2575. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2576. Approx operator()( T const& value ) {
  2577. Approx approx( static_cast<double>(value) );
  2578. approx.m_epsilon = m_epsilon;
  2579. approx.m_margin = m_margin;
  2580. approx.m_scale = m_scale;
  2581. return approx;
  2582. }
  2583. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2584. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2585. {}
  2586. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2587. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2588. auto lhs_v = static_cast<double>(lhs);
  2589. return rhs.equalityComparisonImpl(lhs_v);
  2590. }
  2591. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2592. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2593. return operator==( rhs, lhs );
  2594. }
  2595. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2596. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2597. return !operator==( lhs, rhs );
  2598. }
  2599. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2600. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2601. return !operator==( rhs, lhs );
  2602. }
  2603. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2604. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2605. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2606. }
  2607. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2608. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2609. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2610. }
  2611. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2612. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2613. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2614. }
  2615. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2616. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2617. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2618. }
  2619. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2620. Approx& epsilon( T const& newEpsilon ) {
  2621. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2622. setEpsilon(epsilonAsDouble);
  2623. return *this;
  2624. }
  2625. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2626. Approx& margin( T const& newMargin ) {
  2627. double marginAsDouble = static_cast<double>(newMargin);
  2628. setMargin(marginAsDouble);
  2629. return *this;
  2630. }
  2631. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2632. Approx& scale( T const& newScale ) {
  2633. m_scale = static_cast<double>(newScale);
  2634. return *this;
  2635. }
  2636. std::string toString() const;
  2637. private:
  2638. double m_epsilon;
  2639. double m_margin;
  2640. double m_scale;
  2641. double m_value;
  2642. };
  2643. } // end namespace Detail
  2644. namespace literals {
  2645. Detail::Approx operator "" _a(long double val);
  2646. Detail::Approx operator "" _a(unsigned long long val);
  2647. } // end namespace literals
  2648. template<>
  2649. struct StringMaker<Catch::Detail::Approx> {
  2650. static std::string convert(Catch::Detail::Approx const& value);
  2651. };
  2652. } // end namespace Catch
  2653. // end catch_approx.h
  2654. // start catch_string_manip.h
  2655. #include <string>
  2656. #include <iosfwd>
  2657. #include <vector>
  2658. namespace Catch {
  2659. bool startsWith( std::string const& s, std::string const& prefix );
  2660. bool startsWith( std::string const& s, char prefix );
  2661. bool endsWith( std::string const& s, std::string const& suffix );
  2662. bool endsWith( std::string const& s, char suffix );
  2663. bool contains( std::string const& s, std::string const& infix );
  2664. void toLowerInPlace( std::string& s );
  2665. std::string toLower( std::string const& s );
  2666. //! Returns a new string without whitespace at the start/end
  2667. std::string trim( std::string const& str );
  2668. //! Returns a substring of the original ref without whitespace. Beware lifetimes!
  2669. StringRef trim(StringRef ref);
  2670. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2671. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2672. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2673. struct pluralise {
  2674. pluralise( std::size_t count, std::string const& label );
  2675. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2676. std::size_t m_count;
  2677. std::string m_label;
  2678. };
  2679. }
  2680. // end catch_string_manip.h
  2681. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2682. // start catch_capture_matchers.h
  2683. // start catch_matchers.h
  2684. #include <string>
  2685. #include <vector>
  2686. namespace Catch {
  2687. namespace Matchers {
  2688. namespace Impl {
  2689. template<typename ArgT> struct MatchAllOf;
  2690. template<typename ArgT> struct MatchAnyOf;
  2691. template<typename ArgT> struct MatchNotOf;
  2692. class MatcherUntypedBase {
  2693. public:
  2694. MatcherUntypedBase() = default;
  2695. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2696. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2697. std::string toString() const;
  2698. protected:
  2699. virtual ~MatcherUntypedBase();
  2700. virtual std::string describe() const = 0;
  2701. mutable std::string m_cachedToString;
  2702. };
  2703. #ifdef __clang__
  2704. # pragma clang diagnostic push
  2705. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2706. #endif
  2707. template<typename ObjectT>
  2708. struct MatcherMethod {
  2709. virtual bool match( ObjectT const& arg ) const = 0;
  2710. };
  2711. #if defined(__OBJC__)
  2712. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2713. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2714. template<>
  2715. struct MatcherMethod<NSString*> {
  2716. virtual bool match( NSString* arg ) const = 0;
  2717. };
  2718. #endif
  2719. #ifdef __clang__
  2720. # pragma clang diagnostic pop
  2721. #endif
  2722. template<typename T>
  2723. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2724. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2725. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2726. MatchNotOf<T> operator ! () const;
  2727. };
  2728. template<typename ArgT>
  2729. struct MatchAllOf : MatcherBase<ArgT> {
  2730. bool match( ArgT const& arg ) const override {
  2731. for( auto matcher : m_matchers ) {
  2732. if (!matcher->match(arg))
  2733. return false;
  2734. }
  2735. return true;
  2736. }
  2737. std::string describe() const override {
  2738. std::string description;
  2739. description.reserve( 4 + m_matchers.size()*32 );
  2740. description += "( ";
  2741. bool first = true;
  2742. for( auto matcher : m_matchers ) {
  2743. if( first )
  2744. first = false;
  2745. else
  2746. description += " and ";
  2747. description += matcher->toString();
  2748. }
  2749. description += " )";
  2750. return description;
  2751. }
  2752. MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
  2753. auto copy(*this);
  2754. copy.m_matchers.push_back( &other );
  2755. return copy;
  2756. }
  2757. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2758. };
  2759. template<typename ArgT>
  2760. struct MatchAnyOf : MatcherBase<ArgT> {
  2761. bool match( ArgT const& arg ) const override {
  2762. for( auto matcher : m_matchers ) {
  2763. if (matcher->match(arg))
  2764. return true;
  2765. }
  2766. return false;
  2767. }
  2768. std::string describe() const override {
  2769. std::string description;
  2770. description.reserve( 4 + m_matchers.size()*32 );
  2771. description += "( ";
  2772. bool first = true;
  2773. for( auto matcher : m_matchers ) {
  2774. if( first )
  2775. first = false;
  2776. else
  2777. description += " or ";
  2778. description += matcher->toString();
  2779. }
  2780. description += " )";
  2781. return description;
  2782. }
  2783. MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
  2784. auto copy(*this);
  2785. copy.m_matchers.push_back( &other );
  2786. return copy;
  2787. }
  2788. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2789. };
  2790. template<typename ArgT>
  2791. struct MatchNotOf : MatcherBase<ArgT> {
  2792. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2793. bool match( ArgT const& arg ) const override {
  2794. return !m_underlyingMatcher.match( arg );
  2795. }
  2796. std::string describe() const override {
  2797. return "not " + m_underlyingMatcher.toString();
  2798. }
  2799. MatcherBase<ArgT> const& m_underlyingMatcher;
  2800. };
  2801. template<typename T>
  2802. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2803. return MatchAllOf<T>() && *this && other;
  2804. }
  2805. template<typename T>
  2806. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2807. return MatchAnyOf<T>() || *this || other;
  2808. }
  2809. template<typename T>
  2810. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2811. return MatchNotOf<T>( *this );
  2812. }
  2813. } // namespace Impl
  2814. } // namespace Matchers
  2815. using namespace Matchers;
  2816. using Matchers::Impl::MatcherBase;
  2817. } // namespace Catch
  2818. // end catch_matchers.h
  2819. // start catch_matchers_exception.hpp
  2820. namespace Catch {
  2821. namespace Matchers {
  2822. namespace Exception {
  2823. class ExceptionMessageMatcher : public MatcherBase<std::exception> {
  2824. std::string m_message;
  2825. public:
  2826. ExceptionMessageMatcher(std::string const& message):
  2827. m_message(message)
  2828. {}
  2829. bool match(std::exception const& ex) const override;
  2830. std::string describe() const override;
  2831. };
  2832. } // namespace Exception
  2833. Exception::ExceptionMessageMatcher Message(std::string const& message);
  2834. } // namespace Matchers
  2835. } // namespace Catch
  2836. // end catch_matchers_exception.hpp
  2837. // start catch_matchers_floating.h
  2838. namespace Catch {
  2839. namespace Matchers {
  2840. namespace Floating {
  2841. enum class FloatingPointKind : uint8_t;
  2842. struct WithinAbsMatcher : MatcherBase<double> {
  2843. WithinAbsMatcher(double target, double margin);
  2844. bool match(double const& matchee) const override;
  2845. std::string describe() const override;
  2846. private:
  2847. double m_target;
  2848. double m_margin;
  2849. };
  2850. struct WithinUlpsMatcher : MatcherBase<double> {
  2851. WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
  2852. bool match(double const& matchee) const override;
  2853. std::string describe() const override;
  2854. private:
  2855. double m_target;
  2856. uint64_t m_ulps;
  2857. FloatingPointKind m_type;
  2858. };
  2859. // Given IEEE-754 format for floats and doubles, we can assume
  2860. // that float -> double promotion is lossless. Given this, we can
  2861. // assume that if we do the standard relative comparison of
  2862. // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
  2863. // the same result if we do this for floats, as if we do this for
  2864. // doubles that were promoted from floats.
  2865. struct WithinRelMatcher : MatcherBase<double> {
  2866. WithinRelMatcher(double target, double epsilon);
  2867. bool match(double const& matchee) const override;
  2868. std::string describe() const override;
  2869. private:
  2870. double m_target;
  2871. double m_epsilon;
  2872. };
  2873. } // namespace Floating
  2874. // The following functions create the actual matcher objects.
  2875. // This allows the types to be inferred
  2876. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
  2877. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
  2878. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2879. Floating::WithinRelMatcher WithinRel(double target, double eps);
  2880. // defaults epsilon to 100*numeric_limits<double>::epsilon()
  2881. Floating::WithinRelMatcher WithinRel(double target);
  2882. Floating::WithinRelMatcher WithinRel(float target, float eps);
  2883. // defaults epsilon to 100*numeric_limits<float>::epsilon()
  2884. Floating::WithinRelMatcher WithinRel(float target);
  2885. } // namespace Matchers
  2886. } // namespace Catch
  2887. // end catch_matchers_floating.h
  2888. // start catch_matchers_generic.hpp
  2889. #include <functional>
  2890. #include <string>
  2891. namespace Catch {
  2892. namespace Matchers {
  2893. namespace Generic {
  2894. namespace Detail {
  2895. std::string finalizeDescription(const std::string& desc);
  2896. }
  2897. template <typename T>
  2898. class PredicateMatcher : public MatcherBase<T> {
  2899. std::function<bool(T const&)> m_predicate;
  2900. std::string m_description;
  2901. public:
  2902. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2903. :m_predicate(std::move(elem)),
  2904. m_description(Detail::finalizeDescription(descr))
  2905. {}
  2906. bool match( T const& item ) const override {
  2907. return m_predicate(item);
  2908. }
  2909. std::string describe() const override {
  2910. return m_description;
  2911. }
  2912. };
  2913. } // namespace Generic
  2914. // The following functions create the actual matcher objects.
  2915. // The user has to explicitly specify type to the function, because
  2916. // inferring std::function<bool(T const&)> is hard (but possible) and
  2917. // requires a lot of TMP.
  2918. template<typename T>
  2919. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2920. return Generic::PredicateMatcher<T>(predicate, description);
  2921. }
  2922. } // namespace Matchers
  2923. } // namespace Catch
  2924. // end catch_matchers_generic.hpp
  2925. // start catch_matchers_string.h
  2926. #include <string>
  2927. namespace Catch {
  2928. namespace Matchers {
  2929. namespace StdString {
  2930. struct CasedString
  2931. {
  2932. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2933. std::string adjustString( std::string const& str ) const;
  2934. std::string caseSensitivitySuffix() const;
  2935. CaseSensitive::Choice m_caseSensitivity;
  2936. std::string m_str;
  2937. };
  2938. struct StringMatcherBase : MatcherBase<std::string> {
  2939. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2940. std::string describe() const override;
  2941. CasedString m_comparator;
  2942. std::string m_operation;
  2943. };
  2944. struct EqualsMatcher : StringMatcherBase {
  2945. EqualsMatcher( CasedString const& comparator );
  2946. bool match( std::string const& source ) const override;
  2947. };
  2948. struct ContainsMatcher : StringMatcherBase {
  2949. ContainsMatcher( CasedString const& comparator );
  2950. bool match( std::string const& source ) const override;
  2951. };
  2952. struct StartsWithMatcher : StringMatcherBase {
  2953. StartsWithMatcher( CasedString const& comparator );
  2954. bool match( std::string const& source ) const override;
  2955. };
  2956. struct EndsWithMatcher : StringMatcherBase {
  2957. EndsWithMatcher( CasedString const& comparator );
  2958. bool match( std::string const& source ) const override;
  2959. };
  2960. struct RegexMatcher : MatcherBase<std::string> {
  2961. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2962. bool match( std::string const& matchee ) const override;
  2963. std::string describe() const override;
  2964. private:
  2965. std::string m_regex;
  2966. CaseSensitive::Choice m_caseSensitivity;
  2967. };
  2968. } // namespace StdString
  2969. // The following functions create the actual matcher objects.
  2970. // This allows the types to be inferred
  2971. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2972. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2973. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2974. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2975. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2976. } // namespace Matchers
  2977. } // namespace Catch
  2978. // end catch_matchers_string.h
  2979. // start catch_matchers_vector.h
  2980. #include <algorithm>
  2981. namespace Catch {
  2982. namespace Matchers {
  2983. namespace Vector {
  2984. template<typename T, typename Alloc>
  2985. struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
  2986. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2987. bool match(std::vector<T, Alloc> const &v) const override {
  2988. for (auto const& el : v) {
  2989. if (el == m_comparator) {
  2990. return true;
  2991. }
  2992. }
  2993. return false;
  2994. }
  2995. std::string describe() const override {
  2996. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2997. }
  2998. T const& m_comparator;
  2999. };
  3000. template<typename T, typename AllocComp, typename AllocMatch>
  3001. struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3002. ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3003. bool match(std::vector<T, AllocMatch> const &v) const override {
  3004. // !TBD: see note in EqualsMatcher
  3005. if (m_comparator.size() > v.size())
  3006. return false;
  3007. for (auto const& comparator : m_comparator) {
  3008. auto present = false;
  3009. for (const auto& el : v) {
  3010. if (el == comparator) {
  3011. present = true;
  3012. break;
  3013. }
  3014. }
  3015. if (!present) {
  3016. return false;
  3017. }
  3018. }
  3019. return true;
  3020. }
  3021. std::string describe() const override {
  3022. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  3023. }
  3024. std::vector<T, AllocComp> const& m_comparator;
  3025. };
  3026. template<typename T, typename AllocComp, typename AllocMatch>
  3027. struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3028. EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3029. bool match(std::vector<T, AllocMatch> const &v) const override {
  3030. // !TBD: This currently works if all elements can be compared using !=
  3031. // - a more general approach would be via a compare template that defaults
  3032. // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
  3033. // - then just call that directly
  3034. if (m_comparator.size() != v.size())
  3035. return false;
  3036. for (std::size_t i = 0; i < v.size(); ++i)
  3037. if (m_comparator[i] != v[i])
  3038. return false;
  3039. return true;
  3040. }
  3041. std::string describe() const override {
  3042. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  3043. }
  3044. std::vector<T, AllocComp> const& m_comparator;
  3045. };
  3046. template<typename T, typename AllocComp, typename AllocMatch>
  3047. struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3048. ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
  3049. bool match(std::vector<T, AllocMatch> const &v) const override {
  3050. if (m_comparator.size() != v.size())
  3051. return false;
  3052. for (std::size_t i = 0; i < v.size(); ++i)
  3053. if (m_comparator[i] != approx(v[i]))
  3054. return false;
  3055. return true;
  3056. }
  3057. std::string describe() const override {
  3058. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  3059. }
  3060. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3061. ApproxMatcher& epsilon( T const& newEpsilon ) {
  3062. approx.epsilon(newEpsilon);
  3063. return *this;
  3064. }
  3065. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3066. ApproxMatcher& margin( T const& newMargin ) {
  3067. approx.margin(newMargin);
  3068. return *this;
  3069. }
  3070. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3071. ApproxMatcher& scale( T const& newScale ) {
  3072. approx.scale(newScale);
  3073. return *this;
  3074. }
  3075. std::vector<T, AllocComp> const& m_comparator;
  3076. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  3077. };
  3078. template<typename T, typename AllocComp, typename AllocMatch>
  3079. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3080. UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
  3081. bool match(std::vector<T, AllocMatch> const& vec) const override {
  3082. if (m_target.size() != vec.size()) {
  3083. return false;
  3084. }
  3085. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  3086. }
  3087. std::string describe() const override {
  3088. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3089. }
  3090. private:
  3091. std::vector<T, AllocComp> const& m_target;
  3092. };
  3093. } // namespace Vector
  3094. // The following functions create the actual matcher objects.
  3095. // This allows the types to be inferred
  3096. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3097. Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
  3098. return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
  3099. }
  3100. template<typename T, typename Alloc = std::allocator<T>>
  3101. Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
  3102. return Vector::ContainsElementMatcher<T, Alloc>( comparator );
  3103. }
  3104. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3105. Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
  3106. return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
  3107. }
  3108. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3109. Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
  3110. return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
  3111. }
  3112. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3113. Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
  3114. return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
  3115. }
  3116. } // namespace Matchers
  3117. } // namespace Catch
  3118. // end catch_matchers_vector.h
  3119. namespace Catch {
  3120. template<typename ArgT, typename MatcherT>
  3121. class MatchExpr : public ITransientExpression {
  3122. ArgT const& m_arg;
  3123. MatcherT m_matcher;
  3124. StringRef m_matcherString;
  3125. public:
  3126. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3127. : ITransientExpression{ true, matcher.match( arg ) },
  3128. m_arg( arg ),
  3129. m_matcher( matcher ),
  3130. m_matcherString( matcherString )
  3131. {}
  3132. void streamReconstructedExpression( std::ostream &os ) const override {
  3133. auto matcherAsString = m_matcher.toString();
  3134. os << Catch::Detail::stringify( m_arg ) << ' ';
  3135. if( matcherAsString == Detail::unprintableString )
  3136. os << m_matcherString;
  3137. else
  3138. os << matcherAsString;
  3139. }
  3140. };
  3141. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3142. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3143. template<typename ArgT, typename MatcherT>
  3144. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3145. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3146. }
  3147. } // namespace Catch
  3148. ///////////////////////////////////////////////////////////////////////////////
  3149. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3150. do { \
  3151. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3152. INTERNAL_CATCH_TRY { \
  3153. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3154. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3155. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3156. } while( false )
  3157. ///////////////////////////////////////////////////////////////////////////////
  3158. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3159. do { \
  3160. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3161. if( catchAssertionHandler.allowThrows() ) \
  3162. try { \
  3163. static_cast<void>(__VA_ARGS__ ); \
  3164. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3165. } \
  3166. catch( exceptionType const& ex ) { \
  3167. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3168. } \
  3169. catch( ... ) { \
  3170. catchAssertionHandler.handleUnexpectedInflightException(); \
  3171. } \
  3172. else \
  3173. catchAssertionHandler.handleThrowingCallSkipped(); \
  3174. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3175. } while( false )
  3176. // end catch_capture_matchers.h
  3177. #endif
  3178. // start catch_generators.hpp
  3179. // start catch_interfaces_generatortracker.h
  3180. #include <memory>
  3181. namespace Catch {
  3182. namespace Generators {
  3183. class GeneratorUntypedBase {
  3184. public:
  3185. GeneratorUntypedBase() = default;
  3186. virtual ~GeneratorUntypedBase();
  3187. // Attempts to move the generator to the next element
  3188. //
  3189. // Returns true iff the move succeeded (and a valid element
  3190. // can be retrieved).
  3191. virtual bool next() = 0;
  3192. };
  3193. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3194. } // namespace Generators
  3195. struct IGeneratorTracker {
  3196. virtual ~IGeneratorTracker();
  3197. virtual auto hasGenerator() const -> bool = 0;
  3198. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3199. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3200. };
  3201. } // namespace Catch
  3202. // end catch_interfaces_generatortracker.h
  3203. // start catch_enforce.h
  3204. #include <exception>
  3205. namespace Catch {
  3206. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3207. template <typename Ex>
  3208. [[noreturn]]
  3209. void throw_exception(Ex const& e) {
  3210. throw e;
  3211. }
  3212. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3213. [[noreturn]]
  3214. void throw_exception(std::exception const& e);
  3215. #endif
  3216. [[noreturn]]
  3217. void throw_logic_error(std::string const& msg);
  3218. [[noreturn]]
  3219. void throw_domain_error(std::string const& msg);
  3220. [[noreturn]]
  3221. void throw_runtime_error(std::string const& msg);
  3222. } // namespace Catch;
  3223. #define CATCH_MAKE_MSG(...) \
  3224. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3225. #define CATCH_INTERNAL_ERROR(...) \
  3226. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
  3227. #define CATCH_ERROR(...) \
  3228. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3229. #define CATCH_RUNTIME_ERROR(...) \
  3230. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3231. #define CATCH_ENFORCE( condition, ... ) \
  3232. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3233. // end catch_enforce.h
  3234. #include <memory>
  3235. #include <vector>
  3236. #include <cassert>
  3237. #include <utility>
  3238. #include <exception>
  3239. namespace Catch {
  3240. class GeneratorException : public std::exception {
  3241. const char* const m_msg = "";
  3242. public:
  3243. GeneratorException(const char* msg):
  3244. m_msg(msg)
  3245. {}
  3246. const char* what() const noexcept override final;
  3247. };
  3248. namespace Generators {
  3249. // !TBD move this into its own location?
  3250. namespace pf{
  3251. template<typename T, typename... Args>
  3252. std::unique_ptr<T> make_unique( Args&&... args ) {
  3253. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3254. }
  3255. }
  3256. template<typename T>
  3257. struct IGenerator : GeneratorUntypedBase {
  3258. virtual ~IGenerator() = default;
  3259. // Returns the current element of the generator
  3260. //
  3261. // \Precondition The generator is either freshly constructed,
  3262. // or the last call to `next()` returned true
  3263. virtual T const& get() const = 0;
  3264. using type = T;
  3265. };
  3266. template<typename T>
  3267. class SingleValueGenerator final : public IGenerator<T> {
  3268. T m_value;
  3269. public:
  3270. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3271. T const& get() const override {
  3272. return m_value;
  3273. }
  3274. bool next() override {
  3275. return false;
  3276. }
  3277. };
  3278. template<typename T>
  3279. class FixedValuesGenerator final : public IGenerator<T> {
  3280. static_assert(!std::is_same<T, bool>::value,
  3281. "FixedValuesGenerator does not support bools because of std::vector<bool>"
  3282. "specialization, use SingleValue Generator instead.");
  3283. std::vector<T> m_values;
  3284. size_t m_idx = 0;
  3285. public:
  3286. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3287. T const& get() const override {
  3288. return m_values[m_idx];
  3289. }
  3290. bool next() override {
  3291. ++m_idx;
  3292. return m_idx < m_values.size();
  3293. }
  3294. };
  3295. template <typename T>
  3296. class GeneratorWrapper final {
  3297. std::unique_ptr<IGenerator<T>> m_generator;
  3298. public:
  3299. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3300. m_generator(std::move(generator))
  3301. {}
  3302. T const& get() const {
  3303. return m_generator->get();
  3304. }
  3305. bool next() {
  3306. return m_generator->next();
  3307. }
  3308. };
  3309. template <typename T>
  3310. GeneratorWrapper<T> value(T&& value) {
  3311. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3312. }
  3313. template <typename T>
  3314. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3315. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3316. }
  3317. template<typename T>
  3318. class Generators : public IGenerator<T> {
  3319. std::vector<GeneratorWrapper<T>> m_generators;
  3320. size_t m_current = 0;
  3321. void populate(GeneratorWrapper<T>&& generator) {
  3322. m_generators.emplace_back(std::move(generator));
  3323. }
  3324. void populate(T&& val) {
  3325. m_generators.emplace_back(value(std::forward<T>(val)));
  3326. }
  3327. template<typename U>
  3328. void populate(U&& val) {
  3329. populate(T(std::forward<U>(val)));
  3330. }
  3331. template<typename U, typename... Gs>
  3332. void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
  3333. populate(std::forward<U>(valueOrGenerator));
  3334. populate(std::forward<Gs>(moreGenerators)...);
  3335. }
  3336. public:
  3337. template <typename... Gs>
  3338. Generators(Gs &&... moreGenerators) {
  3339. m_generators.reserve(sizeof...(Gs));
  3340. populate(std::forward<Gs>(moreGenerators)...);
  3341. }
  3342. T const& get() const override {
  3343. return m_generators[m_current].get();
  3344. }
  3345. bool next() override {
  3346. if (m_current >= m_generators.size()) {
  3347. return false;
  3348. }
  3349. const bool current_status = m_generators[m_current].next();
  3350. if (!current_status) {
  3351. ++m_current;
  3352. }
  3353. return m_current < m_generators.size();
  3354. }
  3355. };
  3356. template<typename... Ts>
  3357. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3358. return values<std::tuple<Ts...>>( tuples );
  3359. }
  3360. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3361. template <typename T>
  3362. struct as {};
  3363. template<typename T, typename... Gs>
  3364. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
  3365. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3366. }
  3367. template<typename T>
  3368. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3369. return Generators<T>(std::move(generator));
  3370. }
  3371. template<typename T, typename... Gs>
  3372. auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3373. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3374. }
  3375. template<typename T, typename U, typename... Gs>
  3376. auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3377. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3378. }
  3379. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3380. template<typename L>
  3381. // Note: The type after -> is weird, because VS2015 cannot parse
  3382. // the expression used in the typedef inside, when it is in
  3383. // return type. Yeah.
  3384. auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3385. using UnderlyingType = typename decltype(generatorExpression())::type;
  3386. IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
  3387. if (!tracker.hasGenerator()) {
  3388. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3389. }
  3390. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3391. return generator.get();
  3392. }
  3393. } // namespace Generators
  3394. } // namespace Catch
  3395. #define GENERATE( ... ) \
  3396. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3397. CATCH_INTERNAL_LINEINFO, \
  3398. [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3399. #define GENERATE_COPY( ... ) \
  3400. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3401. CATCH_INTERNAL_LINEINFO, \
  3402. [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3403. #define GENERATE_REF( ... ) \
  3404. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3405. CATCH_INTERNAL_LINEINFO, \
  3406. [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3407. // end catch_generators.hpp
  3408. // start catch_generators_generic.hpp
  3409. namespace Catch {
  3410. namespace Generators {
  3411. template <typename T>
  3412. class TakeGenerator : public IGenerator<T> {
  3413. GeneratorWrapper<T> m_generator;
  3414. size_t m_returned = 0;
  3415. size_t m_target;
  3416. public:
  3417. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3418. m_generator(std::move(generator)),
  3419. m_target(target)
  3420. {
  3421. assert(target != 0 && "Empty generators are not allowed");
  3422. }
  3423. T const& get() const override {
  3424. return m_generator.get();
  3425. }
  3426. bool next() override {
  3427. ++m_returned;
  3428. if (m_returned >= m_target) {
  3429. return false;
  3430. }
  3431. const auto success = m_generator.next();
  3432. // If the underlying generator does not contain enough values
  3433. // then we cut short as well
  3434. if (!success) {
  3435. m_returned = m_target;
  3436. }
  3437. return success;
  3438. }
  3439. };
  3440. template <typename T>
  3441. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3442. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3443. }
  3444. template <typename T, typename Predicate>
  3445. class FilterGenerator : public IGenerator<T> {
  3446. GeneratorWrapper<T> m_generator;
  3447. Predicate m_predicate;
  3448. public:
  3449. template <typename P = Predicate>
  3450. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3451. m_generator(std::move(generator)),
  3452. m_predicate(std::forward<P>(pred))
  3453. {
  3454. if (!m_predicate(m_generator.get())) {
  3455. // It might happen that there are no values that pass the
  3456. // filter. In that case we throw an exception.
  3457. auto has_initial_value = next();
  3458. if (!has_initial_value) {
  3459. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3460. }
  3461. }
  3462. }
  3463. T const& get() const override {
  3464. return m_generator.get();
  3465. }
  3466. bool next() override {
  3467. bool success = m_generator.next();
  3468. if (!success) {
  3469. return false;
  3470. }
  3471. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3472. return success;
  3473. }
  3474. };
  3475. template <typename T, typename Predicate>
  3476. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3477. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3478. }
  3479. template <typename T>
  3480. class RepeatGenerator : public IGenerator<T> {
  3481. static_assert(!std::is_same<T, bool>::value,
  3482. "RepeatGenerator currently does not support bools"
  3483. "because of std::vector<bool> specialization");
  3484. GeneratorWrapper<T> m_generator;
  3485. mutable std::vector<T> m_returned;
  3486. size_t m_target_repeats;
  3487. size_t m_current_repeat = 0;
  3488. size_t m_repeat_index = 0;
  3489. public:
  3490. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3491. m_generator(std::move(generator)),
  3492. m_target_repeats(repeats)
  3493. {
  3494. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3495. }
  3496. T const& get() const override {
  3497. if (m_current_repeat == 0) {
  3498. m_returned.push_back(m_generator.get());
  3499. return m_returned.back();
  3500. }
  3501. return m_returned[m_repeat_index];
  3502. }
  3503. bool next() override {
  3504. // There are 2 basic cases:
  3505. // 1) We are still reading the generator
  3506. // 2) We are reading our own cache
  3507. // In the first case, we need to poke the underlying generator.
  3508. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3509. if (m_current_repeat == 0) {
  3510. const auto success = m_generator.next();
  3511. if (!success) {
  3512. ++m_current_repeat;
  3513. }
  3514. return m_current_repeat < m_target_repeats;
  3515. }
  3516. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3517. ++m_repeat_index;
  3518. if (m_repeat_index == m_returned.size()) {
  3519. m_repeat_index = 0;
  3520. ++m_current_repeat;
  3521. }
  3522. return m_current_repeat < m_target_repeats;
  3523. }
  3524. };
  3525. template <typename T>
  3526. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3527. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3528. }
  3529. template <typename T, typename U, typename Func>
  3530. class MapGenerator : public IGenerator<T> {
  3531. // TBD: provide static assert for mapping function, for friendly error message
  3532. GeneratorWrapper<U> m_generator;
  3533. Func m_function;
  3534. // To avoid returning dangling reference, we have to save the values
  3535. T m_cache;
  3536. public:
  3537. template <typename F2 = Func>
  3538. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3539. m_generator(std::move(generator)),
  3540. m_function(std::forward<F2>(function)),
  3541. m_cache(m_function(m_generator.get()))
  3542. {}
  3543. T const& get() const override {
  3544. return m_cache;
  3545. }
  3546. bool next() override {
  3547. const auto success = m_generator.next();
  3548. if (success) {
  3549. m_cache = m_function(m_generator.get());
  3550. }
  3551. return success;
  3552. }
  3553. };
  3554. template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
  3555. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3556. return GeneratorWrapper<T>(
  3557. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3558. );
  3559. }
  3560. template <typename T, typename U, typename Func>
  3561. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3562. return GeneratorWrapper<T>(
  3563. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3564. );
  3565. }
  3566. template <typename T>
  3567. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3568. std::vector<T> m_chunk;
  3569. size_t m_chunk_size;
  3570. GeneratorWrapper<T> m_generator;
  3571. bool m_used_up = false;
  3572. public:
  3573. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3574. m_chunk_size(size), m_generator(std::move(generator))
  3575. {
  3576. m_chunk.reserve(m_chunk_size);
  3577. if (m_chunk_size != 0) {
  3578. m_chunk.push_back(m_generator.get());
  3579. for (size_t i = 1; i < m_chunk_size; ++i) {
  3580. if (!m_generator.next()) {
  3581. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3582. }
  3583. m_chunk.push_back(m_generator.get());
  3584. }
  3585. }
  3586. }
  3587. std::vector<T> const& get() const override {
  3588. return m_chunk;
  3589. }
  3590. bool next() override {
  3591. m_chunk.clear();
  3592. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3593. if (!m_generator.next()) {
  3594. return false;
  3595. }
  3596. m_chunk.push_back(m_generator.get());
  3597. }
  3598. return true;
  3599. }
  3600. };
  3601. template <typename T>
  3602. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3603. return GeneratorWrapper<std::vector<T>>(
  3604. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3605. );
  3606. }
  3607. } // namespace Generators
  3608. } // namespace Catch
  3609. // end catch_generators_generic.hpp
  3610. // start catch_generators_specific.hpp
  3611. // start catch_context.h
  3612. #include <memory>
  3613. namespace Catch {
  3614. struct IResultCapture;
  3615. struct IRunner;
  3616. struct IConfig;
  3617. struct IMutableContext;
  3618. using IConfigPtr = std::shared_ptr<IConfig const>;
  3619. struct IContext
  3620. {
  3621. virtual ~IContext();
  3622. virtual IResultCapture* getResultCapture() = 0;
  3623. virtual IRunner* getRunner() = 0;
  3624. virtual IConfigPtr const& getConfig() const = 0;
  3625. };
  3626. struct IMutableContext : IContext
  3627. {
  3628. virtual ~IMutableContext();
  3629. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3630. virtual void setRunner( IRunner* runner ) = 0;
  3631. virtual void setConfig( IConfigPtr const& config ) = 0;
  3632. private:
  3633. static IMutableContext *currentContext;
  3634. friend IMutableContext& getCurrentMutableContext();
  3635. friend void cleanUpContext();
  3636. static void createContext();
  3637. };
  3638. inline IMutableContext& getCurrentMutableContext()
  3639. {
  3640. if( !IMutableContext::currentContext )
  3641. IMutableContext::createContext();
  3642. // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
  3643. return *IMutableContext::currentContext;
  3644. }
  3645. inline IContext& getCurrentContext()
  3646. {
  3647. return getCurrentMutableContext();
  3648. }
  3649. void cleanUpContext();
  3650. class SimplePcg32;
  3651. SimplePcg32& rng();
  3652. }
  3653. // end catch_context.h
  3654. // start catch_interfaces_config.h
  3655. // start catch_option.hpp
  3656. namespace Catch {
  3657. // An optional type
  3658. template<typename T>
  3659. class Option {
  3660. public:
  3661. Option() : nullableValue( nullptr ) {}
  3662. Option( T const& _value )
  3663. : nullableValue( new( storage ) T( _value ) )
  3664. {}
  3665. Option( Option const& _other )
  3666. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3667. {}
  3668. ~Option() {
  3669. reset();
  3670. }
  3671. Option& operator= ( Option const& _other ) {
  3672. if( &_other != this ) {
  3673. reset();
  3674. if( _other )
  3675. nullableValue = new( storage ) T( *_other );
  3676. }
  3677. return *this;
  3678. }
  3679. Option& operator = ( T const& _value ) {
  3680. reset();
  3681. nullableValue = new( storage ) T( _value );
  3682. return *this;
  3683. }
  3684. void reset() {
  3685. if( nullableValue )
  3686. nullableValue->~T();
  3687. nullableValue = nullptr;
  3688. }
  3689. T& operator*() { return *nullableValue; }
  3690. T const& operator*() const { return *nullableValue; }
  3691. T* operator->() { return nullableValue; }
  3692. const T* operator->() const { return nullableValue; }
  3693. T valueOr( T const& defaultValue ) const {
  3694. return nullableValue ? *nullableValue : defaultValue;
  3695. }
  3696. bool some() const { return nullableValue != nullptr; }
  3697. bool none() const { return nullableValue == nullptr; }
  3698. bool operator !() const { return nullableValue == nullptr; }
  3699. explicit operator bool() const {
  3700. return some();
  3701. }
  3702. private:
  3703. T *nullableValue;
  3704. alignas(alignof(T)) char storage[sizeof(T)];
  3705. };
  3706. } // end namespace Catch
  3707. // end catch_option.hpp
  3708. #include <chrono>
  3709. #include <iosfwd>
  3710. #include <string>
  3711. #include <vector>
  3712. #include <memory>
  3713. namespace Catch {
  3714. enum class Verbosity {
  3715. Quiet = 0,
  3716. Normal,
  3717. High
  3718. };
  3719. struct WarnAbout { enum What {
  3720. Nothing = 0x00,
  3721. NoAssertions = 0x01,
  3722. NoTests = 0x02
  3723. }; };
  3724. struct ShowDurations { enum OrNot {
  3725. DefaultForReporter,
  3726. Always,
  3727. Never
  3728. }; };
  3729. struct RunTests { enum InWhatOrder {
  3730. InDeclarationOrder,
  3731. InLexicographicalOrder,
  3732. InRandomOrder
  3733. }; };
  3734. struct UseColour { enum YesOrNo {
  3735. Auto,
  3736. Yes,
  3737. No
  3738. }; };
  3739. struct WaitForKeypress { enum When {
  3740. Never,
  3741. BeforeStart = 1,
  3742. BeforeExit = 2,
  3743. BeforeStartAndExit = BeforeStart | BeforeExit
  3744. }; };
  3745. class TestSpec;
  3746. struct IConfig : NonCopyable {
  3747. virtual ~IConfig();
  3748. virtual bool allowThrows() const = 0;
  3749. virtual std::ostream& stream() const = 0;
  3750. virtual std::string name() const = 0;
  3751. virtual bool includeSuccessfulResults() const = 0;
  3752. virtual bool shouldDebugBreak() const = 0;
  3753. virtual bool warnAboutMissingAssertions() const = 0;
  3754. virtual bool warnAboutNoTests() const = 0;
  3755. virtual int abortAfter() const = 0;
  3756. virtual bool showInvisibles() const = 0;
  3757. virtual ShowDurations::OrNot showDurations() const = 0;
  3758. virtual double minDuration() const = 0;
  3759. virtual TestSpec const& testSpec() const = 0;
  3760. virtual bool hasTestFilters() const = 0;
  3761. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3762. virtual RunTests::InWhatOrder runOrder() const = 0;
  3763. virtual unsigned int rngSeed() const = 0;
  3764. virtual UseColour::YesOrNo useColour() const = 0;
  3765. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3766. virtual Verbosity verbosity() const = 0;
  3767. virtual bool benchmarkNoAnalysis() const = 0;
  3768. virtual int benchmarkSamples() const = 0;
  3769. virtual double benchmarkConfidenceInterval() const = 0;
  3770. virtual unsigned int benchmarkResamples() const = 0;
  3771. virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
  3772. };
  3773. using IConfigPtr = std::shared_ptr<IConfig const>;
  3774. }
  3775. // end catch_interfaces_config.h
  3776. // start catch_random_number_generator.h
  3777. #include <cstdint>
  3778. namespace Catch {
  3779. // This is a simple implementation of C++11 Uniform Random Number
  3780. // Generator. It does not provide all operators, because Catch2
  3781. // does not use it, but it should behave as expected inside stdlib's
  3782. // distributions.
  3783. // The implementation is based on the PCG family (http://pcg-random.org)
  3784. class SimplePcg32 {
  3785. using state_type = std::uint64_t;
  3786. public:
  3787. using result_type = std::uint32_t;
  3788. static constexpr result_type (min)() {
  3789. return 0;
  3790. }
  3791. static constexpr result_type (max)() {
  3792. return static_cast<result_type>(-1);
  3793. }
  3794. // Provide some default initial state for the default constructor
  3795. SimplePcg32():SimplePcg32(0xed743cc4U) {}
  3796. explicit SimplePcg32(result_type seed_);
  3797. void seed(result_type seed_);
  3798. void discard(uint64_t skip);
  3799. result_type operator()();
  3800. private:
  3801. friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3802. friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3803. // In theory we also need operator<< and operator>>
  3804. // In practice we do not use them, so we will skip them for now
  3805. std::uint64_t m_state;
  3806. // This part of the state determines which "stream" of the numbers
  3807. // is chosen -- we take it as a constant for Catch2, so we only
  3808. // need to deal with seeding the main state.
  3809. // Picked by reading 8 bytes from `/dev/random` :-)
  3810. static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
  3811. };
  3812. } // end namespace Catch
  3813. // end catch_random_number_generator.h
  3814. #include <random>
  3815. namespace Catch {
  3816. namespace Generators {
  3817. template <typename Float>
  3818. class RandomFloatingGenerator final : public IGenerator<Float> {
  3819. Catch::SimplePcg32& m_rng;
  3820. std::uniform_real_distribution<Float> m_dist;
  3821. Float m_current_number;
  3822. public:
  3823. RandomFloatingGenerator(Float a, Float b):
  3824. m_rng(rng()),
  3825. m_dist(a, b) {
  3826. static_cast<void>(next());
  3827. }
  3828. Float const& get() const override {
  3829. return m_current_number;
  3830. }
  3831. bool next() override {
  3832. m_current_number = m_dist(m_rng);
  3833. return true;
  3834. }
  3835. };
  3836. template <typename Integer>
  3837. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3838. Catch::SimplePcg32& m_rng;
  3839. std::uniform_int_distribution<Integer> m_dist;
  3840. Integer m_current_number;
  3841. public:
  3842. RandomIntegerGenerator(Integer a, Integer b):
  3843. m_rng(rng()),
  3844. m_dist(a, b) {
  3845. static_cast<void>(next());
  3846. }
  3847. Integer const& get() const override {
  3848. return m_current_number;
  3849. }
  3850. bool next() override {
  3851. m_current_number = m_dist(m_rng);
  3852. return true;
  3853. }
  3854. };
  3855. // TODO: Ideally this would be also constrained against the various char types,
  3856. // but I don't expect users to run into that in practice.
  3857. template <typename T>
  3858. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3859. GeneratorWrapper<T>>::type
  3860. random(T a, T b) {
  3861. return GeneratorWrapper<T>(
  3862. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3863. );
  3864. }
  3865. template <typename T>
  3866. typename std::enable_if<std::is_floating_point<T>::value,
  3867. GeneratorWrapper<T>>::type
  3868. random(T a, T b) {
  3869. return GeneratorWrapper<T>(
  3870. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3871. );
  3872. }
  3873. template <typename T>
  3874. class RangeGenerator final : public IGenerator<T> {
  3875. T m_current;
  3876. T m_end;
  3877. T m_step;
  3878. bool m_positive;
  3879. public:
  3880. RangeGenerator(T const& start, T const& end, T const& step):
  3881. m_current(start),
  3882. m_end(end),
  3883. m_step(step),
  3884. m_positive(m_step > T(0))
  3885. {
  3886. assert(m_current != m_end && "Range start and end cannot be equal");
  3887. assert(m_step != T(0) && "Step size cannot be zero");
  3888. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3889. }
  3890. RangeGenerator(T const& start, T const& end):
  3891. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3892. {}
  3893. T const& get() const override {
  3894. return m_current;
  3895. }
  3896. bool next() override {
  3897. m_current += m_step;
  3898. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3899. }
  3900. };
  3901. template <typename T>
  3902. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3903. static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
  3904. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3905. }
  3906. template <typename T>
  3907. GeneratorWrapper<T> range(T const& start, T const& end) {
  3908. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3909. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3910. }
  3911. template <typename T>
  3912. class IteratorGenerator final : public IGenerator<T> {
  3913. static_assert(!std::is_same<T, bool>::value,
  3914. "IteratorGenerator currently does not support bools"
  3915. "because of std::vector<bool> specialization");
  3916. std::vector<T> m_elems;
  3917. size_t m_current = 0;
  3918. public:
  3919. template <typename InputIterator, typename InputSentinel>
  3920. IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
  3921. if (m_elems.empty()) {
  3922. Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
  3923. }
  3924. }
  3925. T const& get() const override {
  3926. return m_elems[m_current];
  3927. }
  3928. bool next() override {
  3929. ++m_current;
  3930. return m_current != m_elems.size();
  3931. }
  3932. };
  3933. template <typename InputIterator,
  3934. typename InputSentinel,
  3935. typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
  3936. GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
  3937. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
  3938. }
  3939. template <typename Container,
  3940. typename ResultType = typename Container::value_type>
  3941. GeneratorWrapper<ResultType> from_range(Container const& cnt) {
  3942. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
  3943. }
  3944. } // namespace Generators
  3945. } // namespace Catch
  3946. // end catch_generators_specific.hpp
  3947. // These files are included here so the single_include script doesn't put them
  3948. // in the conditionally compiled sections
  3949. // start catch_test_case_info.h
  3950. #include <string>
  3951. #include <vector>
  3952. #include <memory>
  3953. #ifdef __clang__
  3954. #pragma clang diagnostic push
  3955. #pragma clang diagnostic ignored "-Wpadded"
  3956. #endif
  3957. namespace Catch {
  3958. struct ITestInvoker;
  3959. struct TestCaseInfo {
  3960. enum SpecialProperties{
  3961. None = 0,
  3962. IsHidden = 1 << 1,
  3963. ShouldFail = 1 << 2,
  3964. MayFail = 1 << 3,
  3965. Throws = 1 << 4,
  3966. NonPortable = 1 << 5,
  3967. Benchmark = 1 << 6
  3968. };
  3969. TestCaseInfo( std::string const& _name,
  3970. std::string const& _className,
  3971. std::string const& _description,
  3972. std::vector<std::string> const& _tags,
  3973. SourceLineInfo const& _lineInfo );
  3974. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3975. bool isHidden() const;
  3976. bool throws() const;
  3977. bool okToFail() const;
  3978. bool expectedToFail() const;
  3979. std::string tagsAsString() const;
  3980. std::string name;
  3981. std::string className;
  3982. std::string description;
  3983. std::vector<std::string> tags;
  3984. std::vector<std::string> lcaseTags;
  3985. SourceLineInfo lineInfo;
  3986. SpecialProperties properties;
  3987. };
  3988. class TestCase : public TestCaseInfo {
  3989. public:
  3990. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3991. TestCase withName( std::string const& _newName ) const;
  3992. void invoke() const;
  3993. TestCaseInfo const& getTestCaseInfo() const;
  3994. bool operator == ( TestCase const& other ) const;
  3995. bool operator < ( TestCase const& other ) const;
  3996. private:
  3997. std::shared_ptr<ITestInvoker> test;
  3998. };
  3999. TestCase makeTestCase( ITestInvoker* testCase,
  4000. std::string const& className,
  4001. NameAndTags const& nameAndTags,
  4002. SourceLineInfo const& lineInfo );
  4003. }
  4004. #ifdef __clang__
  4005. #pragma clang diagnostic pop
  4006. #endif
  4007. // end catch_test_case_info.h
  4008. // start catch_interfaces_runner.h
  4009. namespace Catch {
  4010. struct IRunner {
  4011. virtual ~IRunner();
  4012. virtual bool aborting() const = 0;
  4013. };
  4014. }
  4015. // end catch_interfaces_runner.h
  4016. #ifdef __OBJC__
  4017. // start catch_objc.hpp
  4018. #import <objc/runtime.h>
  4019. #include <string>
  4020. // NB. Any general catch headers included here must be included
  4021. // in catch.hpp first to make sure they are included by the single
  4022. // header for non obj-usage
  4023. ///////////////////////////////////////////////////////////////////////////////
  4024. // This protocol is really only here for (self) documenting purposes, since
  4025. // all its methods are optional.
  4026. @protocol OcFixture
  4027. @optional
  4028. -(void) setUp;
  4029. -(void) tearDown;
  4030. @end
  4031. namespace Catch {
  4032. class OcMethod : public ITestInvoker {
  4033. public:
  4034. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  4035. virtual void invoke() const {
  4036. id obj = [[m_cls alloc] init];
  4037. performOptionalSelector( obj, @selector(setUp) );
  4038. performOptionalSelector( obj, m_sel );
  4039. performOptionalSelector( obj, @selector(tearDown) );
  4040. arcSafeRelease( obj );
  4041. }
  4042. private:
  4043. virtual ~OcMethod() {}
  4044. Class m_cls;
  4045. SEL m_sel;
  4046. };
  4047. namespace Detail{
  4048. inline std::string getAnnotation( Class cls,
  4049. std::string const& annotationName,
  4050. std::string const& testCaseName ) {
  4051. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  4052. SEL sel = NSSelectorFromString( selStr );
  4053. arcSafeRelease( selStr );
  4054. id value = performOptionalSelector( cls, sel );
  4055. if( value )
  4056. return [(NSString*)value UTF8String];
  4057. return "";
  4058. }
  4059. }
  4060. inline std::size_t registerTestMethods() {
  4061. std::size_t noTestMethods = 0;
  4062. int noClasses = objc_getClassList( nullptr, 0 );
  4063. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  4064. objc_getClassList( classes, noClasses );
  4065. for( int c = 0; c < noClasses; c++ ) {
  4066. Class cls = classes[c];
  4067. {
  4068. u_int count;
  4069. Method* methods = class_copyMethodList( cls, &count );
  4070. for( u_int m = 0; m < count ; m++ ) {
  4071. SEL selector = method_getName(methods[m]);
  4072. std::string methodName = sel_getName(selector);
  4073. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  4074. std::string testCaseName = methodName.substr( 15 );
  4075. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  4076. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  4077. const char* className = class_getName( cls );
  4078. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  4079. noTestMethods++;
  4080. }
  4081. }
  4082. free(methods);
  4083. }
  4084. }
  4085. return noTestMethods;
  4086. }
  4087. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  4088. namespace Matchers {
  4089. namespace Impl {
  4090. namespace NSStringMatchers {
  4091. struct StringHolder : MatcherBase<NSString*>{
  4092. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  4093. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  4094. StringHolder() {
  4095. arcSafeRelease( m_substr );
  4096. }
  4097. bool match( NSString* str ) const override {
  4098. return false;
  4099. }
  4100. NSString* CATCH_ARC_STRONG m_substr;
  4101. };
  4102. struct Equals : StringHolder {
  4103. Equals( NSString* substr ) : StringHolder( substr ){}
  4104. bool match( NSString* str ) const override {
  4105. return (str != nil || m_substr == nil ) &&
  4106. [str isEqualToString:m_substr];
  4107. }
  4108. std::string describe() const override {
  4109. return "equals string: " + Catch::Detail::stringify( m_substr );
  4110. }
  4111. };
  4112. struct Contains : StringHolder {
  4113. Contains( NSString* substr ) : StringHolder( substr ){}
  4114. bool match( NSString* str ) const override {
  4115. return (str != nil || m_substr == nil ) &&
  4116. [str rangeOfString:m_substr].location != NSNotFound;
  4117. }
  4118. std::string describe() const override {
  4119. return "contains string: " + Catch::Detail::stringify( m_substr );
  4120. }
  4121. };
  4122. struct StartsWith : StringHolder {
  4123. StartsWith( NSString* substr ) : StringHolder( substr ){}
  4124. bool match( NSString* str ) const override {
  4125. return (str != nil || m_substr == nil ) &&
  4126. [str rangeOfString:m_substr].location == 0;
  4127. }
  4128. std::string describe() const override {
  4129. return "starts with: " + Catch::Detail::stringify( m_substr );
  4130. }
  4131. };
  4132. struct EndsWith : StringHolder {
  4133. EndsWith( NSString* substr ) : StringHolder( substr ){}
  4134. bool match( NSString* str ) const override {
  4135. return (str != nil || m_substr == nil ) &&
  4136. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  4137. }
  4138. std::string describe() const override {
  4139. return "ends with: " + Catch::Detail::stringify( m_substr );
  4140. }
  4141. };
  4142. } // namespace NSStringMatchers
  4143. } // namespace Impl
  4144. inline Impl::NSStringMatchers::Equals
  4145. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  4146. inline Impl::NSStringMatchers::Contains
  4147. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  4148. inline Impl::NSStringMatchers::StartsWith
  4149. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  4150. inline Impl::NSStringMatchers::EndsWith
  4151. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  4152. } // namespace Matchers
  4153. using namespace Matchers;
  4154. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  4155. } // namespace Catch
  4156. ///////////////////////////////////////////////////////////////////////////////
  4157. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  4158. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  4159. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4160. { \
  4161. return @ name; \
  4162. } \
  4163. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4164. { \
  4165. return @ desc; \
  4166. } \
  4167. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4168. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4169. // end catch_objc.hpp
  4170. #endif
  4171. // Benchmarking needs the externally-facing parts of reporters to work
  4172. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4173. // start catch_external_interfaces.h
  4174. // start catch_reporter_bases.hpp
  4175. // start catch_interfaces_reporter.h
  4176. // start catch_config.hpp
  4177. // start catch_test_spec_parser.h
  4178. #ifdef __clang__
  4179. #pragma clang diagnostic push
  4180. #pragma clang diagnostic ignored "-Wpadded"
  4181. #endif
  4182. // start catch_test_spec.h
  4183. #ifdef __clang__
  4184. #pragma clang diagnostic push
  4185. #pragma clang diagnostic ignored "-Wpadded"
  4186. #endif
  4187. // start catch_wildcard_pattern.h
  4188. namespace Catch
  4189. {
  4190. class WildcardPattern {
  4191. enum WildcardPosition {
  4192. NoWildcard = 0,
  4193. WildcardAtStart = 1,
  4194. WildcardAtEnd = 2,
  4195. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4196. };
  4197. public:
  4198. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4199. virtual ~WildcardPattern() = default;
  4200. virtual bool matches( std::string const& str ) const;
  4201. private:
  4202. std::string normaliseString( std::string const& str ) const;
  4203. CaseSensitive::Choice m_caseSensitivity;
  4204. WildcardPosition m_wildcard = NoWildcard;
  4205. std::string m_pattern;
  4206. };
  4207. }
  4208. // end catch_wildcard_pattern.h
  4209. #include <string>
  4210. #include <vector>
  4211. #include <memory>
  4212. namespace Catch {
  4213. struct IConfig;
  4214. class TestSpec {
  4215. class Pattern {
  4216. public:
  4217. explicit Pattern( std::string const& name );
  4218. virtual ~Pattern();
  4219. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4220. std::string const& name() const;
  4221. private:
  4222. std::string const m_name;
  4223. };
  4224. using PatternPtr = std::shared_ptr<Pattern>;
  4225. class NamePattern : public Pattern {
  4226. public:
  4227. explicit NamePattern( std::string const& name, std::string const& filterString );
  4228. bool matches( TestCaseInfo const& testCase ) const override;
  4229. private:
  4230. WildcardPattern m_wildcardPattern;
  4231. };
  4232. class TagPattern : public Pattern {
  4233. public:
  4234. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4235. bool matches( TestCaseInfo const& testCase ) const override;
  4236. private:
  4237. std::string m_tag;
  4238. };
  4239. class ExcludedPattern : public Pattern {
  4240. public:
  4241. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4242. bool matches( TestCaseInfo const& testCase ) const override;
  4243. private:
  4244. PatternPtr m_underlyingPattern;
  4245. };
  4246. struct Filter {
  4247. std::vector<PatternPtr> m_patterns;
  4248. bool matches( TestCaseInfo const& testCase ) const;
  4249. std::string name() const;
  4250. };
  4251. public:
  4252. struct FilterMatch {
  4253. std::string name;
  4254. std::vector<TestCase const*> tests;
  4255. };
  4256. using Matches = std::vector<FilterMatch>;
  4257. using vectorStrings = std::vector<std::string>;
  4258. bool hasFilters() const;
  4259. bool matches( TestCaseInfo const& testCase ) const;
  4260. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4261. const vectorStrings & getInvalidArgs() const;
  4262. private:
  4263. std::vector<Filter> m_filters;
  4264. std::vector<std::string> m_invalidArgs;
  4265. friend class TestSpecParser;
  4266. };
  4267. }
  4268. #ifdef __clang__
  4269. #pragma clang diagnostic pop
  4270. #endif
  4271. // end catch_test_spec.h
  4272. // start catch_interfaces_tag_alias_registry.h
  4273. #include <string>
  4274. namespace Catch {
  4275. struct TagAlias;
  4276. struct ITagAliasRegistry {
  4277. virtual ~ITagAliasRegistry();
  4278. // Nullptr if not present
  4279. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4280. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4281. static ITagAliasRegistry const& get();
  4282. };
  4283. } // end namespace Catch
  4284. // end catch_interfaces_tag_alias_registry.h
  4285. namespace Catch {
  4286. class TestSpecParser {
  4287. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4288. Mode m_mode = None;
  4289. Mode lastMode = None;
  4290. bool m_exclusion = false;
  4291. std::size_t m_pos = 0;
  4292. std::size_t m_realPatternPos = 0;
  4293. std::string m_arg;
  4294. std::string m_substring;
  4295. std::string m_patternName;
  4296. std::vector<std::size_t> m_escapeChars;
  4297. TestSpec::Filter m_currentFilter;
  4298. TestSpec m_testSpec;
  4299. ITagAliasRegistry const* m_tagAliases = nullptr;
  4300. public:
  4301. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4302. TestSpecParser& parse( std::string const& arg );
  4303. TestSpec testSpec();
  4304. private:
  4305. bool visitChar( char c );
  4306. void startNewMode( Mode mode );
  4307. bool processNoneChar( char c );
  4308. void processNameChar( char c );
  4309. bool processOtherChar( char c );
  4310. void endMode();
  4311. void escape();
  4312. bool isControlChar( char c ) const;
  4313. void saveLastMode();
  4314. void revertBackToLastMode();
  4315. void addFilter();
  4316. bool separate();
  4317. // Handles common preprocessing of the pattern for name/tag patterns
  4318. std::string preprocessPattern();
  4319. // Adds the current pattern as a test name
  4320. void addNamePattern();
  4321. // Adds the current pattern as a tag
  4322. void addTagPattern();
  4323. inline void addCharToPattern(char c) {
  4324. m_substring += c;
  4325. m_patternName += c;
  4326. m_realPatternPos++;
  4327. }
  4328. };
  4329. TestSpec parseTestSpec( std::string const& arg );
  4330. } // namespace Catch
  4331. #ifdef __clang__
  4332. #pragma clang diagnostic pop
  4333. #endif
  4334. // end catch_test_spec_parser.h
  4335. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4336. #include <memory>
  4337. #include <vector>
  4338. #include <string>
  4339. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4340. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4341. #endif
  4342. namespace Catch {
  4343. struct IStream;
  4344. struct ConfigData {
  4345. bool listTests = false;
  4346. bool listTags = false;
  4347. bool listReporters = false;
  4348. bool listTestNamesOnly = false;
  4349. bool showSuccessfulTests = false;
  4350. bool shouldDebugBreak = false;
  4351. bool noThrow = false;
  4352. bool showHelp = false;
  4353. bool showInvisibles = false;
  4354. bool filenamesAsTags = false;
  4355. bool libIdentify = false;
  4356. int abortAfter = -1;
  4357. unsigned int rngSeed = 0;
  4358. bool benchmarkNoAnalysis = false;
  4359. unsigned int benchmarkSamples = 100;
  4360. double benchmarkConfidenceInterval = 0.95;
  4361. unsigned int benchmarkResamples = 100000;
  4362. std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
  4363. Verbosity verbosity = Verbosity::Normal;
  4364. WarnAbout::What warnings = WarnAbout::Nothing;
  4365. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4366. double minDuration = -1;
  4367. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4368. UseColour::YesOrNo useColour = UseColour::Auto;
  4369. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4370. std::string outputFilename;
  4371. std::string name;
  4372. std::string processName;
  4373. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4374. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4375. #endif
  4376. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4377. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4378. std::vector<std::string> testsOrTags;
  4379. std::vector<std::string> sectionsToRun;
  4380. };
  4381. class Config : public IConfig {
  4382. public:
  4383. Config() = default;
  4384. Config( ConfigData const& data );
  4385. virtual ~Config() = default;
  4386. std::string const& getFilename() const;
  4387. bool listTests() const;
  4388. bool listTestNamesOnly() const;
  4389. bool listTags() const;
  4390. bool listReporters() const;
  4391. std::string getProcessName() const;
  4392. std::string const& getReporterName() const;
  4393. std::vector<std::string> const& getTestsOrTags() const override;
  4394. std::vector<std::string> const& getSectionsToRun() const override;
  4395. TestSpec const& testSpec() const override;
  4396. bool hasTestFilters() const override;
  4397. bool showHelp() const;
  4398. // IConfig interface
  4399. bool allowThrows() const override;
  4400. std::ostream& stream() const override;
  4401. std::string name() const override;
  4402. bool includeSuccessfulResults() const override;
  4403. bool warnAboutMissingAssertions() const override;
  4404. bool warnAboutNoTests() const override;
  4405. ShowDurations::OrNot showDurations() const override;
  4406. double minDuration() const override;
  4407. RunTests::InWhatOrder runOrder() const override;
  4408. unsigned int rngSeed() const override;
  4409. UseColour::YesOrNo useColour() const override;
  4410. bool shouldDebugBreak() const override;
  4411. int abortAfter() const override;
  4412. bool showInvisibles() const override;
  4413. Verbosity verbosity() const override;
  4414. bool benchmarkNoAnalysis() const override;
  4415. int benchmarkSamples() const override;
  4416. double benchmarkConfidenceInterval() const override;
  4417. unsigned int benchmarkResamples() const override;
  4418. std::chrono::milliseconds benchmarkWarmupTime() const override;
  4419. private:
  4420. IStream const* openStream();
  4421. ConfigData m_data;
  4422. std::unique_ptr<IStream const> m_stream;
  4423. TestSpec m_testSpec;
  4424. bool m_hasTestFilters = false;
  4425. };
  4426. } // end namespace Catch
  4427. // end catch_config.hpp
  4428. // start catch_assertionresult.h
  4429. #include <string>
  4430. namespace Catch {
  4431. struct AssertionResultData
  4432. {
  4433. AssertionResultData() = delete;
  4434. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4435. std::string message;
  4436. mutable std::string reconstructedExpression;
  4437. LazyExpression lazyExpression;
  4438. ResultWas::OfType resultType;
  4439. std::string reconstructExpression() const;
  4440. };
  4441. class AssertionResult {
  4442. public:
  4443. AssertionResult() = delete;
  4444. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4445. bool isOk() const;
  4446. bool succeeded() const;
  4447. ResultWas::OfType getResultType() const;
  4448. bool hasExpression() const;
  4449. bool hasMessage() const;
  4450. std::string getExpression() const;
  4451. std::string getExpressionInMacro() const;
  4452. bool hasExpandedExpression() const;
  4453. std::string getExpandedExpression() const;
  4454. std::string getMessage() const;
  4455. SourceLineInfo getSourceInfo() const;
  4456. StringRef getTestMacroName() const;
  4457. //protected:
  4458. AssertionInfo m_info;
  4459. AssertionResultData m_resultData;
  4460. };
  4461. } // end namespace Catch
  4462. // end catch_assertionresult.h
  4463. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4464. // start catch_estimate.hpp
  4465. // Statistics estimates
  4466. namespace Catch {
  4467. namespace Benchmark {
  4468. template <typename Duration>
  4469. struct Estimate {
  4470. Duration point;
  4471. Duration lower_bound;
  4472. Duration upper_bound;
  4473. double confidence_interval;
  4474. template <typename Duration2>
  4475. operator Estimate<Duration2>() const {
  4476. return { point, lower_bound, upper_bound, confidence_interval };
  4477. }
  4478. };
  4479. } // namespace Benchmark
  4480. } // namespace Catch
  4481. // end catch_estimate.hpp
  4482. // start catch_outlier_classification.hpp
  4483. // Outlier information
  4484. namespace Catch {
  4485. namespace Benchmark {
  4486. struct OutlierClassification {
  4487. int samples_seen = 0;
  4488. int low_severe = 0; // more than 3 times IQR below Q1
  4489. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4490. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4491. int high_severe = 0; // more than 3 times IQR above Q3
  4492. int total() const {
  4493. return low_severe + low_mild + high_mild + high_severe;
  4494. }
  4495. };
  4496. } // namespace Benchmark
  4497. } // namespace Catch
  4498. // end catch_outlier_classification.hpp
  4499. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4500. #include <string>
  4501. #include <iosfwd>
  4502. #include <map>
  4503. #include <set>
  4504. #include <memory>
  4505. #include <algorithm>
  4506. namespace Catch {
  4507. struct ReporterConfig {
  4508. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4509. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4510. std::ostream& stream() const;
  4511. IConfigPtr fullConfig() const;
  4512. private:
  4513. std::ostream* m_stream;
  4514. IConfigPtr m_fullConfig;
  4515. };
  4516. struct ReporterPreferences {
  4517. bool shouldRedirectStdOut = false;
  4518. bool shouldReportAllAssertions = false;
  4519. };
  4520. template<typename T>
  4521. struct LazyStat : Option<T> {
  4522. LazyStat& operator=( T const& _value ) {
  4523. Option<T>::operator=( _value );
  4524. used = false;
  4525. return *this;
  4526. }
  4527. void reset() {
  4528. Option<T>::reset();
  4529. used = false;
  4530. }
  4531. bool used = false;
  4532. };
  4533. struct TestRunInfo {
  4534. TestRunInfo( std::string const& _name );
  4535. std::string name;
  4536. };
  4537. struct GroupInfo {
  4538. GroupInfo( std::string const& _name,
  4539. std::size_t _groupIndex,
  4540. std::size_t _groupsCount );
  4541. std::string name;
  4542. std::size_t groupIndex;
  4543. std::size_t groupsCounts;
  4544. };
  4545. struct AssertionStats {
  4546. AssertionStats( AssertionResult const& _assertionResult,
  4547. std::vector<MessageInfo> const& _infoMessages,
  4548. Totals const& _totals );
  4549. AssertionStats( AssertionStats const& ) = default;
  4550. AssertionStats( AssertionStats && ) = default;
  4551. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4552. AssertionStats& operator = ( AssertionStats && ) = delete;
  4553. virtual ~AssertionStats();
  4554. AssertionResult assertionResult;
  4555. std::vector<MessageInfo> infoMessages;
  4556. Totals totals;
  4557. };
  4558. struct SectionStats {
  4559. SectionStats( SectionInfo const& _sectionInfo,
  4560. Counts const& _assertions,
  4561. double _durationInSeconds,
  4562. bool _missingAssertions );
  4563. SectionStats( SectionStats const& ) = default;
  4564. SectionStats( SectionStats && ) = default;
  4565. SectionStats& operator = ( SectionStats const& ) = default;
  4566. SectionStats& operator = ( SectionStats && ) = default;
  4567. virtual ~SectionStats();
  4568. SectionInfo sectionInfo;
  4569. Counts assertions;
  4570. double durationInSeconds;
  4571. bool missingAssertions;
  4572. };
  4573. struct TestCaseStats {
  4574. TestCaseStats( TestCaseInfo const& _testInfo,
  4575. Totals const& _totals,
  4576. std::string const& _stdOut,
  4577. std::string const& _stdErr,
  4578. bool _aborting );
  4579. TestCaseStats( TestCaseStats const& ) = default;
  4580. TestCaseStats( TestCaseStats && ) = default;
  4581. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4582. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4583. virtual ~TestCaseStats();
  4584. TestCaseInfo testInfo;
  4585. Totals totals;
  4586. std::string stdOut;
  4587. std::string stdErr;
  4588. bool aborting;
  4589. };
  4590. struct TestGroupStats {
  4591. TestGroupStats( GroupInfo const& _groupInfo,
  4592. Totals const& _totals,
  4593. bool _aborting );
  4594. TestGroupStats( GroupInfo const& _groupInfo );
  4595. TestGroupStats( TestGroupStats const& ) = default;
  4596. TestGroupStats( TestGroupStats && ) = default;
  4597. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4598. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4599. virtual ~TestGroupStats();
  4600. GroupInfo groupInfo;
  4601. Totals totals;
  4602. bool aborting;
  4603. };
  4604. struct TestRunStats {
  4605. TestRunStats( TestRunInfo const& _runInfo,
  4606. Totals const& _totals,
  4607. bool _aborting );
  4608. TestRunStats( TestRunStats const& ) = default;
  4609. TestRunStats( TestRunStats && ) = default;
  4610. TestRunStats& operator = ( TestRunStats const& ) = default;
  4611. TestRunStats& operator = ( TestRunStats && ) = default;
  4612. virtual ~TestRunStats();
  4613. TestRunInfo runInfo;
  4614. Totals totals;
  4615. bool aborting;
  4616. };
  4617. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4618. struct BenchmarkInfo {
  4619. std::string name;
  4620. double estimatedDuration;
  4621. int iterations;
  4622. int samples;
  4623. unsigned int resamples;
  4624. double clockResolution;
  4625. double clockCost;
  4626. };
  4627. template <class Duration>
  4628. struct BenchmarkStats {
  4629. BenchmarkInfo info;
  4630. std::vector<Duration> samples;
  4631. Benchmark::Estimate<Duration> mean;
  4632. Benchmark::Estimate<Duration> standardDeviation;
  4633. Benchmark::OutlierClassification outliers;
  4634. double outlierVariance;
  4635. template <typename Duration2>
  4636. operator BenchmarkStats<Duration2>() const {
  4637. std::vector<Duration2> samples2;
  4638. samples2.reserve(samples.size());
  4639. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4640. return {
  4641. info,
  4642. std::move(samples2),
  4643. mean,
  4644. standardDeviation,
  4645. outliers,
  4646. outlierVariance,
  4647. };
  4648. }
  4649. };
  4650. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4651. struct IStreamingReporter {
  4652. virtual ~IStreamingReporter() = default;
  4653. // Implementing class must also provide the following static methods:
  4654. // static std::string getDescription();
  4655. // static std::set<Verbosity> getSupportedVerbosities()
  4656. virtual ReporterPreferences getPreferences() const = 0;
  4657. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4658. virtual void reportInvalidArguments(std::string const&) {}
  4659. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4660. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4661. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4662. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4663. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4664. virtual void benchmarkPreparing( std::string const& ) {}
  4665. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4666. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4667. virtual void benchmarkFailed( std::string const& ) {}
  4668. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4669. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4670. // The return value indicates if the messages buffer should be cleared:
  4671. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4672. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4673. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4674. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4675. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4676. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4677. // Default empty implementation provided
  4678. virtual void fatalErrorEncountered( StringRef name );
  4679. virtual bool isMulti() const;
  4680. };
  4681. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4682. struct IReporterFactory {
  4683. virtual ~IReporterFactory();
  4684. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4685. virtual std::string getDescription() const = 0;
  4686. };
  4687. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4688. struct IReporterRegistry {
  4689. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4690. using Listeners = std::vector<IReporterFactoryPtr>;
  4691. virtual ~IReporterRegistry();
  4692. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4693. virtual FactoryMap const& getFactories() const = 0;
  4694. virtual Listeners const& getListeners() const = 0;
  4695. };
  4696. } // end namespace Catch
  4697. // end catch_interfaces_reporter.h
  4698. #include <algorithm>
  4699. #include <cstring>
  4700. #include <cfloat>
  4701. #include <cstdio>
  4702. #include <cassert>
  4703. #include <memory>
  4704. #include <ostream>
  4705. namespace Catch {
  4706. void prepareExpandedExpression(AssertionResult& result);
  4707. // Returns double formatted as %.3f (format expected on output)
  4708. std::string getFormattedDuration( double duration );
  4709. //! Should the reporter show
  4710. bool shouldShowDuration( IConfig const& config, double duration );
  4711. std::string serializeFilters( std::vector<std::string> const& container );
  4712. template<typename DerivedT>
  4713. struct StreamingReporterBase : IStreamingReporter {
  4714. StreamingReporterBase( ReporterConfig const& _config )
  4715. : m_config( _config.fullConfig() ),
  4716. stream( _config.stream() )
  4717. {
  4718. m_reporterPrefs.shouldRedirectStdOut = false;
  4719. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4720. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4721. }
  4722. ReporterPreferences getPreferences() const override {
  4723. return m_reporterPrefs;
  4724. }
  4725. static std::set<Verbosity> getSupportedVerbosities() {
  4726. return { Verbosity::Normal };
  4727. }
  4728. ~StreamingReporterBase() override = default;
  4729. void noMatchingTestCases(std::string const&) override {}
  4730. void reportInvalidArguments(std::string const&) override {}
  4731. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4732. currentTestRunInfo = _testRunInfo;
  4733. }
  4734. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4735. currentGroupInfo = _groupInfo;
  4736. }
  4737. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4738. currentTestCaseInfo = _testInfo;
  4739. }
  4740. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4741. m_sectionStack.push_back(_sectionInfo);
  4742. }
  4743. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4744. m_sectionStack.pop_back();
  4745. }
  4746. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4747. currentTestCaseInfo.reset();
  4748. }
  4749. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4750. currentGroupInfo.reset();
  4751. }
  4752. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4753. currentTestCaseInfo.reset();
  4754. currentGroupInfo.reset();
  4755. currentTestRunInfo.reset();
  4756. }
  4757. void skipTest(TestCaseInfo const&) override {
  4758. // Don't do anything with this by default.
  4759. // It can optionally be overridden in the derived class.
  4760. }
  4761. IConfigPtr m_config;
  4762. std::ostream& stream;
  4763. LazyStat<TestRunInfo> currentTestRunInfo;
  4764. LazyStat<GroupInfo> currentGroupInfo;
  4765. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4766. std::vector<SectionInfo> m_sectionStack;
  4767. ReporterPreferences m_reporterPrefs;
  4768. };
  4769. template<typename DerivedT>
  4770. struct CumulativeReporterBase : IStreamingReporter {
  4771. template<typename T, typename ChildNodeT>
  4772. struct Node {
  4773. explicit Node( T const& _value ) : value( _value ) {}
  4774. virtual ~Node() {}
  4775. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4776. T value;
  4777. ChildNodes children;
  4778. };
  4779. struct SectionNode {
  4780. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4781. virtual ~SectionNode() = default;
  4782. bool operator == (SectionNode const& other) const {
  4783. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4784. }
  4785. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4786. return operator==(*other);
  4787. }
  4788. SectionStats stats;
  4789. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4790. using Assertions = std::vector<AssertionStats>;
  4791. ChildSections childSections;
  4792. Assertions assertions;
  4793. std::string stdOut;
  4794. std::string stdErr;
  4795. };
  4796. struct BySectionInfo {
  4797. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4798. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4799. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4800. return ((node->stats.sectionInfo.name == m_other.name) &&
  4801. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4802. }
  4803. void operator=(BySectionInfo const&) = delete;
  4804. private:
  4805. SectionInfo const& m_other;
  4806. };
  4807. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4808. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4809. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4810. CumulativeReporterBase( ReporterConfig const& _config )
  4811. : m_config( _config.fullConfig() ),
  4812. stream( _config.stream() )
  4813. {
  4814. m_reporterPrefs.shouldRedirectStdOut = false;
  4815. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4816. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4817. }
  4818. ~CumulativeReporterBase() override = default;
  4819. ReporterPreferences getPreferences() const override {
  4820. return m_reporterPrefs;
  4821. }
  4822. static std::set<Verbosity> getSupportedVerbosities() {
  4823. return { Verbosity::Normal };
  4824. }
  4825. void testRunStarting( TestRunInfo const& ) override {}
  4826. void testGroupStarting( GroupInfo const& ) override {}
  4827. void testCaseStarting( TestCaseInfo const& ) override {}
  4828. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4829. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4830. std::shared_ptr<SectionNode> node;
  4831. if( m_sectionStack.empty() ) {
  4832. if( !m_rootSection )
  4833. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4834. node = m_rootSection;
  4835. }
  4836. else {
  4837. SectionNode& parentNode = *m_sectionStack.back();
  4838. auto it =
  4839. std::find_if( parentNode.childSections.begin(),
  4840. parentNode.childSections.end(),
  4841. BySectionInfo( sectionInfo ) );
  4842. if( it == parentNode.childSections.end() ) {
  4843. node = std::make_shared<SectionNode>( incompleteStats );
  4844. parentNode.childSections.push_back( node );
  4845. }
  4846. else
  4847. node = *it;
  4848. }
  4849. m_sectionStack.push_back( node );
  4850. m_deepestSection = std::move(node);
  4851. }
  4852. void assertionStarting(AssertionInfo const&) override {}
  4853. bool assertionEnded(AssertionStats const& assertionStats) override {
  4854. assert(!m_sectionStack.empty());
  4855. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4856. // which getExpandedExpression() calls to build the expression string.
  4857. // Our section stack copy of the assertionResult will likely outlive the
  4858. // temporary, so it must be expanded or discarded now to avoid calling
  4859. // a destroyed object later.
  4860. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4861. SectionNode& sectionNode = *m_sectionStack.back();
  4862. sectionNode.assertions.push_back(assertionStats);
  4863. return true;
  4864. }
  4865. void sectionEnded(SectionStats const& sectionStats) override {
  4866. assert(!m_sectionStack.empty());
  4867. SectionNode& node = *m_sectionStack.back();
  4868. node.stats = sectionStats;
  4869. m_sectionStack.pop_back();
  4870. }
  4871. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4872. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4873. assert(m_sectionStack.size() == 0);
  4874. node->children.push_back(m_rootSection);
  4875. m_testCases.push_back(node);
  4876. m_rootSection.reset();
  4877. assert(m_deepestSection);
  4878. m_deepestSection->stdOut = testCaseStats.stdOut;
  4879. m_deepestSection->stdErr = testCaseStats.stdErr;
  4880. }
  4881. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4882. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4883. node->children.swap(m_testCases);
  4884. m_testGroups.push_back(node);
  4885. }
  4886. void testRunEnded(TestRunStats const& testRunStats) override {
  4887. auto node = std::make_shared<TestRunNode>(testRunStats);
  4888. node->children.swap(m_testGroups);
  4889. m_testRuns.push_back(node);
  4890. testRunEndedCumulative();
  4891. }
  4892. virtual void testRunEndedCumulative() = 0;
  4893. void skipTest(TestCaseInfo const&) override {}
  4894. IConfigPtr m_config;
  4895. std::ostream& stream;
  4896. std::vector<AssertionStats> m_assertions;
  4897. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4898. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4899. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4900. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4901. std::shared_ptr<SectionNode> m_rootSection;
  4902. std::shared_ptr<SectionNode> m_deepestSection;
  4903. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4904. ReporterPreferences m_reporterPrefs;
  4905. };
  4906. template<char C>
  4907. char const* getLineOfChars() {
  4908. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4909. if( !*line ) {
  4910. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4911. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4912. }
  4913. return line;
  4914. }
  4915. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4916. TestEventListenerBase( ReporterConfig const& _config );
  4917. static std::set<Verbosity> getSupportedVerbosities();
  4918. void assertionStarting(AssertionInfo const&) override;
  4919. bool assertionEnded(AssertionStats const&) override;
  4920. };
  4921. } // end namespace Catch
  4922. // end catch_reporter_bases.hpp
  4923. // start catch_console_colour.h
  4924. namespace Catch {
  4925. struct Colour {
  4926. enum Code {
  4927. None = 0,
  4928. White,
  4929. Red,
  4930. Green,
  4931. Blue,
  4932. Cyan,
  4933. Yellow,
  4934. Grey,
  4935. Bright = 0x10,
  4936. BrightRed = Bright | Red,
  4937. BrightGreen = Bright | Green,
  4938. LightGrey = Bright | Grey,
  4939. BrightWhite = Bright | White,
  4940. BrightYellow = Bright | Yellow,
  4941. // By intention
  4942. FileName = LightGrey,
  4943. Warning = BrightYellow,
  4944. ResultError = BrightRed,
  4945. ResultSuccess = BrightGreen,
  4946. ResultExpectedFailure = Warning,
  4947. Error = BrightRed,
  4948. Success = Green,
  4949. OriginalExpression = Cyan,
  4950. ReconstructedExpression = BrightYellow,
  4951. SecondaryText = LightGrey,
  4952. Headers = White
  4953. };
  4954. // Use constructed object for RAII guard
  4955. Colour( Code _colourCode );
  4956. Colour( Colour&& other ) noexcept;
  4957. Colour& operator=( Colour&& other ) noexcept;
  4958. ~Colour();
  4959. // Use static method for one-shot changes
  4960. static void use( Code _colourCode );
  4961. private:
  4962. bool m_moved = false;
  4963. };
  4964. std::ostream& operator << ( std::ostream& os, Colour const& );
  4965. } // end namespace Catch
  4966. // end catch_console_colour.h
  4967. // start catch_reporter_registrars.hpp
  4968. namespace Catch {
  4969. template<typename T>
  4970. class ReporterRegistrar {
  4971. class ReporterFactory : public IReporterFactory {
  4972. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4973. return std::unique_ptr<T>( new T( config ) );
  4974. }
  4975. std::string getDescription() const override {
  4976. return T::getDescription();
  4977. }
  4978. };
  4979. public:
  4980. explicit ReporterRegistrar( std::string const& name ) {
  4981. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4982. }
  4983. };
  4984. template<typename T>
  4985. class ListenerRegistrar {
  4986. class ListenerFactory : public IReporterFactory {
  4987. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4988. return std::unique_ptr<T>( new T( config ) );
  4989. }
  4990. std::string getDescription() const override {
  4991. return std::string();
  4992. }
  4993. };
  4994. public:
  4995. ListenerRegistrar() {
  4996. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4997. }
  4998. };
  4999. }
  5000. #if !defined(CATCH_CONFIG_DISABLE)
  5001. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  5002. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5003. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5004. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  5005. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5006. #define CATCH_REGISTER_LISTENER( listenerType ) \
  5007. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5008. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5009. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  5010. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5011. #else // CATCH_CONFIG_DISABLE
  5012. #define CATCH_REGISTER_REPORTER(name, reporterType)
  5013. #define CATCH_REGISTER_LISTENER(listenerType)
  5014. #endif // CATCH_CONFIG_DISABLE
  5015. // end catch_reporter_registrars.hpp
  5016. // Allow users to base their work off existing reporters
  5017. // start catch_reporter_compact.h
  5018. namespace Catch {
  5019. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  5020. using StreamingReporterBase::StreamingReporterBase;
  5021. ~CompactReporter() override;
  5022. static std::string getDescription();
  5023. void noMatchingTestCases(std::string const& spec) override;
  5024. void assertionStarting(AssertionInfo const&) override;
  5025. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5026. void sectionEnded(SectionStats const& _sectionStats) override;
  5027. void testRunEnded(TestRunStats const& _testRunStats) override;
  5028. };
  5029. } // end namespace Catch
  5030. // end catch_reporter_compact.h
  5031. // start catch_reporter_console.h
  5032. #if defined(_MSC_VER)
  5033. #pragma warning(push)
  5034. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  5035. // Note that 4062 (not all labels are handled
  5036. // and default is missing) is enabled
  5037. #endif
  5038. namespace Catch {
  5039. // Fwd decls
  5040. struct SummaryColumn;
  5041. class TablePrinter;
  5042. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  5043. std::unique_ptr<TablePrinter> m_tablePrinter;
  5044. ConsoleReporter(ReporterConfig const& config);
  5045. ~ConsoleReporter() override;
  5046. static std::string getDescription();
  5047. void noMatchingTestCases(std::string const& spec) override;
  5048. void reportInvalidArguments(std::string const&arg) override;
  5049. void assertionStarting(AssertionInfo const&) override;
  5050. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5051. void sectionStarting(SectionInfo const& _sectionInfo) override;
  5052. void sectionEnded(SectionStats const& _sectionStats) override;
  5053. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5054. void benchmarkPreparing(std::string const& name) override;
  5055. void benchmarkStarting(BenchmarkInfo const& info) override;
  5056. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  5057. void benchmarkFailed(std::string const& error) override;
  5058. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5059. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  5060. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  5061. void testRunEnded(TestRunStats const& _testRunStats) override;
  5062. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  5063. private:
  5064. void lazyPrint();
  5065. void lazyPrintWithoutClosingBenchmarkTable();
  5066. void lazyPrintRunInfo();
  5067. void lazyPrintGroupInfo();
  5068. void printTestCaseAndSectionHeader();
  5069. void printClosedHeader(std::string const& _name);
  5070. void printOpenHeader(std::string const& _name);
  5071. // if string has a : in first line will set indent to follow it on
  5072. // subsequent lines
  5073. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  5074. void printTotals(Totals const& totals);
  5075. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  5076. void printTotalsDivider(Totals const& totals);
  5077. void printSummaryDivider();
  5078. void printTestFilters();
  5079. private:
  5080. bool m_headerPrinted = false;
  5081. };
  5082. } // end namespace Catch
  5083. #if defined(_MSC_VER)
  5084. #pragma warning(pop)
  5085. #endif
  5086. // end catch_reporter_console.h
  5087. // start catch_reporter_junit.h
  5088. // start catch_xmlwriter.h
  5089. #include <vector>
  5090. namespace Catch {
  5091. enum class XmlFormatting {
  5092. None = 0x00,
  5093. Indent = 0x01,
  5094. Newline = 0x02,
  5095. };
  5096. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
  5097. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
  5098. class XmlEncode {
  5099. public:
  5100. enum ForWhat { ForTextNodes, ForAttributes };
  5101. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  5102. void encodeTo( std::ostream& os ) const;
  5103. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  5104. private:
  5105. std::string m_str;
  5106. ForWhat m_forWhat;
  5107. };
  5108. class XmlWriter {
  5109. public:
  5110. class ScopedElement {
  5111. public:
  5112. ScopedElement( XmlWriter* writer, XmlFormatting fmt );
  5113. ScopedElement( ScopedElement&& other ) noexcept;
  5114. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5115. ~ScopedElement();
  5116. ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
  5117. template<typename T>
  5118. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5119. m_writer->writeAttribute( name, attribute );
  5120. return *this;
  5121. }
  5122. private:
  5123. mutable XmlWriter* m_writer = nullptr;
  5124. XmlFormatting m_fmt;
  5125. };
  5126. XmlWriter( std::ostream& os = Catch::cout() );
  5127. ~XmlWriter();
  5128. XmlWriter( XmlWriter const& ) = delete;
  5129. XmlWriter& operator=( XmlWriter const& ) = delete;
  5130. XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5131. ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5132. XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5133. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5134. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5135. template<typename T>
  5136. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5137. ReusableStringStream rss;
  5138. rss << attribute;
  5139. return writeAttribute( name, rss.str() );
  5140. }
  5141. XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5142. XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5143. void writeStylesheetRef( std::string const& url );
  5144. XmlWriter& writeBlankLine();
  5145. void ensureTagClosed();
  5146. private:
  5147. void applyFormatting(XmlFormatting fmt);
  5148. void writeDeclaration();
  5149. void newlineIfNecessary();
  5150. bool m_tagIsOpen = false;
  5151. bool m_needsNewline = false;
  5152. std::vector<std::string> m_tags;
  5153. std::string m_indent;
  5154. std::ostream& m_os;
  5155. };
  5156. }
  5157. // end catch_xmlwriter.h
  5158. namespace Catch {
  5159. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5160. public:
  5161. JunitReporter(ReporterConfig const& _config);
  5162. ~JunitReporter() override;
  5163. static std::string getDescription();
  5164. void noMatchingTestCases(std::string const& /*spec*/) override;
  5165. void testRunStarting(TestRunInfo const& runInfo) override;
  5166. void testGroupStarting(GroupInfo const& groupInfo) override;
  5167. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5168. bool assertionEnded(AssertionStats const& assertionStats) override;
  5169. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5170. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5171. void testRunEndedCumulative() override;
  5172. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5173. void writeTestCase(TestCaseNode const& testCaseNode);
  5174. void writeSection(std::string const& className,
  5175. std::string const& rootName,
  5176. SectionNode const& sectionNode);
  5177. void writeAssertions(SectionNode const& sectionNode);
  5178. void writeAssertion(AssertionStats const& stats);
  5179. XmlWriter xml;
  5180. Timer suiteTimer;
  5181. std::string stdOutForSuite;
  5182. std::string stdErrForSuite;
  5183. unsigned int unexpectedExceptions = 0;
  5184. bool m_okToFail = false;
  5185. };
  5186. } // end namespace Catch
  5187. // end catch_reporter_junit.h
  5188. // start catch_reporter_xml.h
  5189. namespace Catch {
  5190. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5191. public:
  5192. XmlReporter(ReporterConfig const& _config);
  5193. ~XmlReporter() override;
  5194. static std::string getDescription();
  5195. virtual std::string getStylesheetRef() const;
  5196. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5197. public: // StreamingReporterBase
  5198. void noMatchingTestCases(std::string const& s) override;
  5199. void testRunStarting(TestRunInfo const& testInfo) override;
  5200. void testGroupStarting(GroupInfo const& groupInfo) override;
  5201. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5202. void sectionStarting(SectionInfo const& sectionInfo) override;
  5203. void assertionStarting(AssertionInfo const&) override;
  5204. bool assertionEnded(AssertionStats const& assertionStats) override;
  5205. void sectionEnded(SectionStats const& sectionStats) override;
  5206. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5207. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5208. void testRunEnded(TestRunStats const& testRunStats) override;
  5209. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5210. void benchmarkPreparing(std::string const& name) override;
  5211. void benchmarkStarting(BenchmarkInfo const&) override;
  5212. void benchmarkEnded(BenchmarkStats<> const&) override;
  5213. void benchmarkFailed(std::string const&) override;
  5214. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5215. private:
  5216. Timer m_testCaseTimer;
  5217. XmlWriter m_xml;
  5218. int m_sectionDepth = 0;
  5219. };
  5220. } // end namespace Catch
  5221. // end catch_reporter_xml.h
  5222. // end catch_external_interfaces.h
  5223. #endif
  5224. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5225. // start catch_benchmarking_all.hpp
  5226. // A proxy header that includes all of the benchmarking headers to allow
  5227. // concise include of the benchmarking features. You should prefer the
  5228. // individual includes in standard use.
  5229. // start catch_benchmark.hpp
  5230. // Benchmark
  5231. // start catch_chronometer.hpp
  5232. // User-facing chronometer
  5233. // start catch_clock.hpp
  5234. // Clocks
  5235. #include <chrono>
  5236. #include <ratio>
  5237. namespace Catch {
  5238. namespace Benchmark {
  5239. template <typename Clock>
  5240. using ClockDuration = typename Clock::duration;
  5241. template <typename Clock>
  5242. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5243. template <typename Clock>
  5244. using TimePoint = typename Clock::time_point;
  5245. using default_clock = std::chrono::steady_clock;
  5246. template <typename Clock>
  5247. struct now {
  5248. TimePoint<Clock> operator()() const {
  5249. return Clock::now();
  5250. }
  5251. };
  5252. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5253. } // namespace Benchmark
  5254. } // namespace Catch
  5255. // end catch_clock.hpp
  5256. // start catch_optimizer.hpp
  5257. // Hinting the optimizer
  5258. #if defined(_MSC_VER)
  5259. # include <atomic> // atomic_thread_fence
  5260. #endif
  5261. namespace Catch {
  5262. namespace Benchmark {
  5263. #if defined(__GNUC__) || defined(__clang__)
  5264. template <typename T>
  5265. inline void keep_memory(T* p) {
  5266. asm volatile("" : : "g"(p) : "memory");
  5267. }
  5268. inline void keep_memory() {
  5269. asm volatile("" : : : "memory");
  5270. }
  5271. namespace Detail {
  5272. inline void optimizer_barrier() { keep_memory(); }
  5273. } // namespace Detail
  5274. #elif defined(_MSC_VER)
  5275. #pragma optimize("", off)
  5276. template <typename T>
  5277. inline void keep_memory(T* p) {
  5278. // thanks @milleniumbug
  5279. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5280. }
  5281. // TODO equivalent keep_memory()
  5282. #pragma optimize("", on)
  5283. namespace Detail {
  5284. inline void optimizer_barrier() {
  5285. std::atomic_thread_fence(std::memory_order_seq_cst);
  5286. }
  5287. } // namespace Detail
  5288. #endif
  5289. template <typename T>
  5290. inline void deoptimize_value(T&& x) {
  5291. keep_memory(&x);
  5292. }
  5293. template <typename Fn, typename... Args>
  5294. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5295. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5296. }
  5297. template <typename Fn, typename... Args>
  5298. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5299. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5300. }
  5301. } // namespace Benchmark
  5302. } // namespace Catch
  5303. // end catch_optimizer.hpp
  5304. // start catch_complete_invoke.hpp
  5305. // Invoke with a special case for void
  5306. #include <type_traits>
  5307. #include <utility>
  5308. namespace Catch {
  5309. namespace Benchmark {
  5310. namespace Detail {
  5311. template <typename T>
  5312. struct CompleteType { using type = T; };
  5313. template <>
  5314. struct CompleteType<void> { struct type {}; };
  5315. template <typename T>
  5316. using CompleteType_t = typename CompleteType<T>::type;
  5317. template <typename Result>
  5318. struct CompleteInvoker {
  5319. template <typename Fun, typename... Args>
  5320. static Result invoke(Fun&& fun, Args&&... args) {
  5321. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5322. }
  5323. };
  5324. template <>
  5325. struct CompleteInvoker<void> {
  5326. template <typename Fun, typename... Args>
  5327. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5328. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5329. return {};
  5330. }
  5331. };
  5332. // invoke and not return void :(
  5333. template <typename Fun, typename... Args>
  5334. CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
  5335. return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5336. }
  5337. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5338. } // namespace Detail
  5339. template <typename Fun>
  5340. Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
  5341. CATCH_TRY{
  5342. return Detail::complete_invoke(std::forward<Fun>(fun));
  5343. } CATCH_CATCH_ALL{
  5344. getResultCapture().benchmarkFailed(translateActiveException());
  5345. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5346. }
  5347. }
  5348. } // namespace Benchmark
  5349. } // namespace Catch
  5350. // end catch_complete_invoke.hpp
  5351. namespace Catch {
  5352. namespace Benchmark {
  5353. namespace Detail {
  5354. struct ChronometerConcept {
  5355. virtual void start() = 0;
  5356. virtual void finish() = 0;
  5357. virtual ~ChronometerConcept() = default;
  5358. };
  5359. template <typename Clock>
  5360. struct ChronometerModel final : public ChronometerConcept {
  5361. void start() override { started = Clock::now(); }
  5362. void finish() override { finished = Clock::now(); }
  5363. ClockDuration<Clock> elapsed() const { return finished - started; }
  5364. TimePoint<Clock> started;
  5365. TimePoint<Clock> finished;
  5366. };
  5367. } // namespace Detail
  5368. struct Chronometer {
  5369. public:
  5370. template <typename Fun>
  5371. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5372. int runs() const { return k; }
  5373. Chronometer(Detail::ChronometerConcept& meter, int k)
  5374. : impl(&meter)
  5375. , k(k) {}
  5376. private:
  5377. template <typename Fun>
  5378. void measure(Fun&& fun, std::false_type) {
  5379. measure([&fun](int) { return fun(); }, std::true_type());
  5380. }
  5381. template <typename Fun>
  5382. void measure(Fun&& fun, std::true_type) {
  5383. Detail::optimizer_barrier();
  5384. impl->start();
  5385. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5386. impl->finish();
  5387. Detail::optimizer_barrier();
  5388. }
  5389. Detail::ChronometerConcept* impl;
  5390. int k;
  5391. };
  5392. } // namespace Benchmark
  5393. } // namespace Catch
  5394. // end catch_chronometer.hpp
  5395. // start catch_environment.hpp
  5396. // Environment information
  5397. namespace Catch {
  5398. namespace Benchmark {
  5399. template <typename Duration>
  5400. struct EnvironmentEstimate {
  5401. Duration mean;
  5402. OutlierClassification outliers;
  5403. template <typename Duration2>
  5404. operator EnvironmentEstimate<Duration2>() const {
  5405. return { mean, outliers };
  5406. }
  5407. };
  5408. template <typename Clock>
  5409. struct Environment {
  5410. using clock_type = Clock;
  5411. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5412. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5413. };
  5414. } // namespace Benchmark
  5415. } // namespace Catch
  5416. // end catch_environment.hpp
  5417. // start catch_execution_plan.hpp
  5418. // Execution plan
  5419. // start catch_benchmark_function.hpp
  5420. // Dumb std::function implementation for consistent call overhead
  5421. #include <cassert>
  5422. #include <type_traits>
  5423. #include <utility>
  5424. #include <memory>
  5425. namespace Catch {
  5426. namespace Benchmark {
  5427. namespace Detail {
  5428. template <typename T>
  5429. using Decay = typename std::decay<T>::type;
  5430. template <typename T, typename U>
  5431. struct is_related
  5432. : std::is_same<Decay<T>, Decay<U>> {};
  5433. /// We need to reinvent std::function because every piece of code that might add overhead
  5434. /// in a measurement context needs to have consistent performance characteristics so that we
  5435. /// can account for it in the measurement.
  5436. /// Implementations of std::function with optimizations that aren't always applicable, like
  5437. /// small buffer optimizations, are not uncommon.
  5438. /// This is effectively an implementation of std::function without any such optimizations;
  5439. /// it may be slow, but it is consistently slow.
  5440. struct BenchmarkFunction {
  5441. private:
  5442. struct callable {
  5443. virtual void call(Chronometer meter) const = 0;
  5444. virtual callable* clone() const = 0;
  5445. virtual ~callable() = default;
  5446. };
  5447. template <typename Fun>
  5448. struct model : public callable {
  5449. model(Fun&& fun) : fun(std::move(fun)) {}
  5450. model(Fun const& fun) : fun(fun) {}
  5451. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5452. void call(Chronometer meter) const override {
  5453. call(meter, is_callable<Fun(Chronometer)>());
  5454. }
  5455. void call(Chronometer meter, std::true_type) const {
  5456. fun(meter);
  5457. }
  5458. void call(Chronometer meter, std::false_type) const {
  5459. meter.measure(fun);
  5460. }
  5461. Fun fun;
  5462. };
  5463. struct do_nothing { void operator()() const {} };
  5464. template <typename T>
  5465. BenchmarkFunction(model<T>* c) : f(c) {}
  5466. public:
  5467. BenchmarkFunction()
  5468. : f(new model<do_nothing>{ {} }) {}
  5469. template <typename Fun,
  5470. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5471. BenchmarkFunction(Fun&& fun)
  5472. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5473. BenchmarkFunction(BenchmarkFunction&& that)
  5474. : f(std::move(that.f)) {}
  5475. BenchmarkFunction(BenchmarkFunction const& that)
  5476. : f(that.f->clone()) {}
  5477. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5478. f = std::move(that.f);
  5479. return *this;
  5480. }
  5481. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5482. f.reset(that.f->clone());
  5483. return *this;
  5484. }
  5485. void operator()(Chronometer meter) const { f->call(meter); }
  5486. private:
  5487. std::unique_ptr<callable> f;
  5488. };
  5489. } // namespace Detail
  5490. } // namespace Benchmark
  5491. } // namespace Catch
  5492. // end catch_benchmark_function.hpp
  5493. // start catch_repeat.hpp
  5494. // repeat algorithm
  5495. #include <type_traits>
  5496. #include <utility>
  5497. namespace Catch {
  5498. namespace Benchmark {
  5499. namespace Detail {
  5500. template <typename Fun>
  5501. struct repeater {
  5502. void operator()(int k) const {
  5503. for (int i = 0; i < k; ++i) {
  5504. fun();
  5505. }
  5506. }
  5507. Fun fun;
  5508. };
  5509. template <typename Fun>
  5510. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5511. return { std::forward<Fun>(fun) };
  5512. }
  5513. } // namespace Detail
  5514. } // namespace Benchmark
  5515. } // namespace Catch
  5516. // end catch_repeat.hpp
  5517. // start catch_run_for_at_least.hpp
  5518. // Run a function for a minimum amount of time
  5519. // start catch_measure.hpp
  5520. // Measure
  5521. // start catch_timing.hpp
  5522. // Timing
  5523. #include <tuple>
  5524. #include <type_traits>
  5525. namespace Catch {
  5526. namespace Benchmark {
  5527. template <typename Duration, typename Result>
  5528. struct Timing {
  5529. Duration elapsed;
  5530. Result result;
  5531. int iterations;
  5532. };
  5533. template <typename Clock, typename Func, typename... Args>
  5534. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
  5535. } // namespace Benchmark
  5536. } // namespace Catch
  5537. // end catch_timing.hpp
  5538. #include <utility>
  5539. namespace Catch {
  5540. namespace Benchmark {
  5541. namespace Detail {
  5542. template <typename Clock, typename Fun, typename... Args>
  5543. TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
  5544. auto start = Clock::now();
  5545. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5546. auto end = Clock::now();
  5547. auto delta = end - start;
  5548. return { delta, std::forward<decltype(r)>(r), 1 };
  5549. }
  5550. } // namespace Detail
  5551. } // namespace Benchmark
  5552. } // namespace Catch
  5553. // end catch_measure.hpp
  5554. #include <utility>
  5555. #include <type_traits>
  5556. namespace Catch {
  5557. namespace Benchmark {
  5558. namespace Detail {
  5559. template <typename Clock, typename Fun>
  5560. TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
  5561. return Detail::measure<Clock>(fun, iters);
  5562. }
  5563. template <typename Clock, typename Fun>
  5564. TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
  5565. Detail::ChronometerModel<Clock> meter;
  5566. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5567. return { meter.elapsed(), std::move(result), iters };
  5568. }
  5569. template <typename Clock, typename Fun>
  5570. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5571. struct optimized_away_error : std::exception {
  5572. const char* what() const noexcept override {
  5573. return "could not measure benchmark, maybe it was optimized away";
  5574. }
  5575. };
  5576. template <typename Clock, typename Fun>
  5577. TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5578. auto iters = seed;
  5579. while (iters < (1 << 30)) {
  5580. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5581. if (Timing.elapsed >= how_long) {
  5582. return { Timing.elapsed, std::move(Timing.result), iters };
  5583. }
  5584. iters *= 2;
  5585. }
  5586. throw optimized_away_error{};
  5587. }
  5588. } // namespace Detail
  5589. } // namespace Benchmark
  5590. } // namespace Catch
  5591. // end catch_run_for_at_least.hpp
  5592. #include <algorithm>
  5593. namespace Catch {
  5594. namespace Benchmark {
  5595. template <typename Duration>
  5596. struct ExecutionPlan {
  5597. int iterations_per_sample;
  5598. Duration estimated_duration;
  5599. Detail::BenchmarkFunction benchmark;
  5600. Duration warmup_time;
  5601. int warmup_iterations;
  5602. template <typename Duration2>
  5603. operator ExecutionPlan<Duration2>() const {
  5604. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5605. }
  5606. template <typename Clock>
  5607. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5608. // warmup a bit
  5609. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5610. std::vector<FloatDuration<Clock>> times;
  5611. times.reserve(cfg.benchmarkSamples());
  5612. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5613. Detail::ChronometerModel<Clock> model;
  5614. this->benchmark(Chronometer(model, iterations_per_sample));
  5615. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5616. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5617. return sample_time / iterations_per_sample;
  5618. });
  5619. return times;
  5620. }
  5621. };
  5622. } // namespace Benchmark
  5623. } // namespace Catch
  5624. // end catch_execution_plan.hpp
  5625. // start catch_estimate_clock.hpp
  5626. // Environment measurement
  5627. // start catch_stats.hpp
  5628. // Statistical analysis tools
  5629. #include <algorithm>
  5630. #include <functional>
  5631. #include <vector>
  5632. #include <iterator>
  5633. #include <numeric>
  5634. #include <tuple>
  5635. #include <cmath>
  5636. #include <utility>
  5637. #include <cstddef>
  5638. #include <random>
  5639. namespace Catch {
  5640. namespace Benchmark {
  5641. namespace Detail {
  5642. using sample = std::vector<double>;
  5643. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5644. template <typename Iterator>
  5645. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5646. std::vector<double> copy(first, last);
  5647. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5648. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5649. auto iqr = q3 - q1;
  5650. auto los = q1 - (iqr * 3.);
  5651. auto lom = q1 - (iqr * 1.5);
  5652. auto him = q3 + (iqr * 1.5);
  5653. auto his = q3 + (iqr * 3.);
  5654. OutlierClassification o;
  5655. for (; first != last; ++first) {
  5656. auto&& t = *first;
  5657. if (t < los) ++o.low_severe;
  5658. else if (t < lom) ++o.low_mild;
  5659. else if (t > his) ++o.high_severe;
  5660. else if (t > him) ++o.high_mild;
  5661. ++o.samples_seen;
  5662. }
  5663. return o;
  5664. }
  5665. template <typename Iterator>
  5666. double mean(Iterator first, Iterator last) {
  5667. auto count = last - first;
  5668. double sum = std::accumulate(first, last, 0.);
  5669. return sum / count;
  5670. }
  5671. template <typename URng, typename Iterator, typename Estimator>
  5672. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5673. auto n = last - first;
  5674. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5675. sample out;
  5676. out.reserve(resamples);
  5677. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5678. std::vector<double> resampled;
  5679. resampled.reserve(n);
  5680. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5681. return estimator(resampled.begin(), resampled.end());
  5682. });
  5683. std::sort(out.begin(), out.end());
  5684. return out;
  5685. }
  5686. template <typename Estimator, typename Iterator>
  5687. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5688. auto n = last - first;
  5689. auto second = std::next(first);
  5690. sample results;
  5691. results.reserve(n);
  5692. for (auto it = first; it != last; ++it) {
  5693. std::iter_swap(it, first);
  5694. results.push_back(estimator(second, last));
  5695. }
  5696. return results;
  5697. }
  5698. inline double normal_cdf(double x) {
  5699. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5700. }
  5701. double erfc_inv(double x);
  5702. double normal_quantile(double p);
  5703. template <typename Iterator, typename Estimator>
  5704. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5705. auto n_samples = last - first;
  5706. double point = estimator(first, last);
  5707. // Degenerate case with a single sample
  5708. if (n_samples == 1) return { point, point, point, confidence_level };
  5709. sample jack = jackknife(estimator, first, last);
  5710. double jack_mean = mean(jack.begin(), jack.end());
  5711. double sum_squares, sum_cubes;
  5712. std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
  5713. auto d = jack_mean - x;
  5714. auto d2 = d * d;
  5715. auto d3 = d2 * d;
  5716. return { sqcb.first + d2, sqcb.second + d3 };
  5717. });
  5718. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5719. int n = static_cast<int>(resample.size());
  5720. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5721. // degenerate case with uniform samples
  5722. if (prob_n == 0) return { point, point, point, confidence_level };
  5723. double bias = normal_quantile(prob_n);
  5724. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5725. auto cumn = [n](double x) -> int {
  5726. return std::lround(normal_cdf(x) * n); };
  5727. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5728. double b1 = bias + z1;
  5729. double b2 = bias - z1;
  5730. double a1 = a(b1);
  5731. double a2 = a(b2);
  5732. auto lo = std::max(cumn(a1), 0);
  5733. auto hi = std::min(cumn(a2), n - 1);
  5734. return { point, resample[lo], resample[hi], confidence_level };
  5735. }
  5736. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5737. struct bootstrap_analysis {
  5738. Estimate<double> mean;
  5739. Estimate<double> standard_deviation;
  5740. double outlier_variance;
  5741. };
  5742. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5743. } // namespace Detail
  5744. } // namespace Benchmark
  5745. } // namespace Catch
  5746. // end catch_stats.hpp
  5747. #include <algorithm>
  5748. #include <iterator>
  5749. #include <tuple>
  5750. #include <vector>
  5751. #include <cmath>
  5752. namespace Catch {
  5753. namespace Benchmark {
  5754. namespace Detail {
  5755. template <typename Clock>
  5756. std::vector<double> resolution(int k) {
  5757. std::vector<TimePoint<Clock>> times;
  5758. times.reserve(k + 1);
  5759. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5760. std::vector<double> deltas;
  5761. deltas.reserve(k);
  5762. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5763. std::back_inserter(deltas),
  5764. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5765. return deltas;
  5766. }
  5767. const auto warmup_iterations = 10000;
  5768. const auto warmup_time = std::chrono::milliseconds(100);
  5769. const auto minimum_ticks = 1000;
  5770. const auto warmup_seed = 10000;
  5771. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5772. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5773. const auto clock_cost_estimation_tick_limit = 100000;
  5774. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5775. const auto clock_cost_estimation_iterations = 10000;
  5776. template <typename Clock>
  5777. int warmup() {
  5778. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5779. .iterations;
  5780. }
  5781. template <typename Clock>
  5782. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5783. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5784. .result;
  5785. return {
  5786. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5787. classify_outliers(r.begin(), r.end()),
  5788. };
  5789. }
  5790. template <typename Clock>
  5791. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5792. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5793. auto time_clock = [](int k) {
  5794. return Detail::measure<Clock>([k] {
  5795. for (int i = 0; i < k; ++i) {
  5796. volatile auto ignored = Clock::now();
  5797. (void)ignored;
  5798. }
  5799. }).elapsed;
  5800. };
  5801. time_clock(1);
  5802. int iters = clock_cost_estimation_iterations;
  5803. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5804. std::vector<double> times;
  5805. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5806. times.reserve(nsamples);
  5807. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5808. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5809. });
  5810. return {
  5811. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5812. classify_outliers(times.begin(), times.end()),
  5813. };
  5814. }
  5815. template <typename Clock>
  5816. Environment<FloatDuration<Clock>> measure_environment() {
  5817. static Environment<FloatDuration<Clock>>* env = nullptr;
  5818. if (env) {
  5819. return *env;
  5820. }
  5821. auto iters = Detail::warmup<Clock>();
  5822. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5823. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5824. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5825. return *env;
  5826. }
  5827. } // namespace Detail
  5828. } // namespace Benchmark
  5829. } // namespace Catch
  5830. // end catch_estimate_clock.hpp
  5831. // start catch_analyse.hpp
  5832. // Run and analyse one benchmark
  5833. // start catch_sample_analysis.hpp
  5834. // Benchmark results
  5835. #include <algorithm>
  5836. #include <vector>
  5837. #include <string>
  5838. #include <iterator>
  5839. namespace Catch {
  5840. namespace Benchmark {
  5841. template <typename Duration>
  5842. struct SampleAnalysis {
  5843. std::vector<Duration> samples;
  5844. Estimate<Duration> mean;
  5845. Estimate<Duration> standard_deviation;
  5846. OutlierClassification outliers;
  5847. double outlier_variance;
  5848. template <typename Duration2>
  5849. operator SampleAnalysis<Duration2>() const {
  5850. std::vector<Duration2> samples2;
  5851. samples2.reserve(samples.size());
  5852. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5853. return {
  5854. std::move(samples2),
  5855. mean,
  5856. standard_deviation,
  5857. outliers,
  5858. outlier_variance,
  5859. };
  5860. }
  5861. };
  5862. } // namespace Benchmark
  5863. } // namespace Catch
  5864. // end catch_sample_analysis.hpp
  5865. #include <algorithm>
  5866. #include <iterator>
  5867. #include <vector>
  5868. namespace Catch {
  5869. namespace Benchmark {
  5870. namespace Detail {
  5871. template <typename Duration, typename Iterator>
  5872. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5873. if (!cfg.benchmarkNoAnalysis()) {
  5874. std::vector<double> samples;
  5875. samples.reserve(last - first);
  5876. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5877. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5878. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5879. auto wrap_estimate = [](Estimate<double> e) {
  5880. return Estimate<Duration> {
  5881. Duration(e.point),
  5882. Duration(e.lower_bound),
  5883. Duration(e.upper_bound),
  5884. e.confidence_interval,
  5885. };
  5886. };
  5887. std::vector<Duration> samples2;
  5888. samples2.reserve(samples.size());
  5889. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5890. return {
  5891. std::move(samples2),
  5892. wrap_estimate(analysis.mean),
  5893. wrap_estimate(analysis.standard_deviation),
  5894. outliers,
  5895. analysis.outlier_variance,
  5896. };
  5897. } else {
  5898. std::vector<Duration> samples;
  5899. samples.reserve(last - first);
  5900. Duration mean = Duration(0);
  5901. int i = 0;
  5902. for (auto it = first; it < last; ++it, ++i) {
  5903. samples.push_back(Duration(*it));
  5904. mean += Duration(*it);
  5905. }
  5906. mean /= i;
  5907. return {
  5908. std::move(samples),
  5909. Estimate<Duration>{mean, mean, mean, 0.0},
  5910. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5911. OutlierClassification{},
  5912. 0.0
  5913. };
  5914. }
  5915. }
  5916. } // namespace Detail
  5917. } // namespace Benchmark
  5918. } // namespace Catch
  5919. // end catch_analyse.hpp
  5920. #include <algorithm>
  5921. #include <functional>
  5922. #include <string>
  5923. #include <vector>
  5924. #include <cmath>
  5925. namespace Catch {
  5926. namespace Benchmark {
  5927. struct Benchmark {
  5928. Benchmark(std::string &&name)
  5929. : name(std::move(name)) {}
  5930. template <class FUN>
  5931. Benchmark(std::string &&name, FUN &&func)
  5932. : fun(std::move(func)), name(std::move(name)) {}
  5933. template <typename Clock>
  5934. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5935. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5936. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
  5937. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5938. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5939. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
  5940. }
  5941. template <typename Clock = default_clock>
  5942. void run() {
  5943. IConfigPtr cfg = getCurrentContext().getConfig();
  5944. auto env = Detail::measure_environment<Clock>();
  5945. getResultCapture().benchmarkPreparing(name);
  5946. CATCH_TRY{
  5947. auto plan = user_code([&] {
  5948. return prepare<Clock>(*cfg, env);
  5949. });
  5950. BenchmarkInfo info {
  5951. name,
  5952. plan.estimated_duration.count(),
  5953. plan.iterations_per_sample,
  5954. cfg->benchmarkSamples(),
  5955. cfg->benchmarkResamples(),
  5956. env.clock_resolution.mean.count(),
  5957. env.clock_cost.mean.count()
  5958. };
  5959. getResultCapture().benchmarkStarting(info);
  5960. auto samples = user_code([&] {
  5961. return plan.template run<Clock>(*cfg, env);
  5962. });
  5963. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5964. BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5965. getResultCapture().benchmarkEnded(stats);
  5966. } CATCH_CATCH_ALL{
  5967. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5968. std::rethrow_exception(std::current_exception());
  5969. }
  5970. }
  5971. // sets lambda to be used in fun *and* executes benchmark!
  5972. template <typename Fun,
  5973. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5974. Benchmark & operator=(Fun func) {
  5975. fun = Detail::BenchmarkFunction(func);
  5976. run();
  5977. return *this;
  5978. }
  5979. explicit operator bool() {
  5980. return true;
  5981. }
  5982. private:
  5983. Detail::BenchmarkFunction fun;
  5984. std::string name;
  5985. };
  5986. }
  5987. } // namespace Catch
  5988. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5989. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5990. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5991. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5992. BenchmarkName = [&](int benchmarkIndex)
  5993. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5994. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5995. BenchmarkName = [&]
  5996. // end catch_benchmark.hpp
  5997. // start catch_constructor.hpp
  5998. // Constructor and destructor helpers
  5999. #include <type_traits>
  6000. namespace Catch {
  6001. namespace Benchmark {
  6002. namespace Detail {
  6003. template <typename T, bool Destruct>
  6004. struct ObjectStorage
  6005. {
  6006. using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
  6007. ObjectStorage() : data() {}
  6008. ObjectStorage(const ObjectStorage& other)
  6009. {
  6010. new(&data) T(other.stored_object());
  6011. }
  6012. ObjectStorage(ObjectStorage&& other)
  6013. {
  6014. new(&data) T(std::move(other.stored_object()));
  6015. }
  6016. ~ObjectStorage() { destruct_on_exit<T>(); }
  6017. template <typename... Args>
  6018. void construct(Args&&... args)
  6019. {
  6020. new (&data) T(std::forward<Args>(args)...);
  6021. }
  6022. template <bool AllowManualDestruction = !Destruct>
  6023. typename std::enable_if<AllowManualDestruction>::type destruct()
  6024. {
  6025. stored_object().~T();
  6026. }
  6027. private:
  6028. // If this is a constructor benchmark, destruct the underlying object
  6029. template <typename U>
  6030. void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
  6031. // Otherwise, don't
  6032. template <typename U>
  6033. void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
  6034. T& stored_object() {
  6035. return *static_cast<T*>(static_cast<void*>(&data));
  6036. }
  6037. T const& stored_object() const {
  6038. return *static_cast<T*>(static_cast<void*>(&data));
  6039. }
  6040. TStorage data;
  6041. };
  6042. }
  6043. template <typename T>
  6044. using storage_for = Detail::ObjectStorage<T, true>;
  6045. template <typename T>
  6046. using destructable_object = Detail::ObjectStorage<T, false>;
  6047. }
  6048. }
  6049. // end catch_constructor.hpp
  6050. // end catch_benchmarking_all.hpp
  6051. #endif
  6052. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6053. #ifdef CATCH_IMPL
  6054. // start catch_impl.hpp
  6055. #ifdef __clang__
  6056. #pragma clang diagnostic push
  6057. #pragma clang diagnostic ignored "-Wweak-vtables"
  6058. #endif
  6059. // Keep these here for external reporters
  6060. // start catch_test_case_tracker.h
  6061. #include <string>
  6062. #include <vector>
  6063. #include <memory>
  6064. namespace Catch {
  6065. namespace TestCaseTracking {
  6066. struct NameAndLocation {
  6067. std::string name;
  6068. SourceLineInfo location;
  6069. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6070. friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
  6071. return lhs.name == rhs.name
  6072. && lhs.location == rhs.location;
  6073. }
  6074. };
  6075. class ITracker;
  6076. using ITrackerPtr = std::shared_ptr<ITracker>;
  6077. class ITracker {
  6078. NameAndLocation m_nameAndLocation;
  6079. public:
  6080. ITracker(NameAndLocation const& nameAndLoc) :
  6081. m_nameAndLocation(nameAndLoc)
  6082. {}
  6083. // static queries
  6084. NameAndLocation const& nameAndLocation() const {
  6085. return m_nameAndLocation;
  6086. }
  6087. virtual ~ITracker();
  6088. // dynamic queries
  6089. virtual bool isComplete() const = 0; // Successfully completed or failed
  6090. virtual bool isSuccessfullyCompleted() const = 0;
  6091. virtual bool isOpen() const = 0; // Started but not complete
  6092. virtual bool hasChildren() const = 0;
  6093. virtual bool hasStarted() const = 0;
  6094. virtual ITracker& parent() = 0;
  6095. // actions
  6096. virtual void close() = 0; // Successfully complete
  6097. virtual void fail() = 0;
  6098. virtual void markAsNeedingAnotherRun() = 0;
  6099. virtual void addChild( ITrackerPtr const& child ) = 0;
  6100. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6101. virtual void openChild() = 0;
  6102. // Debug/ checking
  6103. virtual bool isSectionTracker() const = 0;
  6104. virtual bool isGeneratorTracker() const = 0;
  6105. };
  6106. class TrackerContext {
  6107. enum RunState {
  6108. NotStarted,
  6109. Executing,
  6110. CompletedCycle
  6111. };
  6112. ITrackerPtr m_rootTracker;
  6113. ITracker* m_currentTracker = nullptr;
  6114. RunState m_runState = NotStarted;
  6115. public:
  6116. ITracker& startRun();
  6117. void endRun();
  6118. void startCycle();
  6119. void completeCycle();
  6120. bool completedCycle() const;
  6121. ITracker& currentTracker();
  6122. void setCurrentTracker( ITracker* tracker );
  6123. };
  6124. class TrackerBase : public ITracker {
  6125. protected:
  6126. enum CycleState {
  6127. NotStarted,
  6128. Executing,
  6129. ExecutingChildren,
  6130. NeedsAnotherRun,
  6131. CompletedSuccessfully,
  6132. Failed
  6133. };
  6134. using Children = std::vector<ITrackerPtr>;
  6135. TrackerContext& m_ctx;
  6136. ITracker* m_parent;
  6137. Children m_children;
  6138. CycleState m_runState = NotStarted;
  6139. public:
  6140. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6141. bool isComplete() const override;
  6142. bool isSuccessfullyCompleted() const override;
  6143. bool isOpen() const override;
  6144. bool hasChildren() const override;
  6145. bool hasStarted() const override {
  6146. return m_runState != NotStarted;
  6147. }
  6148. void addChild( ITrackerPtr const& child ) override;
  6149. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6150. ITracker& parent() override;
  6151. void openChild() override;
  6152. bool isSectionTracker() const override;
  6153. bool isGeneratorTracker() const override;
  6154. void open();
  6155. void close() override;
  6156. void fail() override;
  6157. void markAsNeedingAnotherRun() override;
  6158. private:
  6159. void moveToParent();
  6160. void moveToThis();
  6161. };
  6162. class SectionTracker : public TrackerBase {
  6163. std::vector<std::string> m_filters;
  6164. std::string m_trimmed_name;
  6165. public:
  6166. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6167. bool isSectionTracker() const override;
  6168. bool isComplete() const override;
  6169. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6170. void tryOpen();
  6171. void addInitialFilters( std::vector<std::string> const& filters );
  6172. void addNextFilters( std::vector<std::string> const& filters );
  6173. };
  6174. } // namespace TestCaseTracking
  6175. using TestCaseTracking::ITracker;
  6176. using TestCaseTracking::TrackerContext;
  6177. using TestCaseTracking::SectionTracker;
  6178. } // namespace Catch
  6179. // end catch_test_case_tracker.h
  6180. // start catch_leak_detector.h
  6181. namespace Catch {
  6182. struct LeakDetector {
  6183. LeakDetector();
  6184. ~LeakDetector();
  6185. };
  6186. }
  6187. // end catch_leak_detector.h
  6188. // Cpp files will be included in the single-header file here
  6189. // start catch_stats.cpp
  6190. // Statistical analysis tools
  6191. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6192. #include <cassert>
  6193. #include <random>
  6194. #if defined(CATCH_CONFIG_USE_ASYNC)
  6195. #include <future>
  6196. #endif
  6197. namespace {
  6198. double erf_inv(double x) {
  6199. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6200. double w, p;
  6201. w = -log((1.0 - x) * (1.0 + x));
  6202. if (w < 6.250000) {
  6203. w = w - 3.125000;
  6204. p = -3.6444120640178196996e-21;
  6205. p = -1.685059138182016589e-19 + p * w;
  6206. p = 1.2858480715256400167e-18 + p * w;
  6207. p = 1.115787767802518096e-17 + p * w;
  6208. p = -1.333171662854620906e-16 + p * w;
  6209. p = 2.0972767875968561637e-17 + p * w;
  6210. p = 6.6376381343583238325e-15 + p * w;
  6211. p = -4.0545662729752068639e-14 + p * w;
  6212. p = -8.1519341976054721522e-14 + p * w;
  6213. p = 2.6335093153082322977e-12 + p * w;
  6214. p = -1.2975133253453532498e-11 + p * w;
  6215. p = -5.4154120542946279317e-11 + p * w;
  6216. p = 1.051212273321532285e-09 + p * w;
  6217. p = -4.1126339803469836976e-09 + p * w;
  6218. p = -2.9070369957882005086e-08 + p * w;
  6219. p = 4.2347877827932403518e-07 + p * w;
  6220. p = -1.3654692000834678645e-06 + p * w;
  6221. p = -1.3882523362786468719e-05 + p * w;
  6222. p = 0.0001867342080340571352 + p * w;
  6223. p = -0.00074070253416626697512 + p * w;
  6224. p = -0.0060336708714301490533 + p * w;
  6225. p = 0.24015818242558961693 + p * w;
  6226. p = 1.6536545626831027356 + p * w;
  6227. } else if (w < 16.000000) {
  6228. w = sqrt(w) - 3.250000;
  6229. p = 2.2137376921775787049e-09;
  6230. p = 9.0756561938885390979e-08 + p * w;
  6231. p = -2.7517406297064545428e-07 + p * w;
  6232. p = 1.8239629214389227755e-08 + p * w;
  6233. p = 1.5027403968909827627e-06 + p * w;
  6234. p = -4.013867526981545969e-06 + p * w;
  6235. p = 2.9234449089955446044e-06 + p * w;
  6236. p = 1.2475304481671778723e-05 + p * w;
  6237. p = -4.7318229009055733981e-05 + p * w;
  6238. p = 6.8284851459573175448e-05 + p * w;
  6239. p = 2.4031110387097893999e-05 + p * w;
  6240. p = -0.0003550375203628474796 + p * w;
  6241. p = 0.00095328937973738049703 + p * w;
  6242. p = -0.0016882755560235047313 + p * w;
  6243. p = 0.0024914420961078508066 + p * w;
  6244. p = -0.0037512085075692412107 + p * w;
  6245. p = 0.005370914553590063617 + p * w;
  6246. p = 1.0052589676941592334 + p * w;
  6247. p = 3.0838856104922207635 + p * w;
  6248. } else {
  6249. w = sqrt(w) - 5.000000;
  6250. p = -2.7109920616438573243e-11;
  6251. p = -2.5556418169965252055e-10 + p * w;
  6252. p = 1.5076572693500548083e-09 + p * w;
  6253. p = -3.7894654401267369937e-09 + p * w;
  6254. p = 7.6157012080783393804e-09 + p * w;
  6255. p = -1.4960026627149240478e-08 + p * w;
  6256. p = 2.9147953450901080826e-08 + p * w;
  6257. p = -6.7711997758452339498e-08 + p * w;
  6258. p = 2.2900482228026654717e-07 + p * w;
  6259. p = -9.9298272942317002539e-07 + p * w;
  6260. p = 4.5260625972231537039e-06 + p * w;
  6261. p = -1.9681778105531670567e-05 + p * w;
  6262. p = 7.5995277030017761139e-05 + p * w;
  6263. p = -0.00021503011930044477347 + p * w;
  6264. p = -0.00013871931833623122026 + p * w;
  6265. p = 1.0103004648645343977 + p * w;
  6266. p = 4.8499064014085844221 + p * w;
  6267. }
  6268. return p * x;
  6269. }
  6270. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6271. auto m = Catch::Benchmark::Detail::mean(first, last);
  6272. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6273. double diff = b - m;
  6274. return a + diff * diff;
  6275. }) / (last - first);
  6276. return std::sqrt(variance);
  6277. }
  6278. }
  6279. namespace Catch {
  6280. namespace Benchmark {
  6281. namespace Detail {
  6282. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6283. auto count = last - first;
  6284. double idx = (count - 1) * k / static_cast<double>(q);
  6285. int j = static_cast<int>(idx);
  6286. double g = idx - j;
  6287. std::nth_element(first, first + j, last);
  6288. auto xj = first[j];
  6289. if (g == 0) return xj;
  6290. auto xj1 = *std::min_element(first + (j + 1), last);
  6291. return xj + g * (xj1 - xj);
  6292. }
  6293. double erfc_inv(double x) {
  6294. return erf_inv(1.0 - x);
  6295. }
  6296. double normal_quantile(double p) {
  6297. static const double ROOT_TWO = std::sqrt(2.0);
  6298. double result = 0.0;
  6299. assert(p >= 0 && p <= 1);
  6300. if (p < 0 || p > 1) {
  6301. return result;
  6302. }
  6303. result = -erfc_inv(2.0 * p);
  6304. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6305. result *= /*sd * */ ROOT_TWO;
  6306. // result += normal disttribution mean (0)
  6307. return result;
  6308. }
  6309. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6310. double sb = stddev.point;
  6311. double mn = mean.point / n;
  6312. double mg_min = mn / 2.;
  6313. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6314. double sg2 = sg * sg;
  6315. double sb2 = sb * sb;
  6316. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6317. double k = mn - x;
  6318. double d = k * k;
  6319. double nd = n * d;
  6320. double k0 = -n * nd;
  6321. double k1 = sb2 - n * sg2 + nd;
  6322. double det = k1 * k1 - 4 * sg2 * k0;
  6323. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6324. };
  6325. auto var_out = [n, sb2, sg2](double c) {
  6326. double nc = n - c;
  6327. return (nc / n) * (sb2 - nc * sg2);
  6328. };
  6329. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6330. }
  6331. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6332. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  6333. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6334. static std::random_device entropy;
  6335. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  6336. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6337. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6338. auto stddev = &standard_deviation;
  6339. #if defined(CATCH_CONFIG_USE_ASYNC)
  6340. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6341. auto seed = entropy();
  6342. return std::async(std::launch::async, [=] {
  6343. std::mt19937 rng(seed);
  6344. auto resampled = resample(rng, n_resamples, first, last, f);
  6345. return bootstrap(confidence_level, first, last, resampled, f);
  6346. });
  6347. };
  6348. auto mean_future = Estimate(mean);
  6349. auto stddev_future = Estimate(stddev);
  6350. auto mean_estimate = mean_future.get();
  6351. auto stddev_estimate = stddev_future.get();
  6352. #else
  6353. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6354. auto seed = entropy();
  6355. std::mt19937 rng(seed);
  6356. auto resampled = resample(rng, n_resamples, first, last, f);
  6357. return bootstrap(confidence_level, first, last, resampled, f);
  6358. };
  6359. auto mean_estimate = Estimate(mean);
  6360. auto stddev_estimate = Estimate(stddev);
  6361. #endif // CATCH_USE_ASYNC
  6362. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6363. return { mean_estimate, stddev_estimate, outlier_variance };
  6364. }
  6365. } // namespace Detail
  6366. } // namespace Benchmark
  6367. } // namespace Catch
  6368. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6369. // end catch_stats.cpp
  6370. // start catch_approx.cpp
  6371. #include <cmath>
  6372. #include <limits>
  6373. namespace {
  6374. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6375. // But without the subtraction to allow for INFINITY in comparison
  6376. bool marginComparison(double lhs, double rhs, double margin) {
  6377. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6378. }
  6379. }
  6380. namespace Catch {
  6381. namespace Detail {
  6382. Approx::Approx ( double value )
  6383. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6384. m_margin( 0.0 ),
  6385. m_scale( 0.0 ),
  6386. m_value( value )
  6387. {}
  6388. Approx Approx::custom() {
  6389. return Approx( 0 );
  6390. }
  6391. Approx Approx::operator-() const {
  6392. auto temp(*this);
  6393. temp.m_value = -temp.m_value;
  6394. return temp;
  6395. }
  6396. std::string Approx::toString() const {
  6397. ReusableStringStream rss;
  6398. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6399. return rss.str();
  6400. }
  6401. bool Approx::equalityComparisonImpl(const double other) const {
  6402. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6403. // Thanks to Richard Harris for his help refining the scaled margin value
  6404. return marginComparison(m_value, other, m_margin)
  6405. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  6406. }
  6407. void Approx::setMargin(double newMargin) {
  6408. CATCH_ENFORCE(newMargin >= 0,
  6409. "Invalid Approx::margin: " << newMargin << '.'
  6410. << " Approx::Margin has to be non-negative.");
  6411. m_margin = newMargin;
  6412. }
  6413. void Approx::setEpsilon(double newEpsilon) {
  6414. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6415. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6416. << " Approx::epsilon has to be in [0, 1]");
  6417. m_epsilon = newEpsilon;
  6418. }
  6419. } // end namespace Detail
  6420. namespace literals {
  6421. Detail::Approx operator "" _a(long double val) {
  6422. return Detail::Approx(val);
  6423. }
  6424. Detail::Approx operator "" _a(unsigned long long val) {
  6425. return Detail::Approx(val);
  6426. }
  6427. } // end namespace literals
  6428. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6429. return value.toString();
  6430. }
  6431. } // end namespace Catch
  6432. // end catch_approx.cpp
  6433. // start catch_assertionhandler.cpp
  6434. // start catch_debugger.h
  6435. namespace Catch {
  6436. bool isDebuggerActive();
  6437. }
  6438. #ifdef CATCH_PLATFORM_MAC
  6439. #if defined(__i386__) || defined(__x86_64__)
  6440. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6441. #elif defined(__aarch64__)
  6442. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6443. #endif
  6444. #elif defined(CATCH_PLATFORM_IPHONE)
  6445. // use inline assembler
  6446. #if defined(__i386__) || defined(__x86_64__)
  6447. #define CATCH_TRAP() __asm__("int $3")
  6448. #elif defined(__aarch64__)
  6449. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6450. #elif defined(__arm__) && !defined(__thumb__)
  6451. #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
  6452. #elif defined(__arm__) && defined(__thumb__)
  6453. #define CATCH_TRAP() __asm__(".inst 0xde01")
  6454. #endif
  6455. #elif defined(CATCH_PLATFORM_LINUX)
  6456. // If we can use inline assembler, do it because this allows us to break
  6457. // directly at the location of the failing check instead of breaking inside
  6458. // raise() called from it, i.e. one stack frame below.
  6459. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6460. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6461. #else // Fall back to the generic way.
  6462. #include <signal.h>
  6463. #define CATCH_TRAP() raise(SIGTRAP)
  6464. #endif
  6465. #elif defined(_MSC_VER)
  6466. #define CATCH_TRAP() __debugbreak()
  6467. #elif defined(__MINGW32__)
  6468. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6469. #define CATCH_TRAP() DebugBreak()
  6470. #endif
  6471. #ifndef CATCH_BREAK_INTO_DEBUGGER
  6472. #ifdef CATCH_TRAP
  6473. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6474. #else
  6475. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6476. #endif
  6477. #endif
  6478. // end catch_debugger.h
  6479. // start catch_run_context.h
  6480. // start catch_fatal_condition.h
  6481. // start catch_windows_h_proxy.h
  6482. #if defined(CATCH_PLATFORM_WINDOWS)
  6483. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6484. # define CATCH_DEFINED_NOMINMAX
  6485. # define NOMINMAX
  6486. #endif
  6487. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6488. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6489. # define WIN32_LEAN_AND_MEAN
  6490. #endif
  6491. #ifdef __AFXDLL
  6492. #include <AfxWin.h>
  6493. #else
  6494. #include <windows.h>
  6495. #endif
  6496. #ifdef CATCH_DEFINED_NOMINMAX
  6497. # undef NOMINMAX
  6498. #endif
  6499. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6500. # undef WIN32_LEAN_AND_MEAN
  6501. #endif
  6502. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6503. // end catch_windows_h_proxy.h
  6504. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6505. namespace Catch {
  6506. struct FatalConditionHandler {
  6507. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6508. FatalConditionHandler();
  6509. static void reset();
  6510. ~FatalConditionHandler();
  6511. private:
  6512. static bool isSet;
  6513. static ULONG guaranteeSize;
  6514. static PVOID exceptionHandlerHandle;
  6515. };
  6516. } // namespace Catch
  6517. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6518. #include <signal.h>
  6519. namespace Catch {
  6520. struct FatalConditionHandler {
  6521. static bool isSet;
  6522. static struct sigaction oldSigActions[];
  6523. static stack_t oldSigStack;
  6524. static char altStackMem[];
  6525. static void handleSignal( int sig );
  6526. FatalConditionHandler();
  6527. ~FatalConditionHandler();
  6528. static void reset();
  6529. };
  6530. } // namespace Catch
  6531. #else
  6532. namespace Catch {
  6533. struct FatalConditionHandler {
  6534. void reset();
  6535. };
  6536. }
  6537. #endif
  6538. // end catch_fatal_condition.h
  6539. #include <string>
  6540. namespace Catch {
  6541. struct IMutableContext;
  6542. ///////////////////////////////////////////////////////////////////////////
  6543. class RunContext : public IResultCapture, public IRunner {
  6544. public:
  6545. RunContext( RunContext const& ) = delete;
  6546. RunContext& operator =( RunContext const& ) = delete;
  6547. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6548. ~RunContext() override;
  6549. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6550. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6551. Totals runTest(TestCase const& testCase);
  6552. IConfigPtr config() const;
  6553. IStreamingReporter& reporter() const;
  6554. public: // IResultCapture
  6555. // Assertion handlers
  6556. void handleExpr
  6557. ( AssertionInfo const& info,
  6558. ITransientExpression const& expr,
  6559. AssertionReaction& reaction ) override;
  6560. void handleMessage
  6561. ( AssertionInfo const& info,
  6562. ResultWas::OfType resultType,
  6563. StringRef const& message,
  6564. AssertionReaction& reaction ) override;
  6565. void handleUnexpectedExceptionNotThrown
  6566. ( AssertionInfo const& info,
  6567. AssertionReaction& reaction ) override;
  6568. void handleUnexpectedInflightException
  6569. ( AssertionInfo const& info,
  6570. std::string const& message,
  6571. AssertionReaction& reaction ) override;
  6572. void handleIncomplete
  6573. ( AssertionInfo const& info ) override;
  6574. void handleNonExpr
  6575. ( AssertionInfo const &info,
  6576. ResultWas::OfType resultType,
  6577. AssertionReaction &reaction ) override;
  6578. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6579. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6580. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6581. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6582. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6583. void benchmarkPreparing( std::string const& name ) override;
  6584. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6585. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6586. void benchmarkFailed( std::string const& error ) override;
  6587. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6588. void pushScopedMessage( MessageInfo const& message ) override;
  6589. void popScopedMessage( MessageInfo const& message ) override;
  6590. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6591. std::string getCurrentTestName() const override;
  6592. const AssertionResult* getLastResult() const override;
  6593. void exceptionEarlyReported() override;
  6594. void handleFatalErrorCondition( StringRef message ) override;
  6595. bool lastAssertionPassed() override;
  6596. void assertionPassed() override;
  6597. public:
  6598. // !TBD We need to do this another way!
  6599. bool aborting() const final;
  6600. private:
  6601. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6602. void invokeActiveTestCase();
  6603. void resetAssertionInfo();
  6604. bool testForMissingAssertions( Counts& assertions );
  6605. void assertionEnded( AssertionResult const& result );
  6606. void reportExpr
  6607. ( AssertionInfo const &info,
  6608. ResultWas::OfType resultType,
  6609. ITransientExpression const *expr,
  6610. bool negated );
  6611. void populateReaction( AssertionReaction& reaction );
  6612. private:
  6613. void handleUnfinishedSections();
  6614. TestRunInfo m_runInfo;
  6615. IMutableContext& m_context;
  6616. TestCase const* m_activeTestCase = nullptr;
  6617. ITracker* m_testCaseTracker = nullptr;
  6618. Option<AssertionResult> m_lastResult;
  6619. IConfigPtr m_config;
  6620. Totals m_totals;
  6621. IStreamingReporterPtr m_reporter;
  6622. std::vector<MessageInfo> m_messages;
  6623. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6624. AssertionInfo m_lastAssertionInfo;
  6625. std::vector<SectionEndInfo> m_unfinishedSections;
  6626. std::vector<ITracker*> m_activeSections;
  6627. TrackerContext m_trackerContext;
  6628. bool m_lastAssertionPassed = false;
  6629. bool m_shouldReportUnexpected = true;
  6630. bool m_includeSuccessfulResults;
  6631. };
  6632. void seedRng(IConfig const& config);
  6633. unsigned int rngSeed();
  6634. } // end namespace Catch
  6635. // end catch_run_context.h
  6636. namespace Catch {
  6637. namespace {
  6638. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6639. expr.streamReconstructedExpression( os );
  6640. return os;
  6641. }
  6642. }
  6643. LazyExpression::LazyExpression( bool isNegated )
  6644. : m_isNegated( isNegated )
  6645. {}
  6646. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6647. LazyExpression::operator bool() const {
  6648. return m_transientExpression != nullptr;
  6649. }
  6650. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6651. if( lazyExpr.m_isNegated )
  6652. os << "!";
  6653. if( lazyExpr ) {
  6654. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6655. os << "(" << *lazyExpr.m_transientExpression << ")";
  6656. else
  6657. os << *lazyExpr.m_transientExpression;
  6658. }
  6659. else {
  6660. os << "{** error - unchecked empty expression requested **}";
  6661. }
  6662. return os;
  6663. }
  6664. AssertionHandler::AssertionHandler
  6665. ( StringRef const& macroName,
  6666. SourceLineInfo const& lineInfo,
  6667. StringRef capturedExpression,
  6668. ResultDisposition::Flags resultDisposition )
  6669. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6670. m_resultCapture( getResultCapture() )
  6671. {}
  6672. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6673. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6674. }
  6675. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6676. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6677. }
  6678. auto AssertionHandler::allowThrows() const -> bool {
  6679. return getCurrentContext().getConfig()->allowThrows();
  6680. }
  6681. void AssertionHandler::complete() {
  6682. setCompleted();
  6683. if( m_reaction.shouldDebugBreak ) {
  6684. // If you find your debugger stopping you here then go one level up on the
  6685. // call-stack for the code that caused it (typically a failed assertion)
  6686. // (To go back to the test and change execution, jump over the throw, next)
  6687. CATCH_BREAK_INTO_DEBUGGER();
  6688. }
  6689. if (m_reaction.shouldThrow) {
  6690. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6691. throw Catch::TestFailureException();
  6692. #else
  6693. CATCH_ERROR( "Test failure requires aborting test!" );
  6694. #endif
  6695. }
  6696. }
  6697. void AssertionHandler::setCompleted() {
  6698. m_completed = true;
  6699. }
  6700. void AssertionHandler::handleUnexpectedInflightException() {
  6701. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6702. }
  6703. void AssertionHandler::handleExceptionThrownAsExpected() {
  6704. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6705. }
  6706. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6707. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6708. }
  6709. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6710. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6711. }
  6712. void AssertionHandler::handleThrowingCallSkipped() {
  6713. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6714. }
  6715. // This is the overload that takes a string and infers the Equals matcher from it
  6716. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6717. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6718. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6719. }
  6720. } // namespace Catch
  6721. // end catch_assertionhandler.cpp
  6722. // start catch_assertionresult.cpp
  6723. namespace Catch {
  6724. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6725. lazyExpression(_lazyExpression),
  6726. resultType(_resultType) {}
  6727. std::string AssertionResultData::reconstructExpression() const {
  6728. if( reconstructedExpression.empty() ) {
  6729. if( lazyExpression ) {
  6730. ReusableStringStream rss;
  6731. rss << lazyExpression;
  6732. reconstructedExpression = rss.str();
  6733. }
  6734. }
  6735. return reconstructedExpression;
  6736. }
  6737. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6738. : m_info( info ),
  6739. m_resultData( data )
  6740. {}
  6741. // Result was a success
  6742. bool AssertionResult::succeeded() const {
  6743. return Catch::isOk( m_resultData.resultType );
  6744. }
  6745. // Result was a success, or failure is suppressed
  6746. bool AssertionResult::isOk() const {
  6747. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6748. }
  6749. ResultWas::OfType AssertionResult::getResultType() const {
  6750. return m_resultData.resultType;
  6751. }
  6752. bool AssertionResult::hasExpression() const {
  6753. return !m_info.capturedExpression.empty();
  6754. }
  6755. bool AssertionResult::hasMessage() const {
  6756. return !m_resultData.message.empty();
  6757. }
  6758. std::string AssertionResult::getExpression() const {
  6759. // Possibly overallocating by 3 characters should be basically free
  6760. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  6761. if (isFalseTest(m_info.resultDisposition)) {
  6762. expr += "!(";
  6763. }
  6764. expr += m_info.capturedExpression;
  6765. if (isFalseTest(m_info.resultDisposition)) {
  6766. expr += ')';
  6767. }
  6768. return expr;
  6769. }
  6770. std::string AssertionResult::getExpressionInMacro() const {
  6771. std::string expr;
  6772. if( m_info.macroName.empty() )
  6773. expr = static_cast<std::string>(m_info.capturedExpression);
  6774. else {
  6775. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6776. expr += m_info.macroName;
  6777. expr += "( ";
  6778. expr += m_info.capturedExpression;
  6779. expr += " )";
  6780. }
  6781. return expr;
  6782. }
  6783. bool AssertionResult::hasExpandedExpression() const {
  6784. return hasExpression() && getExpandedExpression() != getExpression();
  6785. }
  6786. std::string AssertionResult::getExpandedExpression() const {
  6787. std::string expr = m_resultData.reconstructExpression();
  6788. return expr.empty()
  6789. ? getExpression()
  6790. : expr;
  6791. }
  6792. std::string AssertionResult::getMessage() const {
  6793. return m_resultData.message;
  6794. }
  6795. SourceLineInfo AssertionResult::getSourceInfo() const {
  6796. return m_info.lineInfo;
  6797. }
  6798. StringRef AssertionResult::getTestMacroName() const {
  6799. return m_info.macroName;
  6800. }
  6801. } // end namespace Catch
  6802. // end catch_assertionresult.cpp
  6803. // start catch_capture_matchers.cpp
  6804. namespace Catch {
  6805. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6806. // This is the general overload that takes a any string matcher
  6807. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6808. // the Equals matcher (so the header does not mention matchers)
  6809. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6810. std::string exceptionMessage = Catch::translateActiveException();
  6811. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6812. handler.handleExpr( expr );
  6813. }
  6814. } // namespace Catch
  6815. // end catch_capture_matchers.cpp
  6816. // start catch_commandline.cpp
  6817. // start catch_commandline.h
  6818. // start catch_clara.h
  6819. // Use Catch's value for console width (store Clara's off to the side, if present)
  6820. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6821. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6822. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6823. #endif
  6824. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6825. #ifdef __clang__
  6826. #pragma clang diagnostic push
  6827. #pragma clang diagnostic ignored "-Wweak-vtables"
  6828. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6829. #pragma clang diagnostic ignored "-Wshadow"
  6830. #endif
  6831. // start clara.hpp
  6832. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6833. //
  6834. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6835. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6836. //
  6837. // See https://github.com/philsquared/Clara for more details
  6838. // Clara v1.1.5
  6839. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6840. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6841. #endif
  6842. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6843. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6844. #endif
  6845. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6846. #ifdef __has_include
  6847. #if __has_include(<optional>) && __cplusplus >= 201703L
  6848. #include <optional>
  6849. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6850. #endif
  6851. #endif
  6852. #endif
  6853. // ----------- #included from clara_textflow.hpp -----------
  6854. // TextFlowCpp
  6855. //
  6856. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6857. //
  6858. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6859. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6860. //
  6861. // This project is hosted at https://github.com/philsquared/textflowcpp
  6862. #include <cassert>
  6863. #include <ostream>
  6864. #include <sstream>
  6865. #include <vector>
  6866. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6867. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6868. #endif
  6869. namespace Catch {
  6870. namespace clara {
  6871. namespace TextFlow {
  6872. inline auto isWhitespace(char c) -> bool {
  6873. static std::string chars = " \t\n\r";
  6874. return chars.find(c) != std::string::npos;
  6875. }
  6876. inline auto isBreakableBefore(char c) -> bool {
  6877. static std::string chars = "[({<|";
  6878. return chars.find(c) != std::string::npos;
  6879. }
  6880. inline auto isBreakableAfter(char c) -> bool {
  6881. static std::string chars = "])}>.,:;*+-=&/\\";
  6882. return chars.find(c) != std::string::npos;
  6883. }
  6884. class Columns;
  6885. class Column {
  6886. std::vector<std::string> m_strings;
  6887. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6888. size_t m_indent = 0;
  6889. size_t m_initialIndent = std::string::npos;
  6890. public:
  6891. class iterator {
  6892. friend Column;
  6893. Column const& m_column;
  6894. size_t m_stringIndex = 0;
  6895. size_t m_pos = 0;
  6896. size_t m_len = 0;
  6897. size_t m_end = 0;
  6898. bool m_suffix = false;
  6899. iterator(Column const& column, size_t stringIndex)
  6900. : m_column(column),
  6901. m_stringIndex(stringIndex) {}
  6902. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6903. auto isBoundary(size_t at) const -> bool {
  6904. assert(at > 0);
  6905. assert(at <= line().size());
  6906. return at == line().size() ||
  6907. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6908. isBreakableBefore(line()[at]) ||
  6909. isBreakableAfter(line()[at - 1]);
  6910. }
  6911. void calcLength() {
  6912. assert(m_stringIndex < m_column.m_strings.size());
  6913. m_suffix = false;
  6914. auto width = m_column.m_width - indent();
  6915. m_end = m_pos;
  6916. if (line()[m_pos] == '\n') {
  6917. ++m_end;
  6918. }
  6919. while (m_end < line().size() && line()[m_end] != '\n')
  6920. ++m_end;
  6921. if (m_end < m_pos + width) {
  6922. m_len = m_end - m_pos;
  6923. } else {
  6924. size_t len = width;
  6925. while (len > 0 && !isBoundary(m_pos + len))
  6926. --len;
  6927. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6928. --len;
  6929. if (len > 0) {
  6930. m_len = len;
  6931. } else {
  6932. m_suffix = true;
  6933. m_len = width - 1;
  6934. }
  6935. }
  6936. }
  6937. auto indent() const -> size_t {
  6938. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6939. return initial == std::string::npos ? m_column.m_indent : initial;
  6940. }
  6941. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6942. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6943. }
  6944. public:
  6945. using difference_type = std::ptrdiff_t;
  6946. using value_type = std::string;
  6947. using pointer = value_type * ;
  6948. using reference = value_type & ;
  6949. using iterator_category = std::forward_iterator_tag;
  6950. explicit iterator(Column const& column) : m_column(column) {
  6951. assert(m_column.m_width > m_column.m_indent);
  6952. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6953. calcLength();
  6954. if (m_len == 0)
  6955. m_stringIndex++; // Empty string
  6956. }
  6957. auto operator *() const -> std::string {
  6958. assert(m_stringIndex < m_column.m_strings.size());
  6959. assert(m_pos <= m_end);
  6960. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6961. }
  6962. auto operator ++() -> iterator& {
  6963. m_pos += m_len;
  6964. if (m_pos < line().size() && line()[m_pos] == '\n')
  6965. m_pos += 1;
  6966. else
  6967. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6968. ++m_pos;
  6969. if (m_pos == line().size()) {
  6970. m_pos = 0;
  6971. ++m_stringIndex;
  6972. }
  6973. if (m_stringIndex < m_column.m_strings.size())
  6974. calcLength();
  6975. return *this;
  6976. }
  6977. auto operator ++(int) -> iterator {
  6978. iterator prev(*this);
  6979. operator++();
  6980. return prev;
  6981. }
  6982. auto operator ==(iterator const& other) const -> bool {
  6983. return
  6984. m_pos == other.m_pos &&
  6985. m_stringIndex == other.m_stringIndex &&
  6986. &m_column == &other.m_column;
  6987. }
  6988. auto operator !=(iterator const& other) const -> bool {
  6989. return !operator==(other);
  6990. }
  6991. };
  6992. using const_iterator = iterator;
  6993. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6994. auto width(size_t newWidth) -> Column& {
  6995. assert(newWidth > 0);
  6996. m_width = newWidth;
  6997. return *this;
  6998. }
  6999. auto indent(size_t newIndent) -> Column& {
  7000. m_indent = newIndent;
  7001. return *this;
  7002. }
  7003. auto initialIndent(size_t newIndent) -> Column& {
  7004. m_initialIndent = newIndent;
  7005. return *this;
  7006. }
  7007. auto width() const -> size_t { return m_width; }
  7008. auto begin() const -> iterator { return iterator(*this); }
  7009. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7010. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7011. bool first = true;
  7012. for (auto line : col) {
  7013. if (first)
  7014. first = false;
  7015. else
  7016. os << "\n";
  7017. os << line;
  7018. }
  7019. return os;
  7020. }
  7021. auto operator + (Column const& other)->Columns;
  7022. auto toString() const -> std::string {
  7023. std::ostringstream oss;
  7024. oss << *this;
  7025. return oss.str();
  7026. }
  7027. };
  7028. class Spacer : public Column {
  7029. public:
  7030. explicit Spacer(size_t spaceWidth) : Column("") {
  7031. width(spaceWidth);
  7032. }
  7033. };
  7034. class Columns {
  7035. std::vector<Column> m_columns;
  7036. public:
  7037. class iterator {
  7038. friend Columns;
  7039. struct EndTag {};
  7040. std::vector<Column> const& m_columns;
  7041. std::vector<Column::iterator> m_iterators;
  7042. size_t m_activeIterators;
  7043. iterator(Columns const& columns, EndTag)
  7044. : m_columns(columns.m_columns),
  7045. m_activeIterators(0) {
  7046. m_iterators.reserve(m_columns.size());
  7047. for (auto const& col : m_columns)
  7048. m_iterators.push_back(col.end());
  7049. }
  7050. public:
  7051. using difference_type = std::ptrdiff_t;
  7052. using value_type = std::string;
  7053. using pointer = value_type * ;
  7054. using reference = value_type & ;
  7055. using iterator_category = std::forward_iterator_tag;
  7056. explicit iterator(Columns const& columns)
  7057. : m_columns(columns.m_columns),
  7058. m_activeIterators(m_columns.size()) {
  7059. m_iterators.reserve(m_columns.size());
  7060. for (auto const& col : m_columns)
  7061. m_iterators.push_back(col.begin());
  7062. }
  7063. auto operator ==(iterator const& other) const -> bool {
  7064. return m_iterators == other.m_iterators;
  7065. }
  7066. auto operator !=(iterator const& other) const -> bool {
  7067. return m_iterators != other.m_iterators;
  7068. }
  7069. auto operator *() const -> std::string {
  7070. std::string row, padding;
  7071. for (size_t i = 0; i < m_columns.size(); ++i) {
  7072. auto width = m_columns[i].width();
  7073. if (m_iterators[i] != m_columns[i].end()) {
  7074. std::string col = *m_iterators[i];
  7075. row += padding + col;
  7076. if (col.size() < width)
  7077. padding = std::string(width - col.size(), ' ');
  7078. else
  7079. padding = "";
  7080. } else {
  7081. padding += std::string(width, ' ');
  7082. }
  7083. }
  7084. return row;
  7085. }
  7086. auto operator ++() -> iterator& {
  7087. for (size_t i = 0; i < m_columns.size(); ++i) {
  7088. if (m_iterators[i] != m_columns[i].end())
  7089. ++m_iterators[i];
  7090. }
  7091. return *this;
  7092. }
  7093. auto operator ++(int) -> iterator {
  7094. iterator prev(*this);
  7095. operator++();
  7096. return prev;
  7097. }
  7098. };
  7099. using const_iterator = iterator;
  7100. auto begin() const -> iterator { return iterator(*this); }
  7101. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7102. auto operator += (Column const& col) -> Columns& {
  7103. m_columns.push_back(col);
  7104. return *this;
  7105. }
  7106. auto operator + (Column const& col) -> Columns {
  7107. Columns combined = *this;
  7108. combined += col;
  7109. return combined;
  7110. }
  7111. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7112. bool first = true;
  7113. for (auto line : cols) {
  7114. if (first)
  7115. first = false;
  7116. else
  7117. os << "\n";
  7118. os << line;
  7119. }
  7120. return os;
  7121. }
  7122. auto toString() const -> std::string {
  7123. std::ostringstream oss;
  7124. oss << *this;
  7125. return oss.str();
  7126. }
  7127. };
  7128. inline auto Column::operator + (Column const& other) -> Columns {
  7129. Columns cols;
  7130. cols += *this;
  7131. cols += other;
  7132. return cols;
  7133. }
  7134. }
  7135. }
  7136. }
  7137. // ----------- end of #include from clara_textflow.hpp -----------
  7138. // ........... back in clara.hpp
  7139. #include <cctype>
  7140. #include <string>
  7141. #include <memory>
  7142. #include <set>
  7143. #include <algorithm>
  7144. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7145. #define CATCH_PLATFORM_WINDOWS
  7146. #endif
  7147. namespace Catch { namespace clara {
  7148. namespace detail {
  7149. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7150. template<typename L>
  7151. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7152. template<typename ClassT, typename ReturnT, typename... Args>
  7153. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7154. static const bool isValid = false;
  7155. };
  7156. template<typename ClassT, typename ReturnT, typename ArgT>
  7157. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7158. static const bool isValid = true;
  7159. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7160. using ReturnType = ReturnT;
  7161. };
  7162. class TokenStream;
  7163. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7164. class Args {
  7165. friend TokenStream;
  7166. std::string m_exeName;
  7167. std::vector<std::string> m_args;
  7168. public:
  7169. Args( int argc, char const* const* argv )
  7170. : m_exeName(argv[0]),
  7171. m_args(argv + 1, argv + argc) {}
  7172. Args( std::initializer_list<std::string> args )
  7173. : m_exeName( *args.begin() ),
  7174. m_args( args.begin()+1, args.end() )
  7175. {}
  7176. auto exeName() const -> std::string {
  7177. return m_exeName;
  7178. }
  7179. };
  7180. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7181. // may encode an option + its argument if the : or = form is used
  7182. enum class TokenType {
  7183. Option, Argument
  7184. };
  7185. struct Token {
  7186. TokenType type;
  7187. std::string token;
  7188. };
  7189. inline auto isOptPrefix( char c ) -> bool {
  7190. return c == '-'
  7191. #ifdef CATCH_PLATFORM_WINDOWS
  7192. || c == '/'
  7193. #endif
  7194. ;
  7195. }
  7196. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7197. class TokenStream {
  7198. using Iterator = std::vector<std::string>::const_iterator;
  7199. Iterator it;
  7200. Iterator itEnd;
  7201. std::vector<Token> m_tokenBuffer;
  7202. void loadBuffer() {
  7203. m_tokenBuffer.resize( 0 );
  7204. // Skip any empty strings
  7205. while( it != itEnd && it->empty() )
  7206. ++it;
  7207. if( it != itEnd ) {
  7208. auto const &next = *it;
  7209. if( isOptPrefix( next[0] ) ) {
  7210. auto delimiterPos = next.find_first_of( " :=" );
  7211. if( delimiterPos != std::string::npos ) {
  7212. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7213. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7214. } else {
  7215. if( next[1] != '-' && next.size() > 2 ) {
  7216. std::string opt = "- ";
  7217. for( size_t i = 1; i < next.size(); ++i ) {
  7218. opt[1] = next[i];
  7219. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7220. }
  7221. } else {
  7222. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7223. }
  7224. }
  7225. } else {
  7226. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7227. }
  7228. }
  7229. }
  7230. public:
  7231. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7232. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7233. loadBuffer();
  7234. }
  7235. explicit operator bool() const {
  7236. return !m_tokenBuffer.empty() || it != itEnd;
  7237. }
  7238. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7239. auto operator*() const -> Token {
  7240. assert( !m_tokenBuffer.empty() );
  7241. return m_tokenBuffer.front();
  7242. }
  7243. auto operator->() const -> Token const * {
  7244. assert( !m_tokenBuffer.empty() );
  7245. return &m_tokenBuffer.front();
  7246. }
  7247. auto operator++() -> TokenStream & {
  7248. if( m_tokenBuffer.size() >= 2 ) {
  7249. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7250. } else {
  7251. if( it != itEnd )
  7252. ++it;
  7253. loadBuffer();
  7254. }
  7255. return *this;
  7256. }
  7257. };
  7258. class ResultBase {
  7259. public:
  7260. enum Type {
  7261. Ok, LogicError, RuntimeError
  7262. };
  7263. protected:
  7264. ResultBase( Type type ) : m_type( type ) {}
  7265. virtual ~ResultBase() = default;
  7266. virtual void enforceOk() const = 0;
  7267. Type m_type;
  7268. };
  7269. template<typename T>
  7270. class ResultValueBase : public ResultBase {
  7271. public:
  7272. auto value() const -> T const & {
  7273. enforceOk();
  7274. return m_value;
  7275. }
  7276. protected:
  7277. ResultValueBase( Type type ) : ResultBase( type ) {}
  7278. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7279. if( m_type == ResultBase::Ok )
  7280. new( &m_value ) T( other.m_value );
  7281. }
  7282. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7283. new( &m_value ) T( value );
  7284. }
  7285. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7286. if( m_type == ResultBase::Ok )
  7287. m_value.~T();
  7288. ResultBase::operator=(other);
  7289. if( m_type == ResultBase::Ok )
  7290. new( &m_value ) T( other.m_value );
  7291. return *this;
  7292. }
  7293. ~ResultValueBase() override {
  7294. if( m_type == Ok )
  7295. m_value.~T();
  7296. }
  7297. union {
  7298. T m_value;
  7299. };
  7300. };
  7301. template<>
  7302. class ResultValueBase<void> : public ResultBase {
  7303. protected:
  7304. using ResultBase::ResultBase;
  7305. };
  7306. template<typename T = void>
  7307. class BasicResult : public ResultValueBase<T> {
  7308. public:
  7309. template<typename U>
  7310. explicit BasicResult( BasicResult<U> const &other )
  7311. : ResultValueBase<T>( other.type() ),
  7312. m_errorMessage( other.errorMessage() )
  7313. {
  7314. assert( type() != ResultBase::Ok );
  7315. }
  7316. template<typename U>
  7317. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7318. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7319. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7320. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7321. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7322. auto type() const -> ResultBase::Type { return m_type; }
  7323. auto errorMessage() const -> std::string { return m_errorMessage; }
  7324. protected:
  7325. void enforceOk() const override {
  7326. // Errors shouldn't reach this point, but if they do
  7327. // the actual error message will be in m_errorMessage
  7328. assert( m_type != ResultBase::LogicError );
  7329. assert( m_type != ResultBase::RuntimeError );
  7330. if( m_type != ResultBase::Ok )
  7331. std::abort();
  7332. }
  7333. std::string m_errorMessage; // Only populated if resultType is an error
  7334. BasicResult( ResultBase::Type type, std::string const &message )
  7335. : ResultValueBase<T>(type),
  7336. m_errorMessage(message)
  7337. {
  7338. assert( m_type != ResultBase::Ok );
  7339. }
  7340. using ResultValueBase<T>::ResultValueBase;
  7341. using ResultBase::m_type;
  7342. };
  7343. enum class ParseResultType {
  7344. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7345. };
  7346. class ParseState {
  7347. public:
  7348. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7349. : m_type(type),
  7350. m_remainingTokens( remainingTokens )
  7351. {}
  7352. auto type() const -> ParseResultType { return m_type; }
  7353. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7354. private:
  7355. ParseResultType m_type;
  7356. TokenStream m_remainingTokens;
  7357. };
  7358. using Result = BasicResult<void>;
  7359. using ParserResult = BasicResult<ParseResultType>;
  7360. using InternalParseResult = BasicResult<ParseState>;
  7361. struct HelpColumns {
  7362. std::string left;
  7363. std::string right;
  7364. };
  7365. template<typename T>
  7366. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7367. std::stringstream ss;
  7368. ss << source;
  7369. ss >> target;
  7370. if( ss.fail() )
  7371. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7372. else
  7373. return ParserResult::ok( ParseResultType::Matched );
  7374. }
  7375. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7376. target = source;
  7377. return ParserResult::ok( ParseResultType::Matched );
  7378. }
  7379. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7380. std::string srcLC = source;
  7381. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
  7382. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7383. target = true;
  7384. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7385. target = false;
  7386. else
  7387. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7388. return ParserResult::ok( ParseResultType::Matched );
  7389. }
  7390. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7391. template<typename T>
  7392. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7393. T temp;
  7394. auto result = convertInto( source, temp );
  7395. if( result )
  7396. target = std::move(temp);
  7397. return result;
  7398. }
  7399. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7400. struct NonCopyable {
  7401. NonCopyable() = default;
  7402. NonCopyable( NonCopyable const & ) = delete;
  7403. NonCopyable( NonCopyable && ) = delete;
  7404. NonCopyable &operator=( NonCopyable const & ) = delete;
  7405. NonCopyable &operator=( NonCopyable && ) = delete;
  7406. };
  7407. struct BoundRef : NonCopyable {
  7408. virtual ~BoundRef() = default;
  7409. virtual auto isContainer() const -> bool { return false; }
  7410. virtual auto isFlag() const -> bool { return false; }
  7411. };
  7412. struct BoundValueRefBase : BoundRef {
  7413. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7414. };
  7415. struct BoundFlagRefBase : BoundRef {
  7416. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7417. virtual auto isFlag() const -> bool { return true; }
  7418. };
  7419. template<typename T>
  7420. struct BoundValueRef : BoundValueRefBase {
  7421. T &m_ref;
  7422. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7423. auto setValue( std::string const &arg ) -> ParserResult override {
  7424. return convertInto( arg, m_ref );
  7425. }
  7426. };
  7427. template<typename T>
  7428. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7429. std::vector<T> &m_ref;
  7430. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7431. auto isContainer() const -> bool override { return true; }
  7432. auto setValue( std::string const &arg ) -> ParserResult override {
  7433. T temp;
  7434. auto result = convertInto( arg, temp );
  7435. if( result )
  7436. m_ref.push_back( temp );
  7437. return result;
  7438. }
  7439. };
  7440. struct BoundFlagRef : BoundFlagRefBase {
  7441. bool &m_ref;
  7442. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7443. auto setFlag( bool flag ) -> ParserResult override {
  7444. m_ref = flag;
  7445. return ParserResult::ok( ParseResultType::Matched );
  7446. }
  7447. };
  7448. template<typename ReturnType>
  7449. struct LambdaInvoker {
  7450. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7451. template<typename L, typename ArgType>
  7452. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7453. return lambda( arg );
  7454. }
  7455. };
  7456. template<>
  7457. struct LambdaInvoker<void> {
  7458. template<typename L, typename ArgType>
  7459. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7460. lambda( arg );
  7461. return ParserResult::ok( ParseResultType::Matched );
  7462. }
  7463. };
  7464. template<typename ArgType, typename L>
  7465. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7466. ArgType temp{};
  7467. auto result = convertInto( arg, temp );
  7468. return !result
  7469. ? result
  7470. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7471. }
  7472. template<typename L>
  7473. struct BoundLambda : BoundValueRefBase {
  7474. L m_lambda;
  7475. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7476. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7477. auto setValue( std::string const &arg ) -> ParserResult override {
  7478. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7479. }
  7480. };
  7481. template<typename L>
  7482. struct BoundFlagLambda : BoundFlagRefBase {
  7483. L m_lambda;
  7484. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7485. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7486. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7487. auto setFlag( bool flag ) -> ParserResult override {
  7488. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7489. }
  7490. };
  7491. enum class Optionality { Optional, Required };
  7492. struct Parser;
  7493. class ParserBase {
  7494. public:
  7495. virtual ~ParserBase() = default;
  7496. virtual auto validate() const -> Result { return Result::ok(); }
  7497. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7498. virtual auto cardinality() const -> size_t { return 1; }
  7499. auto parse( Args const &args ) const -> InternalParseResult {
  7500. return parse( args.exeName(), TokenStream( args ) );
  7501. }
  7502. };
  7503. template<typename DerivedT>
  7504. class ComposableParserImpl : public ParserBase {
  7505. public:
  7506. template<typename T>
  7507. auto operator|( T const &other ) const -> Parser;
  7508. template<typename T>
  7509. auto operator+( T const &other ) const -> Parser;
  7510. };
  7511. // Common code and state for Args and Opts
  7512. template<typename DerivedT>
  7513. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7514. protected:
  7515. Optionality m_optionality = Optionality::Optional;
  7516. std::shared_ptr<BoundRef> m_ref;
  7517. std::string m_hint;
  7518. std::string m_description;
  7519. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7520. public:
  7521. template<typename T>
  7522. ParserRefImpl( T &ref, std::string const &hint )
  7523. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7524. m_hint( hint )
  7525. {}
  7526. template<typename LambdaT>
  7527. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7528. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7529. m_hint(hint)
  7530. {}
  7531. auto operator()( std::string const &description ) -> DerivedT & {
  7532. m_description = description;
  7533. return static_cast<DerivedT &>( *this );
  7534. }
  7535. auto optional() -> DerivedT & {
  7536. m_optionality = Optionality::Optional;
  7537. return static_cast<DerivedT &>( *this );
  7538. };
  7539. auto required() -> DerivedT & {
  7540. m_optionality = Optionality::Required;
  7541. return static_cast<DerivedT &>( *this );
  7542. };
  7543. auto isOptional() const -> bool {
  7544. return m_optionality == Optionality::Optional;
  7545. }
  7546. auto cardinality() const -> size_t override {
  7547. if( m_ref->isContainer() )
  7548. return 0;
  7549. else
  7550. return 1;
  7551. }
  7552. auto hint() const -> std::string { return m_hint; }
  7553. };
  7554. class ExeName : public ComposableParserImpl<ExeName> {
  7555. std::shared_ptr<std::string> m_name;
  7556. std::shared_ptr<BoundValueRefBase> m_ref;
  7557. template<typename LambdaT>
  7558. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7559. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7560. }
  7561. public:
  7562. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7563. explicit ExeName( std::string &ref ) : ExeName() {
  7564. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7565. }
  7566. template<typename LambdaT>
  7567. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7568. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7569. }
  7570. // The exe name is not parsed out of the normal tokens, but is handled specially
  7571. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7572. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7573. }
  7574. auto name() const -> std::string { return *m_name; }
  7575. auto set( std::string const& newName ) -> ParserResult {
  7576. auto lastSlash = newName.find_last_of( "\\/" );
  7577. auto filename = ( lastSlash == std::string::npos )
  7578. ? newName
  7579. : newName.substr( lastSlash+1 );
  7580. *m_name = filename;
  7581. if( m_ref )
  7582. return m_ref->setValue( filename );
  7583. else
  7584. return ParserResult::ok( ParseResultType::Matched );
  7585. }
  7586. };
  7587. class Arg : public ParserRefImpl<Arg> {
  7588. public:
  7589. using ParserRefImpl::ParserRefImpl;
  7590. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7591. auto validationResult = validate();
  7592. if( !validationResult )
  7593. return InternalParseResult( validationResult );
  7594. auto remainingTokens = tokens;
  7595. auto const &token = *remainingTokens;
  7596. if( token.type != TokenType::Argument )
  7597. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7598. assert( !m_ref->isFlag() );
  7599. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7600. auto result = valueRef->setValue( remainingTokens->token );
  7601. if( !result )
  7602. return InternalParseResult( result );
  7603. else
  7604. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7605. }
  7606. };
  7607. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7608. #ifdef CATCH_PLATFORM_WINDOWS
  7609. if( optName[0] == '/' )
  7610. return "-" + optName.substr( 1 );
  7611. else
  7612. #endif
  7613. return optName;
  7614. }
  7615. class Opt : public ParserRefImpl<Opt> {
  7616. protected:
  7617. std::vector<std::string> m_optNames;
  7618. public:
  7619. template<typename LambdaT>
  7620. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7621. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7622. template<typename LambdaT>
  7623. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7624. template<typename T>
  7625. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7626. auto operator[]( std::string const &optName ) -> Opt & {
  7627. m_optNames.push_back( optName );
  7628. return *this;
  7629. }
  7630. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7631. std::ostringstream oss;
  7632. bool first = true;
  7633. for( auto const &opt : m_optNames ) {
  7634. if (first)
  7635. first = false;
  7636. else
  7637. oss << ", ";
  7638. oss << opt;
  7639. }
  7640. if( !m_hint.empty() )
  7641. oss << " <" << m_hint << ">";
  7642. return { { oss.str(), m_description } };
  7643. }
  7644. auto isMatch( std::string const &optToken ) const -> bool {
  7645. auto normalisedToken = normaliseOpt( optToken );
  7646. for( auto const &name : m_optNames ) {
  7647. if( normaliseOpt( name ) == normalisedToken )
  7648. return true;
  7649. }
  7650. return false;
  7651. }
  7652. using ParserBase::parse;
  7653. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7654. auto validationResult = validate();
  7655. if( !validationResult )
  7656. return InternalParseResult( validationResult );
  7657. auto remainingTokens = tokens;
  7658. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7659. auto const &token = *remainingTokens;
  7660. if( isMatch(token.token ) ) {
  7661. if( m_ref->isFlag() ) {
  7662. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7663. auto result = flagRef->setFlag( true );
  7664. if( !result )
  7665. return InternalParseResult( result );
  7666. if( result.value() == ParseResultType::ShortCircuitAll )
  7667. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7668. } else {
  7669. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7670. ++remainingTokens;
  7671. if( !remainingTokens )
  7672. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7673. auto const &argToken = *remainingTokens;
  7674. if( argToken.type != TokenType::Argument )
  7675. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7676. auto result = valueRef->setValue( argToken.token );
  7677. if( !result )
  7678. return InternalParseResult( result );
  7679. if( result.value() == ParseResultType::ShortCircuitAll )
  7680. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7681. }
  7682. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7683. }
  7684. }
  7685. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7686. }
  7687. auto validate() const -> Result override {
  7688. if( m_optNames.empty() )
  7689. return Result::logicError( "No options supplied to Opt" );
  7690. for( auto const &name : m_optNames ) {
  7691. if( name.empty() )
  7692. return Result::logicError( "Option name cannot be empty" );
  7693. #ifdef CATCH_PLATFORM_WINDOWS
  7694. if( name[0] != '-' && name[0] != '/' )
  7695. return Result::logicError( "Option name must begin with '-' or '/'" );
  7696. #else
  7697. if( name[0] != '-' )
  7698. return Result::logicError( "Option name must begin with '-'" );
  7699. #endif
  7700. }
  7701. return ParserRefImpl::validate();
  7702. }
  7703. };
  7704. struct Help : Opt {
  7705. Help( bool &showHelpFlag )
  7706. : Opt([&]( bool flag ) {
  7707. showHelpFlag = flag;
  7708. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7709. })
  7710. {
  7711. static_cast<Opt &>( *this )
  7712. ("display usage information")
  7713. ["-?"]["-h"]["--help"]
  7714. .optional();
  7715. }
  7716. };
  7717. struct Parser : ParserBase {
  7718. mutable ExeName m_exeName;
  7719. std::vector<Opt> m_options;
  7720. std::vector<Arg> m_args;
  7721. auto operator|=( ExeName const &exeName ) -> Parser & {
  7722. m_exeName = exeName;
  7723. return *this;
  7724. }
  7725. auto operator|=( Arg const &arg ) -> Parser & {
  7726. m_args.push_back(arg);
  7727. return *this;
  7728. }
  7729. auto operator|=( Opt const &opt ) -> Parser & {
  7730. m_options.push_back(opt);
  7731. return *this;
  7732. }
  7733. auto operator|=( Parser const &other ) -> Parser & {
  7734. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7735. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7736. return *this;
  7737. }
  7738. template<typename T>
  7739. auto operator|( T const &other ) const -> Parser {
  7740. return Parser( *this ) |= other;
  7741. }
  7742. // Forward deprecated interface with '+' instead of '|'
  7743. template<typename T>
  7744. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7745. template<typename T>
  7746. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7747. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7748. std::vector<HelpColumns> cols;
  7749. for (auto const &o : m_options) {
  7750. auto childCols = o.getHelpColumns();
  7751. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7752. }
  7753. return cols;
  7754. }
  7755. void writeToStream( std::ostream &os ) const {
  7756. if (!m_exeName.name().empty()) {
  7757. os << "usage:\n" << " " << m_exeName.name() << " ";
  7758. bool required = true, first = true;
  7759. for( auto const &arg : m_args ) {
  7760. if (first)
  7761. first = false;
  7762. else
  7763. os << " ";
  7764. if( arg.isOptional() && required ) {
  7765. os << "[";
  7766. required = false;
  7767. }
  7768. os << "<" << arg.hint() << ">";
  7769. if( arg.cardinality() == 0 )
  7770. os << " ... ";
  7771. }
  7772. if( !required )
  7773. os << "]";
  7774. if( !m_options.empty() )
  7775. os << " options";
  7776. os << "\n\nwhere options are:" << std::endl;
  7777. }
  7778. auto rows = getHelpColumns();
  7779. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7780. size_t optWidth = 0;
  7781. for( auto const &cols : rows )
  7782. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7783. optWidth = (std::min)(optWidth, consoleWidth/2);
  7784. for( auto const &cols : rows ) {
  7785. auto row =
  7786. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7787. TextFlow::Spacer(4) +
  7788. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7789. os << row << std::endl;
  7790. }
  7791. }
  7792. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7793. parser.writeToStream( os );
  7794. return os;
  7795. }
  7796. auto validate() const -> Result override {
  7797. for( auto const &opt : m_options ) {
  7798. auto result = opt.validate();
  7799. if( !result )
  7800. return result;
  7801. }
  7802. for( auto const &arg : m_args ) {
  7803. auto result = arg.validate();
  7804. if( !result )
  7805. return result;
  7806. }
  7807. return Result::ok();
  7808. }
  7809. using ParserBase::parse;
  7810. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7811. struct ParserInfo {
  7812. ParserBase const* parser = nullptr;
  7813. size_t count = 0;
  7814. };
  7815. const size_t totalParsers = m_options.size() + m_args.size();
  7816. assert( totalParsers < 512 );
  7817. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7818. ParserInfo parseInfos[512];
  7819. {
  7820. size_t i = 0;
  7821. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7822. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7823. }
  7824. m_exeName.set( exeName );
  7825. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7826. while( result.value().remainingTokens() ) {
  7827. bool tokenParsed = false;
  7828. for( size_t i = 0; i < totalParsers; ++i ) {
  7829. auto& parseInfo = parseInfos[i];
  7830. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7831. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7832. if (!result)
  7833. return result;
  7834. if (result.value().type() != ParseResultType::NoMatch) {
  7835. tokenParsed = true;
  7836. ++parseInfo.count;
  7837. break;
  7838. }
  7839. }
  7840. }
  7841. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7842. return result;
  7843. if( !tokenParsed )
  7844. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7845. }
  7846. // !TBD Check missing required options
  7847. return result;
  7848. }
  7849. };
  7850. template<typename DerivedT>
  7851. template<typename T>
  7852. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7853. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7854. }
  7855. } // namespace detail
  7856. // A Combined parser
  7857. using detail::Parser;
  7858. // A parser for options
  7859. using detail::Opt;
  7860. // A parser for arguments
  7861. using detail::Arg;
  7862. // Wrapper for argc, argv from main()
  7863. using detail::Args;
  7864. // Specifies the name of the executable
  7865. using detail::ExeName;
  7866. // Convenience wrapper for option parser that specifies the help option
  7867. using detail::Help;
  7868. // enum of result types from a parse
  7869. using detail::ParseResultType;
  7870. // Result type for parser operation
  7871. using detail::ParserResult;
  7872. }} // namespace Catch::clara
  7873. // end clara.hpp
  7874. #ifdef __clang__
  7875. #pragma clang diagnostic pop
  7876. #endif
  7877. // Restore Clara's value for console width, if present
  7878. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7879. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7880. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7881. #endif
  7882. // end catch_clara.h
  7883. namespace Catch {
  7884. clara::Parser makeCommandLineParser( ConfigData& config );
  7885. } // end namespace Catch
  7886. // end catch_commandline.h
  7887. #include <fstream>
  7888. #include <ctime>
  7889. namespace Catch {
  7890. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7891. using namespace clara;
  7892. auto const setWarning = [&]( std::string const& warning ) {
  7893. auto warningSet = [&]() {
  7894. if( warning == "NoAssertions" )
  7895. return WarnAbout::NoAssertions;
  7896. if ( warning == "NoTests" )
  7897. return WarnAbout::NoTests;
  7898. return WarnAbout::Nothing;
  7899. }();
  7900. if (warningSet == WarnAbout::Nothing)
  7901. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7902. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7903. return ParserResult::ok( ParseResultType::Matched );
  7904. };
  7905. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7906. std::ifstream f( filename.c_str() );
  7907. if( !f.is_open() )
  7908. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7909. std::string line;
  7910. while( std::getline( f, line ) ) {
  7911. line = trim(line);
  7912. if( !line.empty() && !startsWith( line, '#' ) ) {
  7913. if( !startsWith( line, '"' ) )
  7914. line = '"' + line + '"';
  7915. config.testsOrTags.push_back( line );
  7916. config.testsOrTags.emplace_back( "," );
  7917. }
  7918. }
  7919. //Remove comma in the end
  7920. if(!config.testsOrTags.empty())
  7921. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  7922. return ParserResult::ok( ParseResultType::Matched );
  7923. };
  7924. auto const setTestOrder = [&]( std::string const& order ) {
  7925. if( startsWith( "declared", order ) )
  7926. config.runOrder = RunTests::InDeclarationOrder;
  7927. else if( startsWith( "lexical", order ) )
  7928. config.runOrder = RunTests::InLexicographicalOrder;
  7929. else if( startsWith( "random", order ) )
  7930. config.runOrder = RunTests::InRandomOrder;
  7931. else
  7932. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7933. return ParserResult::ok( ParseResultType::Matched );
  7934. };
  7935. auto const setRngSeed = [&]( std::string const& seed ) {
  7936. if( seed != "time" )
  7937. return clara::detail::convertInto( seed, config.rngSeed );
  7938. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7939. return ParserResult::ok( ParseResultType::Matched );
  7940. };
  7941. auto const setColourUsage = [&]( std::string const& useColour ) {
  7942. auto mode = toLower( useColour );
  7943. if( mode == "yes" )
  7944. config.useColour = UseColour::Yes;
  7945. else if( mode == "no" )
  7946. config.useColour = UseColour::No;
  7947. else if( mode == "auto" )
  7948. config.useColour = UseColour::Auto;
  7949. else
  7950. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7951. return ParserResult::ok( ParseResultType::Matched );
  7952. };
  7953. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7954. auto keypressLc = toLower( keypress );
  7955. if (keypressLc == "never")
  7956. config.waitForKeypress = WaitForKeypress::Never;
  7957. else if( keypressLc == "start" )
  7958. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7959. else if( keypressLc == "exit" )
  7960. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7961. else if( keypressLc == "both" )
  7962. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7963. else
  7964. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  7965. return ParserResult::ok( ParseResultType::Matched );
  7966. };
  7967. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7968. auto lcVerbosity = toLower( verbosity );
  7969. if( lcVerbosity == "quiet" )
  7970. config.verbosity = Verbosity::Quiet;
  7971. else if( lcVerbosity == "normal" )
  7972. config.verbosity = Verbosity::Normal;
  7973. else if( lcVerbosity == "high" )
  7974. config.verbosity = Verbosity::High;
  7975. else
  7976. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7977. return ParserResult::ok( ParseResultType::Matched );
  7978. };
  7979. auto const setReporter = [&]( std::string const& reporter ) {
  7980. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7981. auto lcReporter = toLower( reporter );
  7982. auto result = factories.find( lcReporter );
  7983. if( factories.end() != result )
  7984. config.reporterName = lcReporter;
  7985. else
  7986. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7987. return ParserResult::ok( ParseResultType::Matched );
  7988. };
  7989. auto cli
  7990. = ExeName( config.processName )
  7991. | Help( config.showHelp )
  7992. | Opt( config.listTests )
  7993. ["-l"]["--list-tests"]
  7994. ( "list all/matching test cases" )
  7995. | Opt( config.listTags )
  7996. ["-t"]["--list-tags"]
  7997. ( "list all/matching tags" )
  7998. | Opt( config.showSuccessfulTests )
  7999. ["-s"]["--success"]
  8000. ( "include successful tests in output" )
  8001. | Opt( config.shouldDebugBreak )
  8002. ["-b"]["--break"]
  8003. ( "break into debugger on failure" )
  8004. | Opt( config.noThrow )
  8005. ["-e"]["--nothrow"]
  8006. ( "skip exception tests" )
  8007. | Opt( config.showInvisibles )
  8008. ["-i"]["--invisibles"]
  8009. ( "show invisibles (tabs, newlines)" )
  8010. | Opt( config.outputFilename, "filename" )
  8011. ["-o"]["--out"]
  8012. ( "output filename" )
  8013. | Opt( setReporter, "name" )
  8014. ["-r"]["--reporter"]
  8015. ( "reporter to use (defaults to console)" )
  8016. | Opt( config.name, "name" )
  8017. ["-n"]["--name"]
  8018. ( "suite name" )
  8019. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8020. ["-a"]["--abort"]
  8021. ( "abort at first failure" )
  8022. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8023. ["-x"]["--abortx"]
  8024. ( "abort after x failures" )
  8025. | Opt( setWarning, "warning name" )
  8026. ["-w"]["--warn"]
  8027. ( "enable warnings" )
  8028. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8029. ["-d"]["--durations"]
  8030. ( "show test durations" )
  8031. | Opt( config.minDuration, "seconds" )
  8032. ["-D"]["--min-duration"]
  8033. ( "show test durations for tests taking at least the given number of seconds" )
  8034. | Opt( loadTestNamesFromFile, "filename" )
  8035. ["-f"]["--input-file"]
  8036. ( "load test names to run from a file" )
  8037. | Opt( config.filenamesAsTags )
  8038. ["-#"]["--filenames-as-tags"]
  8039. ( "adds a tag for the filename" )
  8040. | Opt( config.sectionsToRun, "section name" )
  8041. ["-c"]["--section"]
  8042. ( "specify section to run" )
  8043. | Opt( setVerbosity, "quiet|normal|high" )
  8044. ["-v"]["--verbosity"]
  8045. ( "set output verbosity" )
  8046. | Opt( config.listTestNamesOnly )
  8047. ["--list-test-names-only"]
  8048. ( "list all/matching test cases names only" )
  8049. | Opt( config.listReporters )
  8050. ["--list-reporters"]
  8051. ( "list all reporters" )
  8052. | Opt( setTestOrder, "decl|lex|rand" )
  8053. ["--order"]
  8054. ( "test case order (defaults to decl)" )
  8055. | Opt( setRngSeed, "'time'|number" )
  8056. ["--rng-seed"]
  8057. ( "set a specific seed for random numbers" )
  8058. | Opt( setColourUsage, "yes|no" )
  8059. ["--use-colour"]
  8060. ( "should output be colourised" )
  8061. | Opt( config.libIdentify )
  8062. ["--libidentify"]
  8063. ( "report name and version according to libidentify standard" )
  8064. | Opt( setWaitForKeypress, "never|start|exit|both" )
  8065. ["--wait-for-keypress"]
  8066. ( "waits for a keypress before exiting" )
  8067. | Opt( config.benchmarkSamples, "samples" )
  8068. ["--benchmark-samples"]
  8069. ( "number of samples to collect (default: 100)" )
  8070. | Opt( config.benchmarkResamples, "resamples" )
  8071. ["--benchmark-resamples"]
  8072. ( "number of resamples for the bootstrap (default: 100000)" )
  8073. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8074. ["--benchmark-confidence-interval"]
  8075. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8076. | Opt( config.benchmarkNoAnalysis )
  8077. ["--benchmark-no-analysis"]
  8078. ( "perform only measurements; do not perform any analysis" )
  8079. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  8080. ["--benchmark-warmup-time"]
  8081. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  8082. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8083. ( "which test or tests to use" );
  8084. return cli;
  8085. }
  8086. } // end namespace Catch
  8087. // end catch_commandline.cpp
  8088. // start catch_common.cpp
  8089. #include <cstring>
  8090. #include <ostream>
  8091. namespace Catch {
  8092. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8093. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8094. }
  8095. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8096. // We can assume that the same file will usually have the same pointer.
  8097. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8098. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8099. }
  8100. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8101. #ifndef __GNUG__
  8102. os << info.file << '(' << info.line << ')';
  8103. #else
  8104. os << info.file << ':' << info.line;
  8105. #endif
  8106. return os;
  8107. }
  8108. std::string StreamEndStop::operator+() const {
  8109. return std::string();
  8110. }
  8111. NonCopyable::NonCopyable() = default;
  8112. NonCopyable::~NonCopyable() = default;
  8113. }
  8114. // end catch_common.cpp
  8115. // start catch_config.cpp
  8116. namespace Catch {
  8117. Config::Config( ConfigData const& data )
  8118. : m_data( data ),
  8119. m_stream( openStream() )
  8120. {
  8121. // We need to trim filter specs to avoid trouble with superfluous
  8122. // whitespace (esp. important for bdd macros, as those are manually
  8123. // aligned with whitespace).
  8124. for (auto& elem : m_data.testsOrTags) {
  8125. elem = trim(elem);
  8126. }
  8127. for (auto& elem : m_data.sectionsToRun) {
  8128. elem = trim(elem);
  8129. }
  8130. TestSpecParser parser(ITagAliasRegistry::get());
  8131. if (!m_data.testsOrTags.empty()) {
  8132. m_hasTestFilters = true;
  8133. for (auto const& testOrTags : m_data.testsOrTags) {
  8134. parser.parse(testOrTags);
  8135. }
  8136. }
  8137. m_testSpec = parser.testSpec();
  8138. }
  8139. std::string const& Config::getFilename() const {
  8140. return m_data.outputFilename ;
  8141. }
  8142. bool Config::listTests() const { return m_data.listTests; }
  8143. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8144. bool Config::listTags() const { return m_data.listTags; }
  8145. bool Config::listReporters() const { return m_data.listReporters; }
  8146. std::string Config::getProcessName() const { return m_data.processName; }
  8147. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8148. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8149. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8150. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8151. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8152. bool Config::showHelp() const { return m_data.showHelp; }
  8153. // IConfig interface
  8154. bool Config::allowThrows() const { return !m_data.noThrow; }
  8155. std::ostream& Config::stream() const { return m_stream->stream(); }
  8156. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8157. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8158. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8159. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8160. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8161. double Config::minDuration() const { return m_data.minDuration; }
  8162. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8163. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8164. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8165. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8166. int Config::abortAfter() const { return m_data.abortAfter; }
  8167. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8168. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8169. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8170. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8171. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8172. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8173. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  8174. IStream const* Config::openStream() {
  8175. return Catch::makeStream(m_data.outputFilename);
  8176. }
  8177. } // end namespace Catch
  8178. // end catch_config.cpp
  8179. // start catch_console_colour.cpp
  8180. #if defined(__clang__)
  8181. # pragma clang diagnostic push
  8182. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8183. #endif
  8184. // start catch_errno_guard.h
  8185. namespace Catch {
  8186. class ErrnoGuard {
  8187. public:
  8188. ErrnoGuard();
  8189. ~ErrnoGuard();
  8190. private:
  8191. int m_oldErrno;
  8192. };
  8193. }
  8194. // end catch_errno_guard.h
  8195. #include <sstream>
  8196. namespace Catch {
  8197. namespace {
  8198. struct IColourImpl {
  8199. virtual ~IColourImpl() = default;
  8200. virtual void use( Colour::Code _colourCode ) = 0;
  8201. };
  8202. struct NoColourImpl : IColourImpl {
  8203. void use( Colour::Code ) override {}
  8204. static IColourImpl* instance() {
  8205. static NoColourImpl s_instance;
  8206. return &s_instance;
  8207. }
  8208. };
  8209. } // anon namespace
  8210. } // namespace Catch
  8211. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8212. # ifdef CATCH_PLATFORM_WINDOWS
  8213. # define CATCH_CONFIG_COLOUR_WINDOWS
  8214. # else
  8215. # define CATCH_CONFIG_COLOUR_ANSI
  8216. # endif
  8217. #endif
  8218. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8219. namespace Catch {
  8220. namespace {
  8221. class Win32ColourImpl : public IColourImpl {
  8222. public:
  8223. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8224. {
  8225. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8226. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8227. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8228. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8229. }
  8230. void use( Colour::Code _colourCode ) override {
  8231. switch( _colourCode ) {
  8232. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8233. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8234. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8235. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8236. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8237. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8238. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8239. case Colour::Grey: return setTextAttribute( 0 );
  8240. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8241. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8242. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8243. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8244. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8245. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8246. default:
  8247. CATCH_ERROR( "Unknown colour requested" );
  8248. }
  8249. }
  8250. private:
  8251. void setTextAttribute( WORD _textAttribute ) {
  8252. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8253. }
  8254. HANDLE stdoutHandle;
  8255. WORD originalForegroundAttributes;
  8256. WORD originalBackgroundAttributes;
  8257. };
  8258. IColourImpl* platformColourInstance() {
  8259. static Win32ColourImpl s_instance;
  8260. IConfigPtr config = getCurrentContext().getConfig();
  8261. UseColour::YesOrNo colourMode = config
  8262. ? config->useColour()
  8263. : UseColour::Auto;
  8264. if( colourMode == UseColour::Auto )
  8265. colourMode = UseColour::Yes;
  8266. return colourMode == UseColour::Yes
  8267. ? &s_instance
  8268. : NoColourImpl::instance();
  8269. }
  8270. } // end anon namespace
  8271. } // end namespace Catch
  8272. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8273. #include <unistd.h>
  8274. namespace Catch {
  8275. namespace {
  8276. // use POSIX/ ANSI console terminal codes
  8277. // Thanks to Adam Strzelecki for original contribution
  8278. // (http://github.com/nanoant)
  8279. // https://github.com/philsquared/Catch/pull/131
  8280. class PosixColourImpl : public IColourImpl {
  8281. public:
  8282. void use( Colour::Code _colourCode ) override {
  8283. switch( _colourCode ) {
  8284. case Colour::None:
  8285. case Colour::White: return setColour( "[0m" );
  8286. case Colour::Red: return setColour( "[0;31m" );
  8287. case Colour::Green: return setColour( "[0;32m" );
  8288. case Colour::Blue: return setColour( "[0;34m" );
  8289. case Colour::Cyan: return setColour( "[0;36m" );
  8290. case Colour::Yellow: return setColour( "[0;33m" );
  8291. case Colour::Grey: return setColour( "[1;30m" );
  8292. case Colour::LightGrey: return setColour( "[0;37m" );
  8293. case Colour::BrightRed: return setColour( "[1;31m" );
  8294. case Colour::BrightGreen: return setColour( "[1;32m" );
  8295. case Colour::BrightWhite: return setColour( "[1;37m" );
  8296. case Colour::BrightYellow: return setColour( "[1;33m" );
  8297. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8298. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8299. }
  8300. }
  8301. static IColourImpl* instance() {
  8302. static PosixColourImpl s_instance;
  8303. return &s_instance;
  8304. }
  8305. private:
  8306. void setColour( const char* _escapeCode ) {
  8307. getCurrentContext().getConfig()->stream()
  8308. << '\033' << _escapeCode;
  8309. }
  8310. };
  8311. bool useColourOnPlatform() {
  8312. return
  8313. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8314. !isDebuggerActive() &&
  8315. #endif
  8316. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8317. isatty(STDOUT_FILENO)
  8318. #else
  8319. false
  8320. #endif
  8321. ;
  8322. }
  8323. IColourImpl* platformColourInstance() {
  8324. ErrnoGuard guard;
  8325. IConfigPtr config = getCurrentContext().getConfig();
  8326. UseColour::YesOrNo colourMode = config
  8327. ? config->useColour()
  8328. : UseColour::Auto;
  8329. if( colourMode == UseColour::Auto )
  8330. colourMode = useColourOnPlatform()
  8331. ? UseColour::Yes
  8332. : UseColour::No;
  8333. return colourMode == UseColour::Yes
  8334. ? PosixColourImpl::instance()
  8335. : NoColourImpl::instance();
  8336. }
  8337. } // end anon namespace
  8338. } // end namespace Catch
  8339. #else // not Windows or ANSI ///////////////////////////////////////////////
  8340. namespace Catch {
  8341. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8342. } // end namespace Catch
  8343. #endif // Windows/ ANSI/ None
  8344. namespace Catch {
  8345. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8346. Colour::Colour( Colour&& other ) noexcept {
  8347. m_moved = other.m_moved;
  8348. other.m_moved = true;
  8349. }
  8350. Colour& Colour::operator=( Colour&& other ) noexcept {
  8351. m_moved = other.m_moved;
  8352. other.m_moved = true;
  8353. return *this;
  8354. }
  8355. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8356. void Colour::use( Code _colourCode ) {
  8357. static IColourImpl* impl = platformColourInstance();
  8358. // Strictly speaking, this cannot possibly happen.
  8359. // However, under some conditions it does happen (see #1626),
  8360. // and this change is small enough that we can let practicality
  8361. // triumph over purity in this case.
  8362. if (impl != nullptr) {
  8363. impl->use( _colourCode );
  8364. }
  8365. }
  8366. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8367. return os;
  8368. }
  8369. } // end namespace Catch
  8370. #if defined(__clang__)
  8371. # pragma clang diagnostic pop
  8372. #endif
  8373. // end catch_console_colour.cpp
  8374. // start catch_context.cpp
  8375. namespace Catch {
  8376. class Context : public IMutableContext, NonCopyable {
  8377. public: // IContext
  8378. IResultCapture* getResultCapture() override {
  8379. return m_resultCapture;
  8380. }
  8381. IRunner* getRunner() override {
  8382. return m_runner;
  8383. }
  8384. IConfigPtr const& getConfig() const override {
  8385. return m_config;
  8386. }
  8387. ~Context() override;
  8388. public: // IMutableContext
  8389. void setResultCapture( IResultCapture* resultCapture ) override {
  8390. m_resultCapture = resultCapture;
  8391. }
  8392. void setRunner( IRunner* runner ) override {
  8393. m_runner = runner;
  8394. }
  8395. void setConfig( IConfigPtr const& config ) override {
  8396. m_config = config;
  8397. }
  8398. friend IMutableContext& getCurrentMutableContext();
  8399. private:
  8400. IConfigPtr m_config;
  8401. IRunner* m_runner = nullptr;
  8402. IResultCapture* m_resultCapture = nullptr;
  8403. };
  8404. IMutableContext *IMutableContext::currentContext = nullptr;
  8405. void IMutableContext::createContext()
  8406. {
  8407. currentContext = new Context();
  8408. }
  8409. void cleanUpContext() {
  8410. delete IMutableContext::currentContext;
  8411. IMutableContext::currentContext = nullptr;
  8412. }
  8413. IContext::~IContext() = default;
  8414. IMutableContext::~IMutableContext() = default;
  8415. Context::~Context() = default;
  8416. SimplePcg32& rng() {
  8417. static SimplePcg32 s_rng;
  8418. return s_rng;
  8419. }
  8420. }
  8421. // end catch_context.cpp
  8422. // start catch_debug_console.cpp
  8423. // start catch_debug_console.h
  8424. #include <string>
  8425. namespace Catch {
  8426. void writeToDebugConsole( std::string const& text );
  8427. }
  8428. // end catch_debug_console.h
  8429. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  8430. #include <android/log.h>
  8431. namespace Catch {
  8432. void writeToDebugConsole( std::string const& text ) {
  8433. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8434. }
  8435. }
  8436. #elif defined(CATCH_PLATFORM_WINDOWS)
  8437. namespace Catch {
  8438. void writeToDebugConsole( std::string const& text ) {
  8439. ::OutputDebugStringA( text.c_str() );
  8440. }
  8441. }
  8442. #else
  8443. namespace Catch {
  8444. void writeToDebugConsole( std::string const& text ) {
  8445. // !TBD: Need a version for Mac/ XCode and other IDEs
  8446. Catch::cout() << text;
  8447. }
  8448. }
  8449. #endif // Platform
  8450. // end catch_debug_console.cpp
  8451. // start catch_debugger.cpp
  8452. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8453. # include <cassert>
  8454. # include <sys/types.h>
  8455. # include <unistd.h>
  8456. # include <cstddef>
  8457. # include <ostream>
  8458. #ifdef __apple_build_version__
  8459. // These headers will only compile with AppleClang (XCode)
  8460. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8461. # include <sys/sysctl.h>
  8462. #endif
  8463. namespace Catch {
  8464. #ifdef __apple_build_version__
  8465. // The following function is taken directly from the following technical note:
  8466. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8467. // Returns true if the current process is being debugged (either
  8468. // running under the debugger or has a debugger attached post facto).
  8469. bool isDebuggerActive(){
  8470. int mib[4];
  8471. struct kinfo_proc info;
  8472. std::size_t size;
  8473. // Initialize the flags so that, if sysctl fails for some bizarre
  8474. // reason, we get a predictable result.
  8475. info.kp_proc.p_flag = 0;
  8476. // Initialize mib, which tells sysctl the info we want, in this case
  8477. // we're looking for information about a specific process ID.
  8478. mib[0] = CTL_KERN;
  8479. mib[1] = KERN_PROC;
  8480. mib[2] = KERN_PROC_PID;
  8481. mib[3] = getpid();
  8482. // Call sysctl.
  8483. size = sizeof(info);
  8484. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8485. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8486. return false;
  8487. }
  8488. // We're being debugged if the P_TRACED flag is set.
  8489. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8490. }
  8491. #else
  8492. bool isDebuggerActive() {
  8493. // We need to find another way to determine this for non-appleclang compilers on macOS
  8494. return false;
  8495. }
  8496. #endif
  8497. } // namespace Catch
  8498. #elif defined(CATCH_PLATFORM_LINUX)
  8499. #include <fstream>
  8500. #include <string>
  8501. namespace Catch{
  8502. // The standard POSIX way of detecting a debugger is to attempt to
  8503. // ptrace() the process, but this needs to be done from a child and not
  8504. // this process itself to still allow attaching to this process later
  8505. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8506. // "debugger" (which doesn't need to be gdb, of course, it could also
  8507. // be strace, for example) in /proc/$PID/status, so just get it from
  8508. // there instead.
  8509. bool isDebuggerActive(){
  8510. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8511. // This way our users can properly assert over errno values
  8512. ErrnoGuard guard;
  8513. std::ifstream in("/proc/self/status");
  8514. for( std::string line; std::getline(in, line); ) {
  8515. static const int PREFIX_LEN = 11;
  8516. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8517. // We're traced if the PID is not 0 and no other PID starts
  8518. // with 0 digit, so it's enough to check for just a single
  8519. // character.
  8520. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8521. }
  8522. }
  8523. return false;
  8524. }
  8525. } // namespace Catch
  8526. #elif defined(_MSC_VER)
  8527. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8528. namespace Catch {
  8529. bool isDebuggerActive() {
  8530. return IsDebuggerPresent() != 0;
  8531. }
  8532. }
  8533. #elif defined(__MINGW32__)
  8534. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8535. namespace Catch {
  8536. bool isDebuggerActive() {
  8537. return IsDebuggerPresent() != 0;
  8538. }
  8539. }
  8540. #else
  8541. namespace Catch {
  8542. bool isDebuggerActive() { return false; }
  8543. }
  8544. #endif // Platform
  8545. // end catch_debugger.cpp
  8546. // start catch_decomposer.cpp
  8547. namespace Catch {
  8548. ITransientExpression::~ITransientExpression() = default;
  8549. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8550. if( lhs.size() + rhs.size() < 40 &&
  8551. lhs.find('\n') == std::string::npos &&
  8552. rhs.find('\n') == std::string::npos )
  8553. os << lhs << " " << op << " " << rhs;
  8554. else
  8555. os << lhs << "\n" << op << "\n" << rhs;
  8556. }
  8557. }
  8558. // end catch_decomposer.cpp
  8559. // start catch_enforce.cpp
  8560. #include <stdexcept>
  8561. namespace Catch {
  8562. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8563. [[noreturn]]
  8564. void throw_exception(std::exception const& e) {
  8565. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8566. << "The message was: " << e.what() << '\n';
  8567. std::terminate();
  8568. }
  8569. #endif
  8570. [[noreturn]]
  8571. void throw_logic_error(std::string const& msg) {
  8572. throw_exception(std::logic_error(msg));
  8573. }
  8574. [[noreturn]]
  8575. void throw_domain_error(std::string const& msg) {
  8576. throw_exception(std::domain_error(msg));
  8577. }
  8578. [[noreturn]]
  8579. void throw_runtime_error(std::string const& msg) {
  8580. throw_exception(std::runtime_error(msg));
  8581. }
  8582. } // namespace Catch;
  8583. // end catch_enforce.cpp
  8584. // start catch_enum_values_registry.cpp
  8585. // start catch_enum_values_registry.h
  8586. #include <vector>
  8587. #include <memory>
  8588. namespace Catch {
  8589. namespace Detail {
  8590. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8591. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8592. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8593. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8594. };
  8595. std::vector<StringRef> parseEnums( StringRef enums );
  8596. } // Detail
  8597. } // Catch
  8598. // end catch_enum_values_registry.h
  8599. #include <map>
  8600. #include <cassert>
  8601. namespace Catch {
  8602. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8603. namespace Detail {
  8604. namespace {
  8605. // Extracts the actual name part of an enum instance
  8606. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  8607. StringRef extractInstanceName(StringRef enumInstance) {
  8608. // Find last occurence of ":"
  8609. size_t name_start = enumInstance.size();
  8610. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  8611. --name_start;
  8612. }
  8613. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  8614. }
  8615. }
  8616. std::vector<StringRef> parseEnums( StringRef enums ) {
  8617. auto enumValues = splitStringRef( enums, ',' );
  8618. std::vector<StringRef> parsed;
  8619. parsed.reserve( enumValues.size() );
  8620. for( auto const& enumValue : enumValues ) {
  8621. parsed.push_back(trim(extractInstanceName(enumValue)));
  8622. }
  8623. return parsed;
  8624. }
  8625. EnumInfo::~EnumInfo() {}
  8626. StringRef EnumInfo::lookup( int value ) const {
  8627. for( auto const& valueToName : m_values ) {
  8628. if( valueToName.first == value )
  8629. return valueToName.second;
  8630. }
  8631. return "{** unexpected enum value **}"_sr;
  8632. }
  8633. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8634. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8635. enumInfo->m_name = enumName;
  8636. enumInfo->m_values.reserve( values.size() );
  8637. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8638. assert( valueNames.size() == values.size() );
  8639. std::size_t i = 0;
  8640. for( auto value : values )
  8641. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  8642. return enumInfo;
  8643. }
  8644. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8645. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  8646. return *m_enumInfos.back();
  8647. }
  8648. } // Detail
  8649. } // Catch
  8650. // end catch_enum_values_registry.cpp
  8651. // start catch_errno_guard.cpp
  8652. #include <cerrno>
  8653. namespace Catch {
  8654. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8655. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8656. }
  8657. // end catch_errno_guard.cpp
  8658. // start catch_exception_translator_registry.cpp
  8659. // start catch_exception_translator_registry.h
  8660. #include <vector>
  8661. #include <string>
  8662. #include <memory>
  8663. namespace Catch {
  8664. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8665. public:
  8666. ~ExceptionTranslatorRegistry();
  8667. virtual void registerTranslator( const IExceptionTranslator* translator );
  8668. std::string translateActiveException() const override;
  8669. std::string tryTranslators() const;
  8670. private:
  8671. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8672. };
  8673. }
  8674. // end catch_exception_translator_registry.h
  8675. #ifdef __OBJC__
  8676. #import "Foundation/Foundation.h"
  8677. #endif
  8678. namespace Catch {
  8679. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8680. }
  8681. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8682. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8683. }
  8684. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8685. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8686. try {
  8687. #ifdef __OBJC__
  8688. // In Objective-C try objective-c exceptions first
  8689. @try {
  8690. return tryTranslators();
  8691. }
  8692. @catch (NSException *exception) {
  8693. return Catch::Detail::stringify( [exception description] );
  8694. }
  8695. #else
  8696. // Compiling a mixed mode project with MSVC means that CLR
  8697. // exceptions will be caught in (...) as well. However, these
  8698. // do not fill-in std::current_exception and thus lead to crash
  8699. // when attempting rethrow.
  8700. // /EHa switch also causes structured exceptions to be caught
  8701. // here, but they fill-in current_exception properly, so
  8702. // at worst the output should be a little weird, instead of
  8703. // causing a crash.
  8704. if (std::current_exception() == nullptr) {
  8705. return "Non C++ exception. Possibly a CLR exception.";
  8706. }
  8707. return tryTranslators();
  8708. #endif
  8709. }
  8710. catch( TestFailureException& ) {
  8711. std::rethrow_exception(std::current_exception());
  8712. }
  8713. catch( std::exception& ex ) {
  8714. return ex.what();
  8715. }
  8716. catch( std::string& msg ) {
  8717. return msg;
  8718. }
  8719. catch( const char* msg ) {
  8720. return msg;
  8721. }
  8722. catch(...) {
  8723. return "Unknown exception";
  8724. }
  8725. }
  8726. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8727. if (m_translators.empty()) {
  8728. std::rethrow_exception(std::current_exception());
  8729. } else {
  8730. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8731. }
  8732. }
  8733. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8734. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8735. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8736. }
  8737. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8738. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8739. }
  8740. #endif
  8741. }
  8742. // end catch_exception_translator_registry.cpp
  8743. // start catch_fatal_condition.cpp
  8744. #if defined(__GNUC__)
  8745. # pragma GCC diagnostic push
  8746. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8747. #endif
  8748. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8749. namespace {
  8750. // Report the error condition
  8751. void reportFatal( char const * const message ) {
  8752. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8753. }
  8754. }
  8755. #endif // signals/SEH handling
  8756. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8757. namespace Catch {
  8758. struct SignalDefs { DWORD id; const char* name; };
  8759. // There is no 1-1 mapping between signals and windows exceptions.
  8760. // Windows can easily distinguish between SO and SigSegV,
  8761. // but SigInt, SigTerm, etc are handled differently.
  8762. static SignalDefs signalDefs[] = {
  8763. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8764. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8765. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8766. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8767. };
  8768. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8769. for (auto const& def : signalDefs) {
  8770. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8771. reportFatal(def.name);
  8772. }
  8773. }
  8774. // If its not an exception we care about, pass it along.
  8775. // This stops us from eating debugger breaks etc.
  8776. return EXCEPTION_CONTINUE_SEARCH;
  8777. }
  8778. FatalConditionHandler::FatalConditionHandler() {
  8779. isSet = true;
  8780. // 32k seems enough for Catch to handle stack overflow,
  8781. // but the value was found experimentally, so there is no strong guarantee
  8782. guaranteeSize = 32 * 1024;
  8783. exceptionHandlerHandle = nullptr;
  8784. // Register as first handler in current chain
  8785. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8786. // Pass in guarantee size to be filled
  8787. SetThreadStackGuarantee(&guaranteeSize);
  8788. }
  8789. void FatalConditionHandler::reset() {
  8790. if (isSet) {
  8791. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8792. SetThreadStackGuarantee(&guaranteeSize);
  8793. exceptionHandlerHandle = nullptr;
  8794. isSet = false;
  8795. }
  8796. }
  8797. FatalConditionHandler::~FatalConditionHandler() {
  8798. reset();
  8799. }
  8800. bool FatalConditionHandler::isSet = false;
  8801. ULONG FatalConditionHandler::guaranteeSize = 0;
  8802. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8803. } // namespace Catch
  8804. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8805. namespace Catch {
  8806. struct SignalDefs {
  8807. int id;
  8808. const char* name;
  8809. };
  8810. // 32kb for the alternate stack seems to be sufficient. However, this value
  8811. // is experimentally determined, so that's not guaranteed.
  8812. static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8813. static SignalDefs signalDefs[] = {
  8814. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8815. { SIGILL, "SIGILL - Illegal instruction signal" },
  8816. { SIGFPE, "SIGFPE - Floating point error signal" },
  8817. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8818. { SIGTERM, "SIGTERM - Termination request signal" },
  8819. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8820. };
  8821. void FatalConditionHandler::handleSignal( int sig ) {
  8822. char const * name = "<unknown signal>";
  8823. for (auto const& def : signalDefs) {
  8824. if (sig == def.id) {
  8825. name = def.name;
  8826. break;
  8827. }
  8828. }
  8829. reset();
  8830. reportFatal(name);
  8831. raise( sig );
  8832. }
  8833. FatalConditionHandler::FatalConditionHandler() {
  8834. isSet = true;
  8835. stack_t sigStack;
  8836. sigStack.ss_sp = altStackMem;
  8837. sigStack.ss_size = sigStackSize;
  8838. sigStack.ss_flags = 0;
  8839. sigaltstack(&sigStack, &oldSigStack);
  8840. struct sigaction sa = { };
  8841. sa.sa_handler = handleSignal;
  8842. sa.sa_flags = SA_ONSTACK;
  8843. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8844. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8845. }
  8846. }
  8847. FatalConditionHandler::~FatalConditionHandler() {
  8848. reset();
  8849. }
  8850. void FatalConditionHandler::reset() {
  8851. if( isSet ) {
  8852. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8853. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8854. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8855. }
  8856. // Return the old stack
  8857. sigaltstack(&oldSigStack, nullptr);
  8858. isSet = false;
  8859. }
  8860. }
  8861. bool FatalConditionHandler::isSet = false;
  8862. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8863. stack_t FatalConditionHandler::oldSigStack = {};
  8864. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8865. } // namespace Catch
  8866. #else
  8867. namespace Catch {
  8868. void FatalConditionHandler::reset() {}
  8869. }
  8870. #endif // signals/SEH handling
  8871. #if defined(__GNUC__)
  8872. # pragma GCC diagnostic pop
  8873. #endif
  8874. // end catch_fatal_condition.cpp
  8875. // start catch_generators.cpp
  8876. #include <limits>
  8877. #include <set>
  8878. namespace Catch {
  8879. IGeneratorTracker::~IGeneratorTracker() {}
  8880. const char* GeneratorException::what() const noexcept {
  8881. return m_msg;
  8882. }
  8883. namespace Generators {
  8884. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8885. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8886. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  8887. }
  8888. } // namespace Generators
  8889. } // namespace Catch
  8890. // end catch_generators.cpp
  8891. // start catch_interfaces_capture.cpp
  8892. namespace Catch {
  8893. IResultCapture::~IResultCapture() = default;
  8894. }
  8895. // end catch_interfaces_capture.cpp
  8896. // start catch_interfaces_config.cpp
  8897. namespace Catch {
  8898. IConfig::~IConfig() = default;
  8899. }
  8900. // end catch_interfaces_config.cpp
  8901. // start catch_interfaces_exception.cpp
  8902. namespace Catch {
  8903. IExceptionTranslator::~IExceptionTranslator() = default;
  8904. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8905. }
  8906. // end catch_interfaces_exception.cpp
  8907. // start catch_interfaces_registry_hub.cpp
  8908. namespace Catch {
  8909. IRegistryHub::~IRegistryHub() = default;
  8910. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8911. }
  8912. // end catch_interfaces_registry_hub.cpp
  8913. // start catch_interfaces_reporter.cpp
  8914. // start catch_reporter_listening.h
  8915. namespace Catch {
  8916. class ListeningReporter : public IStreamingReporter {
  8917. using Reporters = std::vector<IStreamingReporterPtr>;
  8918. Reporters m_listeners;
  8919. IStreamingReporterPtr m_reporter = nullptr;
  8920. ReporterPreferences m_preferences;
  8921. public:
  8922. ListeningReporter();
  8923. void addListener( IStreamingReporterPtr&& listener );
  8924. void addReporter( IStreamingReporterPtr&& reporter );
  8925. public: // IStreamingReporter
  8926. ReporterPreferences getPreferences() const override;
  8927. void noMatchingTestCases( std::string const& spec ) override;
  8928. void reportInvalidArguments(std::string const&arg) override;
  8929. static std::set<Verbosity> getSupportedVerbosities();
  8930. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8931. void benchmarkPreparing(std::string const& name) override;
  8932. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8933. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8934. void benchmarkFailed(std::string const&) override;
  8935. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8936. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8937. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8938. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8939. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8940. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8941. // The return value indicates if the messages buffer should be cleared:
  8942. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8943. void sectionEnded( SectionStats const& sectionStats ) override;
  8944. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8945. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8946. void testRunEnded( TestRunStats const& testRunStats ) override;
  8947. void skipTest( TestCaseInfo const& testInfo ) override;
  8948. bool isMulti() const override;
  8949. };
  8950. } // end namespace Catch
  8951. // end catch_reporter_listening.h
  8952. namespace Catch {
  8953. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8954. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8955. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8956. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8957. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8958. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8959. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8960. GroupInfo::GroupInfo( std::string const& _name,
  8961. std::size_t _groupIndex,
  8962. std::size_t _groupsCount )
  8963. : name( _name ),
  8964. groupIndex( _groupIndex ),
  8965. groupsCounts( _groupsCount )
  8966. {}
  8967. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8968. std::vector<MessageInfo> const& _infoMessages,
  8969. Totals const& _totals )
  8970. : assertionResult( _assertionResult ),
  8971. infoMessages( _infoMessages ),
  8972. totals( _totals )
  8973. {
  8974. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8975. if( assertionResult.hasMessage() ) {
  8976. // Copy message into messages list.
  8977. // !TBD This should have been done earlier, somewhere
  8978. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8979. builder << assertionResult.getMessage();
  8980. builder.m_info.message = builder.m_stream.str();
  8981. infoMessages.push_back( builder.m_info );
  8982. }
  8983. }
  8984. AssertionStats::~AssertionStats() = default;
  8985. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8986. Counts const& _assertions,
  8987. double _durationInSeconds,
  8988. bool _missingAssertions )
  8989. : sectionInfo( _sectionInfo ),
  8990. assertions( _assertions ),
  8991. durationInSeconds( _durationInSeconds ),
  8992. missingAssertions( _missingAssertions )
  8993. {}
  8994. SectionStats::~SectionStats() = default;
  8995. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8996. Totals const& _totals,
  8997. std::string const& _stdOut,
  8998. std::string const& _stdErr,
  8999. bool _aborting )
  9000. : testInfo( _testInfo ),
  9001. totals( _totals ),
  9002. stdOut( _stdOut ),
  9003. stdErr( _stdErr ),
  9004. aborting( _aborting )
  9005. {}
  9006. TestCaseStats::~TestCaseStats() = default;
  9007. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9008. Totals const& _totals,
  9009. bool _aborting )
  9010. : groupInfo( _groupInfo ),
  9011. totals( _totals ),
  9012. aborting( _aborting )
  9013. {}
  9014. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9015. : groupInfo( _groupInfo ),
  9016. aborting( false )
  9017. {}
  9018. TestGroupStats::~TestGroupStats() = default;
  9019. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9020. Totals const& _totals,
  9021. bool _aborting )
  9022. : runInfo( _runInfo ),
  9023. totals( _totals ),
  9024. aborting( _aborting )
  9025. {}
  9026. TestRunStats::~TestRunStats() = default;
  9027. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9028. bool IStreamingReporter::isMulti() const { return false; }
  9029. IReporterFactory::~IReporterFactory() = default;
  9030. IReporterRegistry::~IReporterRegistry() = default;
  9031. } // end namespace Catch
  9032. // end catch_interfaces_reporter.cpp
  9033. // start catch_interfaces_runner.cpp
  9034. namespace Catch {
  9035. IRunner::~IRunner() = default;
  9036. }
  9037. // end catch_interfaces_runner.cpp
  9038. // start catch_interfaces_testcase.cpp
  9039. namespace Catch {
  9040. ITestInvoker::~ITestInvoker() = default;
  9041. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9042. }
  9043. // end catch_interfaces_testcase.cpp
  9044. // start catch_leak_detector.cpp
  9045. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9046. #include <crtdbg.h>
  9047. namespace Catch {
  9048. LeakDetector::LeakDetector() {
  9049. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9050. flag |= _CRTDBG_LEAK_CHECK_DF;
  9051. flag |= _CRTDBG_ALLOC_MEM_DF;
  9052. _CrtSetDbgFlag(flag);
  9053. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9054. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9055. // Change this to leaking allocation's number to break there
  9056. _CrtSetBreakAlloc(-1);
  9057. }
  9058. }
  9059. #else
  9060. Catch::LeakDetector::LeakDetector() {}
  9061. #endif
  9062. Catch::LeakDetector::~LeakDetector() {
  9063. Catch::cleanUp();
  9064. }
  9065. // end catch_leak_detector.cpp
  9066. // start catch_list.cpp
  9067. // start catch_list.h
  9068. #include <set>
  9069. namespace Catch {
  9070. std::size_t listTests( Config const& config );
  9071. std::size_t listTestsNamesOnly( Config const& config );
  9072. struct TagInfo {
  9073. void add( std::string const& spelling );
  9074. std::string all() const;
  9075. std::set<std::string> spellings;
  9076. std::size_t count = 0;
  9077. };
  9078. std::size_t listTags( Config const& config );
  9079. std::size_t listReporters();
  9080. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9081. } // end namespace Catch
  9082. // end catch_list.h
  9083. // start catch_text.h
  9084. namespace Catch {
  9085. using namespace clara::TextFlow;
  9086. }
  9087. // end catch_text.h
  9088. #include <limits>
  9089. #include <algorithm>
  9090. #include <iomanip>
  9091. namespace Catch {
  9092. std::size_t listTests( Config const& config ) {
  9093. TestSpec const& testSpec = config.testSpec();
  9094. if( config.hasTestFilters() )
  9095. Catch::cout() << "Matching test cases:\n";
  9096. else {
  9097. Catch::cout() << "All available test cases:\n";
  9098. }
  9099. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9100. for( auto const& testCaseInfo : matchedTestCases ) {
  9101. Colour::Code colour = testCaseInfo.isHidden()
  9102. ? Colour::SecondaryText
  9103. : Colour::None;
  9104. Colour colourGuard( colour );
  9105. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9106. if( config.verbosity() >= Verbosity::High ) {
  9107. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9108. std::string description = testCaseInfo.description;
  9109. if( description.empty() )
  9110. description = "(NO DESCRIPTION)";
  9111. Catch::cout() << Column( description ).indent(4) << std::endl;
  9112. }
  9113. if( !testCaseInfo.tags.empty() )
  9114. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9115. }
  9116. if( !config.hasTestFilters() )
  9117. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9118. else
  9119. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9120. return matchedTestCases.size();
  9121. }
  9122. std::size_t listTestsNamesOnly( Config const& config ) {
  9123. TestSpec const& testSpec = config.testSpec();
  9124. std::size_t matchedTests = 0;
  9125. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9126. for( auto const& testCaseInfo : matchedTestCases ) {
  9127. matchedTests++;
  9128. if( startsWith( testCaseInfo.name, '#' ) )
  9129. Catch::cout() << '"' << testCaseInfo.name << '"';
  9130. else
  9131. Catch::cout() << testCaseInfo.name;
  9132. if ( config.verbosity() >= Verbosity::High )
  9133. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9134. Catch::cout() << std::endl;
  9135. }
  9136. return matchedTests;
  9137. }
  9138. void TagInfo::add( std::string const& spelling ) {
  9139. ++count;
  9140. spellings.insert( spelling );
  9141. }
  9142. std::string TagInfo::all() const {
  9143. size_t size = 0;
  9144. for (auto const& spelling : spellings) {
  9145. // Add 2 for the brackes
  9146. size += spelling.size() + 2;
  9147. }
  9148. std::string out; out.reserve(size);
  9149. for (auto const& spelling : spellings) {
  9150. out += '[';
  9151. out += spelling;
  9152. out += ']';
  9153. }
  9154. return out;
  9155. }
  9156. std::size_t listTags( Config const& config ) {
  9157. TestSpec const& testSpec = config.testSpec();
  9158. if( config.hasTestFilters() )
  9159. Catch::cout() << "Tags for matching test cases:\n";
  9160. else {
  9161. Catch::cout() << "All available tags:\n";
  9162. }
  9163. std::map<std::string, TagInfo> tagCounts;
  9164. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9165. for( auto const& testCase : matchedTestCases ) {
  9166. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9167. std::string lcaseTagName = toLower( tagName );
  9168. auto countIt = tagCounts.find( lcaseTagName );
  9169. if( countIt == tagCounts.end() )
  9170. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9171. countIt->second.add( tagName );
  9172. }
  9173. }
  9174. for( auto const& tagCount : tagCounts ) {
  9175. ReusableStringStream rss;
  9176. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9177. auto str = rss.str();
  9178. auto wrapper = Column( tagCount.second.all() )
  9179. .initialIndent( 0 )
  9180. .indent( str.size() )
  9181. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9182. Catch::cout() << str << wrapper << '\n';
  9183. }
  9184. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9185. return tagCounts.size();
  9186. }
  9187. std::size_t listReporters() {
  9188. Catch::cout() << "Available reporters:\n";
  9189. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9190. std::size_t maxNameLen = 0;
  9191. for( auto const& factoryKvp : factories )
  9192. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9193. for( auto const& factoryKvp : factories ) {
  9194. Catch::cout()
  9195. << Column( factoryKvp.first + ":" )
  9196. .indent(2)
  9197. .width( 5+maxNameLen )
  9198. + Column( factoryKvp.second->getDescription() )
  9199. .initialIndent(0)
  9200. .indent(2)
  9201. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9202. << "\n";
  9203. }
  9204. Catch::cout() << std::endl;
  9205. return factories.size();
  9206. }
  9207. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9208. Option<std::size_t> listedCount;
  9209. getCurrentMutableContext().setConfig( config );
  9210. if( config->listTests() )
  9211. listedCount = listedCount.valueOr(0) + listTests( *config );
  9212. if( config->listTestNamesOnly() )
  9213. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9214. if( config->listTags() )
  9215. listedCount = listedCount.valueOr(0) + listTags( *config );
  9216. if( config->listReporters() )
  9217. listedCount = listedCount.valueOr(0) + listReporters();
  9218. return listedCount;
  9219. }
  9220. } // end namespace Catch
  9221. // end catch_list.cpp
  9222. // start catch_matchers.cpp
  9223. namespace Catch {
  9224. namespace Matchers {
  9225. namespace Impl {
  9226. std::string MatcherUntypedBase::toString() const {
  9227. if( m_cachedToString.empty() )
  9228. m_cachedToString = describe();
  9229. return m_cachedToString;
  9230. }
  9231. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9232. } // namespace Impl
  9233. } // namespace Matchers
  9234. using namespace Matchers;
  9235. using Matchers::Impl::MatcherBase;
  9236. } // namespace Catch
  9237. // end catch_matchers.cpp
  9238. // start catch_matchers_exception.cpp
  9239. namespace Catch {
  9240. namespace Matchers {
  9241. namespace Exception {
  9242. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  9243. return ex.what() == m_message;
  9244. }
  9245. std::string ExceptionMessageMatcher::describe() const {
  9246. return "exception message matches \"" + m_message + "\"";
  9247. }
  9248. }
  9249. Exception::ExceptionMessageMatcher Message(std::string const& message) {
  9250. return Exception::ExceptionMessageMatcher(message);
  9251. }
  9252. // namespace Exception
  9253. } // namespace Matchers
  9254. } // namespace Catch
  9255. // end catch_matchers_exception.cpp
  9256. // start catch_matchers_floating.cpp
  9257. // start catch_polyfills.hpp
  9258. namespace Catch {
  9259. bool isnan(float f);
  9260. bool isnan(double d);
  9261. }
  9262. // end catch_polyfills.hpp
  9263. // start catch_to_string.hpp
  9264. #include <string>
  9265. namespace Catch {
  9266. template <typename T>
  9267. std::string to_string(T const& t) {
  9268. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9269. return std::to_string(t);
  9270. #else
  9271. ReusableStringStream rss;
  9272. rss << t;
  9273. return rss.str();
  9274. #endif
  9275. }
  9276. } // end namespace Catch
  9277. // end catch_to_string.hpp
  9278. #include <algorithm>
  9279. #include <cmath>
  9280. #include <cstdlib>
  9281. #include <cstdint>
  9282. #include <cstring>
  9283. #include <sstream>
  9284. #include <type_traits>
  9285. #include <iomanip>
  9286. #include <limits>
  9287. namespace Catch {
  9288. namespace {
  9289. int32_t convert(float f) {
  9290. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9291. int32_t i;
  9292. std::memcpy(&i, &f, sizeof(f));
  9293. return i;
  9294. }
  9295. int64_t convert(double d) {
  9296. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9297. int64_t i;
  9298. std::memcpy(&i, &d, sizeof(d));
  9299. return i;
  9300. }
  9301. template <typename FP>
  9302. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  9303. // Comparison with NaN should always be false.
  9304. // This way we can rule it out before getting into the ugly details
  9305. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9306. return false;
  9307. }
  9308. auto lc = convert(lhs);
  9309. auto rc = convert(rhs);
  9310. if ((lc < 0) != (rc < 0)) {
  9311. // Potentially we can have +0 and -0
  9312. return lhs == rhs;
  9313. }
  9314. auto ulpDiff = std::abs(lc - rc);
  9315. return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
  9316. }
  9317. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9318. float nextafter(float x, float y) {
  9319. return ::nextafterf(x, y);
  9320. }
  9321. double nextafter(double x, double y) {
  9322. return ::nextafter(x, y);
  9323. }
  9324. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  9325. template <typename FP>
  9326. FP step(FP start, FP direction, uint64_t steps) {
  9327. for (uint64_t i = 0; i < steps; ++i) {
  9328. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9329. start = Catch::nextafter(start, direction);
  9330. #else
  9331. start = std::nextafter(start, direction);
  9332. #endif
  9333. }
  9334. return start;
  9335. }
  9336. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9337. // But without the subtraction to allow for INFINITY in comparison
  9338. bool marginComparison(double lhs, double rhs, double margin) {
  9339. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  9340. }
  9341. template <typename FloatingPoint>
  9342. void write(std::ostream& out, FloatingPoint num) {
  9343. out << std::scientific
  9344. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  9345. << num;
  9346. }
  9347. } // end anonymous namespace
  9348. namespace Matchers {
  9349. namespace Floating {
  9350. enum class FloatingPointKind : uint8_t {
  9351. Float,
  9352. Double
  9353. };
  9354. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9355. :m_target{ target }, m_margin{ margin } {
  9356. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9357. << " Margin has to be non-negative.");
  9358. }
  9359. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9360. // But without the subtraction to allow for INFINITY in comparison
  9361. bool WithinAbsMatcher::match(double const& matchee) const {
  9362. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9363. }
  9364. std::string WithinAbsMatcher::describe() const {
  9365. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9366. }
  9367. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
  9368. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9369. CATCH_ENFORCE(m_type == FloatingPointKind::Double
  9370. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  9371. "Provided ULP is impossibly large for a float comparison.");
  9372. }
  9373. #if defined(__clang__)
  9374. #pragma clang diagnostic push
  9375. // Clang <3.5 reports on the default branch in the switch below
  9376. #pragma clang diagnostic ignored "-Wunreachable-code"
  9377. #endif
  9378. bool WithinUlpsMatcher::match(double const& matchee) const {
  9379. switch (m_type) {
  9380. case FloatingPointKind::Float:
  9381. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9382. case FloatingPointKind::Double:
  9383. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9384. default:
  9385. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9386. }
  9387. }
  9388. #if defined(__clang__)
  9389. #pragma clang diagnostic pop
  9390. #endif
  9391. std::string WithinUlpsMatcher::describe() const {
  9392. std::stringstream ret;
  9393. ret << "is within " << m_ulps << " ULPs of ";
  9394. if (m_type == FloatingPointKind::Float) {
  9395. write(ret, static_cast<float>(m_target));
  9396. ret << 'f';
  9397. } else {
  9398. write(ret, m_target);
  9399. }
  9400. ret << " ([";
  9401. if (m_type == FloatingPointKind::Double) {
  9402. write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
  9403. ret << ", ";
  9404. write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
  9405. } else {
  9406. // We have to cast INFINITY to float because of MinGW, see #1782
  9407. write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
  9408. ret << ", ";
  9409. write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
  9410. }
  9411. ret << "])";
  9412. return ret.str();
  9413. }
  9414. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  9415. m_target(target),
  9416. m_epsilon(epsilon){
  9417. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  9418. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  9419. }
  9420. bool WithinRelMatcher::match(double const& matchee) const {
  9421. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  9422. return marginComparison(matchee, m_target,
  9423. std::isinf(relMargin)? 0 : relMargin);
  9424. }
  9425. std::string WithinRelMatcher::describe() const {
  9426. Catch::ReusableStringStream sstr;
  9427. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  9428. return sstr.str();
  9429. }
  9430. }// namespace Floating
  9431. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  9432. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9433. }
  9434. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  9435. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9436. }
  9437. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9438. return Floating::WithinAbsMatcher(target, margin);
  9439. }
  9440. Floating::WithinRelMatcher WithinRel(double target, double eps) {
  9441. return Floating::WithinRelMatcher(target, eps);
  9442. }
  9443. Floating::WithinRelMatcher WithinRel(double target) {
  9444. return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  9445. }
  9446. Floating::WithinRelMatcher WithinRel(float target, float eps) {
  9447. return Floating::WithinRelMatcher(target, eps);
  9448. }
  9449. Floating::WithinRelMatcher WithinRel(float target) {
  9450. return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  9451. }
  9452. } // namespace Matchers
  9453. } // namespace Catch
  9454. // end catch_matchers_floating.cpp
  9455. // start catch_matchers_generic.cpp
  9456. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9457. if (desc.empty()) {
  9458. return "matches undescribed predicate";
  9459. } else {
  9460. return "matches predicate: \"" + desc + '"';
  9461. }
  9462. }
  9463. // end catch_matchers_generic.cpp
  9464. // start catch_matchers_string.cpp
  9465. #include <regex>
  9466. namespace Catch {
  9467. namespace Matchers {
  9468. namespace StdString {
  9469. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9470. : m_caseSensitivity( caseSensitivity ),
  9471. m_str( adjustString( str ) )
  9472. {}
  9473. std::string CasedString::adjustString( std::string const& str ) const {
  9474. return m_caseSensitivity == CaseSensitive::No
  9475. ? toLower( str )
  9476. : str;
  9477. }
  9478. std::string CasedString::caseSensitivitySuffix() const {
  9479. return m_caseSensitivity == CaseSensitive::No
  9480. ? " (case insensitive)"
  9481. : std::string();
  9482. }
  9483. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9484. : m_comparator( comparator ),
  9485. m_operation( operation ) {
  9486. }
  9487. std::string StringMatcherBase::describe() const {
  9488. std::string description;
  9489. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9490. m_comparator.caseSensitivitySuffix().size());
  9491. description += m_operation;
  9492. description += ": \"";
  9493. description += m_comparator.m_str;
  9494. description += "\"";
  9495. description += m_comparator.caseSensitivitySuffix();
  9496. return description;
  9497. }
  9498. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9499. bool EqualsMatcher::match( std::string const& source ) const {
  9500. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9501. }
  9502. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9503. bool ContainsMatcher::match( std::string const& source ) const {
  9504. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9505. }
  9506. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9507. bool StartsWithMatcher::match( std::string const& source ) const {
  9508. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9509. }
  9510. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9511. bool EndsWithMatcher::match( std::string const& source ) const {
  9512. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9513. }
  9514. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9515. bool RegexMatcher::match(std::string const& matchee) const {
  9516. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9517. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9518. flags |= std::regex::icase;
  9519. }
  9520. auto reg = std::regex(m_regex, flags);
  9521. return std::regex_match(matchee, reg);
  9522. }
  9523. std::string RegexMatcher::describe() const {
  9524. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9525. }
  9526. } // namespace StdString
  9527. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9528. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9529. }
  9530. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9531. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9532. }
  9533. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9534. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9535. }
  9536. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9537. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9538. }
  9539. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9540. return StdString::RegexMatcher(regex, caseSensitivity);
  9541. }
  9542. } // namespace Matchers
  9543. } // namespace Catch
  9544. // end catch_matchers_string.cpp
  9545. // start catch_message.cpp
  9546. // start catch_uncaught_exceptions.h
  9547. namespace Catch {
  9548. bool uncaught_exceptions();
  9549. } // end namespace Catch
  9550. // end catch_uncaught_exceptions.h
  9551. #include <cassert>
  9552. #include <stack>
  9553. namespace Catch {
  9554. MessageInfo::MessageInfo( StringRef const& _macroName,
  9555. SourceLineInfo const& _lineInfo,
  9556. ResultWas::OfType _type )
  9557. : macroName( _macroName ),
  9558. lineInfo( _lineInfo ),
  9559. type( _type ),
  9560. sequence( ++globalCount )
  9561. {}
  9562. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9563. return sequence == other.sequence;
  9564. }
  9565. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9566. return sequence < other.sequence;
  9567. }
  9568. // This may need protecting if threading support is added
  9569. unsigned int MessageInfo::globalCount = 0;
  9570. ////////////////////////////////////////////////////////////////////////////
  9571. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9572. SourceLineInfo const& lineInfo,
  9573. ResultWas::OfType type )
  9574. :m_info(macroName, lineInfo, type) {}
  9575. ////////////////////////////////////////////////////////////////////////////
  9576. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9577. : m_info( builder.m_info ), m_moved()
  9578. {
  9579. m_info.message = builder.m_stream.str();
  9580. getResultCapture().pushScopedMessage( m_info );
  9581. }
  9582. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9583. : m_info( old.m_info ), m_moved()
  9584. {
  9585. old.m_moved = true;
  9586. }
  9587. ScopedMessage::~ScopedMessage() {
  9588. if ( !uncaught_exceptions() && !m_moved ){
  9589. getResultCapture().popScopedMessage(m_info);
  9590. }
  9591. }
  9592. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9593. auto trimmed = [&] (size_t start, size_t end) {
  9594. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  9595. ++start;
  9596. }
  9597. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  9598. --end;
  9599. }
  9600. return names.substr(start, end - start + 1);
  9601. };
  9602. auto skipq = [&] (size_t start, char quote) {
  9603. for (auto i = start + 1; i < names.size() ; ++i) {
  9604. if (names[i] == quote)
  9605. return i;
  9606. if (names[i] == '\\')
  9607. ++i;
  9608. }
  9609. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9610. };
  9611. size_t start = 0;
  9612. std::stack<char> openings;
  9613. for (size_t pos = 0; pos < names.size(); ++pos) {
  9614. char c = names[pos];
  9615. switch (c) {
  9616. case '[':
  9617. case '{':
  9618. case '(':
  9619. // It is basically impossible to disambiguate between
  9620. // comparison and start of template args in this context
  9621. // case '<':
  9622. openings.push(c);
  9623. break;
  9624. case ']':
  9625. case '}':
  9626. case ')':
  9627. // case '>':
  9628. openings.pop();
  9629. break;
  9630. case '"':
  9631. case '\'':
  9632. pos = skipq(pos, c);
  9633. break;
  9634. case ',':
  9635. if (start != pos && openings.empty()) {
  9636. m_messages.emplace_back(macroName, lineInfo, resultType);
  9637. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  9638. m_messages.back().message += " := ";
  9639. start = pos;
  9640. }
  9641. }
  9642. }
  9643. assert(openings.empty() && "Mismatched openings");
  9644. m_messages.emplace_back(macroName, lineInfo, resultType);
  9645. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  9646. m_messages.back().message += " := ";
  9647. }
  9648. Capturer::~Capturer() {
  9649. if ( !uncaught_exceptions() ){
  9650. assert( m_captured == m_messages.size() );
  9651. for( size_t i = 0; i < m_captured; ++i )
  9652. m_resultCapture.popScopedMessage( m_messages[i] );
  9653. }
  9654. }
  9655. void Capturer::captureValue( size_t index, std::string const& value ) {
  9656. assert( index < m_messages.size() );
  9657. m_messages[index].message += value;
  9658. m_resultCapture.pushScopedMessage( m_messages[index] );
  9659. m_captured++;
  9660. }
  9661. } // end namespace Catch
  9662. // end catch_message.cpp
  9663. // start catch_output_redirect.cpp
  9664. // start catch_output_redirect.h
  9665. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9666. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9667. #include <cstdio>
  9668. #include <iosfwd>
  9669. #include <string>
  9670. namespace Catch {
  9671. class RedirectedStream {
  9672. std::ostream& m_originalStream;
  9673. std::ostream& m_redirectionStream;
  9674. std::streambuf* m_prevBuf;
  9675. public:
  9676. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9677. ~RedirectedStream();
  9678. };
  9679. class RedirectedStdOut {
  9680. ReusableStringStream m_rss;
  9681. RedirectedStream m_cout;
  9682. public:
  9683. RedirectedStdOut();
  9684. auto str() const -> std::string;
  9685. };
  9686. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9687. // This means that we need to redirect 2 streams into 1 to keep proper
  9688. // order of writes
  9689. class RedirectedStdErr {
  9690. ReusableStringStream m_rss;
  9691. RedirectedStream m_cerr;
  9692. RedirectedStream m_clog;
  9693. public:
  9694. RedirectedStdErr();
  9695. auto str() const -> std::string;
  9696. };
  9697. class RedirectedStreams {
  9698. public:
  9699. RedirectedStreams(RedirectedStreams const&) = delete;
  9700. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9701. RedirectedStreams(RedirectedStreams&&) = delete;
  9702. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9703. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9704. ~RedirectedStreams();
  9705. private:
  9706. std::string& m_redirectedCout;
  9707. std::string& m_redirectedCerr;
  9708. RedirectedStdOut m_redirectedStdOut;
  9709. RedirectedStdErr m_redirectedStdErr;
  9710. };
  9711. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9712. // Windows's implementation of std::tmpfile is terrible (it tries
  9713. // to create a file inside system folder, thus requiring elevated
  9714. // privileges for the binary), so we have to use tmpnam(_s) and
  9715. // create the file ourselves there.
  9716. class TempFile {
  9717. public:
  9718. TempFile(TempFile const&) = delete;
  9719. TempFile& operator=(TempFile const&) = delete;
  9720. TempFile(TempFile&&) = delete;
  9721. TempFile& operator=(TempFile&&) = delete;
  9722. TempFile();
  9723. ~TempFile();
  9724. std::FILE* getFile();
  9725. std::string getContents();
  9726. private:
  9727. std::FILE* m_file = nullptr;
  9728. #if defined(_MSC_VER)
  9729. char m_buffer[L_tmpnam] = { 0 };
  9730. #endif
  9731. };
  9732. class OutputRedirect {
  9733. public:
  9734. OutputRedirect(OutputRedirect const&) = delete;
  9735. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9736. OutputRedirect(OutputRedirect&&) = delete;
  9737. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9738. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9739. ~OutputRedirect();
  9740. private:
  9741. int m_originalStdout = -1;
  9742. int m_originalStderr = -1;
  9743. TempFile m_stdoutFile;
  9744. TempFile m_stderrFile;
  9745. std::string& m_stdoutDest;
  9746. std::string& m_stderrDest;
  9747. };
  9748. #endif
  9749. } // end namespace Catch
  9750. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9751. // end catch_output_redirect.h
  9752. #include <cstdio>
  9753. #include <cstring>
  9754. #include <fstream>
  9755. #include <sstream>
  9756. #include <stdexcept>
  9757. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9758. #if defined(_MSC_VER)
  9759. #include <io.h> //_dup and _dup2
  9760. #define dup _dup
  9761. #define dup2 _dup2
  9762. #define fileno _fileno
  9763. #else
  9764. #include <unistd.h> // dup and dup2
  9765. #endif
  9766. #endif
  9767. namespace Catch {
  9768. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9769. : m_originalStream( originalStream ),
  9770. m_redirectionStream( redirectionStream ),
  9771. m_prevBuf( m_originalStream.rdbuf() )
  9772. {
  9773. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9774. }
  9775. RedirectedStream::~RedirectedStream() {
  9776. m_originalStream.rdbuf( m_prevBuf );
  9777. }
  9778. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9779. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9780. RedirectedStdErr::RedirectedStdErr()
  9781. : m_cerr( Catch::cerr(), m_rss.get() ),
  9782. m_clog( Catch::clog(), m_rss.get() )
  9783. {}
  9784. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9785. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9786. : m_redirectedCout(redirectedCout),
  9787. m_redirectedCerr(redirectedCerr)
  9788. {}
  9789. RedirectedStreams::~RedirectedStreams() {
  9790. m_redirectedCout += m_redirectedStdOut.str();
  9791. m_redirectedCerr += m_redirectedStdErr.str();
  9792. }
  9793. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9794. #if defined(_MSC_VER)
  9795. TempFile::TempFile() {
  9796. if (tmpnam_s(m_buffer)) {
  9797. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9798. }
  9799. if (fopen_s(&m_file, m_buffer, "w+")) {
  9800. char buffer[100];
  9801. if (strerror_s(buffer, errno)) {
  9802. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9803. }
  9804. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9805. }
  9806. }
  9807. #else
  9808. TempFile::TempFile() {
  9809. m_file = std::tmpfile();
  9810. if (!m_file) {
  9811. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9812. }
  9813. }
  9814. #endif
  9815. TempFile::~TempFile() {
  9816. // TBD: What to do about errors here?
  9817. std::fclose(m_file);
  9818. // We manually create the file on Windows only, on Linux
  9819. // it will be autodeleted
  9820. #if defined(_MSC_VER)
  9821. std::remove(m_buffer);
  9822. #endif
  9823. }
  9824. FILE* TempFile::getFile() {
  9825. return m_file;
  9826. }
  9827. std::string TempFile::getContents() {
  9828. std::stringstream sstr;
  9829. char buffer[100] = {};
  9830. std::rewind(m_file);
  9831. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9832. sstr << buffer;
  9833. }
  9834. return sstr.str();
  9835. }
  9836. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9837. m_originalStdout(dup(1)),
  9838. m_originalStderr(dup(2)),
  9839. m_stdoutDest(stdout_dest),
  9840. m_stderrDest(stderr_dest) {
  9841. dup2(fileno(m_stdoutFile.getFile()), 1);
  9842. dup2(fileno(m_stderrFile.getFile()), 2);
  9843. }
  9844. OutputRedirect::~OutputRedirect() {
  9845. Catch::cout() << std::flush;
  9846. fflush(stdout);
  9847. // Since we support overriding these streams, we flush cerr
  9848. // even though std::cerr is unbuffered
  9849. Catch::cerr() << std::flush;
  9850. Catch::clog() << std::flush;
  9851. fflush(stderr);
  9852. dup2(m_originalStdout, 1);
  9853. dup2(m_originalStderr, 2);
  9854. m_stdoutDest += m_stdoutFile.getContents();
  9855. m_stderrDest += m_stderrFile.getContents();
  9856. }
  9857. #endif // CATCH_CONFIG_NEW_CAPTURE
  9858. } // namespace Catch
  9859. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9860. #if defined(_MSC_VER)
  9861. #undef dup
  9862. #undef dup2
  9863. #undef fileno
  9864. #endif
  9865. #endif
  9866. // end catch_output_redirect.cpp
  9867. // start catch_polyfills.cpp
  9868. #include <cmath>
  9869. namespace Catch {
  9870. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9871. bool isnan(float f) {
  9872. return std::isnan(f);
  9873. }
  9874. bool isnan(double d) {
  9875. return std::isnan(d);
  9876. }
  9877. #else
  9878. // For now we only use this for embarcadero
  9879. bool isnan(float f) {
  9880. return std::_isnan(f);
  9881. }
  9882. bool isnan(double d) {
  9883. return std::_isnan(d);
  9884. }
  9885. #endif
  9886. } // end namespace Catch
  9887. // end catch_polyfills.cpp
  9888. // start catch_random_number_generator.cpp
  9889. namespace Catch {
  9890. namespace {
  9891. #if defined(_MSC_VER)
  9892. #pragma warning(push)
  9893. #pragma warning(disable:4146) // we negate uint32 during the rotate
  9894. #endif
  9895. // Safe rotr implementation thanks to John Regehr
  9896. uint32_t rotate_right(uint32_t val, uint32_t count) {
  9897. const uint32_t mask = 31;
  9898. count &= mask;
  9899. return (val >> count) | (val << (-count & mask));
  9900. }
  9901. #if defined(_MSC_VER)
  9902. #pragma warning(pop)
  9903. #endif
  9904. }
  9905. SimplePcg32::SimplePcg32(result_type seed_) {
  9906. seed(seed_);
  9907. }
  9908. void SimplePcg32::seed(result_type seed_) {
  9909. m_state = 0;
  9910. (*this)();
  9911. m_state += seed_;
  9912. (*this)();
  9913. }
  9914. void SimplePcg32::discard(uint64_t skip) {
  9915. // We could implement this to run in O(log n) steps, but this
  9916. // should suffice for our use case.
  9917. for (uint64_t s = 0; s < skip; ++s) {
  9918. static_cast<void>((*this)());
  9919. }
  9920. }
  9921. SimplePcg32::result_type SimplePcg32::operator()() {
  9922. // prepare the output value
  9923. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  9924. const auto output = rotate_right(xorshifted, m_state >> 59u);
  9925. // advance state
  9926. m_state = m_state * 6364136223846793005ULL + s_inc;
  9927. return output;
  9928. }
  9929. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9930. return lhs.m_state == rhs.m_state;
  9931. }
  9932. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9933. return lhs.m_state != rhs.m_state;
  9934. }
  9935. }
  9936. // end catch_random_number_generator.cpp
  9937. // start catch_registry_hub.cpp
  9938. // start catch_test_case_registry_impl.h
  9939. #include <vector>
  9940. #include <set>
  9941. #include <algorithm>
  9942. #include <ios>
  9943. namespace Catch {
  9944. class TestCase;
  9945. struct IConfig;
  9946. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9947. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  9948. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9949. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9950. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9951. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9952. class TestRegistry : public ITestCaseRegistry {
  9953. public:
  9954. virtual ~TestRegistry() = default;
  9955. virtual void registerTest( TestCase const& testCase );
  9956. std::vector<TestCase> const& getAllTests() const override;
  9957. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9958. private:
  9959. std::vector<TestCase> m_functions;
  9960. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9961. mutable std::vector<TestCase> m_sortedFunctions;
  9962. std::size_t m_unnamedCount = 0;
  9963. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9964. };
  9965. ///////////////////////////////////////////////////////////////////////////
  9966. class TestInvokerAsFunction : public ITestInvoker {
  9967. void(*m_testAsFunction)();
  9968. public:
  9969. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9970. void invoke() const override;
  9971. };
  9972. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9973. ///////////////////////////////////////////////////////////////////////////
  9974. } // end namespace Catch
  9975. // end catch_test_case_registry_impl.h
  9976. // start catch_reporter_registry.h
  9977. #include <map>
  9978. namespace Catch {
  9979. class ReporterRegistry : public IReporterRegistry {
  9980. public:
  9981. ~ReporterRegistry() override;
  9982. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9983. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9984. void registerListener( IReporterFactoryPtr const& factory );
  9985. FactoryMap const& getFactories() const override;
  9986. Listeners const& getListeners() const override;
  9987. private:
  9988. FactoryMap m_factories;
  9989. Listeners m_listeners;
  9990. };
  9991. }
  9992. // end catch_reporter_registry.h
  9993. // start catch_tag_alias_registry.h
  9994. // start catch_tag_alias.h
  9995. #include <string>
  9996. namespace Catch {
  9997. struct TagAlias {
  9998. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9999. std::string tag;
  10000. SourceLineInfo lineInfo;
  10001. };
  10002. } // end namespace Catch
  10003. // end catch_tag_alias.h
  10004. #include <map>
  10005. namespace Catch {
  10006. class TagAliasRegistry : public ITagAliasRegistry {
  10007. public:
  10008. ~TagAliasRegistry() override;
  10009. TagAlias const* find( std::string const& alias ) const override;
  10010. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10011. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10012. private:
  10013. std::map<std::string, TagAlias> m_registry;
  10014. };
  10015. } // end namespace Catch
  10016. // end catch_tag_alias_registry.h
  10017. // start catch_startup_exception_registry.h
  10018. #include <vector>
  10019. #include <exception>
  10020. namespace Catch {
  10021. class StartupExceptionRegistry {
  10022. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10023. public:
  10024. void add(std::exception_ptr const& exception) noexcept;
  10025. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10026. private:
  10027. std::vector<std::exception_ptr> m_exceptions;
  10028. #endif
  10029. };
  10030. } // end namespace Catch
  10031. // end catch_startup_exception_registry.h
  10032. // start catch_singletons.hpp
  10033. namespace Catch {
  10034. struct ISingleton {
  10035. virtual ~ISingleton();
  10036. };
  10037. void addSingleton( ISingleton* singleton );
  10038. void cleanupSingletons();
  10039. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10040. class Singleton : SingletonImplT, public ISingleton {
  10041. static auto getInternal() -> Singleton* {
  10042. static Singleton* s_instance = nullptr;
  10043. if( !s_instance ) {
  10044. s_instance = new Singleton;
  10045. addSingleton( s_instance );
  10046. }
  10047. return s_instance;
  10048. }
  10049. public:
  10050. static auto get() -> InterfaceT const& {
  10051. return *getInternal();
  10052. }
  10053. static auto getMutable() -> MutableInterfaceT& {
  10054. return *getInternal();
  10055. }
  10056. };
  10057. } // namespace Catch
  10058. // end catch_singletons.hpp
  10059. namespace Catch {
  10060. namespace {
  10061. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10062. private NonCopyable {
  10063. public: // IRegistryHub
  10064. RegistryHub() = default;
  10065. IReporterRegistry const& getReporterRegistry() const override {
  10066. return m_reporterRegistry;
  10067. }
  10068. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10069. return m_testCaseRegistry;
  10070. }
  10071. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10072. return m_exceptionTranslatorRegistry;
  10073. }
  10074. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10075. return m_tagAliasRegistry;
  10076. }
  10077. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10078. return m_exceptionRegistry;
  10079. }
  10080. public: // IMutableRegistryHub
  10081. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10082. m_reporterRegistry.registerReporter( name, factory );
  10083. }
  10084. void registerListener( IReporterFactoryPtr const& factory ) override {
  10085. m_reporterRegistry.registerListener( factory );
  10086. }
  10087. void registerTest( TestCase const& testInfo ) override {
  10088. m_testCaseRegistry.registerTest( testInfo );
  10089. }
  10090. void registerTranslator( const IExceptionTranslator* translator ) override {
  10091. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10092. }
  10093. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10094. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10095. }
  10096. void registerStartupException() noexcept override {
  10097. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10098. m_exceptionRegistry.add(std::current_exception());
  10099. #else
  10100. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  10101. #endif
  10102. }
  10103. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10104. return m_enumValuesRegistry;
  10105. }
  10106. private:
  10107. TestRegistry m_testCaseRegistry;
  10108. ReporterRegistry m_reporterRegistry;
  10109. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10110. TagAliasRegistry m_tagAliasRegistry;
  10111. StartupExceptionRegistry m_exceptionRegistry;
  10112. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10113. };
  10114. }
  10115. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10116. IRegistryHub const& getRegistryHub() {
  10117. return RegistryHubSingleton::get();
  10118. }
  10119. IMutableRegistryHub& getMutableRegistryHub() {
  10120. return RegistryHubSingleton::getMutable();
  10121. }
  10122. void cleanUp() {
  10123. cleanupSingletons();
  10124. cleanUpContext();
  10125. }
  10126. std::string translateActiveException() {
  10127. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10128. }
  10129. } // end namespace Catch
  10130. // end catch_registry_hub.cpp
  10131. // start catch_reporter_registry.cpp
  10132. namespace Catch {
  10133. ReporterRegistry::~ReporterRegistry() = default;
  10134. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10135. auto it = m_factories.find( name );
  10136. if( it == m_factories.end() )
  10137. return nullptr;
  10138. return it->second->create( ReporterConfig( config ) );
  10139. }
  10140. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10141. m_factories.emplace(name, factory);
  10142. }
  10143. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10144. m_listeners.push_back( factory );
  10145. }
  10146. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10147. return m_factories;
  10148. }
  10149. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10150. return m_listeners;
  10151. }
  10152. }
  10153. // end catch_reporter_registry.cpp
  10154. // start catch_result_type.cpp
  10155. namespace Catch {
  10156. bool isOk( ResultWas::OfType resultType ) {
  10157. return ( resultType & ResultWas::FailureBit ) == 0;
  10158. }
  10159. bool isJustInfo( int flags ) {
  10160. return flags == ResultWas::Info;
  10161. }
  10162. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10163. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10164. }
  10165. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10166. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10167. } // end namespace Catch
  10168. // end catch_result_type.cpp
  10169. // start catch_run_context.cpp
  10170. #include <cassert>
  10171. #include <algorithm>
  10172. #include <sstream>
  10173. namespace Catch {
  10174. namespace Generators {
  10175. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10176. GeneratorBasePtr m_generator;
  10177. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10178. : TrackerBase( nameAndLocation, ctx, parent )
  10179. {}
  10180. ~GeneratorTracker();
  10181. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10182. std::shared_ptr<GeneratorTracker> tracker;
  10183. ITracker& currentTracker = ctx.currentTracker();
  10184. // Under specific circumstances, the generator we want
  10185. // to acquire is also the current tracker. If this is
  10186. // the case, we have to avoid looking through current
  10187. // tracker's children, and instead return the current
  10188. // tracker.
  10189. // A case where this check is important is e.g.
  10190. // for (int i = 0; i < 5; ++i) {
  10191. // int n = GENERATE(1, 2);
  10192. // }
  10193. //
  10194. // without it, the code above creates 5 nested generators.
  10195. if (currentTracker.nameAndLocation() == nameAndLocation) {
  10196. auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
  10197. assert(thisTracker);
  10198. assert(thisTracker->isGeneratorTracker());
  10199. tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
  10200. } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10201. assert( childTracker );
  10202. assert( childTracker->isGeneratorTracker() );
  10203. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10204. } else {
  10205. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10206. currentTracker.addChild( tracker );
  10207. }
  10208. if( !tracker->isComplete() ) {
  10209. tracker->open();
  10210. }
  10211. return *tracker;
  10212. }
  10213. // TrackerBase interface
  10214. bool isGeneratorTracker() const override { return true; }
  10215. auto hasGenerator() const -> bool override {
  10216. return !!m_generator;
  10217. }
  10218. void close() override {
  10219. TrackerBase::close();
  10220. // If a generator has a child (it is followed by a section)
  10221. // and none of its children have started, then we must wait
  10222. // until later to start consuming its values.
  10223. // This catches cases where `GENERATE` is placed between two
  10224. // `SECTION`s.
  10225. // **The check for m_children.empty cannot be removed**.
  10226. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  10227. const bool should_wait_for_child =
  10228. !m_children.empty() &&
  10229. std::find_if( m_children.begin(),
  10230. m_children.end(),
  10231. []( TestCaseTracking::ITrackerPtr tracker ) {
  10232. return tracker->hasStarted();
  10233. } ) == m_children.end();
  10234. // This check is a bit tricky, because m_generator->next()
  10235. // has a side-effect, where it consumes generator's current
  10236. // value, but we do not want to invoke the side-effect if
  10237. // this generator is still waiting for any child to start.
  10238. if ( should_wait_for_child ||
  10239. ( m_runState == CompletedSuccessfully &&
  10240. m_generator->next() ) ) {
  10241. m_children.clear();
  10242. m_runState = Executing;
  10243. }
  10244. }
  10245. // IGeneratorTracker interface
  10246. auto getGenerator() const -> GeneratorBasePtr const& override {
  10247. return m_generator;
  10248. }
  10249. void setGenerator( GeneratorBasePtr&& generator ) override {
  10250. m_generator = std::move( generator );
  10251. }
  10252. };
  10253. GeneratorTracker::~GeneratorTracker() {}
  10254. }
  10255. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10256. : m_runInfo(_config->name()),
  10257. m_context(getCurrentMutableContext()),
  10258. m_config(_config),
  10259. m_reporter(std::move(reporter)),
  10260. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10261. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10262. {
  10263. m_context.setRunner(this);
  10264. m_context.setConfig(m_config);
  10265. m_context.setResultCapture(this);
  10266. m_reporter->testRunStarting(m_runInfo);
  10267. }
  10268. RunContext::~RunContext() {
  10269. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10270. }
  10271. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10272. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10273. }
  10274. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10275. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10276. }
  10277. Totals RunContext::runTest(TestCase const& testCase) {
  10278. Totals prevTotals = m_totals;
  10279. std::string redirectedCout;
  10280. std::string redirectedCerr;
  10281. auto const& testInfo = testCase.getTestCaseInfo();
  10282. m_reporter->testCaseStarting(testInfo);
  10283. m_activeTestCase = &testCase;
  10284. ITracker& rootTracker = m_trackerContext.startRun();
  10285. assert(rootTracker.isSectionTracker());
  10286. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10287. do {
  10288. m_trackerContext.startCycle();
  10289. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10290. runCurrentTest(redirectedCout, redirectedCerr);
  10291. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10292. Totals deltaTotals = m_totals.delta(prevTotals);
  10293. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10294. deltaTotals.assertions.failed++;
  10295. deltaTotals.testCases.passed--;
  10296. deltaTotals.testCases.failed++;
  10297. }
  10298. m_totals.testCases += deltaTotals.testCases;
  10299. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10300. deltaTotals,
  10301. redirectedCout,
  10302. redirectedCerr,
  10303. aborting()));
  10304. m_activeTestCase = nullptr;
  10305. m_testCaseTracker = nullptr;
  10306. return deltaTotals;
  10307. }
  10308. IConfigPtr RunContext::config() const {
  10309. return m_config;
  10310. }
  10311. IStreamingReporter& RunContext::reporter() const {
  10312. return *m_reporter;
  10313. }
  10314. void RunContext::assertionEnded(AssertionResult const & result) {
  10315. if (result.getResultType() == ResultWas::Ok) {
  10316. m_totals.assertions.passed++;
  10317. m_lastAssertionPassed = true;
  10318. } else if (!result.isOk()) {
  10319. m_lastAssertionPassed = false;
  10320. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10321. m_totals.assertions.failedButOk++;
  10322. else
  10323. m_totals.assertions.failed++;
  10324. }
  10325. else {
  10326. m_lastAssertionPassed = true;
  10327. }
  10328. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10329. // and should be let to clear themselves out.
  10330. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10331. if (result.getResultType() != ResultWas::Warning)
  10332. m_messageScopes.clear();
  10333. // Reset working state
  10334. resetAssertionInfo();
  10335. m_lastResult = result;
  10336. }
  10337. void RunContext::resetAssertionInfo() {
  10338. m_lastAssertionInfo.macroName = StringRef();
  10339. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10340. }
  10341. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10342. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10343. if (!sectionTracker.isOpen())
  10344. return false;
  10345. m_activeSections.push_back(&sectionTracker);
  10346. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10347. m_reporter->sectionStarting(sectionInfo);
  10348. assertions = m_totals.assertions;
  10349. return true;
  10350. }
  10351. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10352. using namespace Generators;
  10353. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  10354. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  10355. m_lastAssertionInfo.lineInfo = lineInfo;
  10356. return tracker;
  10357. }
  10358. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10359. if (assertions.total() != 0)
  10360. return false;
  10361. if (!m_config->warnAboutMissingAssertions())
  10362. return false;
  10363. if (m_trackerContext.currentTracker().hasChildren())
  10364. return false;
  10365. m_totals.assertions.failed++;
  10366. assertions.failed++;
  10367. return true;
  10368. }
  10369. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10370. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10371. bool missingAssertions = testForMissingAssertions(assertions);
  10372. if (!m_activeSections.empty()) {
  10373. m_activeSections.back()->close();
  10374. m_activeSections.pop_back();
  10375. }
  10376. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10377. m_messages.clear();
  10378. m_messageScopes.clear();
  10379. }
  10380. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10381. if (m_unfinishedSections.empty())
  10382. m_activeSections.back()->fail();
  10383. else
  10384. m_activeSections.back()->close();
  10385. m_activeSections.pop_back();
  10386. m_unfinishedSections.push_back(endInfo);
  10387. }
  10388. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10389. void RunContext::benchmarkPreparing(std::string const& name) {
  10390. m_reporter->benchmarkPreparing(name);
  10391. }
  10392. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10393. m_reporter->benchmarkStarting( info );
  10394. }
  10395. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10396. m_reporter->benchmarkEnded( stats );
  10397. }
  10398. void RunContext::benchmarkFailed(std::string const & error) {
  10399. m_reporter->benchmarkFailed(error);
  10400. }
  10401. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10402. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10403. m_messages.push_back(message);
  10404. }
  10405. void RunContext::popScopedMessage(MessageInfo const & message) {
  10406. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10407. }
  10408. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10409. m_messageScopes.emplace_back( builder );
  10410. }
  10411. std::string RunContext::getCurrentTestName() const {
  10412. return m_activeTestCase
  10413. ? m_activeTestCase->getTestCaseInfo().name
  10414. : std::string();
  10415. }
  10416. const AssertionResult * RunContext::getLastResult() const {
  10417. return &(*m_lastResult);
  10418. }
  10419. void RunContext::exceptionEarlyReported() {
  10420. m_shouldReportUnexpected = false;
  10421. }
  10422. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10423. // First notify reporter that bad things happened
  10424. m_reporter->fatalErrorEncountered(message);
  10425. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10426. // Instead, fake a result data.
  10427. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10428. tempResult.message = static_cast<std::string>(message);
  10429. AssertionResult result(m_lastAssertionInfo, tempResult);
  10430. assertionEnded(result);
  10431. handleUnfinishedSections();
  10432. // Recreate section for test case (as we will lose the one that was in scope)
  10433. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10434. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10435. Counts assertions;
  10436. assertions.failed = 1;
  10437. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10438. m_reporter->sectionEnded(testCaseSectionStats);
  10439. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10440. Totals deltaTotals;
  10441. deltaTotals.testCases.failed = 1;
  10442. deltaTotals.assertions.failed = 1;
  10443. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10444. deltaTotals,
  10445. std::string(),
  10446. std::string(),
  10447. false));
  10448. m_totals.testCases.failed++;
  10449. testGroupEnded(std::string(), m_totals, 1, 1);
  10450. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10451. }
  10452. bool RunContext::lastAssertionPassed() {
  10453. return m_lastAssertionPassed;
  10454. }
  10455. void RunContext::assertionPassed() {
  10456. m_lastAssertionPassed = true;
  10457. ++m_totals.assertions.passed;
  10458. resetAssertionInfo();
  10459. m_messageScopes.clear();
  10460. }
  10461. bool RunContext::aborting() const {
  10462. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10463. }
  10464. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10465. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10466. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10467. m_reporter->sectionStarting(testCaseSection);
  10468. Counts prevAssertions = m_totals.assertions;
  10469. double duration = 0;
  10470. m_shouldReportUnexpected = true;
  10471. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10472. seedRng(*m_config);
  10473. Timer timer;
  10474. CATCH_TRY {
  10475. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10476. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10477. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10478. timer.start();
  10479. invokeActiveTestCase();
  10480. #else
  10481. OutputRedirect r(redirectedCout, redirectedCerr);
  10482. timer.start();
  10483. invokeActiveTestCase();
  10484. #endif
  10485. } else {
  10486. timer.start();
  10487. invokeActiveTestCase();
  10488. }
  10489. duration = timer.getElapsedSeconds();
  10490. } CATCH_CATCH_ANON (TestFailureException&) {
  10491. // This just means the test was aborted due to failure
  10492. } CATCH_CATCH_ALL {
  10493. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10494. // are reported without translation at the point of origin.
  10495. if( m_shouldReportUnexpected ) {
  10496. AssertionReaction dummyReaction;
  10497. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10498. }
  10499. }
  10500. Counts assertions = m_totals.assertions - prevAssertions;
  10501. bool missingAssertions = testForMissingAssertions(assertions);
  10502. m_testCaseTracker->close();
  10503. handleUnfinishedSections();
  10504. m_messages.clear();
  10505. m_messageScopes.clear();
  10506. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10507. m_reporter->sectionEnded(testCaseSectionStats);
  10508. }
  10509. void RunContext::invokeActiveTestCase() {
  10510. FatalConditionHandler fatalConditionHandler; // Handle signals
  10511. m_activeTestCase->invoke();
  10512. fatalConditionHandler.reset();
  10513. }
  10514. void RunContext::handleUnfinishedSections() {
  10515. // If sections ended prematurely due to an exception we stored their
  10516. // infos here so we can tear them down outside the unwind process.
  10517. for (auto it = m_unfinishedSections.rbegin(),
  10518. itEnd = m_unfinishedSections.rend();
  10519. it != itEnd;
  10520. ++it)
  10521. sectionEnded(*it);
  10522. m_unfinishedSections.clear();
  10523. }
  10524. void RunContext::handleExpr(
  10525. AssertionInfo const& info,
  10526. ITransientExpression const& expr,
  10527. AssertionReaction& reaction
  10528. ) {
  10529. m_reporter->assertionStarting( info );
  10530. bool negated = isFalseTest( info.resultDisposition );
  10531. bool result = expr.getResult() != negated;
  10532. if( result ) {
  10533. if (!m_includeSuccessfulResults) {
  10534. assertionPassed();
  10535. }
  10536. else {
  10537. reportExpr(info, ResultWas::Ok, &expr, negated);
  10538. }
  10539. }
  10540. else {
  10541. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10542. populateReaction( reaction );
  10543. }
  10544. }
  10545. void RunContext::reportExpr(
  10546. AssertionInfo const &info,
  10547. ResultWas::OfType resultType,
  10548. ITransientExpression const *expr,
  10549. bool negated ) {
  10550. m_lastAssertionInfo = info;
  10551. AssertionResultData data( resultType, LazyExpression( negated ) );
  10552. AssertionResult assertionResult{ info, data };
  10553. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10554. assertionEnded( assertionResult );
  10555. }
  10556. void RunContext::handleMessage(
  10557. AssertionInfo const& info,
  10558. ResultWas::OfType resultType,
  10559. StringRef const& message,
  10560. AssertionReaction& reaction
  10561. ) {
  10562. m_reporter->assertionStarting( info );
  10563. m_lastAssertionInfo = info;
  10564. AssertionResultData data( resultType, LazyExpression( false ) );
  10565. data.message = static_cast<std::string>(message);
  10566. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10567. assertionEnded( assertionResult );
  10568. if( !assertionResult.isOk() )
  10569. populateReaction( reaction );
  10570. }
  10571. void RunContext::handleUnexpectedExceptionNotThrown(
  10572. AssertionInfo const& info,
  10573. AssertionReaction& reaction
  10574. ) {
  10575. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10576. }
  10577. void RunContext::handleUnexpectedInflightException(
  10578. AssertionInfo const& info,
  10579. std::string const& message,
  10580. AssertionReaction& reaction
  10581. ) {
  10582. m_lastAssertionInfo = info;
  10583. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10584. data.message = message;
  10585. AssertionResult assertionResult{ info, data };
  10586. assertionEnded( assertionResult );
  10587. populateReaction( reaction );
  10588. }
  10589. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10590. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10591. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10592. }
  10593. void RunContext::handleIncomplete(
  10594. AssertionInfo const& info
  10595. ) {
  10596. m_lastAssertionInfo = info;
  10597. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10598. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10599. AssertionResult assertionResult{ info, data };
  10600. assertionEnded( assertionResult );
  10601. }
  10602. void RunContext::handleNonExpr(
  10603. AssertionInfo const &info,
  10604. ResultWas::OfType resultType,
  10605. AssertionReaction &reaction
  10606. ) {
  10607. m_lastAssertionInfo = info;
  10608. AssertionResultData data( resultType, LazyExpression( false ) );
  10609. AssertionResult assertionResult{ info, data };
  10610. assertionEnded( assertionResult );
  10611. if( !assertionResult.isOk() )
  10612. populateReaction( reaction );
  10613. }
  10614. IResultCapture& getResultCapture() {
  10615. if (auto* capture = getCurrentContext().getResultCapture())
  10616. return *capture;
  10617. else
  10618. CATCH_INTERNAL_ERROR("No result capture instance");
  10619. }
  10620. void seedRng(IConfig const& config) {
  10621. if (config.rngSeed() != 0) {
  10622. std::srand(config.rngSeed());
  10623. rng().seed(config.rngSeed());
  10624. }
  10625. }
  10626. unsigned int rngSeed() {
  10627. return getCurrentContext().getConfig()->rngSeed();
  10628. }
  10629. }
  10630. // end catch_run_context.cpp
  10631. // start catch_section.cpp
  10632. namespace Catch {
  10633. Section::Section( SectionInfo const& info )
  10634. : m_info( info ),
  10635. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10636. {
  10637. m_timer.start();
  10638. }
  10639. Section::~Section() {
  10640. if( m_sectionIncluded ) {
  10641. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10642. if( uncaught_exceptions() )
  10643. getResultCapture().sectionEndedEarly( endInfo );
  10644. else
  10645. getResultCapture().sectionEnded( endInfo );
  10646. }
  10647. }
  10648. // This indicates whether the section should be executed or not
  10649. Section::operator bool() const {
  10650. return m_sectionIncluded;
  10651. }
  10652. } // end namespace Catch
  10653. // end catch_section.cpp
  10654. // start catch_section_info.cpp
  10655. namespace Catch {
  10656. SectionInfo::SectionInfo
  10657. ( SourceLineInfo const& _lineInfo,
  10658. std::string const& _name )
  10659. : name( _name ),
  10660. lineInfo( _lineInfo )
  10661. {}
  10662. } // end namespace Catch
  10663. // end catch_section_info.cpp
  10664. // start catch_session.cpp
  10665. // start catch_session.h
  10666. #include <memory>
  10667. namespace Catch {
  10668. class Session : NonCopyable {
  10669. public:
  10670. Session();
  10671. ~Session() override;
  10672. void showHelp() const;
  10673. void libIdentify();
  10674. int applyCommandLine( int argc, char const * const * argv );
  10675. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10676. int applyCommandLine( int argc, wchar_t const * const * argv );
  10677. #endif
  10678. void useConfigData( ConfigData const& configData );
  10679. template<typename CharT>
  10680. int run(int argc, CharT const * const argv[]) {
  10681. if (m_startupExceptions)
  10682. return 1;
  10683. int returnCode = applyCommandLine(argc, argv);
  10684. if (returnCode == 0)
  10685. returnCode = run();
  10686. return returnCode;
  10687. }
  10688. int run();
  10689. clara::Parser const& cli() const;
  10690. void cli( clara::Parser const& newParser );
  10691. ConfigData& configData();
  10692. Config& config();
  10693. private:
  10694. int runInternal();
  10695. clara::Parser m_cli;
  10696. ConfigData m_configData;
  10697. std::shared_ptr<Config> m_config;
  10698. bool m_startupExceptions = false;
  10699. };
  10700. } // end namespace Catch
  10701. // end catch_session.h
  10702. // start catch_version.h
  10703. #include <iosfwd>
  10704. namespace Catch {
  10705. // Versioning information
  10706. struct Version {
  10707. Version( Version const& ) = delete;
  10708. Version& operator=( Version const& ) = delete;
  10709. Version( unsigned int _majorVersion,
  10710. unsigned int _minorVersion,
  10711. unsigned int _patchNumber,
  10712. char const * const _branchName,
  10713. unsigned int _buildNumber );
  10714. unsigned int const majorVersion;
  10715. unsigned int const minorVersion;
  10716. unsigned int const patchNumber;
  10717. // buildNumber is only used if branchName is not null
  10718. char const * const branchName;
  10719. unsigned int const buildNumber;
  10720. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10721. };
  10722. Version const& libraryVersion();
  10723. }
  10724. // end catch_version.h
  10725. #include <cstdlib>
  10726. #include <iomanip>
  10727. #include <set>
  10728. #include <iterator>
  10729. namespace Catch {
  10730. namespace {
  10731. const int MaxExitCode = 255;
  10732. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10733. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10734. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10735. return reporter;
  10736. }
  10737. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10738. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10739. return createReporter(config->getReporterName(), config);
  10740. }
  10741. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10742. // when the return type is std::unique_ptr<IStreamingReporter>
  10743. // doesn't compile without a std::move call. However, this causes
  10744. // a warning on newer platforms. Thus, we have to work around
  10745. // it a bit and downcast the pointer manually.
  10746. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10747. auto& multi = static_cast<ListeningReporter&>(*ret);
  10748. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10749. for (auto const& listener : listeners) {
  10750. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10751. }
  10752. multi.addReporter(createReporter(config->getReporterName(), config));
  10753. return ret;
  10754. }
  10755. class TestGroup {
  10756. public:
  10757. explicit TestGroup(std::shared_ptr<Config> const& config)
  10758. : m_config{config}
  10759. , m_context{config, makeReporter(config)}
  10760. {
  10761. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10762. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10763. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10764. if (m_matches.empty() && invalidArgs.empty()) {
  10765. for (auto const& test : allTestCases)
  10766. if (!test.isHidden())
  10767. m_tests.emplace(&test);
  10768. } else {
  10769. for (auto const& match : m_matches)
  10770. m_tests.insert(match.tests.begin(), match.tests.end());
  10771. }
  10772. }
  10773. Totals execute() {
  10774. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10775. Totals totals;
  10776. m_context.testGroupStarting(m_config->name(), 1, 1);
  10777. for (auto const& testCase : m_tests) {
  10778. if (!m_context.aborting())
  10779. totals += m_context.runTest(*testCase);
  10780. else
  10781. m_context.reporter().skipTest(*testCase);
  10782. }
  10783. for (auto const& match : m_matches) {
  10784. if (match.tests.empty()) {
  10785. m_context.reporter().noMatchingTestCases(match.name);
  10786. totals.error = -1;
  10787. }
  10788. }
  10789. if (!invalidArgs.empty()) {
  10790. for (auto const& invalidArg: invalidArgs)
  10791. m_context.reporter().reportInvalidArguments(invalidArg);
  10792. }
  10793. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10794. return totals;
  10795. }
  10796. private:
  10797. using Tests = std::set<TestCase const*>;
  10798. std::shared_ptr<Config> m_config;
  10799. RunContext m_context;
  10800. Tests m_tests;
  10801. TestSpec::Matches m_matches;
  10802. };
  10803. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10804. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10805. for (auto& testCase : tests) {
  10806. auto tags = testCase.tags;
  10807. std::string filename = testCase.lineInfo.file;
  10808. auto lastSlash = filename.find_last_of("\\/");
  10809. if (lastSlash != std::string::npos) {
  10810. filename.erase(0, lastSlash);
  10811. filename[0] = '#';
  10812. }
  10813. auto lastDot = filename.find_last_of('.');
  10814. if (lastDot != std::string::npos) {
  10815. filename.erase(lastDot);
  10816. }
  10817. tags.push_back(std::move(filename));
  10818. setTags(testCase, tags);
  10819. }
  10820. }
  10821. } // anon namespace
  10822. Session::Session() {
  10823. static bool alreadyInstantiated = false;
  10824. if( alreadyInstantiated ) {
  10825. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10826. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10827. }
  10828. // There cannot be exceptions at startup in no-exception mode.
  10829. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10830. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10831. if ( !exceptions.empty() ) {
  10832. config();
  10833. getCurrentMutableContext().setConfig(m_config);
  10834. m_startupExceptions = true;
  10835. Colour colourGuard( Colour::Red );
  10836. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10837. // iterate over all exceptions and notify user
  10838. for ( const auto& ex_ptr : exceptions ) {
  10839. try {
  10840. std::rethrow_exception(ex_ptr);
  10841. } catch ( std::exception const& ex ) {
  10842. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10843. }
  10844. }
  10845. }
  10846. #endif
  10847. alreadyInstantiated = true;
  10848. m_cli = makeCommandLineParser( m_configData );
  10849. }
  10850. Session::~Session() {
  10851. Catch::cleanUp();
  10852. }
  10853. void Session::showHelp() const {
  10854. Catch::cout()
  10855. << "\nCatch v" << libraryVersion() << "\n"
  10856. << m_cli << std::endl
  10857. << "For more detailed usage please see the project docs\n" << std::endl;
  10858. }
  10859. void Session::libIdentify() {
  10860. Catch::cout()
  10861. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  10862. << std::left << std::setw(16) << "category: " << "testframework\n"
  10863. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10864. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10865. }
  10866. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10867. if( m_startupExceptions )
  10868. return 1;
  10869. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10870. if( !result ) {
  10871. config();
  10872. getCurrentMutableContext().setConfig(m_config);
  10873. Catch::cerr()
  10874. << Colour( Colour::Red )
  10875. << "\nError(s) in input:\n"
  10876. << Column( result.errorMessage() ).indent( 2 )
  10877. << "\n\n";
  10878. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10879. return MaxExitCode;
  10880. }
  10881. if( m_configData.showHelp )
  10882. showHelp();
  10883. if( m_configData.libIdentify )
  10884. libIdentify();
  10885. m_config.reset();
  10886. return 0;
  10887. }
  10888. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10889. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10890. char **utf8Argv = new char *[ argc ];
  10891. for ( int i = 0; i < argc; ++i ) {
  10892. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  10893. utf8Argv[ i ] = new char[ bufSize ];
  10894. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  10895. }
  10896. int returnCode = applyCommandLine( argc, utf8Argv );
  10897. for ( int i = 0; i < argc; ++i )
  10898. delete [] utf8Argv[ i ];
  10899. delete [] utf8Argv;
  10900. return returnCode;
  10901. }
  10902. #endif
  10903. void Session::useConfigData( ConfigData const& configData ) {
  10904. m_configData = configData;
  10905. m_config.reset();
  10906. }
  10907. int Session::run() {
  10908. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10909. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10910. static_cast<void>(std::getchar());
  10911. }
  10912. int exitCode = runInternal();
  10913. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10914. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10915. static_cast<void>(std::getchar());
  10916. }
  10917. return exitCode;
  10918. }
  10919. clara::Parser const& Session::cli() const {
  10920. return m_cli;
  10921. }
  10922. void Session::cli( clara::Parser const& newParser ) {
  10923. m_cli = newParser;
  10924. }
  10925. ConfigData& Session::configData() {
  10926. return m_configData;
  10927. }
  10928. Config& Session::config() {
  10929. if( !m_config )
  10930. m_config = std::make_shared<Config>( m_configData );
  10931. return *m_config;
  10932. }
  10933. int Session::runInternal() {
  10934. if( m_startupExceptions )
  10935. return 1;
  10936. if (m_configData.showHelp || m_configData.libIdentify) {
  10937. return 0;
  10938. }
  10939. CATCH_TRY {
  10940. config(); // Force config to be constructed
  10941. seedRng( *m_config );
  10942. if( m_configData.filenamesAsTags )
  10943. applyFilenamesAsTags( *m_config );
  10944. // Handle list request
  10945. if( Option<std::size_t> listed = list( m_config ) )
  10946. return static_cast<int>( *listed );
  10947. TestGroup tests { m_config };
  10948. auto const totals = tests.execute();
  10949. if( m_config->warnAboutNoTests() && totals.error == -1 )
  10950. return 2;
  10951. // Note that on unices only the lower 8 bits are usually used, clamping
  10952. // the return value to 255 prevents false negative when some multiple
  10953. // of 256 tests has failed
  10954. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10955. }
  10956. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10957. catch( std::exception& ex ) {
  10958. Catch::cerr() << ex.what() << std::endl;
  10959. return MaxExitCode;
  10960. }
  10961. #endif
  10962. }
  10963. } // end namespace Catch
  10964. // end catch_session.cpp
  10965. // start catch_singletons.cpp
  10966. #include <vector>
  10967. namespace Catch {
  10968. namespace {
  10969. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10970. static std::vector<ISingleton*>* g_singletons = nullptr;
  10971. if( !g_singletons )
  10972. g_singletons = new std::vector<ISingleton*>();
  10973. return g_singletons;
  10974. }
  10975. }
  10976. ISingleton::~ISingleton() {}
  10977. void addSingleton(ISingleton* singleton ) {
  10978. getSingletons()->push_back( singleton );
  10979. }
  10980. void cleanupSingletons() {
  10981. auto& singletons = getSingletons();
  10982. for( auto singleton : *singletons )
  10983. delete singleton;
  10984. delete singletons;
  10985. singletons = nullptr;
  10986. }
  10987. } // namespace Catch
  10988. // end catch_singletons.cpp
  10989. // start catch_startup_exception_registry.cpp
  10990. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10991. namespace Catch {
  10992. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10993. CATCH_TRY {
  10994. m_exceptions.push_back(exception);
  10995. } CATCH_CATCH_ALL {
  10996. // If we run out of memory during start-up there's really not a lot more we can do about it
  10997. std::terminate();
  10998. }
  10999. }
  11000. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  11001. return m_exceptions;
  11002. }
  11003. } // end namespace Catch
  11004. #endif
  11005. // end catch_startup_exception_registry.cpp
  11006. // start catch_stream.cpp
  11007. #include <cstdio>
  11008. #include <iostream>
  11009. #include <fstream>
  11010. #include <sstream>
  11011. #include <vector>
  11012. #include <memory>
  11013. namespace Catch {
  11014. Catch::IStream::~IStream() = default;
  11015. namespace Detail { namespace {
  11016. template<typename WriterF, std::size_t bufferSize=256>
  11017. class StreamBufImpl : public std::streambuf {
  11018. char data[bufferSize];
  11019. WriterF m_writer;
  11020. public:
  11021. StreamBufImpl() {
  11022. setp( data, data + sizeof(data) );
  11023. }
  11024. ~StreamBufImpl() noexcept {
  11025. StreamBufImpl::sync();
  11026. }
  11027. private:
  11028. int overflow( int c ) override {
  11029. sync();
  11030. if( c != EOF ) {
  11031. if( pbase() == epptr() )
  11032. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11033. else
  11034. sputc( static_cast<char>( c ) );
  11035. }
  11036. return 0;
  11037. }
  11038. int sync() override {
  11039. if( pbase() != pptr() ) {
  11040. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11041. setp( pbase(), epptr() );
  11042. }
  11043. return 0;
  11044. }
  11045. };
  11046. ///////////////////////////////////////////////////////////////////////////
  11047. struct OutputDebugWriter {
  11048. void operator()( std::string const&str ) {
  11049. writeToDebugConsole( str );
  11050. }
  11051. };
  11052. ///////////////////////////////////////////////////////////////////////////
  11053. class FileStream : public IStream {
  11054. mutable std::ofstream m_ofs;
  11055. public:
  11056. FileStream( StringRef filename ) {
  11057. m_ofs.open( filename.c_str() );
  11058. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11059. }
  11060. ~FileStream() override = default;
  11061. public: // IStream
  11062. std::ostream& stream() const override {
  11063. return m_ofs;
  11064. }
  11065. };
  11066. ///////////////////////////////////////////////////////////////////////////
  11067. class CoutStream : public IStream {
  11068. mutable std::ostream m_os;
  11069. public:
  11070. // Store the streambuf from cout up-front because
  11071. // cout may get redirected when running tests
  11072. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11073. ~CoutStream() override = default;
  11074. public: // IStream
  11075. std::ostream& stream() const override { return m_os; }
  11076. };
  11077. ///////////////////////////////////////////////////////////////////////////
  11078. class DebugOutStream : public IStream {
  11079. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11080. mutable std::ostream m_os;
  11081. public:
  11082. DebugOutStream()
  11083. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11084. m_os( m_streamBuf.get() )
  11085. {}
  11086. ~DebugOutStream() override = default;
  11087. public: // IStream
  11088. std::ostream& stream() const override { return m_os; }
  11089. };
  11090. }} // namespace anon::detail
  11091. ///////////////////////////////////////////////////////////////////////////
  11092. auto makeStream( StringRef const &filename ) -> IStream const* {
  11093. if( filename.empty() )
  11094. return new Detail::CoutStream();
  11095. else if( filename[0] == '%' ) {
  11096. if( filename == "%debug" )
  11097. return new Detail::DebugOutStream();
  11098. else
  11099. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11100. }
  11101. else
  11102. return new Detail::FileStream( filename );
  11103. }
  11104. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11105. struct StringStreams {
  11106. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11107. std::vector<std::size_t> m_unused;
  11108. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11109. auto add() -> std::size_t {
  11110. if( m_unused.empty() ) {
  11111. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11112. return m_streams.size()-1;
  11113. }
  11114. else {
  11115. auto index = m_unused.back();
  11116. m_unused.pop_back();
  11117. return index;
  11118. }
  11119. }
  11120. void release( std::size_t index ) {
  11121. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11122. m_unused.push_back(index);
  11123. }
  11124. };
  11125. ReusableStringStream::ReusableStringStream()
  11126. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11127. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11128. {}
  11129. ReusableStringStream::~ReusableStringStream() {
  11130. static_cast<std::ostringstream*>( m_oss )->str("");
  11131. m_oss->clear();
  11132. Singleton<StringStreams>::getMutable().release( m_index );
  11133. }
  11134. auto ReusableStringStream::str() const -> std::string {
  11135. return static_cast<std::ostringstream*>( m_oss )->str();
  11136. }
  11137. ///////////////////////////////////////////////////////////////////////////
  11138. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11139. std::ostream& cout() { return std::cout; }
  11140. std::ostream& cerr() { return std::cerr; }
  11141. std::ostream& clog() { return std::clog; }
  11142. #endif
  11143. }
  11144. // end catch_stream.cpp
  11145. // start catch_string_manip.cpp
  11146. #include <algorithm>
  11147. #include <ostream>
  11148. #include <cstring>
  11149. #include <cctype>
  11150. #include <vector>
  11151. namespace Catch {
  11152. namespace {
  11153. char toLowerCh(char c) {
  11154. return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
  11155. }
  11156. }
  11157. bool startsWith( std::string const& s, std::string const& prefix ) {
  11158. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11159. }
  11160. bool startsWith( std::string const& s, char prefix ) {
  11161. return !s.empty() && s[0] == prefix;
  11162. }
  11163. bool endsWith( std::string const& s, std::string const& suffix ) {
  11164. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11165. }
  11166. bool endsWith( std::string const& s, char suffix ) {
  11167. return !s.empty() && s[s.size()-1] == suffix;
  11168. }
  11169. bool contains( std::string const& s, std::string const& infix ) {
  11170. return s.find( infix ) != std::string::npos;
  11171. }
  11172. void toLowerInPlace( std::string& s ) {
  11173. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11174. }
  11175. std::string toLower( std::string const& s ) {
  11176. std::string lc = s;
  11177. toLowerInPlace( lc );
  11178. return lc;
  11179. }
  11180. std::string trim( std::string const& str ) {
  11181. static char const* whitespaceChars = "\n\r\t ";
  11182. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11183. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11184. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11185. }
  11186. StringRef trim(StringRef ref) {
  11187. const auto is_ws = [](char c) {
  11188. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  11189. };
  11190. size_t real_begin = 0;
  11191. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  11192. size_t real_end = ref.size();
  11193. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  11194. return ref.substr(real_begin, real_end - real_begin);
  11195. }
  11196. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11197. bool replaced = false;
  11198. std::size_t i = str.find( replaceThis );
  11199. while( i != std::string::npos ) {
  11200. replaced = true;
  11201. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11202. if( i < str.size()-withThis.size() )
  11203. i = str.find( replaceThis, i+withThis.size() );
  11204. else
  11205. i = std::string::npos;
  11206. }
  11207. return replaced;
  11208. }
  11209. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11210. std::vector<StringRef> subStrings;
  11211. std::size_t start = 0;
  11212. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11213. if( str[pos] == delimiter ) {
  11214. if( pos - start > 1 )
  11215. subStrings.push_back( str.substr( start, pos-start ) );
  11216. start = pos+1;
  11217. }
  11218. }
  11219. if( start < str.size() )
  11220. subStrings.push_back( str.substr( start, str.size()-start ) );
  11221. return subStrings;
  11222. }
  11223. pluralise::pluralise( std::size_t count, std::string const& label )
  11224. : m_count( count ),
  11225. m_label( label )
  11226. {}
  11227. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11228. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11229. if( pluraliser.m_count != 1 )
  11230. os << 's';
  11231. return os;
  11232. }
  11233. }
  11234. // end catch_string_manip.cpp
  11235. // start catch_stringref.cpp
  11236. #include <algorithm>
  11237. #include <ostream>
  11238. #include <cstring>
  11239. #include <cstdint>
  11240. namespace Catch {
  11241. StringRef::StringRef( char const* rawChars ) noexcept
  11242. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11243. {}
  11244. auto StringRef::c_str() const -> char const* {
  11245. CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
  11246. return m_start;
  11247. }
  11248. auto StringRef::data() const noexcept -> char const* {
  11249. return m_start;
  11250. }
  11251. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11252. if (start < m_size) {
  11253. return StringRef(m_start + start, (std::min)(m_size - start, size));
  11254. } else {
  11255. return StringRef();
  11256. }
  11257. }
  11258. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11259. return m_size == other.m_size
  11260. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  11261. }
  11262. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11263. return os.write(str.data(), str.size());
  11264. }
  11265. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11266. lhs.append(rhs.data(), rhs.size());
  11267. return lhs;
  11268. }
  11269. } // namespace Catch
  11270. // end catch_stringref.cpp
  11271. // start catch_tag_alias.cpp
  11272. namespace Catch {
  11273. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11274. }
  11275. // end catch_tag_alias.cpp
  11276. // start catch_tag_alias_autoregistrar.cpp
  11277. namespace Catch {
  11278. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11279. CATCH_TRY {
  11280. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11281. } CATCH_CATCH_ALL {
  11282. // Do not throw when constructing global objects, instead register the exception to be processed later
  11283. getMutableRegistryHub().registerStartupException();
  11284. }
  11285. }
  11286. }
  11287. // end catch_tag_alias_autoregistrar.cpp
  11288. // start catch_tag_alias_registry.cpp
  11289. #include <sstream>
  11290. namespace Catch {
  11291. TagAliasRegistry::~TagAliasRegistry() {}
  11292. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11293. auto it = m_registry.find( alias );
  11294. if( it != m_registry.end() )
  11295. return &(it->second);
  11296. else
  11297. return nullptr;
  11298. }
  11299. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11300. std::string expandedTestSpec = unexpandedTestSpec;
  11301. for( auto const& registryKvp : m_registry ) {
  11302. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11303. if( pos != std::string::npos ) {
  11304. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11305. registryKvp.second.tag +
  11306. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11307. }
  11308. }
  11309. return expandedTestSpec;
  11310. }
  11311. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11312. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11313. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11314. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11315. "error: tag alias, '" << alias << "' already registered.\n"
  11316. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11317. << "\tRedefined at: " << lineInfo );
  11318. }
  11319. ITagAliasRegistry::~ITagAliasRegistry() {}
  11320. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11321. return getRegistryHub().getTagAliasRegistry();
  11322. }
  11323. } // end namespace Catch
  11324. // end catch_tag_alias_registry.cpp
  11325. // start catch_test_case_info.cpp
  11326. #include <cctype>
  11327. #include <exception>
  11328. #include <algorithm>
  11329. #include <sstream>
  11330. namespace Catch {
  11331. namespace {
  11332. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11333. if( startsWith( tag, '.' ) ||
  11334. tag == "!hide" )
  11335. return TestCaseInfo::IsHidden;
  11336. else if( tag == "!throws" )
  11337. return TestCaseInfo::Throws;
  11338. else if( tag == "!shouldfail" )
  11339. return TestCaseInfo::ShouldFail;
  11340. else if( tag == "!mayfail" )
  11341. return TestCaseInfo::MayFail;
  11342. else if( tag == "!nonportable" )
  11343. return TestCaseInfo::NonPortable;
  11344. else if( tag == "!benchmark" )
  11345. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11346. else
  11347. return TestCaseInfo::None;
  11348. }
  11349. bool isReservedTag( std::string const& tag ) {
  11350. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11351. }
  11352. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11353. CATCH_ENFORCE( !isReservedTag(tag),
  11354. "Tag name: [" << tag << "] is not allowed.\n"
  11355. << "Tag names starting with non alphanumeric characters are reserved\n"
  11356. << _lineInfo );
  11357. }
  11358. }
  11359. TestCase makeTestCase( ITestInvoker* _testCase,
  11360. std::string const& _className,
  11361. NameAndTags const& nameAndTags,
  11362. SourceLineInfo const& _lineInfo )
  11363. {
  11364. bool isHidden = false;
  11365. // Parse out tags
  11366. std::vector<std::string> tags;
  11367. std::string desc, tag;
  11368. bool inTag = false;
  11369. for (char c : nameAndTags.tags) {
  11370. if( !inTag ) {
  11371. if( c == '[' )
  11372. inTag = true;
  11373. else
  11374. desc += c;
  11375. }
  11376. else {
  11377. if( c == ']' ) {
  11378. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11379. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11380. isHidden = true;
  11381. else if( prop == TestCaseInfo::None )
  11382. enforceNotReservedTag( tag, _lineInfo );
  11383. // Merged hide tags like `[.approvals]` should be added as
  11384. // `[.][approvals]`. The `[.]` is added at later point, so
  11385. // we only strip the prefix
  11386. if (startsWith(tag, '.') && tag.size() > 1) {
  11387. tag.erase(0, 1);
  11388. }
  11389. tags.push_back( tag );
  11390. tag.clear();
  11391. inTag = false;
  11392. }
  11393. else
  11394. tag += c;
  11395. }
  11396. }
  11397. if( isHidden ) {
  11398. // Add all "hidden" tags to make them behave identically
  11399. tags.insert( tags.end(), { ".", "!hide" } );
  11400. }
  11401. TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
  11402. return TestCase( _testCase, std::move(info) );
  11403. }
  11404. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11405. std::sort(begin(tags), end(tags));
  11406. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11407. testCaseInfo.lcaseTags.clear();
  11408. for( auto const& tag : tags ) {
  11409. std::string lcaseTag = toLower( tag );
  11410. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11411. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11412. }
  11413. testCaseInfo.tags = std::move(tags);
  11414. }
  11415. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11416. std::string const& _className,
  11417. std::string const& _description,
  11418. std::vector<std::string> const& _tags,
  11419. SourceLineInfo const& _lineInfo )
  11420. : name( _name ),
  11421. className( _className ),
  11422. description( _description ),
  11423. lineInfo( _lineInfo ),
  11424. properties( None )
  11425. {
  11426. setTags( *this, _tags );
  11427. }
  11428. bool TestCaseInfo::isHidden() const {
  11429. return ( properties & IsHidden ) != 0;
  11430. }
  11431. bool TestCaseInfo::throws() const {
  11432. return ( properties & Throws ) != 0;
  11433. }
  11434. bool TestCaseInfo::okToFail() const {
  11435. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11436. }
  11437. bool TestCaseInfo::expectedToFail() const {
  11438. return ( properties & (ShouldFail ) ) != 0;
  11439. }
  11440. std::string TestCaseInfo::tagsAsString() const {
  11441. std::string ret;
  11442. // '[' and ']' per tag
  11443. std::size_t full_size = 2 * tags.size();
  11444. for (const auto& tag : tags) {
  11445. full_size += tag.size();
  11446. }
  11447. ret.reserve(full_size);
  11448. for (const auto& tag : tags) {
  11449. ret.push_back('[');
  11450. ret.append(tag);
  11451. ret.push_back(']');
  11452. }
  11453. return ret;
  11454. }
  11455. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11456. TestCase TestCase::withName( std::string const& _newName ) const {
  11457. TestCase other( *this );
  11458. other.name = _newName;
  11459. return other;
  11460. }
  11461. void TestCase::invoke() const {
  11462. test->invoke();
  11463. }
  11464. bool TestCase::operator == ( TestCase const& other ) const {
  11465. return test.get() == other.test.get() &&
  11466. name == other.name &&
  11467. className == other.className;
  11468. }
  11469. bool TestCase::operator < ( TestCase const& other ) const {
  11470. return name < other.name;
  11471. }
  11472. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11473. {
  11474. return *this;
  11475. }
  11476. } // end namespace Catch
  11477. // end catch_test_case_info.cpp
  11478. // start catch_test_case_registry_impl.cpp
  11479. #include <algorithm>
  11480. #include <sstream>
  11481. namespace Catch {
  11482. namespace {
  11483. struct TestHasher {
  11484. explicit TestHasher(Catch::SimplePcg32& rng_instance) {
  11485. basis = rng_instance();
  11486. basis <<= 32;
  11487. basis |= rng_instance();
  11488. }
  11489. uint64_t basis;
  11490. uint64_t operator()(TestCase const& t) const {
  11491. // Modified FNV-1a hash
  11492. static constexpr uint64_t prime = 1099511628211;
  11493. uint64_t hash = basis;
  11494. for (const char c : t.name) {
  11495. hash ^= c;
  11496. hash *= prime;
  11497. }
  11498. return hash;
  11499. }
  11500. };
  11501. } // end unnamed namespace
  11502. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11503. switch( config.runOrder() ) {
  11504. case RunTests::InDeclarationOrder:
  11505. // already in declaration order
  11506. break;
  11507. case RunTests::InLexicographicalOrder: {
  11508. std::vector<TestCase> sorted = unsortedTestCases;
  11509. std::sort( sorted.begin(), sorted.end() );
  11510. return sorted;
  11511. }
  11512. case RunTests::InRandomOrder: {
  11513. seedRng( config );
  11514. TestHasher h( rng() );
  11515. using hashedTest = std::pair<uint64_t, TestCase const*>;
  11516. std::vector<hashedTest> indexed_tests;
  11517. indexed_tests.reserve( unsortedTestCases.size() );
  11518. for (auto const& testCase : unsortedTestCases) {
  11519. indexed_tests.emplace_back(h(testCase), &testCase);
  11520. }
  11521. std::sort(indexed_tests.begin(), indexed_tests.end(),
  11522. [](hashedTest const& lhs, hashedTest const& rhs) {
  11523. if (lhs.first == rhs.first) {
  11524. return lhs.second->name < rhs.second->name;
  11525. }
  11526. return lhs.first < rhs.first;
  11527. });
  11528. std::vector<TestCase> sorted;
  11529. sorted.reserve( indexed_tests.size() );
  11530. for (auto const& hashed : indexed_tests) {
  11531. sorted.emplace_back(*hashed.second);
  11532. }
  11533. return sorted;
  11534. }
  11535. }
  11536. return unsortedTestCases;
  11537. }
  11538. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11539. return !testCase.throws() || config.allowThrows();
  11540. }
  11541. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11542. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11543. }
  11544. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11545. std::set<TestCase> seenFunctions;
  11546. for( auto const& function : functions ) {
  11547. auto prev = seenFunctions.insert( function );
  11548. CATCH_ENFORCE( prev.second,
  11549. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11550. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11551. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11552. }
  11553. }
  11554. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11555. std::vector<TestCase> filtered;
  11556. filtered.reserve( testCases.size() );
  11557. for (auto const& testCase : testCases) {
  11558. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11559. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11560. filtered.push_back(testCase);
  11561. }
  11562. }
  11563. return filtered;
  11564. }
  11565. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11566. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11567. }
  11568. void TestRegistry::registerTest( TestCase const& testCase ) {
  11569. std::string name = testCase.getTestCaseInfo().name;
  11570. if( name.empty() ) {
  11571. ReusableStringStream rss;
  11572. rss << "Anonymous test case " << ++m_unnamedCount;
  11573. return registerTest( testCase.withName( rss.str() ) );
  11574. }
  11575. m_functions.push_back( testCase );
  11576. }
  11577. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11578. return m_functions;
  11579. }
  11580. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11581. if( m_sortedFunctions.empty() )
  11582. enforceNoDuplicateTestCases( m_functions );
  11583. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11584. m_sortedFunctions = sortTests( config, m_functions );
  11585. m_currentSortOrder = config.runOrder();
  11586. }
  11587. return m_sortedFunctions;
  11588. }
  11589. ///////////////////////////////////////////////////////////////////////////
  11590. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11591. void TestInvokerAsFunction::invoke() const {
  11592. m_testAsFunction();
  11593. }
  11594. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11595. std::string className(classOrQualifiedMethodName);
  11596. if( startsWith( className, '&' ) )
  11597. {
  11598. std::size_t lastColons = className.rfind( "::" );
  11599. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11600. if( penultimateColons == std::string::npos )
  11601. penultimateColons = 1;
  11602. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11603. }
  11604. return className;
  11605. }
  11606. } // end namespace Catch
  11607. // end catch_test_case_registry_impl.cpp
  11608. // start catch_test_case_tracker.cpp
  11609. #include <algorithm>
  11610. #include <cassert>
  11611. #include <stdexcept>
  11612. #include <memory>
  11613. #include <sstream>
  11614. #if defined(__clang__)
  11615. # pragma clang diagnostic push
  11616. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11617. #endif
  11618. namespace Catch {
  11619. namespace TestCaseTracking {
  11620. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11621. : name( _name ),
  11622. location( _location )
  11623. {}
  11624. ITracker::~ITracker() = default;
  11625. ITracker& TrackerContext::startRun() {
  11626. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11627. m_currentTracker = nullptr;
  11628. m_runState = Executing;
  11629. return *m_rootTracker;
  11630. }
  11631. void TrackerContext::endRun() {
  11632. m_rootTracker.reset();
  11633. m_currentTracker = nullptr;
  11634. m_runState = NotStarted;
  11635. }
  11636. void TrackerContext::startCycle() {
  11637. m_currentTracker = m_rootTracker.get();
  11638. m_runState = Executing;
  11639. }
  11640. void TrackerContext::completeCycle() {
  11641. m_runState = CompletedCycle;
  11642. }
  11643. bool TrackerContext::completedCycle() const {
  11644. return m_runState == CompletedCycle;
  11645. }
  11646. ITracker& TrackerContext::currentTracker() {
  11647. return *m_currentTracker;
  11648. }
  11649. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11650. m_currentTracker = tracker;
  11651. }
  11652. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  11653. ITracker(nameAndLocation),
  11654. m_ctx( ctx ),
  11655. m_parent( parent )
  11656. {}
  11657. bool TrackerBase::isComplete() const {
  11658. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11659. }
  11660. bool TrackerBase::isSuccessfullyCompleted() const {
  11661. return m_runState == CompletedSuccessfully;
  11662. }
  11663. bool TrackerBase::isOpen() const {
  11664. return m_runState != NotStarted && !isComplete();
  11665. }
  11666. bool TrackerBase::hasChildren() const {
  11667. return !m_children.empty();
  11668. }
  11669. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11670. m_children.push_back( child );
  11671. }
  11672. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11673. auto it = std::find_if( m_children.begin(), m_children.end(),
  11674. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11675. return
  11676. tracker->nameAndLocation().location == nameAndLocation.location &&
  11677. tracker->nameAndLocation().name == nameAndLocation.name;
  11678. } );
  11679. return( it != m_children.end() )
  11680. ? *it
  11681. : nullptr;
  11682. }
  11683. ITracker& TrackerBase::parent() {
  11684. assert( m_parent ); // Should always be non-null except for root
  11685. return *m_parent;
  11686. }
  11687. void TrackerBase::openChild() {
  11688. if( m_runState != ExecutingChildren ) {
  11689. m_runState = ExecutingChildren;
  11690. if( m_parent )
  11691. m_parent->openChild();
  11692. }
  11693. }
  11694. bool TrackerBase::isSectionTracker() const { return false; }
  11695. bool TrackerBase::isGeneratorTracker() const { return false; }
  11696. void TrackerBase::open() {
  11697. m_runState = Executing;
  11698. moveToThis();
  11699. if( m_parent )
  11700. m_parent->openChild();
  11701. }
  11702. void TrackerBase::close() {
  11703. // Close any still open children (e.g. generators)
  11704. while( &m_ctx.currentTracker() != this )
  11705. m_ctx.currentTracker().close();
  11706. switch( m_runState ) {
  11707. case NeedsAnotherRun:
  11708. break;
  11709. case Executing:
  11710. m_runState = CompletedSuccessfully;
  11711. break;
  11712. case ExecutingChildren:
  11713. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11714. m_runState = CompletedSuccessfully;
  11715. break;
  11716. case NotStarted:
  11717. case CompletedSuccessfully:
  11718. case Failed:
  11719. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11720. default:
  11721. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11722. }
  11723. moveToParent();
  11724. m_ctx.completeCycle();
  11725. }
  11726. void TrackerBase::fail() {
  11727. m_runState = Failed;
  11728. if( m_parent )
  11729. m_parent->markAsNeedingAnotherRun();
  11730. moveToParent();
  11731. m_ctx.completeCycle();
  11732. }
  11733. void TrackerBase::markAsNeedingAnotherRun() {
  11734. m_runState = NeedsAnotherRun;
  11735. }
  11736. void TrackerBase::moveToParent() {
  11737. assert( m_parent );
  11738. m_ctx.setCurrentTracker( m_parent );
  11739. }
  11740. void TrackerBase::moveToThis() {
  11741. m_ctx.setCurrentTracker( this );
  11742. }
  11743. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11744. : TrackerBase( nameAndLocation, ctx, parent ),
  11745. m_trimmed_name(trim(nameAndLocation.name))
  11746. {
  11747. if( parent ) {
  11748. while( !parent->isSectionTracker() )
  11749. parent = &parent->parent();
  11750. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11751. addNextFilters( parentSection.m_filters );
  11752. }
  11753. }
  11754. bool SectionTracker::isComplete() const {
  11755. bool complete = true;
  11756. if (m_filters.empty()
  11757. || m_filters[0] == ""
  11758. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  11759. complete = TrackerBase::isComplete();
  11760. }
  11761. return complete;
  11762. }
  11763. bool SectionTracker::isSectionTracker() const { return true; }
  11764. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11765. std::shared_ptr<SectionTracker> section;
  11766. ITracker& currentTracker = ctx.currentTracker();
  11767. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11768. assert( childTracker );
  11769. assert( childTracker->isSectionTracker() );
  11770. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11771. }
  11772. else {
  11773. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11774. currentTracker.addChild( section );
  11775. }
  11776. if( !ctx.completedCycle() )
  11777. section->tryOpen();
  11778. return *section;
  11779. }
  11780. void SectionTracker::tryOpen() {
  11781. if( !isComplete() )
  11782. open();
  11783. }
  11784. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11785. if( !filters.empty() ) {
  11786. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  11787. m_filters.emplace_back(""); // Root - should never be consulted
  11788. m_filters.emplace_back(""); // Test Case - not a section filter
  11789. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11790. }
  11791. }
  11792. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11793. if( filters.size() > 1 )
  11794. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  11795. }
  11796. } // namespace TestCaseTracking
  11797. using TestCaseTracking::ITracker;
  11798. using TestCaseTracking::TrackerContext;
  11799. using TestCaseTracking::SectionTracker;
  11800. } // namespace Catch
  11801. #if defined(__clang__)
  11802. # pragma clang diagnostic pop
  11803. #endif
  11804. // end catch_test_case_tracker.cpp
  11805. // start catch_test_registry.cpp
  11806. namespace Catch {
  11807. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11808. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11809. }
  11810. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11811. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11812. CATCH_TRY {
  11813. getMutableRegistryHub()
  11814. .registerTest(
  11815. makeTestCase(
  11816. invoker,
  11817. extractClassName( classOrMethod ),
  11818. nameAndTags,
  11819. lineInfo));
  11820. } CATCH_CATCH_ALL {
  11821. // Do not throw when constructing global objects, instead register the exception to be processed later
  11822. getMutableRegistryHub().registerStartupException();
  11823. }
  11824. }
  11825. AutoReg::~AutoReg() = default;
  11826. }
  11827. // end catch_test_registry.cpp
  11828. // start catch_test_spec.cpp
  11829. #include <algorithm>
  11830. #include <string>
  11831. #include <vector>
  11832. #include <memory>
  11833. namespace Catch {
  11834. TestSpec::Pattern::Pattern( std::string const& name )
  11835. : m_name( name )
  11836. {}
  11837. TestSpec::Pattern::~Pattern() = default;
  11838. std::string const& TestSpec::Pattern::name() const {
  11839. return m_name;
  11840. }
  11841. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11842. : Pattern( filterString )
  11843. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11844. {}
  11845. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11846. return m_wildcardPattern.matches( testCase.name );
  11847. }
  11848. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11849. : Pattern( filterString )
  11850. , m_tag( toLower( tag ) )
  11851. {}
  11852. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11853. return std::find(begin(testCase.lcaseTags),
  11854. end(testCase.lcaseTags),
  11855. m_tag) != end(testCase.lcaseTags);
  11856. }
  11857. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11858. : Pattern( underlyingPattern->name() )
  11859. , m_underlyingPattern( underlyingPattern )
  11860. {}
  11861. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11862. return !m_underlyingPattern->matches( testCase );
  11863. }
  11864. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11865. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11866. }
  11867. std::string TestSpec::Filter::name() const {
  11868. std::string name;
  11869. for( auto const& p : m_patterns )
  11870. name += p->name();
  11871. return name;
  11872. }
  11873. bool TestSpec::hasFilters() const {
  11874. return !m_filters.empty();
  11875. }
  11876. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11877. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11878. }
  11879. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11880. {
  11881. Matches matches( m_filters.size() );
  11882. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11883. std::vector<TestCase const*> currentMatches;
  11884. for( auto const& test : testCases )
  11885. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11886. currentMatches.emplace_back( &test );
  11887. return FilterMatch{ filter.name(), currentMatches };
  11888. } );
  11889. return matches;
  11890. }
  11891. const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
  11892. return (m_invalidArgs);
  11893. }
  11894. }
  11895. // end catch_test_spec.cpp
  11896. // start catch_test_spec_parser.cpp
  11897. namespace Catch {
  11898. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11899. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11900. m_mode = None;
  11901. m_exclusion = false;
  11902. m_arg = m_tagAliases->expandAliases( arg );
  11903. m_escapeChars.clear();
  11904. m_substring.reserve(m_arg.size());
  11905. m_patternName.reserve(m_arg.size());
  11906. m_realPatternPos = 0;
  11907. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11908. //if visitChar fails
  11909. if( !visitChar( m_arg[m_pos] ) ){
  11910. m_testSpec.m_invalidArgs.push_back(arg);
  11911. break;
  11912. }
  11913. endMode();
  11914. return *this;
  11915. }
  11916. TestSpec TestSpecParser::testSpec() {
  11917. addFilter();
  11918. return m_testSpec;
  11919. }
  11920. bool TestSpecParser::visitChar( char c ) {
  11921. if( (m_mode != EscapedName) && (c == '\\') ) {
  11922. escape();
  11923. addCharToPattern(c);
  11924. return true;
  11925. }else if((m_mode != EscapedName) && (c == ',') ) {
  11926. return separate();
  11927. }
  11928. switch( m_mode ) {
  11929. case None:
  11930. if( processNoneChar( c ) )
  11931. return true;
  11932. break;
  11933. case Name:
  11934. processNameChar( c );
  11935. break;
  11936. case EscapedName:
  11937. endMode();
  11938. addCharToPattern(c);
  11939. return true;
  11940. default:
  11941. case Tag:
  11942. case QuotedName:
  11943. if( processOtherChar( c ) )
  11944. return true;
  11945. break;
  11946. }
  11947. m_substring += c;
  11948. if( !isControlChar( c ) ) {
  11949. m_patternName += c;
  11950. m_realPatternPos++;
  11951. }
  11952. return true;
  11953. }
  11954. // Two of the processing methods return true to signal the caller to return
  11955. // without adding the given character to the current pattern strings
  11956. bool TestSpecParser::processNoneChar( char c ) {
  11957. switch( c ) {
  11958. case ' ':
  11959. return true;
  11960. case '~':
  11961. m_exclusion = true;
  11962. return false;
  11963. case '[':
  11964. startNewMode( Tag );
  11965. return false;
  11966. case '"':
  11967. startNewMode( QuotedName );
  11968. return false;
  11969. default:
  11970. startNewMode( Name );
  11971. return false;
  11972. }
  11973. }
  11974. void TestSpecParser::processNameChar( char c ) {
  11975. if( c == '[' ) {
  11976. if( m_substring == "exclude:" )
  11977. m_exclusion = true;
  11978. else
  11979. endMode();
  11980. startNewMode( Tag );
  11981. }
  11982. }
  11983. bool TestSpecParser::processOtherChar( char c ) {
  11984. if( !isControlChar( c ) )
  11985. return false;
  11986. m_substring += c;
  11987. endMode();
  11988. return true;
  11989. }
  11990. void TestSpecParser::startNewMode( Mode mode ) {
  11991. m_mode = mode;
  11992. }
  11993. void TestSpecParser::endMode() {
  11994. switch( m_mode ) {
  11995. case Name:
  11996. case QuotedName:
  11997. return addNamePattern();
  11998. case Tag:
  11999. return addTagPattern();
  12000. case EscapedName:
  12001. revertBackToLastMode();
  12002. return;
  12003. case None:
  12004. default:
  12005. return startNewMode( None );
  12006. }
  12007. }
  12008. void TestSpecParser::escape() {
  12009. saveLastMode();
  12010. m_mode = EscapedName;
  12011. m_escapeChars.push_back(m_realPatternPos);
  12012. }
  12013. bool TestSpecParser::isControlChar( char c ) const {
  12014. switch( m_mode ) {
  12015. default:
  12016. return false;
  12017. case None:
  12018. return c == '~';
  12019. case Name:
  12020. return c == '[';
  12021. case EscapedName:
  12022. return true;
  12023. case QuotedName:
  12024. return c == '"';
  12025. case Tag:
  12026. return c == '[' || c == ']';
  12027. }
  12028. }
  12029. void TestSpecParser::addFilter() {
  12030. if( !m_currentFilter.m_patterns.empty() ) {
  12031. m_testSpec.m_filters.push_back( m_currentFilter );
  12032. m_currentFilter = TestSpec::Filter();
  12033. }
  12034. }
  12035. void TestSpecParser::saveLastMode() {
  12036. lastMode = m_mode;
  12037. }
  12038. void TestSpecParser::revertBackToLastMode() {
  12039. m_mode = lastMode;
  12040. }
  12041. bool TestSpecParser::separate() {
  12042. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  12043. //invalid argument, signal failure to previous scope.
  12044. m_mode = None;
  12045. m_pos = m_arg.size();
  12046. m_substring.clear();
  12047. m_patternName.clear();
  12048. m_realPatternPos = 0;
  12049. return false;
  12050. }
  12051. endMode();
  12052. addFilter();
  12053. return true; //success
  12054. }
  12055. std::string TestSpecParser::preprocessPattern() {
  12056. std::string token = m_patternName;
  12057. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  12058. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  12059. m_escapeChars.clear();
  12060. if (startsWith(token, "exclude:")) {
  12061. m_exclusion = true;
  12062. token = token.substr(8);
  12063. }
  12064. m_patternName.clear();
  12065. m_realPatternPos = 0;
  12066. return token;
  12067. }
  12068. void TestSpecParser::addNamePattern() {
  12069. auto token = preprocessPattern();
  12070. if (!token.empty()) {
  12071. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
  12072. if (m_exclusion)
  12073. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12074. m_currentFilter.m_patterns.push_back(pattern);
  12075. }
  12076. m_substring.clear();
  12077. m_exclusion = false;
  12078. m_mode = None;
  12079. }
  12080. void TestSpecParser::addTagPattern() {
  12081. auto token = preprocessPattern();
  12082. if (!token.empty()) {
  12083. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  12084. // we have to create a separate hide tag and shorten the real one
  12085. if (token.size() > 1 && token[0] == '.') {
  12086. token.erase(token.begin());
  12087. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
  12088. if (m_exclusion) {
  12089. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12090. }
  12091. m_currentFilter.m_patterns.push_back(pattern);
  12092. }
  12093. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
  12094. if (m_exclusion) {
  12095. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12096. }
  12097. m_currentFilter.m_patterns.push_back(pattern);
  12098. }
  12099. m_substring.clear();
  12100. m_exclusion = false;
  12101. m_mode = None;
  12102. }
  12103. TestSpec parseTestSpec( std::string const& arg ) {
  12104. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12105. }
  12106. } // namespace Catch
  12107. // end catch_test_spec_parser.cpp
  12108. // start catch_timer.cpp
  12109. #include <chrono>
  12110. static const uint64_t nanosecondsInSecond = 1000000000;
  12111. namespace Catch {
  12112. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12113. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12114. }
  12115. namespace {
  12116. auto estimateClockResolution() -> uint64_t {
  12117. uint64_t sum = 0;
  12118. static const uint64_t iterations = 1000000;
  12119. auto startTime = getCurrentNanosecondsSinceEpoch();
  12120. for( std::size_t i = 0; i < iterations; ++i ) {
  12121. uint64_t ticks;
  12122. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12123. do {
  12124. ticks = getCurrentNanosecondsSinceEpoch();
  12125. } while( ticks == baseTicks );
  12126. auto delta = ticks - baseTicks;
  12127. sum += delta;
  12128. // If we have been calibrating for over 3 seconds -- the clock
  12129. // is terrible and we should move on.
  12130. // TBD: How to signal that the measured resolution is probably wrong?
  12131. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12132. return sum / ( i + 1u );
  12133. }
  12134. }
  12135. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12136. // - and potentially do more iterations if there's a high variance.
  12137. return sum/iterations;
  12138. }
  12139. }
  12140. auto getEstimatedClockResolution() -> uint64_t {
  12141. static auto s_resolution = estimateClockResolution();
  12142. return s_resolution;
  12143. }
  12144. void Timer::start() {
  12145. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12146. }
  12147. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12148. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12149. }
  12150. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12151. return getElapsedNanoseconds()/1000;
  12152. }
  12153. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12154. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12155. }
  12156. auto Timer::getElapsedSeconds() const -> double {
  12157. return getElapsedMicroseconds()/1000000.0;
  12158. }
  12159. } // namespace Catch
  12160. // end catch_timer.cpp
  12161. // start catch_tostring.cpp
  12162. #if defined(__clang__)
  12163. # pragma clang diagnostic push
  12164. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12165. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12166. #endif
  12167. // Enable specific decls locally
  12168. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12169. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12170. #endif
  12171. #include <cmath>
  12172. #include <iomanip>
  12173. namespace Catch {
  12174. namespace Detail {
  12175. const std::string unprintableString = "{?}";
  12176. namespace {
  12177. const int hexThreshold = 255;
  12178. struct Endianness {
  12179. enum Arch { Big, Little };
  12180. static Arch which() {
  12181. int one = 1;
  12182. // If the lowest byte we read is non-zero, we can assume
  12183. // that little endian format is used.
  12184. auto value = *reinterpret_cast<char*>(&one);
  12185. return value ? Little : Big;
  12186. }
  12187. };
  12188. }
  12189. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12190. // Reverse order for little endian architectures
  12191. int i = 0, end = static_cast<int>( size ), inc = 1;
  12192. if( Endianness::which() == Endianness::Little ) {
  12193. i = end-1;
  12194. end = inc = -1;
  12195. }
  12196. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12197. ReusableStringStream rss;
  12198. rss << "0x" << std::setfill('0') << std::hex;
  12199. for( ; i != end; i += inc )
  12200. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12201. return rss.str();
  12202. }
  12203. }
  12204. template<typename T>
  12205. std::string fpToString( T value, int precision ) {
  12206. if (Catch::isnan(value)) {
  12207. return "nan";
  12208. }
  12209. ReusableStringStream rss;
  12210. rss << std::setprecision( precision )
  12211. << std::fixed
  12212. << value;
  12213. std::string d = rss.str();
  12214. std::size_t i = d.find_last_not_of( '0' );
  12215. if( i != std::string::npos && i != d.size()-1 ) {
  12216. if( d[i] == '.' )
  12217. i++;
  12218. d = d.substr( 0, i+1 );
  12219. }
  12220. return d;
  12221. }
  12222. //// ======================================================= ////
  12223. //
  12224. // Out-of-line defs for full specialization of StringMaker
  12225. //
  12226. //// ======================================================= ////
  12227. std::string StringMaker<std::string>::convert(const std::string& str) {
  12228. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12229. return '"' + str + '"';
  12230. }
  12231. std::string s("\"");
  12232. for (char c : str) {
  12233. switch (c) {
  12234. case '\n':
  12235. s.append("\\n");
  12236. break;
  12237. case '\t':
  12238. s.append("\\t");
  12239. break;
  12240. default:
  12241. s.push_back(c);
  12242. break;
  12243. }
  12244. }
  12245. s.append("\"");
  12246. return s;
  12247. }
  12248. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12249. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12250. return ::Catch::Detail::stringify(std::string{ str });
  12251. }
  12252. #endif
  12253. std::string StringMaker<char const*>::convert(char const* str) {
  12254. if (str) {
  12255. return ::Catch::Detail::stringify(std::string{ str });
  12256. } else {
  12257. return{ "{null string}" };
  12258. }
  12259. }
  12260. std::string StringMaker<char*>::convert(char* str) {
  12261. if (str) {
  12262. return ::Catch::Detail::stringify(std::string{ str });
  12263. } else {
  12264. return{ "{null string}" };
  12265. }
  12266. }
  12267. #ifdef CATCH_CONFIG_WCHAR
  12268. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12269. std::string s;
  12270. s.reserve(wstr.size());
  12271. for (auto c : wstr) {
  12272. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12273. }
  12274. return ::Catch::Detail::stringify(s);
  12275. }
  12276. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12277. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12278. return StringMaker<std::wstring>::convert(std::wstring(str));
  12279. }
  12280. # endif
  12281. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12282. if (str) {
  12283. return ::Catch::Detail::stringify(std::wstring{ str });
  12284. } else {
  12285. return{ "{null string}" };
  12286. }
  12287. }
  12288. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12289. if (str) {
  12290. return ::Catch::Detail::stringify(std::wstring{ str });
  12291. } else {
  12292. return{ "{null string}" };
  12293. }
  12294. }
  12295. #endif
  12296. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12297. #include <cstddef>
  12298. std::string StringMaker<std::byte>::convert(std::byte value) {
  12299. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12300. }
  12301. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12302. std::string StringMaker<int>::convert(int value) {
  12303. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12304. }
  12305. std::string StringMaker<long>::convert(long value) {
  12306. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12307. }
  12308. std::string StringMaker<long long>::convert(long long value) {
  12309. ReusableStringStream rss;
  12310. rss << value;
  12311. if (value > Detail::hexThreshold) {
  12312. rss << " (0x" << std::hex << value << ')';
  12313. }
  12314. return rss.str();
  12315. }
  12316. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12317. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12318. }
  12319. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12320. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12321. }
  12322. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12323. ReusableStringStream rss;
  12324. rss << value;
  12325. if (value > Detail::hexThreshold) {
  12326. rss << " (0x" << std::hex << value << ')';
  12327. }
  12328. return rss.str();
  12329. }
  12330. std::string StringMaker<bool>::convert(bool b) {
  12331. return b ? "true" : "false";
  12332. }
  12333. std::string StringMaker<signed char>::convert(signed char value) {
  12334. if (value == '\r') {
  12335. return "'\\r'";
  12336. } else if (value == '\f') {
  12337. return "'\\f'";
  12338. } else if (value == '\n') {
  12339. return "'\\n'";
  12340. } else if (value == '\t') {
  12341. return "'\\t'";
  12342. } else if ('\0' <= value && value < ' ') {
  12343. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12344. } else {
  12345. char chstr[] = "' '";
  12346. chstr[1] = value;
  12347. return chstr;
  12348. }
  12349. }
  12350. std::string StringMaker<char>::convert(char c) {
  12351. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12352. }
  12353. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12354. return ::Catch::Detail::stringify(static_cast<char>(c));
  12355. }
  12356. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12357. return "nullptr";
  12358. }
  12359. int StringMaker<float>::precision = 5;
  12360. std::string StringMaker<float>::convert(float value) {
  12361. return fpToString(value, precision) + 'f';
  12362. }
  12363. int StringMaker<double>::precision = 10;
  12364. std::string StringMaker<double>::convert(double value) {
  12365. return fpToString(value, precision);
  12366. }
  12367. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12368. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12369. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12370. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12371. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12372. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12373. } // end namespace Catch
  12374. #if defined(__clang__)
  12375. # pragma clang diagnostic pop
  12376. #endif
  12377. // end catch_tostring.cpp
  12378. // start catch_totals.cpp
  12379. namespace Catch {
  12380. Counts Counts::operator - ( Counts const& other ) const {
  12381. Counts diff;
  12382. diff.passed = passed - other.passed;
  12383. diff.failed = failed - other.failed;
  12384. diff.failedButOk = failedButOk - other.failedButOk;
  12385. return diff;
  12386. }
  12387. Counts& Counts::operator += ( Counts const& other ) {
  12388. passed += other.passed;
  12389. failed += other.failed;
  12390. failedButOk += other.failedButOk;
  12391. return *this;
  12392. }
  12393. std::size_t Counts::total() const {
  12394. return passed + failed + failedButOk;
  12395. }
  12396. bool Counts::allPassed() const {
  12397. return failed == 0 && failedButOk == 0;
  12398. }
  12399. bool Counts::allOk() const {
  12400. return failed == 0;
  12401. }
  12402. Totals Totals::operator - ( Totals const& other ) const {
  12403. Totals diff;
  12404. diff.assertions = assertions - other.assertions;
  12405. diff.testCases = testCases - other.testCases;
  12406. return diff;
  12407. }
  12408. Totals& Totals::operator += ( Totals const& other ) {
  12409. assertions += other.assertions;
  12410. testCases += other.testCases;
  12411. return *this;
  12412. }
  12413. Totals Totals::delta( Totals const& prevTotals ) const {
  12414. Totals diff = *this - prevTotals;
  12415. if( diff.assertions.failed > 0 )
  12416. ++diff.testCases.failed;
  12417. else if( diff.assertions.failedButOk > 0 )
  12418. ++diff.testCases.failedButOk;
  12419. else
  12420. ++diff.testCases.passed;
  12421. return diff;
  12422. }
  12423. }
  12424. // end catch_totals.cpp
  12425. // start catch_uncaught_exceptions.cpp
  12426. // start catch_config_uncaught_exceptions.hpp
  12427. // Copyright Catch2 Authors
  12428. // Distributed under the Boost Software License, Version 1.0.
  12429. // (See accompanying file LICENSE_1_0.txt or copy at
  12430. // https://www.boost.org/LICENSE_1_0.txt)
  12431. // SPDX-License-Identifier: BSL-1.0
  12432. #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12433. #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12434. #if defined(_MSC_VER)
  12435. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  12436. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12437. # endif
  12438. #endif
  12439. #include <exception>
  12440. #if defined(__cpp_lib_uncaught_exceptions) \
  12441. && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12442. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12443. #endif // __cpp_lib_uncaught_exceptions
  12444. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
  12445. && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
  12446. && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12447. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12448. #endif
  12449. #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12450. // end catch_config_uncaught_exceptions.hpp
  12451. #include <exception>
  12452. namespace Catch {
  12453. bool uncaught_exceptions() {
  12454. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  12455. return false;
  12456. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12457. return std::uncaught_exceptions() > 0;
  12458. #else
  12459. return std::uncaught_exception();
  12460. #endif
  12461. }
  12462. } // end namespace Catch
  12463. // end catch_uncaught_exceptions.cpp
  12464. // start catch_version.cpp
  12465. #include <ostream>
  12466. namespace Catch {
  12467. Version::Version
  12468. ( unsigned int _majorVersion,
  12469. unsigned int _minorVersion,
  12470. unsigned int _patchNumber,
  12471. char const * const _branchName,
  12472. unsigned int _buildNumber )
  12473. : majorVersion( _majorVersion ),
  12474. minorVersion( _minorVersion ),
  12475. patchNumber( _patchNumber ),
  12476. branchName( _branchName ),
  12477. buildNumber( _buildNumber )
  12478. {}
  12479. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12480. os << version.majorVersion << '.'
  12481. << version.minorVersion << '.'
  12482. << version.patchNumber;
  12483. // branchName is never null -> 0th char is \0 if it is empty
  12484. if (version.branchName[0]) {
  12485. os << '-' << version.branchName
  12486. << '.' << version.buildNumber;
  12487. }
  12488. return os;
  12489. }
  12490. Version const& libraryVersion() {
  12491. static Version version( 2, 13, 2, "", 0 );
  12492. return version;
  12493. }
  12494. }
  12495. // end catch_version.cpp
  12496. // start catch_wildcard_pattern.cpp
  12497. namespace Catch {
  12498. WildcardPattern::WildcardPattern( std::string const& pattern,
  12499. CaseSensitive::Choice caseSensitivity )
  12500. : m_caseSensitivity( caseSensitivity ),
  12501. m_pattern( normaliseString( pattern ) )
  12502. {
  12503. if( startsWith( m_pattern, '*' ) ) {
  12504. m_pattern = m_pattern.substr( 1 );
  12505. m_wildcard = WildcardAtStart;
  12506. }
  12507. if( endsWith( m_pattern, '*' ) ) {
  12508. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12509. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12510. }
  12511. }
  12512. bool WildcardPattern::matches( std::string const& str ) const {
  12513. switch( m_wildcard ) {
  12514. case NoWildcard:
  12515. return m_pattern == normaliseString( str );
  12516. case WildcardAtStart:
  12517. return endsWith( normaliseString( str ), m_pattern );
  12518. case WildcardAtEnd:
  12519. return startsWith( normaliseString( str ), m_pattern );
  12520. case WildcardAtBothEnds:
  12521. return contains( normaliseString( str ), m_pattern );
  12522. default:
  12523. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12524. }
  12525. }
  12526. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  12527. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  12528. }
  12529. }
  12530. // end catch_wildcard_pattern.cpp
  12531. // start catch_xmlwriter.cpp
  12532. #include <iomanip>
  12533. #include <type_traits>
  12534. namespace Catch {
  12535. namespace {
  12536. size_t trailingBytes(unsigned char c) {
  12537. if ((c & 0xE0) == 0xC0) {
  12538. return 2;
  12539. }
  12540. if ((c & 0xF0) == 0xE0) {
  12541. return 3;
  12542. }
  12543. if ((c & 0xF8) == 0xF0) {
  12544. return 4;
  12545. }
  12546. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12547. }
  12548. uint32_t headerValue(unsigned char c) {
  12549. if ((c & 0xE0) == 0xC0) {
  12550. return c & 0x1F;
  12551. }
  12552. if ((c & 0xF0) == 0xE0) {
  12553. return c & 0x0F;
  12554. }
  12555. if ((c & 0xF8) == 0xF0) {
  12556. return c & 0x07;
  12557. }
  12558. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12559. }
  12560. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12561. std::ios_base::fmtflags f(os.flags());
  12562. os << "\\x"
  12563. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12564. << static_cast<int>(c);
  12565. os.flags(f);
  12566. }
  12567. bool shouldNewline(XmlFormatting fmt) {
  12568. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
  12569. }
  12570. bool shouldIndent(XmlFormatting fmt) {
  12571. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
  12572. }
  12573. } // anonymous namespace
  12574. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  12575. return static_cast<XmlFormatting>(
  12576. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
  12577. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12578. );
  12579. }
  12580. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  12581. return static_cast<XmlFormatting>(
  12582. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
  12583. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12584. );
  12585. }
  12586. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12587. : m_str( str ),
  12588. m_forWhat( forWhat )
  12589. {}
  12590. void XmlEncode::encodeTo( std::ostream& os ) const {
  12591. // Apostrophe escaping not necessary if we always use " to write attributes
  12592. // (see: http://www.w3.org/TR/xml/#syntax)
  12593. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12594. unsigned char c = m_str[idx];
  12595. switch (c) {
  12596. case '<': os << "&lt;"; break;
  12597. case '&': os << "&amp;"; break;
  12598. case '>':
  12599. // See: http://www.w3.org/TR/xml/#syntax
  12600. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12601. os << "&gt;";
  12602. else
  12603. os << c;
  12604. break;
  12605. case '\"':
  12606. if (m_forWhat == ForAttributes)
  12607. os << "&quot;";
  12608. else
  12609. os << c;
  12610. break;
  12611. default:
  12612. // Check for control characters and invalid utf-8
  12613. // Escape control characters in standard ascii
  12614. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12615. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12616. hexEscapeChar(os, c);
  12617. break;
  12618. }
  12619. // Plain ASCII: Write it to stream
  12620. if (c < 0x7F) {
  12621. os << c;
  12622. break;
  12623. }
  12624. // UTF-8 territory
  12625. // Check if the encoding is valid and if it is not, hex escape bytes.
  12626. // Important: We do not check the exact decoded values for validity, only the encoding format
  12627. // First check that this bytes is a valid lead byte:
  12628. // This means that it is not encoded as 1111 1XXX
  12629. // Or as 10XX XXXX
  12630. if (c < 0xC0 ||
  12631. c >= 0xF8) {
  12632. hexEscapeChar(os, c);
  12633. break;
  12634. }
  12635. auto encBytes = trailingBytes(c);
  12636. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12637. if (idx + encBytes - 1 >= m_str.size()) {
  12638. hexEscapeChar(os, c);
  12639. break;
  12640. }
  12641. // The header is valid, check data
  12642. // The next encBytes bytes must together be a valid utf-8
  12643. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12644. bool valid = true;
  12645. uint32_t value = headerValue(c);
  12646. for (std::size_t n = 1; n < encBytes; ++n) {
  12647. unsigned char nc = m_str[idx + n];
  12648. valid &= ((nc & 0xC0) == 0x80);
  12649. value = (value << 6) | (nc & 0x3F);
  12650. }
  12651. if (
  12652. // Wrong bit pattern of following bytes
  12653. (!valid) ||
  12654. // Overlong encodings
  12655. (value < 0x80) ||
  12656. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12657. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12658. // Encoded value out of range
  12659. (value >= 0x110000)
  12660. ) {
  12661. hexEscapeChar(os, c);
  12662. break;
  12663. }
  12664. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12665. for (std::size_t n = 0; n < encBytes; ++n) {
  12666. os << m_str[idx + n];
  12667. }
  12668. idx += encBytes - 1;
  12669. break;
  12670. }
  12671. }
  12672. }
  12673. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12674. xmlEncode.encodeTo( os );
  12675. return os;
  12676. }
  12677. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  12678. : m_writer( writer ),
  12679. m_fmt(fmt)
  12680. {}
  12681. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12682. : m_writer( other.m_writer ),
  12683. m_fmt(other.m_fmt)
  12684. {
  12685. other.m_writer = nullptr;
  12686. other.m_fmt = XmlFormatting::None;
  12687. }
  12688. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12689. if ( m_writer ) {
  12690. m_writer->endElement();
  12691. }
  12692. m_writer = other.m_writer;
  12693. other.m_writer = nullptr;
  12694. m_fmt = other.m_fmt;
  12695. other.m_fmt = XmlFormatting::None;
  12696. return *this;
  12697. }
  12698. XmlWriter::ScopedElement::~ScopedElement() {
  12699. if (m_writer) {
  12700. m_writer->endElement(m_fmt);
  12701. }
  12702. }
  12703. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
  12704. m_writer->writeText( text, fmt );
  12705. return *this;
  12706. }
  12707. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12708. {
  12709. writeDeclaration();
  12710. }
  12711. XmlWriter::~XmlWriter() {
  12712. while (!m_tags.empty()) {
  12713. endElement();
  12714. }
  12715. newlineIfNecessary();
  12716. }
  12717. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  12718. ensureTagClosed();
  12719. newlineIfNecessary();
  12720. if (shouldIndent(fmt)) {
  12721. m_os << m_indent;
  12722. m_indent += " ";
  12723. }
  12724. m_os << '<' << name;
  12725. m_tags.push_back( name );
  12726. m_tagIsOpen = true;
  12727. applyFormatting(fmt);
  12728. return *this;
  12729. }
  12730. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  12731. ScopedElement scoped( this, fmt );
  12732. startElement( name, fmt );
  12733. return scoped;
  12734. }
  12735. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  12736. m_indent = m_indent.substr(0, m_indent.size() - 2);
  12737. if( m_tagIsOpen ) {
  12738. m_os << "/>";
  12739. m_tagIsOpen = false;
  12740. } else {
  12741. newlineIfNecessary();
  12742. if (shouldIndent(fmt)) {
  12743. m_os << m_indent;
  12744. }
  12745. m_os << "</" << m_tags.back() << ">";
  12746. }
  12747. m_os << std::flush;
  12748. applyFormatting(fmt);
  12749. m_tags.pop_back();
  12750. return *this;
  12751. }
  12752. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12753. if( !name.empty() && !attribute.empty() )
  12754. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12755. return *this;
  12756. }
  12757. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12758. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12759. return *this;
  12760. }
  12761. XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
  12762. if( !text.empty() ){
  12763. bool tagWasOpen = m_tagIsOpen;
  12764. ensureTagClosed();
  12765. if (tagWasOpen && shouldIndent(fmt)) {
  12766. m_os << m_indent;
  12767. }
  12768. m_os << XmlEncode( text );
  12769. applyFormatting(fmt);
  12770. }
  12771. return *this;
  12772. }
  12773. XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
  12774. ensureTagClosed();
  12775. if (shouldIndent(fmt)) {
  12776. m_os << m_indent;
  12777. }
  12778. m_os << "<!--" << text << "-->";
  12779. applyFormatting(fmt);
  12780. return *this;
  12781. }
  12782. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12783. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12784. }
  12785. XmlWriter& XmlWriter::writeBlankLine() {
  12786. ensureTagClosed();
  12787. m_os << '\n';
  12788. return *this;
  12789. }
  12790. void XmlWriter::ensureTagClosed() {
  12791. if( m_tagIsOpen ) {
  12792. m_os << '>' << std::flush;
  12793. newlineIfNecessary();
  12794. m_tagIsOpen = false;
  12795. }
  12796. }
  12797. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  12798. m_needsNewline = shouldNewline(fmt);
  12799. }
  12800. void XmlWriter::writeDeclaration() {
  12801. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12802. }
  12803. void XmlWriter::newlineIfNecessary() {
  12804. if( m_needsNewline ) {
  12805. m_os << std::endl;
  12806. m_needsNewline = false;
  12807. }
  12808. }
  12809. }
  12810. // end catch_xmlwriter.cpp
  12811. // start catch_reporter_bases.cpp
  12812. #include <cstring>
  12813. #include <cfloat>
  12814. #include <cstdio>
  12815. #include <cassert>
  12816. #include <memory>
  12817. namespace Catch {
  12818. void prepareExpandedExpression(AssertionResult& result) {
  12819. result.getExpandedExpression();
  12820. }
  12821. // Because formatting using c++ streams is stateful, drop down to C is required
  12822. // Alternatively we could use stringstream, but its performance is... not good.
  12823. std::string getFormattedDuration( double duration ) {
  12824. // Max exponent + 1 is required to represent the whole part
  12825. // + 1 for decimal point
  12826. // + 3 for the 3 decimal places
  12827. // + 1 for null terminator
  12828. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12829. char buffer[maxDoubleSize];
  12830. // Save previous errno, to prevent sprintf from overwriting it
  12831. ErrnoGuard guard;
  12832. #ifdef _MSC_VER
  12833. sprintf_s(buffer, "%.3f", duration);
  12834. #else
  12835. std::sprintf(buffer, "%.3f", duration);
  12836. #endif
  12837. return std::string(buffer);
  12838. }
  12839. bool shouldShowDuration( IConfig const& config, double duration ) {
  12840. if ( config.showDurations() == ShowDurations::Always ) {
  12841. return true;
  12842. }
  12843. if ( config.showDurations() == ShowDurations::Never ) {
  12844. return false;
  12845. }
  12846. const double min = config.minDuration();
  12847. return min >= 0 && duration >= min;
  12848. }
  12849. std::string serializeFilters( std::vector<std::string> const& container ) {
  12850. ReusableStringStream oss;
  12851. bool first = true;
  12852. for (auto&& filter : container)
  12853. {
  12854. if (!first)
  12855. oss << ' ';
  12856. else
  12857. first = false;
  12858. oss << filter;
  12859. }
  12860. return oss.str();
  12861. }
  12862. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12863. :StreamingReporterBase(_config) {}
  12864. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12865. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12866. }
  12867. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12868. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12869. return false;
  12870. }
  12871. } // end namespace Catch
  12872. // end catch_reporter_bases.cpp
  12873. // start catch_reporter_compact.cpp
  12874. namespace {
  12875. #ifdef CATCH_PLATFORM_MAC
  12876. const char* failedString() { return "FAILED"; }
  12877. const char* passedString() { return "PASSED"; }
  12878. #else
  12879. const char* failedString() { return "failed"; }
  12880. const char* passedString() { return "passed"; }
  12881. #endif
  12882. // Colour::LightGrey
  12883. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12884. std::string bothOrAll( std::size_t count ) {
  12885. return count == 1 ? std::string() :
  12886. count == 2 ? "both " : "all " ;
  12887. }
  12888. } // anon namespace
  12889. namespace Catch {
  12890. namespace {
  12891. // Colour, message variants:
  12892. // - white: No tests ran.
  12893. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12894. // - white: Passed [both/all] N test cases (no assertions).
  12895. // - red: Failed N tests cases, failed M assertions.
  12896. // - green: Passed [both/all] N tests cases with M assertions.
  12897. void printTotals(std::ostream& out, const Totals& totals) {
  12898. if (totals.testCases.total() == 0) {
  12899. out << "No tests ran.";
  12900. } else if (totals.testCases.failed == totals.testCases.total()) {
  12901. Colour colour(Colour::ResultError);
  12902. const std::string qualify_assertions_failed =
  12903. totals.assertions.failed == totals.assertions.total() ?
  12904. bothOrAll(totals.assertions.failed) : std::string();
  12905. out <<
  12906. "Failed " << bothOrAll(totals.testCases.failed)
  12907. << pluralise(totals.testCases.failed, "test case") << ", "
  12908. "failed " << qualify_assertions_failed <<
  12909. pluralise(totals.assertions.failed, "assertion") << '.';
  12910. } else if (totals.assertions.total() == 0) {
  12911. out <<
  12912. "Passed " << bothOrAll(totals.testCases.total())
  12913. << pluralise(totals.testCases.total(), "test case")
  12914. << " (no assertions).";
  12915. } else if (totals.assertions.failed) {
  12916. Colour colour(Colour::ResultError);
  12917. out <<
  12918. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12919. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12920. } else {
  12921. Colour colour(Colour::ResultSuccess);
  12922. out <<
  12923. "Passed " << bothOrAll(totals.testCases.passed)
  12924. << pluralise(totals.testCases.passed, "test case") <<
  12925. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12926. }
  12927. }
  12928. // Implementation of CompactReporter formatting
  12929. class AssertionPrinter {
  12930. public:
  12931. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12932. AssertionPrinter(AssertionPrinter const&) = delete;
  12933. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12934. : stream(_stream)
  12935. , result(_stats.assertionResult)
  12936. , messages(_stats.infoMessages)
  12937. , itMessage(_stats.infoMessages.begin())
  12938. , printInfoMessages(_printInfoMessages) {}
  12939. void print() {
  12940. printSourceInfo();
  12941. itMessage = messages.begin();
  12942. switch (result.getResultType()) {
  12943. case ResultWas::Ok:
  12944. printResultType(Colour::ResultSuccess, passedString());
  12945. printOriginalExpression();
  12946. printReconstructedExpression();
  12947. if (!result.hasExpression())
  12948. printRemainingMessages(Colour::None);
  12949. else
  12950. printRemainingMessages();
  12951. break;
  12952. case ResultWas::ExpressionFailed:
  12953. if (result.isOk())
  12954. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12955. else
  12956. printResultType(Colour::Error, failedString());
  12957. printOriginalExpression();
  12958. printReconstructedExpression();
  12959. printRemainingMessages();
  12960. break;
  12961. case ResultWas::ThrewException:
  12962. printResultType(Colour::Error, failedString());
  12963. printIssue("unexpected exception with message:");
  12964. printMessage();
  12965. printExpressionWas();
  12966. printRemainingMessages();
  12967. break;
  12968. case ResultWas::FatalErrorCondition:
  12969. printResultType(Colour::Error, failedString());
  12970. printIssue("fatal error condition with message:");
  12971. printMessage();
  12972. printExpressionWas();
  12973. printRemainingMessages();
  12974. break;
  12975. case ResultWas::DidntThrowException:
  12976. printResultType(Colour::Error, failedString());
  12977. printIssue("expected exception, got none");
  12978. printExpressionWas();
  12979. printRemainingMessages();
  12980. break;
  12981. case ResultWas::Info:
  12982. printResultType(Colour::None, "info");
  12983. printMessage();
  12984. printRemainingMessages();
  12985. break;
  12986. case ResultWas::Warning:
  12987. printResultType(Colour::None, "warning");
  12988. printMessage();
  12989. printRemainingMessages();
  12990. break;
  12991. case ResultWas::ExplicitFailure:
  12992. printResultType(Colour::Error, failedString());
  12993. printIssue("explicitly");
  12994. printRemainingMessages(Colour::None);
  12995. break;
  12996. // These cases are here to prevent compiler warnings
  12997. case ResultWas::Unknown:
  12998. case ResultWas::FailureBit:
  12999. case ResultWas::Exception:
  13000. printResultType(Colour::Error, "** internal error **");
  13001. break;
  13002. }
  13003. }
  13004. private:
  13005. void printSourceInfo() const {
  13006. Colour colourGuard(Colour::FileName);
  13007. stream << result.getSourceInfo() << ':';
  13008. }
  13009. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  13010. if (!passOrFail.empty()) {
  13011. {
  13012. Colour colourGuard(colour);
  13013. stream << ' ' << passOrFail;
  13014. }
  13015. stream << ':';
  13016. }
  13017. }
  13018. void printIssue(std::string const& issue) const {
  13019. stream << ' ' << issue;
  13020. }
  13021. void printExpressionWas() {
  13022. if (result.hasExpression()) {
  13023. stream << ';';
  13024. {
  13025. Colour colour(dimColour());
  13026. stream << " expression was:";
  13027. }
  13028. printOriginalExpression();
  13029. }
  13030. }
  13031. void printOriginalExpression() const {
  13032. if (result.hasExpression()) {
  13033. stream << ' ' << result.getExpression();
  13034. }
  13035. }
  13036. void printReconstructedExpression() const {
  13037. if (result.hasExpandedExpression()) {
  13038. {
  13039. Colour colour(dimColour());
  13040. stream << " for: ";
  13041. }
  13042. stream << result.getExpandedExpression();
  13043. }
  13044. }
  13045. void printMessage() {
  13046. if (itMessage != messages.end()) {
  13047. stream << " '" << itMessage->message << '\'';
  13048. ++itMessage;
  13049. }
  13050. }
  13051. void printRemainingMessages(Colour::Code colour = dimColour()) {
  13052. if (itMessage == messages.end())
  13053. return;
  13054. const auto itEnd = messages.cend();
  13055. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  13056. {
  13057. Colour colourGuard(colour);
  13058. stream << " with " << pluralise(N, "message") << ':';
  13059. }
  13060. while (itMessage != itEnd) {
  13061. // If this assertion is a warning ignore any INFO messages
  13062. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  13063. printMessage();
  13064. if (itMessage != itEnd) {
  13065. Colour colourGuard(dimColour());
  13066. stream << " and";
  13067. }
  13068. continue;
  13069. }
  13070. ++itMessage;
  13071. }
  13072. }
  13073. private:
  13074. std::ostream& stream;
  13075. AssertionResult const& result;
  13076. std::vector<MessageInfo> messages;
  13077. std::vector<MessageInfo>::const_iterator itMessage;
  13078. bool printInfoMessages;
  13079. };
  13080. } // anon namespace
  13081. std::string CompactReporter::getDescription() {
  13082. return "Reports test results on a single line, suitable for IDEs";
  13083. }
  13084. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  13085. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13086. }
  13087. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  13088. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  13089. AssertionResult const& result = _assertionStats.assertionResult;
  13090. bool printInfoMessages = true;
  13091. // Drop out if result was successful and we're not printing those
  13092. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  13093. if( result.getResultType() != ResultWas::Warning )
  13094. return false;
  13095. printInfoMessages = false;
  13096. }
  13097. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  13098. printer.print();
  13099. stream << std::endl;
  13100. return true;
  13101. }
  13102. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  13103. double dur = _sectionStats.durationInSeconds;
  13104. if ( shouldShowDuration( *m_config, dur ) ) {
  13105. stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13106. }
  13107. }
  13108. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  13109. printTotals( stream, _testRunStats.totals );
  13110. stream << '\n' << std::endl;
  13111. StreamingReporterBase::testRunEnded( _testRunStats );
  13112. }
  13113. CompactReporter::~CompactReporter() {}
  13114. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  13115. } // end namespace Catch
  13116. // end catch_reporter_compact.cpp
  13117. // start catch_reporter_console.cpp
  13118. #include <cfloat>
  13119. #include <cstdio>
  13120. #if defined(_MSC_VER)
  13121. #pragma warning(push)
  13122. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13123. // Note that 4062 (not all labels are handled and default is missing) is enabled
  13124. #endif
  13125. #if defined(__clang__)
  13126. # pragma clang diagnostic push
  13127. // For simplicity, benchmarking-only helpers are always enabled
  13128. # pragma clang diagnostic ignored "-Wunused-function"
  13129. #endif
  13130. namespace Catch {
  13131. namespace {
  13132. // Formatter impl for ConsoleReporter
  13133. class ConsoleAssertionPrinter {
  13134. public:
  13135. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  13136. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  13137. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13138. : stream(_stream),
  13139. stats(_stats),
  13140. result(_stats.assertionResult),
  13141. colour(Colour::None),
  13142. message(result.getMessage()),
  13143. messages(_stats.infoMessages),
  13144. printInfoMessages(_printInfoMessages) {
  13145. switch (result.getResultType()) {
  13146. case ResultWas::Ok:
  13147. colour = Colour::Success;
  13148. passOrFail = "PASSED";
  13149. //if( result.hasMessage() )
  13150. if (_stats.infoMessages.size() == 1)
  13151. messageLabel = "with message";
  13152. if (_stats.infoMessages.size() > 1)
  13153. messageLabel = "with messages";
  13154. break;
  13155. case ResultWas::ExpressionFailed:
  13156. if (result.isOk()) {
  13157. colour = Colour::Success;
  13158. passOrFail = "FAILED - but was ok";
  13159. } else {
  13160. colour = Colour::Error;
  13161. passOrFail = "FAILED";
  13162. }
  13163. if (_stats.infoMessages.size() == 1)
  13164. messageLabel = "with message";
  13165. if (_stats.infoMessages.size() > 1)
  13166. messageLabel = "with messages";
  13167. break;
  13168. case ResultWas::ThrewException:
  13169. colour = Colour::Error;
  13170. passOrFail = "FAILED";
  13171. messageLabel = "due to unexpected exception with ";
  13172. if (_stats.infoMessages.size() == 1)
  13173. messageLabel += "message";
  13174. if (_stats.infoMessages.size() > 1)
  13175. messageLabel += "messages";
  13176. break;
  13177. case ResultWas::FatalErrorCondition:
  13178. colour = Colour::Error;
  13179. passOrFail = "FAILED";
  13180. messageLabel = "due to a fatal error condition";
  13181. break;
  13182. case ResultWas::DidntThrowException:
  13183. colour = Colour::Error;
  13184. passOrFail = "FAILED";
  13185. messageLabel = "because no exception was thrown where one was expected";
  13186. break;
  13187. case ResultWas::Info:
  13188. messageLabel = "info";
  13189. break;
  13190. case ResultWas::Warning:
  13191. messageLabel = "warning";
  13192. break;
  13193. case ResultWas::ExplicitFailure:
  13194. passOrFail = "FAILED";
  13195. colour = Colour::Error;
  13196. if (_stats.infoMessages.size() == 1)
  13197. messageLabel = "explicitly with message";
  13198. if (_stats.infoMessages.size() > 1)
  13199. messageLabel = "explicitly with messages";
  13200. break;
  13201. // These cases are here to prevent compiler warnings
  13202. case ResultWas::Unknown:
  13203. case ResultWas::FailureBit:
  13204. case ResultWas::Exception:
  13205. passOrFail = "** internal error **";
  13206. colour = Colour::Error;
  13207. break;
  13208. }
  13209. }
  13210. void print() const {
  13211. printSourceInfo();
  13212. if (stats.totals.assertions.total() > 0) {
  13213. printResultType();
  13214. printOriginalExpression();
  13215. printReconstructedExpression();
  13216. } else {
  13217. stream << '\n';
  13218. }
  13219. printMessage();
  13220. }
  13221. private:
  13222. void printResultType() const {
  13223. if (!passOrFail.empty()) {
  13224. Colour colourGuard(colour);
  13225. stream << passOrFail << ":\n";
  13226. }
  13227. }
  13228. void printOriginalExpression() const {
  13229. if (result.hasExpression()) {
  13230. Colour colourGuard(Colour::OriginalExpression);
  13231. stream << " ";
  13232. stream << result.getExpressionInMacro();
  13233. stream << '\n';
  13234. }
  13235. }
  13236. void printReconstructedExpression() const {
  13237. if (result.hasExpandedExpression()) {
  13238. stream << "with expansion:\n";
  13239. Colour colourGuard(Colour::ReconstructedExpression);
  13240. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13241. }
  13242. }
  13243. void printMessage() const {
  13244. if (!messageLabel.empty())
  13245. stream << messageLabel << ':' << '\n';
  13246. for (auto const& msg : messages) {
  13247. // If this assertion is a warning ignore any INFO messages
  13248. if (printInfoMessages || msg.type != ResultWas::Info)
  13249. stream << Column(msg.message).indent(2) << '\n';
  13250. }
  13251. }
  13252. void printSourceInfo() const {
  13253. Colour colourGuard(Colour::FileName);
  13254. stream << result.getSourceInfo() << ": ";
  13255. }
  13256. std::ostream& stream;
  13257. AssertionStats const& stats;
  13258. AssertionResult const& result;
  13259. Colour::Code colour;
  13260. std::string passOrFail;
  13261. std::string messageLabel;
  13262. std::string message;
  13263. std::vector<MessageInfo> messages;
  13264. bool printInfoMessages;
  13265. };
  13266. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13267. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13268. return (ratio == 0 && number > 0) ? 1 : ratio;
  13269. }
  13270. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13271. if (i > j && i > k)
  13272. return i;
  13273. else if (j > k)
  13274. return j;
  13275. else
  13276. return k;
  13277. }
  13278. struct ColumnInfo {
  13279. enum Justification { Left, Right };
  13280. std::string name;
  13281. int width;
  13282. Justification justification;
  13283. };
  13284. struct ColumnBreak {};
  13285. struct RowBreak {};
  13286. class Duration {
  13287. enum class Unit {
  13288. Auto,
  13289. Nanoseconds,
  13290. Microseconds,
  13291. Milliseconds,
  13292. Seconds,
  13293. Minutes
  13294. };
  13295. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13296. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13297. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13298. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13299. double m_inNanoseconds;
  13300. Unit m_units;
  13301. public:
  13302. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  13303. : m_inNanoseconds(inNanoseconds),
  13304. m_units(units) {
  13305. if (m_units == Unit::Auto) {
  13306. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13307. m_units = Unit::Nanoseconds;
  13308. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13309. m_units = Unit::Microseconds;
  13310. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13311. m_units = Unit::Milliseconds;
  13312. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13313. m_units = Unit::Seconds;
  13314. else
  13315. m_units = Unit::Minutes;
  13316. }
  13317. }
  13318. auto value() const -> double {
  13319. switch (m_units) {
  13320. case Unit::Microseconds:
  13321. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13322. case Unit::Milliseconds:
  13323. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13324. case Unit::Seconds:
  13325. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13326. case Unit::Minutes:
  13327. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13328. default:
  13329. return m_inNanoseconds;
  13330. }
  13331. }
  13332. auto unitsAsString() const -> std::string {
  13333. switch (m_units) {
  13334. case Unit::Nanoseconds:
  13335. return "ns";
  13336. case Unit::Microseconds:
  13337. return "us";
  13338. case Unit::Milliseconds:
  13339. return "ms";
  13340. case Unit::Seconds:
  13341. return "s";
  13342. case Unit::Minutes:
  13343. return "m";
  13344. default:
  13345. return "** internal error **";
  13346. }
  13347. }
  13348. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13349. return os << duration.value() << ' ' << duration.unitsAsString();
  13350. }
  13351. };
  13352. } // end anon namespace
  13353. class TablePrinter {
  13354. std::ostream& m_os;
  13355. std::vector<ColumnInfo> m_columnInfos;
  13356. std::ostringstream m_oss;
  13357. int m_currentColumn = -1;
  13358. bool m_isOpen = false;
  13359. public:
  13360. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13361. : m_os( os ),
  13362. m_columnInfos( std::move( columnInfos ) ) {}
  13363. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13364. return m_columnInfos;
  13365. }
  13366. void open() {
  13367. if (!m_isOpen) {
  13368. m_isOpen = true;
  13369. *this << RowBreak();
  13370. Columns headerCols;
  13371. Spacer spacer(2);
  13372. for (auto const& info : m_columnInfos) {
  13373. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13374. headerCols += spacer;
  13375. }
  13376. m_os << headerCols << '\n';
  13377. m_os << Catch::getLineOfChars<'-'>() << '\n';
  13378. }
  13379. }
  13380. void close() {
  13381. if (m_isOpen) {
  13382. *this << RowBreak();
  13383. m_os << std::endl;
  13384. m_isOpen = false;
  13385. }
  13386. }
  13387. template<typename T>
  13388. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13389. tp.m_oss << value;
  13390. return tp;
  13391. }
  13392. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13393. auto colStr = tp.m_oss.str();
  13394. const auto strSize = colStr.size();
  13395. tp.m_oss.str("");
  13396. tp.open();
  13397. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13398. tp.m_currentColumn = -1;
  13399. tp.m_os << '\n';
  13400. }
  13401. tp.m_currentColumn++;
  13402. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13403. auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
  13404. ? std::string(colInfo.width - (strSize + 1), ' ')
  13405. : std::string();
  13406. if (colInfo.justification == ColumnInfo::Left)
  13407. tp.m_os << colStr << padding << ' ';
  13408. else
  13409. tp.m_os << padding << colStr << ' ';
  13410. return tp;
  13411. }
  13412. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13413. if (tp.m_currentColumn > 0) {
  13414. tp.m_os << '\n';
  13415. tp.m_currentColumn = -1;
  13416. }
  13417. return tp;
  13418. }
  13419. };
  13420. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13421. : StreamingReporterBase(config),
  13422. m_tablePrinter(new TablePrinter(config.stream(),
  13423. [&config]() -> std::vector<ColumnInfo> {
  13424. if (config.fullConfig()->benchmarkNoAnalysis())
  13425. {
  13426. return{
  13427. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13428. { " samples", 14, ColumnInfo::Right },
  13429. { " iterations", 14, ColumnInfo::Right },
  13430. { " mean", 14, ColumnInfo::Right }
  13431. };
  13432. }
  13433. else
  13434. {
  13435. return{
  13436. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13437. { "samples mean std dev", 14, ColumnInfo::Right },
  13438. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13439. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13440. };
  13441. }
  13442. }())) {}
  13443. ConsoleReporter::~ConsoleReporter() = default;
  13444. std::string ConsoleReporter::getDescription() {
  13445. return "Reports test results as plain lines of text";
  13446. }
  13447. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13448. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13449. }
  13450. void ConsoleReporter::reportInvalidArguments(std::string const&arg){
  13451. stream << "Invalid Filter: " << arg << std::endl;
  13452. }
  13453. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13454. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13455. AssertionResult const& result = _assertionStats.assertionResult;
  13456. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13457. // Drop out if result was successful but we're not printing them.
  13458. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13459. return false;
  13460. lazyPrint();
  13461. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13462. printer.print();
  13463. stream << std::endl;
  13464. return true;
  13465. }
  13466. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13467. m_tablePrinter->close();
  13468. m_headerPrinted = false;
  13469. StreamingReporterBase::sectionStarting(_sectionInfo);
  13470. }
  13471. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13472. m_tablePrinter->close();
  13473. if (_sectionStats.missingAssertions) {
  13474. lazyPrint();
  13475. Colour colour(Colour::ResultError);
  13476. if (m_sectionStack.size() > 1)
  13477. stream << "\nNo assertions in section";
  13478. else
  13479. stream << "\nNo assertions in test case";
  13480. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13481. }
  13482. double dur = _sectionStats.durationInSeconds;
  13483. if (shouldShowDuration(*m_config, dur)) {
  13484. stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13485. }
  13486. if (m_headerPrinted) {
  13487. m_headerPrinted = false;
  13488. }
  13489. StreamingReporterBase::sectionEnded(_sectionStats);
  13490. }
  13491. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13492. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13493. lazyPrintWithoutClosingBenchmarkTable();
  13494. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13495. bool firstLine = true;
  13496. for (auto line : nameCol) {
  13497. if (!firstLine)
  13498. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13499. else
  13500. firstLine = false;
  13501. (*m_tablePrinter) << line << ColumnBreak();
  13502. }
  13503. }
  13504. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13505. (*m_tablePrinter) << info.samples << ColumnBreak()
  13506. << info.iterations << ColumnBreak();
  13507. if (!m_config->benchmarkNoAnalysis())
  13508. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  13509. }
  13510. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13511. if (m_config->benchmarkNoAnalysis())
  13512. {
  13513. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  13514. }
  13515. else
  13516. {
  13517. (*m_tablePrinter) << ColumnBreak()
  13518. << Duration(stats.mean.point.count()) << ColumnBreak()
  13519. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13520. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13521. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13522. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13523. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13524. }
  13525. }
  13526. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13527. Colour colour(Colour::Red);
  13528. (*m_tablePrinter)
  13529. << "Benchmark failed (" << error << ')'
  13530. << ColumnBreak() << RowBreak();
  13531. }
  13532. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13533. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13534. m_tablePrinter->close();
  13535. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13536. m_headerPrinted = false;
  13537. }
  13538. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13539. if (currentGroupInfo.used) {
  13540. printSummaryDivider();
  13541. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13542. printTotals(_testGroupStats.totals);
  13543. stream << '\n' << std::endl;
  13544. }
  13545. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13546. }
  13547. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13548. printTotalsDivider(_testRunStats.totals);
  13549. printTotals(_testRunStats.totals);
  13550. stream << std::endl;
  13551. StreamingReporterBase::testRunEnded(_testRunStats);
  13552. }
  13553. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13554. StreamingReporterBase::testRunStarting(_testInfo);
  13555. printTestFilters();
  13556. }
  13557. void ConsoleReporter::lazyPrint() {
  13558. m_tablePrinter->close();
  13559. lazyPrintWithoutClosingBenchmarkTable();
  13560. }
  13561. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13562. if (!currentTestRunInfo.used)
  13563. lazyPrintRunInfo();
  13564. if (!currentGroupInfo.used)
  13565. lazyPrintGroupInfo();
  13566. if (!m_headerPrinted) {
  13567. printTestCaseAndSectionHeader();
  13568. m_headerPrinted = true;
  13569. }
  13570. }
  13571. void ConsoleReporter::lazyPrintRunInfo() {
  13572. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13573. Colour colour(Colour::SecondaryText);
  13574. stream << currentTestRunInfo->name
  13575. << " is a Catch v" << libraryVersion() << " host application.\n"
  13576. << "Run with -? for options\n\n";
  13577. if (m_config->rngSeed() != 0)
  13578. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13579. currentTestRunInfo.used = true;
  13580. }
  13581. void ConsoleReporter::lazyPrintGroupInfo() {
  13582. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13583. printClosedHeader("Group: " + currentGroupInfo->name);
  13584. currentGroupInfo.used = true;
  13585. }
  13586. }
  13587. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13588. assert(!m_sectionStack.empty());
  13589. printOpenHeader(currentTestCaseInfo->name);
  13590. if (m_sectionStack.size() > 1) {
  13591. Colour colourGuard(Colour::Headers);
  13592. auto
  13593. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13594. itEnd = m_sectionStack.end();
  13595. for (; it != itEnd; ++it)
  13596. printHeaderString(it->name, 2);
  13597. }
  13598. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13599. stream << getLineOfChars<'-'>() << '\n';
  13600. Colour colourGuard(Colour::FileName);
  13601. stream << lineInfo << '\n';
  13602. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13603. }
  13604. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13605. printOpenHeader(_name);
  13606. stream << getLineOfChars<'.'>() << '\n';
  13607. }
  13608. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13609. stream << getLineOfChars<'-'>() << '\n';
  13610. {
  13611. Colour colourGuard(Colour::Headers);
  13612. printHeaderString(_name);
  13613. }
  13614. }
  13615. // if string has a : in first line will set indent to follow it on
  13616. // subsequent lines
  13617. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13618. std::size_t i = _string.find(": ");
  13619. if (i != std::string::npos)
  13620. i += 2;
  13621. else
  13622. i = 0;
  13623. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13624. }
  13625. struct SummaryColumn {
  13626. SummaryColumn( std::string _label, Colour::Code _colour )
  13627. : label( std::move( _label ) ),
  13628. colour( _colour ) {}
  13629. SummaryColumn addRow( std::size_t count ) {
  13630. ReusableStringStream rss;
  13631. rss << count;
  13632. std::string row = rss.str();
  13633. for (auto& oldRow : rows) {
  13634. while (oldRow.size() < row.size())
  13635. oldRow = ' ' + oldRow;
  13636. while (oldRow.size() > row.size())
  13637. row = ' ' + row;
  13638. }
  13639. rows.push_back(row);
  13640. return *this;
  13641. }
  13642. std::string label;
  13643. Colour::Code colour;
  13644. std::vector<std::string> rows;
  13645. };
  13646. void ConsoleReporter::printTotals( Totals const& totals ) {
  13647. if (totals.testCases.total() == 0) {
  13648. stream << Colour(Colour::Warning) << "No tests ran\n";
  13649. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13650. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13651. stream << " ("
  13652. << pluralise(totals.assertions.passed, "assertion") << " in "
  13653. << pluralise(totals.testCases.passed, "test case") << ')'
  13654. << '\n';
  13655. } else {
  13656. std::vector<SummaryColumn> columns;
  13657. columns.push_back(SummaryColumn("", Colour::None)
  13658. .addRow(totals.testCases.total())
  13659. .addRow(totals.assertions.total()));
  13660. columns.push_back(SummaryColumn("passed", Colour::Success)
  13661. .addRow(totals.testCases.passed)
  13662. .addRow(totals.assertions.passed));
  13663. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13664. .addRow(totals.testCases.failed)
  13665. .addRow(totals.assertions.failed));
  13666. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13667. .addRow(totals.testCases.failedButOk)
  13668. .addRow(totals.assertions.failedButOk));
  13669. printSummaryRow("test cases", columns, 0);
  13670. printSummaryRow("assertions", columns, 1);
  13671. }
  13672. }
  13673. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13674. for (auto col : cols) {
  13675. std::string value = col.rows[row];
  13676. if (col.label.empty()) {
  13677. stream << label << ": ";
  13678. if (value != "0")
  13679. stream << value;
  13680. else
  13681. stream << Colour(Colour::Warning) << "- none -";
  13682. } else if (value != "0") {
  13683. stream << Colour(Colour::LightGrey) << " | ";
  13684. stream << Colour(col.colour)
  13685. << value << ' ' << col.label;
  13686. }
  13687. }
  13688. stream << '\n';
  13689. }
  13690. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13691. if (totals.testCases.total() > 0) {
  13692. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13693. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13694. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13695. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13696. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13697. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13698. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13699. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13700. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13701. if (totals.testCases.allPassed())
  13702. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13703. else
  13704. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13705. } else {
  13706. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13707. }
  13708. stream << '\n';
  13709. }
  13710. void ConsoleReporter::printSummaryDivider() {
  13711. stream << getLineOfChars<'-'>() << '\n';
  13712. }
  13713. void ConsoleReporter::printTestFilters() {
  13714. if (m_config->testSpec().hasFilters()) {
  13715. Colour guard(Colour::BrightYellow);
  13716. stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
  13717. }
  13718. }
  13719. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13720. } // end namespace Catch
  13721. #if defined(_MSC_VER)
  13722. #pragma warning(pop)
  13723. #endif
  13724. #if defined(__clang__)
  13725. # pragma clang diagnostic pop
  13726. #endif
  13727. // end catch_reporter_console.cpp
  13728. // start catch_reporter_junit.cpp
  13729. #include <cassert>
  13730. #include <sstream>
  13731. #include <ctime>
  13732. #include <algorithm>
  13733. namespace Catch {
  13734. namespace {
  13735. std::string getCurrentTimestamp() {
  13736. // Beware, this is not reentrant because of backward compatibility issues
  13737. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13738. time_t rawtime;
  13739. std::time(&rawtime);
  13740. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13741. #ifdef _MSC_VER
  13742. std::tm timeInfo = {};
  13743. gmtime_s(&timeInfo, &rawtime);
  13744. #else
  13745. std::tm* timeInfo;
  13746. timeInfo = std::gmtime(&rawtime);
  13747. #endif
  13748. char timeStamp[timeStampSize];
  13749. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13750. #ifdef _MSC_VER
  13751. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13752. #else
  13753. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13754. #endif
  13755. return std::string(timeStamp);
  13756. }
  13757. std::string fileNameTag(const std::vector<std::string> &tags) {
  13758. auto it = std::find_if(begin(tags),
  13759. end(tags),
  13760. [] (std::string const& tag) {return tag.front() == '#'; });
  13761. if (it != tags.end())
  13762. return it->substr(1);
  13763. return std::string();
  13764. }
  13765. } // anonymous namespace
  13766. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13767. : CumulativeReporterBase( _config ),
  13768. xml( _config.stream() )
  13769. {
  13770. m_reporterPrefs.shouldRedirectStdOut = true;
  13771. m_reporterPrefs.shouldReportAllAssertions = true;
  13772. }
  13773. JunitReporter::~JunitReporter() {}
  13774. std::string JunitReporter::getDescription() {
  13775. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13776. }
  13777. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13778. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13779. CumulativeReporterBase::testRunStarting( runInfo );
  13780. xml.startElement( "testsuites" );
  13781. }
  13782. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13783. suiteTimer.start();
  13784. stdOutForSuite.clear();
  13785. stdErrForSuite.clear();
  13786. unexpectedExceptions = 0;
  13787. CumulativeReporterBase::testGroupStarting( groupInfo );
  13788. }
  13789. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13790. m_okToFail = testCaseInfo.okToFail();
  13791. }
  13792. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13793. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13794. unexpectedExceptions++;
  13795. return CumulativeReporterBase::assertionEnded( assertionStats );
  13796. }
  13797. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13798. stdOutForSuite += testCaseStats.stdOut;
  13799. stdErrForSuite += testCaseStats.stdErr;
  13800. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13801. }
  13802. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13803. double suiteTime = suiteTimer.getElapsedSeconds();
  13804. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13805. writeGroup( *m_testGroups.back(), suiteTime );
  13806. }
  13807. void JunitReporter::testRunEndedCumulative() {
  13808. xml.endElement();
  13809. }
  13810. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13811. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13812. TestGroupStats const& stats = groupNode.value;
  13813. xml.writeAttribute( "name", stats.groupInfo.name );
  13814. xml.writeAttribute( "errors", unexpectedExceptions );
  13815. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13816. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13817. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13818. if( m_config->showDurations() == ShowDurations::Never )
  13819. xml.writeAttribute( "time", "" );
  13820. else
  13821. xml.writeAttribute( "time", suiteTime );
  13822. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13823. // Write properties if there are any
  13824. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13825. auto properties = xml.scopedElement("properties");
  13826. if (m_config->hasTestFilters()) {
  13827. xml.scopedElement("property")
  13828. .writeAttribute("name", "filters")
  13829. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13830. }
  13831. if (m_config->rngSeed() != 0) {
  13832. xml.scopedElement("property")
  13833. .writeAttribute("name", "random-seed")
  13834. .writeAttribute("value", m_config->rngSeed());
  13835. }
  13836. }
  13837. // Write test cases
  13838. for( auto const& child : groupNode.children )
  13839. writeTestCase( *child );
  13840. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  13841. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  13842. }
  13843. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13844. TestCaseStats const& stats = testCaseNode.value;
  13845. // All test cases have exactly one section - which represents the
  13846. // test case itself. That section may have 0-n nested sections
  13847. assert( testCaseNode.children.size() == 1 );
  13848. SectionNode const& rootSection = *testCaseNode.children.front();
  13849. std::string className = stats.testInfo.className;
  13850. if( className.empty() ) {
  13851. className = fileNameTag(stats.testInfo.tags);
  13852. if ( className.empty() )
  13853. className = "global";
  13854. }
  13855. if ( !m_config->name().empty() )
  13856. className = m_config->name() + "." + className;
  13857. writeSection( className, "", rootSection );
  13858. }
  13859. void JunitReporter::writeSection( std::string const& className,
  13860. std::string const& rootName,
  13861. SectionNode const& sectionNode ) {
  13862. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13863. if( !rootName.empty() )
  13864. name = rootName + '/' + name;
  13865. if( !sectionNode.assertions.empty() ||
  13866. !sectionNode.stdOut.empty() ||
  13867. !sectionNode.stdErr.empty() ) {
  13868. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13869. if( className.empty() ) {
  13870. xml.writeAttribute( "classname", name );
  13871. xml.writeAttribute( "name", "root" );
  13872. }
  13873. else {
  13874. xml.writeAttribute( "classname", className );
  13875. xml.writeAttribute( "name", name );
  13876. }
  13877. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13878. // This is not ideal, but it should be enough to mimic gtest's
  13879. // junit output.
  13880. // Ideally the JUnit reporter would also handle `skipTest`
  13881. // events and write those out appropriately.
  13882. xml.writeAttribute( "status", "run" );
  13883. writeAssertions( sectionNode );
  13884. if( !sectionNode.stdOut.empty() )
  13885. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  13886. if( !sectionNode.stdErr.empty() )
  13887. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  13888. }
  13889. for( auto const& childNode : sectionNode.childSections )
  13890. if( className.empty() )
  13891. writeSection( name, "", *childNode );
  13892. else
  13893. writeSection( className, name, *childNode );
  13894. }
  13895. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13896. for( auto const& assertion : sectionNode.assertions )
  13897. writeAssertion( assertion );
  13898. }
  13899. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13900. AssertionResult const& result = stats.assertionResult;
  13901. if( !result.isOk() ) {
  13902. std::string elementName;
  13903. switch( result.getResultType() ) {
  13904. case ResultWas::ThrewException:
  13905. case ResultWas::FatalErrorCondition:
  13906. elementName = "error";
  13907. break;
  13908. case ResultWas::ExplicitFailure:
  13909. case ResultWas::ExpressionFailed:
  13910. case ResultWas::DidntThrowException:
  13911. elementName = "failure";
  13912. break;
  13913. // We should never see these here:
  13914. case ResultWas::Info:
  13915. case ResultWas::Warning:
  13916. case ResultWas::Ok:
  13917. case ResultWas::Unknown:
  13918. case ResultWas::FailureBit:
  13919. case ResultWas::Exception:
  13920. elementName = "internalError";
  13921. break;
  13922. }
  13923. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13924. xml.writeAttribute( "message", result.getExpression() );
  13925. xml.writeAttribute( "type", result.getTestMacroName() );
  13926. ReusableStringStream rss;
  13927. if (stats.totals.assertions.total() > 0) {
  13928. rss << "FAILED" << ":\n";
  13929. if (result.hasExpression()) {
  13930. rss << " ";
  13931. rss << result.getExpressionInMacro();
  13932. rss << '\n';
  13933. }
  13934. if (result.hasExpandedExpression()) {
  13935. rss << "with expansion:\n";
  13936. rss << Column(result.getExpandedExpression()).indent(2) << '\n';
  13937. }
  13938. } else {
  13939. rss << '\n';
  13940. }
  13941. if( !result.getMessage().empty() )
  13942. rss << result.getMessage() << '\n';
  13943. for( auto const& msg : stats.infoMessages )
  13944. if( msg.type == ResultWas::Info )
  13945. rss << msg.message << '\n';
  13946. rss << "at " << result.getSourceInfo();
  13947. xml.writeText( rss.str(), XmlFormatting::Newline );
  13948. }
  13949. }
  13950. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13951. } // end namespace Catch
  13952. // end catch_reporter_junit.cpp
  13953. // start catch_reporter_listening.cpp
  13954. #include <cassert>
  13955. namespace Catch {
  13956. ListeningReporter::ListeningReporter() {
  13957. // We will assume that listeners will always want all assertions
  13958. m_preferences.shouldReportAllAssertions = true;
  13959. }
  13960. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13961. m_listeners.push_back( std::move( listener ) );
  13962. }
  13963. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13964. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13965. m_reporter = std::move( reporter );
  13966. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13967. }
  13968. ReporterPreferences ListeningReporter::getPreferences() const {
  13969. return m_preferences;
  13970. }
  13971. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13972. return std::set<Verbosity>{ };
  13973. }
  13974. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13975. for ( auto const& listener : m_listeners ) {
  13976. listener->noMatchingTestCases( spec );
  13977. }
  13978. m_reporter->noMatchingTestCases( spec );
  13979. }
  13980. void ListeningReporter::reportInvalidArguments(std::string const&arg){
  13981. for ( auto const& listener : m_listeners ) {
  13982. listener->reportInvalidArguments( arg );
  13983. }
  13984. m_reporter->reportInvalidArguments( arg );
  13985. }
  13986. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13987. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13988. for (auto const& listener : m_listeners) {
  13989. listener->benchmarkPreparing(name);
  13990. }
  13991. m_reporter->benchmarkPreparing(name);
  13992. }
  13993. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13994. for ( auto const& listener : m_listeners ) {
  13995. listener->benchmarkStarting( benchmarkInfo );
  13996. }
  13997. m_reporter->benchmarkStarting( benchmarkInfo );
  13998. }
  13999. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  14000. for ( auto const& listener : m_listeners ) {
  14001. listener->benchmarkEnded( benchmarkStats );
  14002. }
  14003. m_reporter->benchmarkEnded( benchmarkStats );
  14004. }
  14005. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  14006. for (auto const& listener : m_listeners) {
  14007. listener->benchmarkFailed(error);
  14008. }
  14009. m_reporter->benchmarkFailed(error);
  14010. }
  14011. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14012. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  14013. for ( auto const& listener : m_listeners ) {
  14014. listener->testRunStarting( testRunInfo );
  14015. }
  14016. m_reporter->testRunStarting( testRunInfo );
  14017. }
  14018. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14019. for ( auto const& listener : m_listeners ) {
  14020. listener->testGroupStarting( groupInfo );
  14021. }
  14022. m_reporter->testGroupStarting( groupInfo );
  14023. }
  14024. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14025. for ( auto const& listener : m_listeners ) {
  14026. listener->testCaseStarting( testInfo );
  14027. }
  14028. m_reporter->testCaseStarting( testInfo );
  14029. }
  14030. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14031. for ( auto const& listener : m_listeners ) {
  14032. listener->sectionStarting( sectionInfo );
  14033. }
  14034. m_reporter->sectionStarting( sectionInfo );
  14035. }
  14036. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  14037. for ( auto const& listener : m_listeners ) {
  14038. listener->assertionStarting( assertionInfo );
  14039. }
  14040. m_reporter->assertionStarting( assertionInfo );
  14041. }
  14042. // The return value indicates if the messages buffer should be cleared:
  14043. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14044. for( auto const& listener : m_listeners ) {
  14045. static_cast<void>( listener->assertionEnded( assertionStats ) );
  14046. }
  14047. return m_reporter->assertionEnded( assertionStats );
  14048. }
  14049. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  14050. for ( auto const& listener : m_listeners ) {
  14051. listener->sectionEnded( sectionStats );
  14052. }
  14053. m_reporter->sectionEnded( sectionStats );
  14054. }
  14055. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14056. for ( auto const& listener : m_listeners ) {
  14057. listener->testCaseEnded( testCaseStats );
  14058. }
  14059. m_reporter->testCaseEnded( testCaseStats );
  14060. }
  14061. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14062. for ( auto const& listener : m_listeners ) {
  14063. listener->testGroupEnded( testGroupStats );
  14064. }
  14065. m_reporter->testGroupEnded( testGroupStats );
  14066. }
  14067. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14068. for ( auto const& listener : m_listeners ) {
  14069. listener->testRunEnded( testRunStats );
  14070. }
  14071. m_reporter->testRunEnded( testRunStats );
  14072. }
  14073. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  14074. for ( auto const& listener : m_listeners ) {
  14075. listener->skipTest( testInfo );
  14076. }
  14077. m_reporter->skipTest( testInfo );
  14078. }
  14079. bool ListeningReporter::isMulti() const {
  14080. return true;
  14081. }
  14082. } // end namespace Catch
  14083. // end catch_reporter_listening.cpp
  14084. // start catch_reporter_xml.cpp
  14085. #if defined(_MSC_VER)
  14086. #pragma warning(push)
  14087. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  14088. // Note that 4062 (not all labels are handled
  14089. // and default is missing) is enabled
  14090. #endif
  14091. namespace Catch {
  14092. XmlReporter::XmlReporter( ReporterConfig const& _config )
  14093. : StreamingReporterBase( _config ),
  14094. m_xml(_config.stream())
  14095. {
  14096. m_reporterPrefs.shouldRedirectStdOut = true;
  14097. m_reporterPrefs.shouldReportAllAssertions = true;
  14098. }
  14099. XmlReporter::~XmlReporter() = default;
  14100. std::string XmlReporter::getDescription() {
  14101. return "Reports test results as an XML document";
  14102. }
  14103. std::string XmlReporter::getStylesheetRef() const {
  14104. return std::string();
  14105. }
  14106. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  14107. m_xml
  14108. .writeAttribute( "filename", sourceInfo.file )
  14109. .writeAttribute( "line", sourceInfo.line );
  14110. }
  14111. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  14112. StreamingReporterBase::noMatchingTestCases( s );
  14113. }
  14114. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  14115. StreamingReporterBase::testRunStarting( testInfo );
  14116. std::string stylesheetRef = getStylesheetRef();
  14117. if( !stylesheetRef.empty() )
  14118. m_xml.writeStylesheetRef( stylesheetRef );
  14119. m_xml.startElement( "Catch" );
  14120. if( !m_config->name().empty() )
  14121. m_xml.writeAttribute( "name", m_config->name() );
  14122. if (m_config->testSpec().hasFilters())
  14123. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  14124. if( m_config->rngSeed() != 0 )
  14125. m_xml.scopedElement( "Randomness" )
  14126. .writeAttribute( "seed", m_config->rngSeed() );
  14127. }
  14128. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14129. StreamingReporterBase::testGroupStarting( groupInfo );
  14130. m_xml.startElement( "Group" )
  14131. .writeAttribute( "name", groupInfo.name );
  14132. }
  14133. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14134. StreamingReporterBase::testCaseStarting(testInfo);
  14135. m_xml.startElement( "TestCase" )
  14136. .writeAttribute( "name", trim( testInfo.name ) )
  14137. .writeAttribute( "description", testInfo.description )
  14138. .writeAttribute( "tags", testInfo.tagsAsString() );
  14139. writeSourceInfo( testInfo.lineInfo );
  14140. if ( m_config->showDurations() == ShowDurations::Always )
  14141. m_testCaseTimer.start();
  14142. m_xml.ensureTagClosed();
  14143. }
  14144. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14145. StreamingReporterBase::sectionStarting( sectionInfo );
  14146. if( m_sectionDepth++ > 0 ) {
  14147. m_xml.startElement( "Section" )
  14148. .writeAttribute( "name", trim( sectionInfo.name ) );
  14149. writeSourceInfo( sectionInfo.lineInfo );
  14150. m_xml.ensureTagClosed();
  14151. }
  14152. }
  14153. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  14154. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14155. AssertionResult const& result = assertionStats.assertionResult;
  14156. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  14157. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  14158. // Print any info messages in <Info> tags.
  14159. for( auto const& msg : assertionStats.infoMessages ) {
  14160. if( msg.type == ResultWas::Info && includeResults ) {
  14161. m_xml.scopedElement( "Info" )
  14162. .writeText( msg.message );
  14163. } else if ( msg.type == ResultWas::Warning ) {
  14164. m_xml.scopedElement( "Warning" )
  14165. .writeText( msg.message );
  14166. }
  14167. }
  14168. }
  14169. // Drop out if result was successful but we're not printing them.
  14170. if( !includeResults && result.getResultType() != ResultWas::Warning )
  14171. return true;
  14172. // Print the expression if there is one.
  14173. if( result.hasExpression() ) {
  14174. m_xml.startElement( "Expression" )
  14175. .writeAttribute( "success", result.succeeded() )
  14176. .writeAttribute( "type", result.getTestMacroName() );
  14177. writeSourceInfo( result.getSourceInfo() );
  14178. m_xml.scopedElement( "Original" )
  14179. .writeText( result.getExpression() );
  14180. m_xml.scopedElement( "Expanded" )
  14181. .writeText( result.getExpandedExpression() );
  14182. }
  14183. // And... Print a result applicable to each result type.
  14184. switch( result.getResultType() ) {
  14185. case ResultWas::ThrewException:
  14186. m_xml.startElement( "Exception" );
  14187. writeSourceInfo( result.getSourceInfo() );
  14188. m_xml.writeText( result.getMessage() );
  14189. m_xml.endElement();
  14190. break;
  14191. case ResultWas::FatalErrorCondition:
  14192. m_xml.startElement( "FatalErrorCondition" );
  14193. writeSourceInfo( result.getSourceInfo() );
  14194. m_xml.writeText( result.getMessage() );
  14195. m_xml.endElement();
  14196. break;
  14197. case ResultWas::Info:
  14198. m_xml.scopedElement( "Info" )
  14199. .writeText( result.getMessage() );
  14200. break;
  14201. case ResultWas::Warning:
  14202. // Warning will already have been written
  14203. break;
  14204. case ResultWas::ExplicitFailure:
  14205. m_xml.startElement( "Failure" );
  14206. writeSourceInfo( result.getSourceInfo() );
  14207. m_xml.writeText( result.getMessage() );
  14208. m_xml.endElement();
  14209. break;
  14210. default:
  14211. break;
  14212. }
  14213. if( result.hasExpression() )
  14214. m_xml.endElement();
  14215. return true;
  14216. }
  14217. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14218. StreamingReporterBase::sectionEnded( sectionStats );
  14219. if( --m_sectionDepth > 0 ) {
  14220. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14221. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14222. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14223. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14224. if ( m_config->showDurations() == ShowDurations::Always )
  14225. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14226. m_xml.endElement();
  14227. }
  14228. }
  14229. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14230. StreamingReporterBase::testCaseEnded( testCaseStats );
  14231. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14232. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14233. if ( m_config->showDurations() == ShowDurations::Always )
  14234. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14235. if( !testCaseStats.stdOut.empty() )
  14236. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  14237. if( !testCaseStats.stdErr.empty() )
  14238. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  14239. m_xml.endElement();
  14240. }
  14241. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14242. StreamingReporterBase::testGroupEnded( testGroupStats );
  14243. // TODO: Check testGroupStats.aborting and act accordingly.
  14244. m_xml.scopedElement( "OverallResults" )
  14245. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14246. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14247. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14248. m_xml.scopedElement( "OverallResultsCases")
  14249. .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
  14250. .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
  14251. .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
  14252. m_xml.endElement();
  14253. }
  14254. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14255. StreamingReporterBase::testRunEnded( testRunStats );
  14256. m_xml.scopedElement( "OverallResults" )
  14257. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14258. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14259. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14260. m_xml.scopedElement( "OverallResultsCases")
  14261. .writeAttribute( "successes", testRunStats.totals.testCases.passed )
  14262. .writeAttribute( "failures", testRunStats.totals.testCases.failed )
  14263. .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
  14264. m_xml.endElement();
  14265. }
  14266. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14267. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14268. m_xml.startElement("BenchmarkResults")
  14269. .writeAttribute("name", name);
  14270. }
  14271. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14272. m_xml.writeAttribute("samples", info.samples)
  14273. .writeAttribute("resamples", info.resamples)
  14274. .writeAttribute("iterations", info.iterations)
  14275. .writeAttribute("clockResolution", info.clockResolution)
  14276. .writeAttribute("estimatedDuration", info.estimatedDuration)
  14277. .writeComment("All values in nano seconds");
  14278. }
  14279. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14280. m_xml.startElement("mean")
  14281. .writeAttribute("value", benchmarkStats.mean.point.count())
  14282. .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
  14283. .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
  14284. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14285. m_xml.endElement();
  14286. m_xml.startElement("standardDeviation")
  14287. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14288. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14289. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14290. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14291. m_xml.endElement();
  14292. m_xml.startElement("outliers")
  14293. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14294. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14295. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14296. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14297. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14298. m_xml.endElement();
  14299. m_xml.endElement();
  14300. }
  14301. void XmlReporter::benchmarkFailed(std::string const &error) {
  14302. m_xml.scopedElement("failed").
  14303. writeAttribute("message", error);
  14304. m_xml.endElement();
  14305. }
  14306. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14307. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14308. } // end namespace Catch
  14309. #if defined(_MSC_VER)
  14310. #pragma warning(pop)
  14311. #endif
  14312. // end catch_reporter_xml.cpp
  14313. namespace Catch {
  14314. LeakDetector leakDetector;
  14315. }
  14316. #ifdef __clang__
  14317. #pragma clang diagnostic pop
  14318. #endif
  14319. // end catch_impl.hpp
  14320. #endif
  14321. #ifdef CATCH_CONFIG_MAIN
  14322. // start catch_default_main.hpp
  14323. #ifndef __OBJC__
  14324. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14325. // Standard C/C++ Win32 Unicode wmain entry point
  14326. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14327. #else
  14328. // Standard C/C++ main entry point
  14329. int main (int argc, char * argv[]) {
  14330. #endif
  14331. return Catch::Session().run( argc, argv );
  14332. }
  14333. #else // __OBJC__
  14334. // Objective-C entry point
  14335. int main (int argc, char * const argv[]) {
  14336. #if !CATCH_ARC_ENABLED
  14337. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14338. #endif
  14339. Catch::registerTestMethods();
  14340. int result = Catch::Session().run( argc, (char**)argv );
  14341. #if !CATCH_ARC_ENABLED
  14342. [pool drain];
  14343. #endif
  14344. return result;
  14345. }
  14346. #endif // __OBJC__
  14347. // end catch_default_main.hpp
  14348. #endif
  14349. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14350. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14351. # undef CLARA_CONFIG_MAIN
  14352. #endif
  14353. #if !defined(CATCH_CONFIG_DISABLE)
  14354. //////
  14355. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14356. #ifdef CATCH_CONFIG_PREFIX_ALL
  14357. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14358. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14359. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14360. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14361. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14362. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14363. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14364. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14365. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14366. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14367. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14368. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14369. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14370. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14371. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14372. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14373. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14374. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14375. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14376. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14377. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14378. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14379. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14380. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14381. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14382. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14383. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14384. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14385. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14386. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14387. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14388. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14389. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14390. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14391. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14392. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14393. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14394. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14395. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14396. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14397. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14398. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14399. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14400. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14401. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14402. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14403. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14404. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14405. #else
  14406. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14407. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14408. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14409. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14410. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14411. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14412. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14413. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14414. #endif
  14415. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14416. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14417. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14418. #else
  14419. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14420. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14421. #endif
  14422. // "BDD-style" convenience wrappers
  14423. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14424. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14425. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14426. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14427. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14428. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14429. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14430. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14431. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14432. #define CATCH_BENCHMARK(...) \
  14433. INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
  14434. #define CATCH_BENCHMARK_ADVANCED(name) \
  14435. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14436. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14437. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14438. #else
  14439. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14440. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14441. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14442. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14443. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14444. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14445. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14446. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14447. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14448. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14449. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14450. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14451. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14452. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14453. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14454. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14455. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14456. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14457. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14458. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14459. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14460. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14461. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14462. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14463. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14464. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  14465. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14466. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14467. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14468. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14469. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14470. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14471. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14472. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14473. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14474. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14475. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14476. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14477. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14478. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14479. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14480. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14481. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14482. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14483. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14484. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14485. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14486. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14487. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14488. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14489. #else
  14490. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14491. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14492. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14493. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14494. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14495. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14496. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14497. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14498. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14499. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14500. #endif
  14501. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14502. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14503. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14504. #else
  14505. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14506. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14507. #endif
  14508. #endif
  14509. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14510. // "BDD-style" convenience wrappers
  14511. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14512. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14513. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14514. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14515. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14516. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14517. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14518. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14519. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14520. #define BENCHMARK(...) \
  14521. INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
  14522. #define BENCHMARK_ADVANCED(name) \
  14523. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  14524. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14525. using Catch::Detail::Approx;
  14526. #else // CATCH_CONFIG_DISABLE
  14527. //////
  14528. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14529. #ifdef CATCH_CONFIG_PREFIX_ALL
  14530. #define CATCH_REQUIRE( ... ) (void)(0)
  14531. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14532. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14533. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14534. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14535. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14536. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14537. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14538. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14539. #define CATCH_CHECK( ... ) (void)(0)
  14540. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14541. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14542. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14543. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14544. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14545. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14546. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14547. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14548. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14549. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14550. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14551. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14552. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14553. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14554. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14555. #define CATCH_INFO( msg ) (void)(0)
  14556. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14557. #define CATCH_WARN( msg ) (void)(0)
  14558. #define CATCH_CAPTURE( msg ) (void)(0)
  14559. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14560. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14561. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14562. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14563. #define CATCH_SECTION( ... )
  14564. #define CATCH_DYNAMIC_SECTION( ... )
  14565. #define CATCH_FAIL( ... ) (void)(0)
  14566. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14567. #define CATCH_SUCCEED( ... ) (void)(0)
  14568. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14569. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14570. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14571. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14572. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14573. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14574. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14575. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14576. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14577. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14578. #else
  14579. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14580. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14581. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14582. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14583. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14584. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14585. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14586. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14587. #endif
  14588. // "BDD-style" convenience wrappers
  14589. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14590. #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 )
  14591. #define CATCH_GIVEN( desc )
  14592. #define CATCH_AND_GIVEN( desc )
  14593. #define CATCH_WHEN( desc )
  14594. #define CATCH_AND_WHEN( desc )
  14595. #define CATCH_THEN( desc )
  14596. #define CATCH_AND_THEN( desc )
  14597. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14598. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14599. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14600. #else
  14601. #define REQUIRE( ... ) (void)(0)
  14602. #define REQUIRE_FALSE( ... ) (void)(0)
  14603. #define REQUIRE_THROWS( ... ) (void)(0)
  14604. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14605. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14606. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14607. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14608. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14609. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14610. #define CHECK( ... ) (void)(0)
  14611. #define CHECK_FALSE( ... ) (void)(0)
  14612. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14613. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14614. #define CHECK_NOFAIL( ... ) (void)(0)
  14615. #define CHECK_THROWS( ... ) (void)(0)
  14616. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14617. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14618. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14619. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14620. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14621. #define CHECK_NOTHROW( ... ) (void)(0)
  14622. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14623. #define CHECK_THAT( arg, matcher ) (void)(0)
  14624. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14625. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14626. #define INFO( msg ) (void)(0)
  14627. #define UNSCOPED_INFO( msg ) (void)(0)
  14628. #define WARN( msg ) (void)(0)
  14629. #define CAPTURE( msg ) (void)(0)
  14630. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14631. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14632. #define METHOD_AS_TEST_CASE( method, ... )
  14633. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14634. #define SECTION( ... )
  14635. #define DYNAMIC_SECTION( ... )
  14636. #define FAIL( ... ) (void)(0)
  14637. #define FAIL_CHECK( ... ) (void)(0)
  14638. #define SUCCEED( ... ) (void)(0)
  14639. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14640. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14641. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14642. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14643. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14644. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14645. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14646. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14647. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14648. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14649. #else
  14650. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14651. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14652. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14653. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14654. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14655. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14656. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14657. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14658. #endif
  14659. #define STATIC_REQUIRE( ... ) (void)(0)
  14660. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14661. #endif
  14662. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14663. // "BDD-style" convenience wrappers
  14664. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14665. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14666. #define GIVEN( desc )
  14667. #define AND_GIVEN( desc )
  14668. #define WHEN( desc )
  14669. #define AND_WHEN( desc )
  14670. #define THEN( desc )
  14671. #define AND_THEN( desc )
  14672. using Catch::Detail::Approx;
  14673. #endif
  14674. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14675. // start catch_reenable_warnings.h
  14676. #ifdef __clang__
  14677. # ifdef __ICC // icpc defines the __clang__ macro
  14678. # pragma warning(pop)
  14679. # else
  14680. # pragma clang diagnostic pop
  14681. # endif
  14682. #elif defined __GNUC__
  14683. # pragma GCC diagnostic pop
  14684. #endif
  14685. // end catch_reenable_warnings.h
  14686. // end catch.hpp
  14687. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED