暫無描述

catch.hpp 605KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075
  1. /*
  2. * Catch v2.9.2
  3. * Generated: 2019-08-08 13:35:12.279703
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 9
  16. #define CATCH_VERSION_PATCH 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  131. _Pragma( "clang diagnostic push" ) \
  132. _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
  133. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  134. _Pragma( "clang diagnostic pop" )
  135. #endif // __clang__
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // Assume that non-Windows platforms support posix signals by default
  138. #if !defined(CATCH_PLATFORM_WINDOWS)
  139. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  140. #endif
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // We know some environments not to support full POSIX signals
  143. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  144. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  145. #endif
  146. #ifdef __OS400__
  147. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  148. # define CATCH_CONFIG_COLOUR_NONE
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Android somehow still does not support std::to_string
  152. #if defined(__ANDROID__)
  153. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // Not all Windows environments support SEH properly
  157. #if defined(__MINGW32__)
  158. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // PS4
  162. #if defined(__ORBIS__)
  163. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  164. #endif
  165. ////////////////////////////////////////////////////////////////////////////////
  166. // Cygwin
  167. #ifdef __CYGWIN__
  168. // Required for some versions of Cygwin to declare gettimeofday
  169. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  170. # define _BSD_SOURCE
  171. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  172. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  173. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  174. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  175. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  176. # endif
  177. #endif // __CYGWIN__
  178. ////////////////////////////////////////////////////////////////////////////////
  179. // Visual C++
  180. #ifdef _MSC_VER
  181. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  182. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  183. # endif
  184. // Universal Windows platform does not support SEH
  185. // Or console colours (or console at all...)
  186. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  187. # define CATCH_CONFIG_COLOUR_NONE
  188. # else
  189. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  190. # endif
  191. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  192. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  193. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  194. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  195. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  196. # endif
  197. #endif // _MSC_VER
  198. #if defined(_REENTRANT) || defined(_MSC_VER)
  199. // Enable async processing, as -pthread is specified or no additional linking is required
  200. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  201. #endif // _MSC_VER
  202. ////////////////////////////////////////////////////////////////////////////////
  203. // Check if we are compiled with -fno-exceptions or equivalent
  204. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  205. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  206. #endif
  207. ////////////////////////////////////////////////////////////////////////////////
  208. // DJGPP
  209. #ifdef __DJGPP__
  210. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  211. #endif // __DJGPP__
  212. ////////////////////////////////////////////////////////////////////////////////
  213. // Embarcadero C++Build
  214. #if defined(__BORLANDC__)
  215. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  216. #endif
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Use of __COUNTER__ is suppressed during code analysis in
  219. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  220. // handled by it.
  221. // Otherwise all supported compilers support COUNTER macro,
  222. // but user still might want to turn it off
  223. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  224. #define CATCH_INTERNAL_CONFIG_COUNTER
  225. #endif
  226. ////////////////////////////////////////////////////////////////////////////////
  227. // RTX is a special version of Windows that is real time.
  228. // This means that it is detected as Windows, but does not provide
  229. // the same set of capabilities as real Windows does.
  230. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  231. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  232. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  233. #define CATCH_CONFIG_COLOUR_NONE
  234. #endif
  235. ////////////////////////////////////////////////////////////////////////////////
  236. // Check if string_view is available and usable
  237. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  238. #if defined(__has_include)
  239. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  240. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  241. #endif
  242. #endif
  243. ////////////////////////////////////////////////////////////////////////////////
  244. // Check if optional is available and usable
  245. #if defined(__has_include)
  246. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  247. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  248. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  249. #endif // __has_include
  250. ////////////////////////////////////////////////////////////////////////////////
  251. // Check if byte is available and usable
  252. #if defined(__has_include)
  253. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  254. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  255. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  256. #endif // __has_include
  257. ////////////////////////////////////////////////////////////////////////////////
  258. // Check if variant is available and usable
  259. #if defined(__has_include)
  260. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  261. # if defined(__clang__) && (__clang_major__ < 8)
  262. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  263. // fix should be in clang 8, workaround in libstdc++ 8.2
  264. # include <ciso646>
  265. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  266. # define CATCH_CONFIG_NO_CPP17_VARIANT
  267. # else
  268. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  269. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  270. # else
  271. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  272. # endif // defined(__clang__) && (__clang_major__ < 8)
  273. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  274. #endif // __has_include
  275. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  276. # define CATCH_CONFIG_COUNTER
  277. #endif
  278. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  279. # define CATCH_CONFIG_WINDOWS_SEH
  280. #endif
  281. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  282. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  283. # define CATCH_CONFIG_POSIX_SIGNALS
  284. #endif
  285. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  286. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  287. # define CATCH_CONFIG_WCHAR
  288. #endif
  289. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  290. # define CATCH_CONFIG_CPP11_TO_STRING
  291. #endif
  292. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  293. # define CATCH_CONFIG_CPP17_OPTIONAL
  294. #endif
  295. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  296. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  297. #endif
  298. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  299. # define CATCH_CONFIG_CPP17_STRING_VIEW
  300. #endif
  301. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  302. # define CATCH_CONFIG_CPP17_VARIANT
  303. #endif
  304. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  305. # define CATCH_CONFIG_CPP17_BYTE
  306. #endif
  307. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  308. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  309. #endif
  310. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  311. # define CATCH_CONFIG_NEW_CAPTURE
  312. #endif
  313. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  314. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  315. #endif
  316. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  317. # define CATCH_CONFIG_POLYFILL_ISNAN
  318. #endif
  319. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  320. # define CATCH_CONFIG_USE_ASYNC
  321. #endif
  322. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  323. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  324. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  325. #endif
  326. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  327. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  328. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  329. #endif
  330. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  331. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  332. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  333. #endif
  334. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  335. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  336. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
  337. #endif
  338. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  339. #define CATCH_TRY if ((true))
  340. #define CATCH_CATCH_ALL if ((false))
  341. #define CATCH_CATCH_ANON(type) if ((false))
  342. #else
  343. #define CATCH_TRY try
  344. #define CATCH_CATCH_ALL catch (...)
  345. #define CATCH_CATCH_ANON(type) catch (type)
  346. #endif
  347. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  348. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  349. #endif
  350. // end catch_compiler_capabilities.h
  351. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  352. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  353. #ifdef CATCH_CONFIG_COUNTER
  354. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  355. #else
  356. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  357. #endif
  358. #include <iosfwd>
  359. #include <string>
  360. #include <cstdint>
  361. // We need a dummy global operator<< so we can bring it into Catch namespace later
  362. struct Catch_global_namespace_dummy {};
  363. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  364. namespace Catch {
  365. struct CaseSensitive { enum Choice {
  366. Yes,
  367. No
  368. }; };
  369. class NonCopyable {
  370. NonCopyable( NonCopyable const& ) = delete;
  371. NonCopyable( NonCopyable && ) = delete;
  372. NonCopyable& operator = ( NonCopyable const& ) = delete;
  373. NonCopyable& operator = ( NonCopyable && ) = delete;
  374. protected:
  375. NonCopyable();
  376. virtual ~NonCopyable();
  377. };
  378. struct SourceLineInfo {
  379. SourceLineInfo() = delete;
  380. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  381. : file( _file ),
  382. line( _line )
  383. {}
  384. SourceLineInfo( SourceLineInfo const& other ) = default;
  385. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  386. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  387. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  388. bool empty() const noexcept;
  389. bool operator == ( SourceLineInfo const& other ) const noexcept;
  390. bool operator < ( SourceLineInfo const& other ) const noexcept;
  391. char const* file;
  392. std::size_t line;
  393. };
  394. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  395. // Bring in operator<< from global namespace into Catch namespace
  396. // This is necessary because the overload of operator<< above makes
  397. // lookup stop at namespace Catch
  398. using ::operator<<;
  399. // Use this in variadic streaming macros to allow
  400. // >> +StreamEndStop
  401. // as well as
  402. // >> stuff +StreamEndStop
  403. struct StreamEndStop {
  404. std::string operator+() const;
  405. };
  406. template<typename T>
  407. T const& operator + ( T const& value, StreamEndStop ) {
  408. return value;
  409. }
  410. }
  411. #define CATCH_INTERNAL_LINEINFO \
  412. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  413. // end catch_common.h
  414. namespace Catch {
  415. struct RegistrarForTagAliases {
  416. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  417. };
  418. } // end namespace Catch
  419. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  420. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  421. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  422. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  423. // end catch_tag_alias_autoregistrar.h
  424. // start catch_test_registry.h
  425. // start catch_interfaces_testcase.h
  426. #include <vector>
  427. namespace Catch {
  428. class TestSpec;
  429. struct ITestInvoker {
  430. virtual void invoke () const = 0;
  431. virtual ~ITestInvoker();
  432. };
  433. class TestCase;
  434. struct IConfig;
  435. struct ITestCaseRegistry {
  436. virtual ~ITestCaseRegistry();
  437. virtual std::vector<TestCase> const& getAllTests() const = 0;
  438. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  439. };
  440. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  441. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  442. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  443. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  444. }
  445. // end catch_interfaces_testcase.h
  446. // start catch_stringref.h
  447. #include <cstddef>
  448. #include <string>
  449. #include <iosfwd>
  450. namespace Catch {
  451. /// A non-owning string class (similar to the forthcoming std::string_view)
  452. /// Note that, because a StringRef may be a substring of another string,
  453. /// it may not be null terminated. c_str() must return a null terminated
  454. /// string, however, and so the StringRef will internally take ownership
  455. /// (taking a copy), if necessary. In theory this ownership is not externally
  456. /// visible - but it does mean (substring) StringRefs should not be shared between
  457. /// threads.
  458. class StringRef {
  459. public:
  460. using size_type = std::size_t;
  461. private:
  462. friend struct StringRefTestAccess;
  463. char const* m_start;
  464. size_type m_size;
  465. char* m_data = nullptr;
  466. void takeOwnership();
  467. static constexpr char const* const s_empty = "";
  468. public: // construction/ assignment
  469. StringRef() noexcept
  470. : StringRef( s_empty, 0 )
  471. {}
  472. StringRef( StringRef const& other ) noexcept
  473. : m_start( other.m_start ),
  474. m_size( other.m_size )
  475. {}
  476. StringRef( StringRef&& other ) noexcept
  477. : m_start( other.m_start ),
  478. m_size( other.m_size ),
  479. m_data( other.m_data )
  480. {
  481. other.m_data = nullptr;
  482. }
  483. StringRef( char const* rawChars ) noexcept;
  484. StringRef( char const* rawChars, size_type size ) noexcept
  485. : m_start( rawChars ),
  486. m_size( size )
  487. {}
  488. StringRef( std::string const& stdString ) noexcept
  489. : m_start( stdString.c_str() ),
  490. m_size( stdString.size() )
  491. {}
  492. ~StringRef() noexcept {
  493. delete[] m_data;
  494. }
  495. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  496. delete[] m_data;
  497. m_data = nullptr;
  498. m_start = other.m_start;
  499. m_size = other.m_size;
  500. return *this;
  501. }
  502. operator std::string() const;
  503. void swap( StringRef& other ) noexcept;
  504. public: // operators
  505. auto operator == ( StringRef const& other ) const noexcept -> bool;
  506. auto operator != ( StringRef const& other ) const noexcept -> bool;
  507. auto operator[] ( size_type index ) const noexcept -> char;
  508. public: // named queries
  509. auto empty() const noexcept -> bool {
  510. return m_size == 0;
  511. }
  512. auto size() const noexcept -> size_type {
  513. return m_size;
  514. }
  515. auto numberOfCharacters() const noexcept -> size_type;
  516. auto c_str() const -> char const*;
  517. public: // substrings and searches
  518. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  519. // Returns the current start pointer.
  520. // Note that the pointer can change when if the StringRef is a substring
  521. auto currentData() const noexcept -> char const*;
  522. private: // ownership queries - may not be consistent between calls
  523. auto isOwned() const noexcept -> bool;
  524. auto isSubstring() const noexcept -> bool;
  525. };
  526. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  527. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  528. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  529. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  530. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  531. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  532. return StringRef( rawChars, size );
  533. }
  534. } // namespace Catch
  535. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  536. return Catch::StringRef( rawChars, size );
  537. }
  538. // end catch_stringref.h
  539. // start catch_type_traits.hpp
  540. #include <type_traits>
  541. namespace Catch{
  542. #ifdef CATCH_CPP17_OR_GREATER
  543. template <typename...>
  544. inline constexpr auto is_unique = std::true_type{};
  545. template <typename T, typename... Rest>
  546. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  547. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  548. >{};
  549. #else
  550. template <typename...>
  551. struct is_unique : std::true_type{};
  552. template <typename T0, typename T1, typename... Rest>
  553. struct is_unique<T0, T1, Rest...> : std::integral_constant
  554. <bool,
  555. !std::is_same<T0, T1>::value
  556. && is_unique<T0, Rest...>::value
  557. && is_unique<T1, Rest...>::value
  558. >{};
  559. #endif
  560. }
  561. // end catch_type_traits.hpp
  562. // start catch_preprocessor.hpp
  563. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  564. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  565. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  566. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  567. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  568. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  569. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  570. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  571. // MSVC needs more evaluations
  572. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  573. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  574. #else
  575. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  576. #endif
  577. #define CATCH_REC_END(...)
  578. #define CATCH_REC_OUT
  579. #define CATCH_EMPTY()
  580. #define CATCH_DEFER(id) id CATCH_EMPTY()
  581. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  582. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  583. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  584. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  585. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  586. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  587. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  588. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  589. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  590. #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__ )
  591. #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__ )
  592. #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__ )
  593. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  594. // and passes userdata as the first parameter to each invocation,
  595. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  596. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  597. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  598. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  599. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  600. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  601. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  602. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  603. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  604. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  605. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  606. #else
  607. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  608. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  609. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  610. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  611. #endif
  612. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  613. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  614. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  615. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  616. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  617. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  618. #else
  619. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  620. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  621. #endif
  622. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  623. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  624. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  625. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  626. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  627. #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)
  628. #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)
  629. #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)
  630. #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6)
  631. #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)
  632. #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)
  633. #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)
  634. #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)
  635. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  636. #define INTERNAL_CATCH_TYPE_GEN\
  637. template<typename...> struct TypeList {};\
  638. template<typename...Ts>\
  639. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  640. \
  641. template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
  642. constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
  643. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  644. constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
  645. template< template<typename...> class L1, typename...E1, typename...Rest>\
  646. constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
  647. \
  648. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  649. constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
  650. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  651. constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
  652. \
  653. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  654. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
  655. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  656. constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
  657. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  658. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  659. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  660. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  661. \
  662. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  663. constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
  664. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  665. constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
  666. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  667. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
  668. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  669. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  670. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  671. static void TestName()
  672. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  673. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  674. static void TestName()
  675. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  676. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  677. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  678. static void TestName()
  679. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  680. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  681. static void TestName()
  682. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  683. template<typename Type>\
  684. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  685. {\
  686. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  687. }
  688. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  689. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  690. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  691. {\
  692. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  693. }
  694. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  695. template<typename Type>\
  696. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  697. {\
  698. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  699. }
  700. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  701. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  702. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  703. {\
  704. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  705. }
  706. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  707. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  708. template<typename TestType> \
  709. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  710. void test();\
  711. }
  712. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  713. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  714. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  715. void test();\
  716. }
  717. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  718. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  719. template<typename TestType> \
  720. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  721. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  722. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  723. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  724. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  725. #define INTERNAL_CATCH_NTTP_0
  726. #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)
  727. #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__)
  728. #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__)
  729. #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__)
  730. #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__)
  731. #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__)
  732. #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__)
  733. #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__)
  734. #else
  735. #define INTERNAL_CATCH_NTTP_0(signature)
  736. #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__))
  737. #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__))
  738. #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__))
  739. #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__))
  740. #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__))
  741. #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__))
  742. #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__))
  743. #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__))
  744. #endif
  745. // end catch_preprocessor.hpp
  746. // start catch_meta.hpp
  747. #include <type_traits>
  748. namespace Catch {
  749. template<typename T>
  750. struct always_false : std::false_type {};
  751. template <typename> struct true_given : std::true_type {};
  752. struct is_callable_tester {
  753. template <typename Fun, typename... Args>
  754. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  755. template <typename...>
  756. std::false_type static test(...);
  757. };
  758. template <typename T>
  759. struct is_callable;
  760. template <typename Fun, typename... Args>
  761. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  762. } // namespace Catch
  763. namespace mpl_{
  764. struct na;
  765. }
  766. // end catch_meta.hpp
  767. namespace Catch {
  768. template<typename C>
  769. class TestInvokerAsMethod : public ITestInvoker {
  770. void (C::*m_testAsMethod)();
  771. public:
  772. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  773. void invoke() const override {
  774. C obj;
  775. (obj.*m_testAsMethod)();
  776. }
  777. };
  778. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  779. template<typename C>
  780. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  781. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  782. }
  783. struct NameAndTags {
  784. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  785. StringRef name;
  786. StringRef tags;
  787. };
  788. struct AutoReg : NonCopyable {
  789. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  790. ~AutoReg();
  791. };
  792. } // end namespace Catch
  793. #if defined(CATCH_CONFIG_DISABLE)
  794. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  795. static void TestName()
  796. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  797. namespace{ \
  798. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  799. void test(); \
  800. }; \
  801. } \
  802. void TestName::test()
  803. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  804. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  805. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  806. namespace{ \
  807. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  808. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  809. } \
  810. } \
  811. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  812. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  813. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  814. 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__ )
  815. #else
  816. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  817. 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__ ) )
  818. #endif
  819. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  820. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  821. 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__ )
  822. #else
  823. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  824. 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__ ) )
  825. #endif
  826. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  827. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  828. 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__ )
  829. #else
  830. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  831. 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__ ) )
  832. #endif
  833. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  834. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  835. 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__ )
  836. #else
  837. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  838. 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__ ) )
  839. #endif
  840. #endif
  841. ///////////////////////////////////////////////////////////////////////////////
  842. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  843. static void TestName(); \
  844. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  845. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  846. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  847. static void TestName()
  848. #define INTERNAL_CATCH_TESTCASE( ... ) \
  849. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  850. ///////////////////////////////////////////////////////////////////////////////
  851. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  852. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  853. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  854. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  855. ///////////////////////////////////////////////////////////////////////////////
  856. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  857. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  858. namespace{ \
  859. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  860. void test(); \
  861. }; \
  862. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  863. } \
  864. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  865. void TestName::test()
  866. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  867. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  868. ///////////////////////////////////////////////////////////////////////////////
  869. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  870. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  871. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  872. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  873. ///////////////////////////////////////////////////////////////////////////////
  874. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  875. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  876. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  877. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  878. namespace {\
  879. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  880. INTERNAL_CATCH_TYPE_GEN\
  881. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  882. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  883. template<typename...Types> \
  884. struct TestName{\
  885. TestName(){\
  886. int index = 0; \
  887. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  888. using expander = int[];\
  889. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  890. }\
  891. };\
  892. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  893. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  894. return 0;\
  895. }();\
  896. }\
  897. }\
  898. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  899. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  900. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  901. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  902. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  903. 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__ )
  904. #else
  905. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  906. 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__ ) )
  907. #endif
  908. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  909. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  910. 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__ )
  911. #else
  912. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  913. 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__ ) )
  914. #endif
  915. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  916. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  917. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  918. template<typename TestType> static void TestFuncName(); \
  919. namespace {\
  920. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  921. INTERNAL_CATCH_TYPE_GEN \
  922. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  923. template<typename... Types> \
  924. struct TestName { \
  925. void reg_tests() { \
  926. int index = 0; \
  927. using expander = int[]; \
  928. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  929. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  930. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  931. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\
  932. } \
  933. }; \
  934. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  935. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  936. TestInit t; \
  937. t.reg_tests(); \
  938. return 0; \
  939. }(); \
  940. } \
  941. } \
  942. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  943. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  944. template<typename TestType> \
  945. static void TestFuncName()
  946. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  947. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  948. 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__)
  949. #else
  950. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  951. 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__ ) )
  952. #endif
  953. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  954. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  955. 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__)
  956. #else
  957. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  958. 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__ ) )
  959. #endif
  960. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  961. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  962. template<typename TestType> static void TestFunc(); \
  963. namespace {\
  964. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  965. INTERNAL_CATCH_TYPE_GEN\
  966. template<typename... Types> \
  967. struct TestName { \
  968. void reg_tests() { \
  969. int index = 0; \
  970. using expander = int[]; \
  971. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */\
  972. } \
  973. };\
  974. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  975. using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
  976. TestInit t; \
  977. t.reg_tests(); \
  978. return 0; \
  979. }(); \
  980. }}\
  981. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  982. template<typename TestType> \
  983. static void TestFunc()
  984. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  985. 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 )
  986. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  987. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  988. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  989. namespace {\
  990. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  991. INTERNAL_CATCH_TYPE_GEN\
  992. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  993. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  994. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  995. template<typename...Types> \
  996. struct TestNameClass{\
  997. TestNameClass(){\
  998. int index = 0; \
  999. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1000. using expander = int[];\
  1001. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  1002. }\
  1003. };\
  1004. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1005. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1006. return 0;\
  1007. }();\
  1008. }\
  1009. }\
  1010. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  1011. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  1012. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1013. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1014. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1015. 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__ )
  1016. #else
  1017. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1018. 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__ ) )
  1019. #endif
  1020. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1021. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1022. 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__ )
  1023. #else
  1024. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1025. 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__ ) )
  1026. #endif
  1027. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1028. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1029. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1030. template<typename TestType> \
  1031. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1032. void test();\
  1033. };\
  1034. namespace {\
  1035. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1036. INTERNAL_CATCH_TYPE_GEN \
  1037. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1038. template<typename...Types>\
  1039. struct TestNameClass{\
  1040. void reg_tests(){\
  1041. int index = 0;\
  1042. using expander = int[];\
  1043. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1044. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1045. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1046. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \
  1047. }\
  1048. };\
  1049. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1050. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1051. TestInit t;\
  1052. t.reg_tests();\
  1053. return 0;\
  1054. }(); \
  1055. }\
  1056. }\
  1057. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1058. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1059. template<typename TestType> \
  1060. void TestName<TestType>::test()
  1061. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1062. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1063. 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__ )
  1064. #else
  1065. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1066. 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__ ) )
  1067. #endif
  1068. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1069. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1070. 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__ )
  1071. #else
  1072. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1073. 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__ ) )
  1074. #endif
  1075. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1076. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1077. template<typename TestType> \
  1078. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1079. void test();\
  1080. };\
  1081. namespace {\
  1082. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1083. INTERNAL_CATCH_TYPE_GEN\
  1084. template<typename...Types>\
  1085. struct TestNameClass{\
  1086. void reg_tests(){\
  1087. int index = 0;\
  1088. using expander = int[];\
  1089. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */ \
  1090. }\
  1091. };\
  1092. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1093. using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
  1094. TestInit t;\
  1095. t.reg_tests();\
  1096. return 0;\
  1097. }(); \
  1098. }}\
  1099. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1100. template<typename TestType> \
  1101. void TestName<TestType>::test()
  1102. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1103. 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 )
  1104. // end catch_test_registry.h
  1105. // start catch_capture.hpp
  1106. // start catch_assertionhandler.h
  1107. // start catch_assertioninfo.h
  1108. // start catch_result_type.h
  1109. namespace Catch {
  1110. // ResultWas::OfType enum
  1111. struct ResultWas { enum OfType {
  1112. Unknown = -1,
  1113. Ok = 0,
  1114. Info = 1,
  1115. Warning = 2,
  1116. FailureBit = 0x10,
  1117. ExpressionFailed = FailureBit | 1,
  1118. ExplicitFailure = FailureBit | 2,
  1119. Exception = 0x100 | FailureBit,
  1120. ThrewException = Exception | 1,
  1121. DidntThrowException = Exception | 2,
  1122. FatalErrorCondition = 0x200 | FailureBit
  1123. }; };
  1124. bool isOk( ResultWas::OfType resultType );
  1125. bool isJustInfo( int flags );
  1126. // ResultDisposition::Flags enum
  1127. struct ResultDisposition { enum Flags {
  1128. Normal = 0x01,
  1129. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1130. FalseTest = 0x04, // Prefix expression with !
  1131. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1132. }; };
  1133. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1134. bool shouldContinueOnFailure( int flags );
  1135. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1136. bool shouldSuppressFailure( int flags );
  1137. } // end namespace Catch
  1138. // end catch_result_type.h
  1139. namespace Catch {
  1140. struct AssertionInfo
  1141. {
  1142. StringRef macroName;
  1143. SourceLineInfo lineInfo;
  1144. StringRef capturedExpression;
  1145. ResultDisposition::Flags resultDisposition;
  1146. // We want to delete this constructor but a compiler bug in 4.8 means
  1147. // the struct is then treated as non-aggregate
  1148. //AssertionInfo() = delete;
  1149. };
  1150. } // end namespace Catch
  1151. // end catch_assertioninfo.h
  1152. // start catch_decomposer.h
  1153. // start catch_tostring.h
  1154. #include <vector>
  1155. #include <cstddef>
  1156. #include <type_traits>
  1157. #include <string>
  1158. // start catch_stream.h
  1159. #include <iosfwd>
  1160. #include <cstddef>
  1161. #include <ostream>
  1162. namespace Catch {
  1163. std::ostream& cout();
  1164. std::ostream& cerr();
  1165. std::ostream& clog();
  1166. class StringRef;
  1167. struct IStream {
  1168. virtual ~IStream();
  1169. virtual std::ostream& stream() const = 0;
  1170. };
  1171. auto makeStream( StringRef const &filename ) -> IStream const*;
  1172. class ReusableStringStream {
  1173. std::size_t m_index;
  1174. std::ostream* m_oss;
  1175. public:
  1176. ReusableStringStream();
  1177. ~ReusableStringStream();
  1178. auto str() const -> std::string;
  1179. template<typename T>
  1180. auto operator << ( T const& value ) -> ReusableStringStream& {
  1181. *m_oss << value;
  1182. return *this;
  1183. }
  1184. auto get() -> std::ostream& { return *m_oss; }
  1185. };
  1186. }
  1187. // end catch_stream.h
  1188. // start catch_interfaces_enum_values_registry.h
  1189. #include <vector>
  1190. namespace Catch {
  1191. namespace Detail {
  1192. struct EnumInfo {
  1193. StringRef m_name;
  1194. std::vector<std::pair<int, std::string>> m_values;
  1195. ~EnumInfo();
  1196. StringRef lookup( int value ) const;
  1197. };
  1198. } // namespace Detail
  1199. struct IMutableEnumValuesRegistry {
  1200. virtual ~IMutableEnumValuesRegistry();
  1201. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1202. template<typename E>
  1203. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1204. std::vector<int> intValues;
  1205. intValues.reserve( values.size() );
  1206. for( auto enumValue : values )
  1207. intValues.push_back( static_cast<int>( enumValue ) );
  1208. return registerEnum( enumName, allEnums, intValues );
  1209. }
  1210. };
  1211. } // Catch
  1212. // end catch_interfaces_enum_values_registry.h
  1213. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1214. #include <string_view>
  1215. #endif
  1216. #ifdef __OBJC__
  1217. // start catch_objc_arc.hpp
  1218. #import <Foundation/Foundation.h>
  1219. #ifdef __has_feature
  1220. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1221. #else
  1222. #define CATCH_ARC_ENABLED 0
  1223. #endif
  1224. void arcSafeRelease( NSObject* obj );
  1225. id performOptionalSelector( id obj, SEL sel );
  1226. #if !CATCH_ARC_ENABLED
  1227. inline void arcSafeRelease( NSObject* obj ) {
  1228. [obj release];
  1229. }
  1230. inline id performOptionalSelector( id obj, SEL sel ) {
  1231. if( [obj respondsToSelector: sel] )
  1232. return [obj performSelector: sel];
  1233. return nil;
  1234. }
  1235. #define CATCH_UNSAFE_UNRETAINED
  1236. #define CATCH_ARC_STRONG
  1237. #else
  1238. inline void arcSafeRelease( NSObject* ){}
  1239. inline id performOptionalSelector( id obj, SEL sel ) {
  1240. #ifdef __clang__
  1241. #pragma clang diagnostic push
  1242. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1243. #endif
  1244. if( [obj respondsToSelector: sel] )
  1245. return [obj performSelector: sel];
  1246. #ifdef __clang__
  1247. #pragma clang diagnostic pop
  1248. #endif
  1249. return nil;
  1250. }
  1251. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1252. #define CATCH_ARC_STRONG __strong
  1253. #endif
  1254. // end catch_objc_arc.hpp
  1255. #endif
  1256. #ifdef _MSC_VER
  1257. #pragma warning(push)
  1258. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1259. #endif
  1260. namespace Catch {
  1261. namespace Detail {
  1262. extern const std::string unprintableString;
  1263. std::string rawMemoryToString( const void *object, std::size_t size );
  1264. template<typename T>
  1265. std::string rawMemoryToString( const T& object ) {
  1266. return rawMemoryToString( &object, sizeof(object) );
  1267. }
  1268. template<typename T>
  1269. class IsStreamInsertable {
  1270. template<typename SS, typename TT>
  1271. static auto test(int)
  1272. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  1273. template<typename, typename>
  1274. static auto test(...)->std::false_type;
  1275. public:
  1276. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1277. };
  1278. template<typename E>
  1279. std::string convertUnknownEnumToString( E e );
  1280. template<typename T>
  1281. typename std::enable_if<
  1282. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1283. std::string>::type convertUnstreamable( T const& ) {
  1284. return Detail::unprintableString;
  1285. }
  1286. template<typename T>
  1287. typename std::enable_if<
  1288. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1289. std::string>::type convertUnstreamable(T const& ex) {
  1290. return ex.what();
  1291. }
  1292. template<typename T>
  1293. typename std::enable_if<
  1294. std::is_enum<T>::value
  1295. , std::string>::type convertUnstreamable( T const& value ) {
  1296. return convertUnknownEnumToString( value );
  1297. }
  1298. #if defined(_MANAGED)
  1299. //! Convert a CLR string to a utf8 std::string
  1300. template<typename T>
  1301. std::string clrReferenceToString( T^ ref ) {
  1302. if (ref == nullptr)
  1303. return std::string("null");
  1304. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1305. cli::pin_ptr<System::Byte> p = &bytes[0];
  1306. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1307. }
  1308. #endif
  1309. } // namespace Detail
  1310. // If we decide for C++14, change these to enable_if_ts
  1311. template <typename T, typename = void>
  1312. struct StringMaker {
  1313. template <typename Fake = T>
  1314. static
  1315. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1316. convert(const Fake& value) {
  1317. ReusableStringStream rss;
  1318. // NB: call using the function-like syntax to avoid ambiguity with
  1319. // user-defined templated operator<< under clang.
  1320. rss.operator<<(value);
  1321. return rss.str();
  1322. }
  1323. template <typename Fake = T>
  1324. static
  1325. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1326. convert( const Fake& value ) {
  1327. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1328. return Detail::convertUnstreamable(value);
  1329. #else
  1330. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1331. #endif
  1332. }
  1333. };
  1334. namespace Detail {
  1335. // This function dispatches all stringification requests inside of Catch.
  1336. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1337. template <typename T>
  1338. std::string stringify(const T& e) {
  1339. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1340. }
  1341. template<typename E>
  1342. std::string convertUnknownEnumToString( E e ) {
  1343. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1344. }
  1345. #if defined(_MANAGED)
  1346. template <typename T>
  1347. std::string stringify( T^ e ) {
  1348. return ::Catch::StringMaker<T^>::convert(e);
  1349. }
  1350. #endif
  1351. } // namespace Detail
  1352. // Some predefined specializations
  1353. template<>
  1354. struct StringMaker<std::string> {
  1355. static std::string convert(const std::string& str);
  1356. };
  1357. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1358. template<>
  1359. struct StringMaker<std::string_view> {
  1360. static std::string convert(std::string_view str);
  1361. };
  1362. #endif
  1363. template<>
  1364. struct StringMaker<char const *> {
  1365. static std::string convert(char const * str);
  1366. };
  1367. template<>
  1368. struct StringMaker<char *> {
  1369. static std::string convert(char * str);
  1370. };
  1371. #ifdef CATCH_CONFIG_WCHAR
  1372. template<>
  1373. struct StringMaker<std::wstring> {
  1374. static std::string convert(const std::wstring& wstr);
  1375. };
  1376. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1377. template<>
  1378. struct StringMaker<std::wstring_view> {
  1379. static std::string convert(std::wstring_view str);
  1380. };
  1381. # endif
  1382. template<>
  1383. struct StringMaker<wchar_t const *> {
  1384. static std::string convert(wchar_t const * str);
  1385. };
  1386. template<>
  1387. struct StringMaker<wchar_t *> {
  1388. static std::string convert(wchar_t * str);
  1389. };
  1390. #endif
  1391. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1392. // while keeping string semantics?
  1393. template<int SZ>
  1394. struct StringMaker<char[SZ]> {
  1395. static std::string convert(char const* str) {
  1396. return ::Catch::Detail::stringify(std::string{ str });
  1397. }
  1398. };
  1399. template<int SZ>
  1400. struct StringMaker<signed char[SZ]> {
  1401. static std::string convert(signed char const* str) {
  1402. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1403. }
  1404. };
  1405. template<int SZ>
  1406. struct StringMaker<unsigned char[SZ]> {
  1407. static std::string convert(unsigned char const* str) {
  1408. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1409. }
  1410. };
  1411. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1412. template<>
  1413. struct StringMaker<std::byte> {
  1414. static std::string convert(std::byte value);
  1415. };
  1416. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1417. template<>
  1418. struct StringMaker<int> {
  1419. static std::string convert(int value);
  1420. };
  1421. template<>
  1422. struct StringMaker<long> {
  1423. static std::string convert(long value);
  1424. };
  1425. template<>
  1426. struct StringMaker<long long> {
  1427. static std::string convert(long long value);
  1428. };
  1429. template<>
  1430. struct StringMaker<unsigned int> {
  1431. static std::string convert(unsigned int value);
  1432. };
  1433. template<>
  1434. struct StringMaker<unsigned long> {
  1435. static std::string convert(unsigned long value);
  1436. };
  1437. template<>
  1438. struct StringMaker<unsigned long long> {
  1439. static std::string convert(unsigned long long value);
  1440. };
  1441. template<>
  1442. struct StringMaker<bool> {
  1443. static std::string convert(bool b);
  1444. };
  1445. template<>
  1446. struct StringMaker<char> {
  1447. static std::string convert(char c);
  1448. };
  1449. template<>
  1450. struct StringMaker<signed char> {
  1451. static std::string convert(signed char c);
  1452. };
  1453. template<>
  1454. struct StringMaker<unsigned char> {
  1455. static std::string convert(unsigned char c);
  1456. };
  1457. template<>
  1458. struct StringMaker<std::nullptr_t> {
  1459. static std::string convert(std::nullptr_t);
  1460. };
  1461. template<>
  1462. struct StringMaker<float> {
  1463. static std::string convert(float value);
  1464. static int precision;
  1465. };
  1466. template<>
  1467. struct StringMaker<double> {
  1468. static std::string convert(double value);
  1469. static int precision;
  1470. };
  1471. template <typename T>
  1472. struct StringMaker<T*> {
  1473. template <typename U>
  1474. static std::string convert(U* p) {
  1475. if (p) {
  1476. return ::Catch::Detail::rawMemoryToString(p);
  1477. } else {
  1478. return "nullptr";
  1479. }
  1480. }
  1481. };
  1482. template <typename R, typename C>
  1483. struct StringMaker<R C::*> {
  1484. static std::string convert(R C::* p) {
  1485. if (p) {
  1486. return ::Catch::Detail::rawMemoryToString(p);
  1487. } else {
  1488. return "nullptr";
  1489. }
  1490. }
  1491. };
  1492. #if defined(_MANAGED)
  1493. template <typename T>
  1494. struct StringMaker<T^> {
  1495. static std::string convert( T^ ref ) {
  1496. return ::Catch::Detail::clrReferenceToString(ref);
  1497. }
  1498. };
  1499. #endif
  1500. namespace Detail {
  1501. template<typename InputIterator>
  1502. std::string rangeToString(InputIterator first, InputIterator last) {
  1503. ReusableStringStream rss;
  1504. rss << "{ ";
  1505. if (first != last) {
  1506. rss << ::Catch::Detail::stringify(*first);
  1507. for (++first; first != last; ++first)
  1508. rss << ", " << ::Catch::Detail::stringify(*first);
  1509. }
  1510. rss << " }";
  1511. return rss.str();
  1512. }
  1513. }
  1514. #ifdef __OBJC__
  1515. template<>
  1516. struct StringMaker<NSString*> {
  1517. static std::string convert(NSString * nsstring) {
  1518. if (!nsstring)
  1519. return "nil";
  1520. return std::string("@") + [nsstring UTF8String];
  1521. }
  1522. };
  1523. template<>
  1524. struct StringMaker<NSObject*> {
  1525. static std::string convert(NSObject* nsObject) {
  1526. return ::Catch::Detail::stringify([nsObject description]);
  1527. }
  1528. };
  1529. namespace Detail {
  1530. inline std::string stringify( NSString* nsstring ) {
  1531. return StringMaker<NSString*>::convert( nsstring );
  1532. }
  1533. } // namespace Detail
  1534. #endif // __OBJC__
  1535. } // namespace Catch
  1536. //////////////////////////////////////////////////////
  1537. // Separate std-lib types stringification, so it can be selectively enabled
  1538. // This means that we do not bring in
  1539. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1540. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1541. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1542. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1543. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1544. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1545. #endif
  1546. // Separate std::pair specialization
  1547. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1548. #include <utility>
  1549. namespace Catch {
  1550. template<typename T1, typename T2>
  1551. struct StringMaker<std::pair<T1, T2> > {
  1552. static std::string convert(const std::pair<T1, T2>& pair) {
  1553. ReusableStringStream rss;
  1554. rss << "{ "
  1555. << ::Catch::Detail::stringify(pair.first)
  1556. << ", "
  1557. << ::Catch::Detail::stringify(pair.second)
  1558. << " }";
  1559. return rss.str();
  1560. }
  1561. };
  1562. }
  1563. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1564. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1565. #include <optional>
  1566. namespace Catch {
  1567. template<typename T>
  1568. struct StringMaker<std::optional<T> > {
  1569. static std::string convert(const std::optional<T>& optional) {
  1570. ReusableStringStream rss;
  1571. if (optional.has_value()) {
  1572. rss << ::Catch::Detail::stringify(*optional);
  1573. } else {
  1574. rss << "{ }";
  1575. }
  1576. return rss.str();
  1577. }
  1578. };
  1579. }
  1580. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1581. // Separate std::tuple specialization
  1582. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1583. #include <tuple>
  1584. namespace Catch {
  1585. namespace Detail {
  1586. template<
  1587. typename Tuple,
  1588. std::size_t N = 0,
  1589. bool = (N < std::tuple_size<Tuple>::value)
  1590. >
  1591. struct TupleElementPrinter {
  1592. static void print(const Tuple& tuple, std::ostream& os) {
  1593. os << (N ? ", " : " ")
  1594. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1595. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1596. }
  1597. };
  1598. template<
  1599. typename Tuple,
  1600. std::size_t N
  1601. >
  1602. struct TupleElementPrinter<Tuple, N, false> {
  1603. static void print(const Tuple&, std::ostream&) {}
  1604. };
  1605. }
  1606. template<typename ...Types>
  1607. struct StringMaker<std::tuple<Types...>> {
  1608. static std::string convert(const std::tuple<Types...>& tuple) {
  1609. ReusableStringStream rss;
  1610. rss << '{';
  1611. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1612. rss << " }";
  1613. return rss.str();
  1614. }
  1615. };
  1616. }
  1617. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1618. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1619. #include <variant>
  1620. namespace Catch {
  1621. template<>
  1622. struct StringMaker<std::monostate> {
  1623. static std::string convert(const std::monostate&) {
  1624. return "{ }";
  1625. }
  1626. };
  1627. template<typename... Elements>
  1628. struct StringMaker<std::variant<Elements...>> {
  1629. static std::string convert(const std::variant<Elements...>& variant) {
  1630. if (variant.valueless_by_exception()) {
  1631. return "{valueless variant}";
  1632. } else {
  1633. return std::visit(
  1634. [](const auto& value) {
  1635. return ::Catch::Detail::stringify(value);
  1636. },
  1637. variant
  1638. );
  1639. }
  1640. }
  1641. };
  1642. }
  1643. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1644. namespace Catch {
  1645. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1646. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1647. using std::begin;
  1648. using std::end;
  1649. not_this_one begin( ... );
  1650. not_this_one end( ... );
  1651. template <typename T>
  1652. struct is_range {
  1653. static const bool value =
  1654. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1655. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1656. };
  1657. #if defined(_MANAGED) // Managed types are never ranges
  1658. template <typename T>
  1659. struct is_range<T^> {
  1660. static const bool value = false;
  1661. };
  1662. #endif
  1663. template<typename Range>
  1664. std::string rangeToString( Range const& range ) {
  1665. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1666. }
  1667. // Handle vector<bool> specially
  1668. template<typename Allocator>
  1669. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1670. ReusableStringStream rss;
  1671. rss << "{ ";
  1672. bool first = true;
  1673. for( bool b : v ) {
  1674. if( first )
  1675. first = false;
  1676. else
  1677. rss << ", ";
  1678. rss << ::Catch::Detail::stringify( b );
  1679. }
  1680. rss << " }";
  1681. return rss.str();
  1682. }
  1683. template<typename R>
  1684. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1685. static std::string convert( R const& range ) {
  1686. return rangeToString( range );
  1687. }
  1688. };
  1689. template <typename T, int SZ>
  1690. struct StringMaker<T[SZ]> {
  1691. static std::string convert(T const(&arr)[SZ]) {
  1692. return rangeToString(arr);
  1693. }
  1694. };
  1695. } // namespace Catch
  1696. // Separate std::chrono::duration specialization
  1697. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1698. #include <ctime>
  1699. #include <ratio>
  1700. #include <chrono>
  1701. namespace Catch {
  1702. template <class Ratio>
  1703. struct ratio_string {
  1704. static std::string symbol();
  1705. };
  1706. template <class Ratio>
  1707. std::string ratio_string<Ratio>::symbol() {
  1708. Catch::ReusableStringStream rss;
  1709. rss << '[' << Ratio::num << '/'
  1710. << Ratio::den << ']';
  1711. return rss.str();
  1712. }
  1713. template <>
  1714. struct ratio_string<std::atto> {
  1715. static std::string symbol();
  1716. };
  1717. template <>
  1718. struct ratio_string<std::femto> {
  1719. static std::string symbol();
  1720. };
  1721. template <>
  1722. struct ratio_string<std::pico> {
  1723. static std::string symbol();
  1724. };
  1725. template <>
  1726. struct ratio_string<std::nano> {
  1727. static std::string symbol();
  1728. };
  1729. template <>
  1730. struct ratio_string<std::micro> {
  1731. static std::string symbol();
  1732. };
  1733. template <>
  1734. struct ratio_string<std::milli> {
  1735. static std::string symbol();
  1736. };
  1737. ////////////
  1738. // std::chrono::duration specializations
  1739. template<typename Value, typename Ratio>
  1740. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1741. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1742. ReusableStringStream rss;
  1743. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1744. return rss.str();
  1745. }
  1746. };
  1747. template<typename Value>
  1748. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1749. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1750. ReusableStringStream rss;
  1751. rss << duration.count() << " s";
  1752. return rss.str();
  1753. }
  1754. };
  1755. template<typename Value>
  1756. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1757. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1758. ReusableStringStream rss;
  1759. rss << duration.count() << " m";
  1760. return rss.str();
  1761. }
  1762. };
  1763. template<typename Value>
  1764. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1765. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1766. ReusableStringStream rss;
  1767. rss << duration.count() << " h";
  1768. return rss.str();
  1769. }
  1770. };
  1771. ////////////
  1772. // std::chrono::time_point specialization
  1773. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1774. template<typename Clock, typename Duration>
  1775. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1776. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1777. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1778. }
  1779. };
  1780. // std::chrono::time_point<system_clock> specialization
  1781. template<typename Duration>
  1782. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1783. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1784. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1785. #ifdef _MSC_VER
  1786. std::tm timeInfo = {};
  1787. gmtime_s(&timeInfo, &converted);
  1788. #else
  1789. std::tm* timeInfo = std::gmtime(&converted);
  1790. #endif
  1791. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1792. char timeStamp[timeStampSize];
  1793. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1794. #ifdef _MSC_VER
  1795. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1796. #else
  1797. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1798. #endif
  1799. return std::string(timeStamp);
  1800. }
  1801. };
  1802. }
  1803. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1804. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1805. namespace Catch { \
  1806. template<> struct StringMaker<enumName> { \
  1807. static std::string convert( enumName value ) { \
  1808. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1809. return enumInfo.lookup( static_cast<int>( value ) ); \
  1810. } \
  1811. }; \
  1812. }
  1813. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1814. #ifdef _MSC_VER
  1815. #pragma warning(pop)
  1816. #endif
  1817. // end catch_tostring.h
  1818. #include <iosfwd>
  1819. #ifdef _MSC_VER
  1820. #pragma warning(push)
  1821. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1822. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1823. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1824. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1825. #pragma warning(disable:4800) // Forcing result to true or false
  1826. #endif
  1827. namespace Catch {
  1828. struct ITransientExpression {
  1829. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1830. auto getResult() const -> bool { return m_result; }
  1831. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1832. ITransientExpression( bool isBinaryExpression, bool result )
  1833. : m_isBinaryExpression( isBinaryExpression ),
  1834. m_result( result )
  1835. {}
  1836. // We don't actually need a virtual destructor, but many static analysers
  1837. // complain if it's not here :-(
  1838. virtual ~ITransientExpression();
  1839. bool m_isBinaryExpression;
  1840. bool m_result;
  1841. };
  1842. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1843. template<typename LhsT, typename RhsT>
  1844. class BinaryExpr : public ITransientExpression {
  1845. LhsT m_lhs;
  1846. StringRef m_op;
  1847. RhsT m_rhs;
  1848. void streamReconstructedExpression( std::ostream &os ) const override {
  1849. formatReconstructedExpression
  1850. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1851. }
  1852. public:
  1853. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1854. : ITransientExpression{ true, comparisonResult },
  1855. m_lhs( lhs ),
  1856. m_op( op ),
  1857. m_rhs( rhs )
  1858. {}
  1859. template<typename T>
  1860. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1861. static_assert(always_false<T>::value,
  1862. "chained comparisons are not supported inside assertions, "
  1863. "wrap the expression inside parentheses, or decompose it");
  1864. }
  1865. template<typename T>
  1866. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1867. static_assert(always_false<T>::value,
  1868. "chained comparisons are not supported inside assertions, "
  1869. "wrap the expression inside parentheses, or decompose it");
  1870. }
  1871. template<typename T>
  1872. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1873. static_assert(always_false<T>::value,
  1874. "chained comparisons are not supported inside assertions, "
  1875. "wrap the expression inside parentheses, or decompose it");
  1876. }
  1877. template<typename T>
  1878. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1879. static_assert(always_false<T>::value,
  1880. "chained comparisons are not supported inside assertions, "
  1881. "wrap the expression inside parentheses, or decompose it");
  1882. }
  1883. template<typename T>
  1884. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1885. static_assert(always_false<T>::value,
  1886. "chained comparisons are not supported inside assertions, "
  1887. "wrap the expression inside parentheses, or decompose it");
  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. };
  1908. template<typename LhsT>
  1909. class UnaryExpr : public ITransientExpression {
  1910. LhsT m_lhs;
  1911. void streamReconstructedExpression( std::ostream &os ) const override {
  1912. os << Catch::Detail::stringify( m_lhs );
  1913. }
  1914. public:
  1915. explicit UnaryExpr( LhsT lhs )
  1916. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1917. m_lhs( lhs )
  1918. {}
  1919. };
  1920. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1921. template<typename LhsT, typename RhsT>
  1922. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1923. template<typename T>
  1924. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1925. template<typename T>
  1926. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1927. template<typename T>
  1928. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1929. template<typename T>
  1930. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1931. template<typename LhsT, typename RhsT>
  1932. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1933. template<typename T>
  1934. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1935. template<typename T>
  1936. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1937. template<typename T>
  1938. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1939. template<typename T>
  1940. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1941. template<typename LhsT>
  1942. class ExprLhs {
  1943. LhsT m_lhs;
  1944. public:
  1945. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1946. template<typename RhsT>
  1947. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1948. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1949. }
  1950. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1951. return { m_lhs == rhs, m_lhs, "==", rhs };
  1952. }
  1953. template<typename RhsT>
  1954. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1955. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1956. }
  1957. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1958. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1959. }
  1960. template<typename RhsT>
  1961. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1962. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1963. }
  1964. template<typename RhsT>
  1965. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1966. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1967. }
  1968. template<typename RhsT>
  1969. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1970. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1971. }
  1972. template<typename RhsT>
  1973. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1974. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1975. }
  1976. template<typename RhsT>
  1977. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1978. static_assert(always_false<RhsT>::value,
  1979. "operator&& is not supported inside assertions, "
  1980. "wrap the expression inside parentheses, or decompose it");
  1981. }
  1982. template<typename RhsT>
  1983. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1984. static_assert(always_false<RhsT>::value,
  1985. "operator|| is not supported inside assertions, "
  1986. "wrap the expression inside parentheses, or decompose it");
  1987. }
  1988. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1989. return UnaryExpr<LhsT>{ m_lhs };
  1990. }
  1991. };
  1992. void handleExpression( ITransientExpression const& expr );
  1993. template<typename T>
  1994. void handleExpression( ExprLhs<T> const& expr ) {
  1995. handleExpression( expr.makeUnaryExpr() );
  1996. }
  1997. struct Decomposer {
  1998. template<typename T>
  1999. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  2000. return ExprLhs<T const&>{ lhs };
  2001. }
  2002. auto operator <=( bool value ) -> ExprLhs<bool> {
  2003. return ExprLhs<bool>{ value };
  2004. }
  2005. };
  2006. } // end namespace Catch
  2007. #ifdef _MSC_VER
  2008. #pragma warning(pop)
  2009. #endif
  2010. // end catch_decomposer.h
  2011. // start catch_interfaces_capture.h
  2012. #include <string>
  2013. #include <chrono>
  2014. namespace Catch {
  2015. class AssertionResult;
  2016. struct AssertionInfo;
  2017. struct SectionInfo;
  2018. struct SectionEndInfo;
  2019. struct MessageInfo;
  2020. struct MessageBuilder;
  2021. struct Counts;
  2022. struct AssertionReaction;
  2023. struct SourceLineInfo;
  2024. struct ITransientExpression;
  2025. struct IGeneratorTracker;
  2026. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2027. struct BenchmarkInfo;
  2028. template <typename Duration = std::chrono::duration<double, std::nano>>
  2029. struct BenchmarkStats;
  2030. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2031. struct IResultCapture {
  2032. virtual ~IResultCapture();
  2033. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2034. Counts& assertions ) = 0;
  2035. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2036. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2037. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2038. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2039. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2040. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2041. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2042. virtual void benchmarkFailed( std::string const& error ) = 0;
  2043. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2044. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2045. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2046. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2047. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2048. virtual void handleExpr
  2049. ( AssertionInfo const& info,
  2050. ITransientExpression const& expr,
  2051. AssertionReaction& reaction ) = 0;
  2052. virtual void handleMessage
  2053. ( AssertionInfo const& info,
  2054. ResultWas::OfType resultType,
  2055. StringRef const& message,
  2056. AssertionReaction& reaction ) = 0;
  2057. virtual void handleUnexpectedExceptionNotThrown
  2058. ( AssertionInfo const& info,
  2059. AssertionReaction& reaction ) = 0;
  2060. virtual void handleUnexpectedInflightException
  2061. ( AssertionInfo const& info,
  2062. std::string const& message,
  2063. AssertionReaction& reaction ) = 0;
  2064. virtual void handleIncomplete
  2065. ( AssertionInfo const& info ) = 0;
  2066. virtual void handleNonExpr
  2067. ( AssertionInfo const &info,
  2068. ResultWas::OfType resultType,
  2069. AssertionReaction &reaction ) = 0;
  2070. virtual bool lastAssertionPassed() = 0;
  2071. virtual void assertionPassed() = 0;
  2072. // Deprecated, do not use:
  2073. virtual std::string getCurrentTestName() const = 0;
  2074. virtual const AssertionResult* getLastResult() const = 0;
  2075. virtual void exceptionEarlyReported() = 0;
  2076. };
  2077. IResultCapture& getResultCapture();
  2078. }
  2079. // end catch_interfaces_capture.h
  2080. namespace Catch {
  2081. struct TestFailureException{};
  2082. struct AssertionResultData;
  2083. struct IResultCapture;
  2084. class RunContext;
  2085. class LazyExpression {
  2086. friend class AssertionHandler;
  2087. friend struct AssertionStats;
  2088. friend class RunContext;
  2089. ITransientExpression const* m_transientExpression = nullptr;
  2090. bool m_isNegated;
  2091. public:
  2092. LazyExpression( bool isNegated );
  2093. LazyExpression( LazyExpression const& other );
  2094. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2095. explicit operator bool() const;
  2096. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2097. };
  2098. struct AssertionReaction {
  2099. bool shouldDebugBreak = false;
  2100. bool shouldThrow = false;
  2101. };
  2102. class AssertionHandler {
  2103. AssertionInfo m_assertionInfo;
  2104. AssertionReaction m_reaction;
  2105. bool m_completed = false;
  2106. IResultCapture& m_resultCapture;
  2107. public:
  2108. AssertionHandler
  2109. ( StringRef const& macroName,
  2110. SourceLineInfo const& lineInfo,
  2111. StringRef capturedExpression,
  2112. ResultDisposition::Flags resultDisposition );
  2113. ~AssertionHandler() {
  2114. if ( !m_completed ) {
  2115. m_resultCapture.handleIncomplete( m_assertionInfo );
  2116. }
  2117. }
  2118. template<typename T>
  2119. void handleExpr( ExprLhs<T> const& expr ) {
  2120. handleExpr( expr.makeUnaryExpr() );
  2121. }
  2122. void handleExpr( ITransientExpression const& expr );
  2123. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2124. void handleExceptionThrownAsExpected();
  2125. void handleUnexpectedExceptionNotThrown();
  2126. void handleExceptionNotThrownAsExpected();
  2127. void handleThrowingCallSkipped();
  2128. void handleUnexpectedInflightException();
  2129. void complete();
  2130. void setCompleted();
  2131. // query
  2132. auto allowThrows() const -> bool;
  2133. };
  2134. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2135. } // namespace Catch
  2136. // end catch_assertionhandler.h
  2137. // start catch_message.h
  2138. #include <string>
  2139. #include <vector>
  2140. namespace Catch {
  2141. struct MessageInfo {
  2142. MessageInfo( StringRef const& _macroName,
  2143. SourceLineInfo const& _lineInfo,
  2144. ResultWas::OfType _type );
  2145. StringRef macroName;
  2146. std::string message;
  2147. SourceLineInfo lineInfo;
  2148. ResultWas::OfType type;
  2149. unsigned int sequence;
  2150. bool operator == ( MessageInfo const& other ) const;
  2151. bool operator < ( MessageInfo const& other ) const;
  2152. private:
  2153. static unsigned int globalCount;
  2154. };
  2155. struct MessageStream {
  2156. template<typename T>
  2157. MessageStream& operator << ( T const& value ) {
  2158. m_stream << value;
  2159. return *this;
  2160. }
  2161. ReusableStringStream m_stream;
  2162. };
  2163. struct MessageBuilder : MessageStream {
  2164. MessageBuilder( StringRef const& macroName,
  2165. SourceLineInfo const& lineInfo,
  2166. ResultWas::OfType type );
  2167. template<typename T>
  2168. MessageBuilder& operator << ( T const& value ) {
  2169. m_stream << value;
  2170. return *this;
  2171. }
  2172. MessageInfo m_info;
  2173. };
  2174. class ScopedMessage {
  2175. public:
  2176. explicit ScopedMessage( MessageBuilder const& builder );
  2177. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2178. ScopedMessage( ScopedMessage&& old );
  2179. ~ScopedMessage();
  2180. MessageInfo m_info;
  2181. bool m_moved;
  2182. };
  2183. class Capturer {
  2184. std::vector<MessageInfo> m_messages;
  2185. IResultCapture& m_resultCapture = getResultCapture();
  2186. size_t m_captured = 0;
  2187. public:
  2188. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2189. ~Capturer();
  2190. void captureValue( size_t index, std::string const& value );
  2191. template<typename T>
  2192. void captureValues( size_t index, T const& value ) {
  2193. captureValue( index, Catch::Detail::stringify( value ) );
  2194. }
  2195. template<typename T, typename... Ts>
  2196. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2197. captureValue( index, Catch::Detail::stringify(value) );
  2198. captureValues( index+1, values... );
  2199. }
  2200. };
  2201. } // end namespace Catch
  2202. // end catch_message.h
  2203. #if !defined(CATCH_CONFIG_DISABLE)
  2204. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2205. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2206. #else
  2207. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2208. #endif
  2209. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2210. ///////////////////////////////////////////////////////////////////////////////
  2211. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2212. // macros.
  2213. #define INTERNAL_CATCH_TRY
  2214. #define INTERNAL_CATCH_CATCH( capturer )
  2215. #else // CATCH_CONFIG_FAST_COMPILE
  2216. #define INTERNAL_CATCH_TRY try
  2217. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2218. #endif
  2219. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2220. ///////////////////////////////////////////////////////////////////////////////
  2221. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2222. do { \
  2223. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2224. INTERNAL_CATCH_TRY { \
  2225. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2226. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2227. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2228. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2229. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2230. } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  2231. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2232. ///////////////////////////////////////////////////////////////////////////////
  2233. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2234. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2235. if( Catch::getResultCapture().lastAssertionPassed() )
  2236. ///////////////////////////////////////////////////////////////////////////////
  2237. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2238. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2239. if( !Catch::getResultCapture().lastAssertionPassed() )
  2240. ///////////////////////////////////////////////////////////////////////////////
  2241. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2242. do { \
  2243. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2244. try { \
  2245. static_cast<void>(__VA_ARGS__); \
  2246. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2247. } \
  2248. catch( ... ) { \
  2249. catchAssertionHandler.handleUnexpectedInflightException(); \
  2250. } \
  2251. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2252. } while( false )
  2253. ///////////////////////////////////////////////////////////////////////////////
  2254. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2255. do { \
  2256. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2257. if( catchAssertionHandler.allowThrows() ) \
  2258. try { \
  2259. static_cast<void>(__VA_ARGS__); \
  2260. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2261. } \
  2262. catch( ... ) { \
  2263. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2264. } \
  2265. else \
  2266. catchAssertionHandler.handleThrowingCallSkipped(); \
  2267. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2268. } while( false )
  2269. ///////////////////////////////////////////////////////////////////////////////
  2270. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2271. do { \
  2272. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2273. if( catchAssertionHandler.allowThrows() ) \
  2274. try { \
  2275. static_cast<void>(expr); \
  2276. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2277. } \
  2278. catch( exceptionType const& ) { \
  2279. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2280. } \
  2281. catch( ... ) { \
  2282. catchAssertionHandler.handleUnexpectedInflightException(); \
  2283. } \
  2284. else \
  2285. catchAssertionHandler.handleThrowingCallSkipped(); \
  2286. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2287. } while( false )
  2288. ///////////////////////////////////////////////////////////////////////////////
  2289. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2290. do { \
  2291. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2292. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2293. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2294. } while( false )
  2295. ///////////////////////////////////////////////////////////////////////////////
  2296. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2297. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2298. varName.captureValues( 0, __VA_ARGS__ )
  2299. ///////////////////////////////////////////////////////////////////////////////
  2300. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2301. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2302. ///////////////////////////////////////////////////////////////////////////////
  2303. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2304. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2305. ///////////////////////////////////////////////////////////////////////////////
  2306. // Although this is matcher-based, it can be used with just a string
  2307. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2308. do { \
  2309. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2310. if( catchAssertionHandler.allowThrows() ) \
  2311. try { \
  2312. static_cast<void>(__VA_ARGS__); \
  2313. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2314. } \
  2315. catch( ... ) { \
  2316. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2317. } \
  2318. else \
  2319. catchAssertionHandler.handleThrowingCallSkipped(); \
  2320. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2321. } while( false )
  2322. #endif // CATCH_CONFIG_DISABLE
  2323. // end catch_capture.hpp
  2324. // start catch_section.h
  2325. // start catch_section_info.h
  2326. // start catch_totals.h
  2327. #include <cstddef>
  2328. namespace Catch {
  2329. struct Counts {
  2330. Counts operator - ( Counts const& other ) const;
  2331. Counts& operator += ( Counts const& other );
  2332. std::size_t total() const;
  2333. bool allPassed() const;
  2334. bool allOk() const;
  2335. std::size_t passed = 0;
  2336. std::size_t failed = 0;
  2337. std::size_t failedButOk = 0;
  2338. };
  2339. struct Totals {
  2340. Totals operator - ( Totals const& other ) const;
  2341. Totals& operator += ( Totals const& other );
  2342. Totals delta( Totals const& prevTotals ) const;
  2343. int error = 0;
  2344. Counts assertions;
  2345. Counts testCases;
  2346. };
  2347. }
  2348. // end catch_totals.h
  2349. #include <string>
  2350. namespace Catch {
  2351. struct SectionInfo {
  2352. SectionInfo
  2353. ( SourceLineInfo const& _lineInfo,
  2354. std::string const& _name );
  2355. // Deprecated
  2356. SectionInfo
  2357. ( SourceLineInfo const& _lineInfo,
  2358. std::string const& _name,
  2359. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2360. std::string name;
  2361. std::string description; // !Deprecated: this will always be empty
  2362. SourceLineInfo lineInfo;
  2363. };
  2364. struct SectionEndInfo {
  2365. SectionInfo sectionInfo;
  2366. Counts prevAssertions;
  2367. double durationInSeconds;
  2368. };
  2369. } // end namespace Catch
  2370. // end catch_section_info.h
  2371. // start catch_timer.h
  2372. #include <cstdint>
  2373. namespace Catch {
  2374. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2375. auto getEstimatedClockResolution() -> uint64_t;
  2376. class Timer {
  2377. uint64_t m_nanoseconds = 0;
  2378. public:
  2379. void start();
  2380. auto getElapsedNanoseconds() const -> uint64_t;
  2381. auto getElapsedMicroseconds() const -> uint64_t;
  2382. auto getElapsedMilliseconds() const -> unsigned int;
  2383. auto getElapsedSeconds() const -> double;
  2384. };
  2385. } // namespace Catch
  2386. // end catch_timer.h
  2387. #include <string>
  2388. namespace Catch {
  2389. class Section : NonCopyable {
  2390. public:
  2391. Section( SectionInfo const& info );
  2392. ~Section();
  2393. // This indicates whether the section should be executed or not
  2394. explicit operator bool() const;
  2395. private:
  2396. SectionInfo m_info;
  2397. std::string m_name;
  2398. Counts m_assertions;
  2399. bool m_sectionIncluded;
  2400. Timer m_timer;
  2401. };
  2402. } // end namespace Catch
  2403. #define INTERNAL_CATCH_SECTION( ... ) \
  2404. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2405. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2406. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2407. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2408. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2409. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2410. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2411. // end catch_section.h
  2412. // start catch_interfaces_exception.h
  2413. // start catch_interfaces_registry_hub.h
  2414. #include <string>
  2415. #include <memory>
  2416. namespace Catch {
  2417. class TestCase;
  2418. struct ITestCaseRegistry;
  2419. struct IExceptionTranslatorRegistry;
  2420. struct IExceptionTranslator;
  2421. struct IReporterRegistry;
  2422. struct IReporterFactory;
  2423. struct ITagAliasRegistry;
  2424. struct IMutableEnumValuesRegistry;
  2425. class StartupExceptionRegistry;
  2426. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2427. struct IRegistryHub {
  2428. virtual ~IRegistryHub();
  2429. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2430. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2431. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2432. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2433. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2434. };
  2435. struct IMutableRegistryHub {
  2436. virtual ~IMutableRegistryHub();
  2437. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2438. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2439. virtual void registerTest( TestCase const& testInfo ) = 0;
  2440. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2441. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2442. virtual void registerStartupException() noexcept = 0;
  2443. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2444. };
  2445. IRegistryHub const& getRegistryHub();
  2446. IMutableRegistryHub& getMutableRegistryHub();
  2447. void cleanUp();
  2448. std::string translateActiveException();
  2449. }
  2450. // end catch_interfaces_registry_hub.h
  2451. #if defined(CATCH_CONFIG_DISABLE)
  2452. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2453. static std::string translatorName( signature )
  2454. #endif
  2455. #include <exception>
  2456. #include <string>
  2457. #include <vector>
  2458. namespace Catch {
  2459. using exceptionTranslateFunction = std::string(*)();
  2460. struct IExceptionTranslator;
  2461. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2462. struct IExceptionTranslator {
  2463. virtual ~IExceptionTranslator();
  2464. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2465. };
  2466. struct IExceptionTranslatorRegistry {
  2467. virtual ~IExceptionTranslatorRegistry();
  2468. virtual std::string translateActiveException() const = 0;
  2469. };
  2470. class ExceptionTranslatorRegistrar {
  2471. template<typename T>
  2472. class ExceptionTranslator : public IExceptionTranslator {
  2473. public:
  2474. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2475. : m_translateFunction( translateFunction )
  2476. {}
  2477. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2478. try {
  2479. if( it == itEnd )
  2480. std::rethrow_exception(std::current_exception());
  2481. else
  2482. return (*it)->translate( it+1, itEnd );
  2483. }
  2484. catch( T& ex ) {
  2485. return m_translateFunction( ex );
  2486. }
  2487. }
  2488. protected:
  2489. std::string(*m_translateFunction)( T& );
  2490. };
  2491. public:
  2492. template<typename T>
  2493. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2494. getMutableRegistryHub().registerTranslator
  2495. ( new ExceptionTranslator<T>( translateFunction ) );
  2496. }
  2497. };
  2498. }
  2499. ///////////////////////////////////////////////////////////////////////////////
  2500. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2501. static std::string translatorName( signature ); \
  2502. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2503. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2504. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2505. static std::string translatorName( signature )
  2506. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2507. // end catch_interfaces_exception.h
  2508. // start catch_approx.h
  2509. #include <type_traits>
  2510. namespace Catch {
  2511. namespace Detail {
  2512. class Approx {
  2513. private:
  2514. bool equalityComparisonImpl(double other) const;
  2515. // Validates the new margin (margin >= 0)
  2516. // out-of-line to avoid including stdexcept in the header
  2517. void setMargin(double margin);
  2518. // Validates the new epsilon (0 < epsilon < 1)
  2519. // out-of-line to avoid including stdexcept in the header
  2520. void setEpsilon(double epsilon);
  2521. public:
  2522. explicit Approx ( double value );
  2523. static Approx custom();
  2524. Approx operator-() const;
  2525. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2526. Approx operator()( T const& value ) {
  2527. Approx approx( static_cast<double>(value) );
  2528. approx.m_epsilon = m_epsilon;
  2529. approx.m_margin = m_margin;
  2530. approx.m_scale = m_scale;
  2531. return approx;
  2532. }
  2533. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2534. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2535. {}
  2536. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2537. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2538. auto lhs_v = static_cast<double>(lhs);
  2539. return rhs.equalityComparisonImpl(lhs_v);
  2540. }
  2541. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2542. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2543. return operator==( rhs, lhs );
  2544. }
  2545. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2546. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2547. return !operator==( lhs, rhs );
  2548. }
  2549. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2550. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2551. return !operator==( rhs, lhs );
  2552. }
  2553. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2554. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2555. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2556. }
  2557. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2558. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2559. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2560. }
  2561. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2562. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2563. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2564. }
  2565. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2566. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2567. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2568. }
  2569. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2570. Approx& epsilon( T const& newEpsilon ) {
  2571. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2572. setEpsilon(epsilonAsDouble);
  2573. return *this;
  2574. }
  2575. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2576. Approx& margin( T const& newMargin ) {
  2577. double marginAsDouble = static_cast<double>(newMargin);
  2578. setMargin(marginAsDouble);
  2579. return *this;
  2580. }
  2581. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2582. Approx& scale( T const& newScale ) {
  2583. m_scale = static_cast<double>(newScale);
  2584. return *this;
  2585. }
  2586. std::string toString() const;
  2587. private:
  2588. double m_epsilon;
  2589. double m_margin;
  2590. double m_scale;
  2591. double m_value;
  2592. };
  2593. } // end namespace Detail
  2594. namespace literals {
  2595. Detail::Approx operator "" _a(long double val);
  2596. Detail::Approx operator "" _a(unsigned long long val);
  2597. } // end namespace literals
  2598. template<>
  2599. struct StringMaker<Catch::Detail::Approx> {
  2600. static std::string convert(Catch::Detail::Approx const& value);
  2601. };
  2602. } // end namespace Catch
  2603. // end catch_approx.h
  2604. // start catch_string_manip.h
  2605. #include <string>
  2606. #include <iosfwd>
  2607. #include <vector>
  2608. namespace Catch {
  2609. bool startsWith( std::string const& s, std::string const& prefix );
  2610. bool startsWith( std::string const& s, char prefix );
  2611. bool endsWith( std::string const& s, std::string const& suffix );
  2612. bool endsWith( std::string const& s, char suffix );
  2613. bool contains( std::string const& s, std::string const& infix );
  2614. void toLowerInPlace( std::string& s );
  2615. std::string toLower( std::string const& s );
  2616. std::string trim( std::string const& str );
  2617. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2618. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2619. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2620. struct pluralise {
  2621. pluralise( std::size_t count, std::string const& label );
  2622. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2623. std::size_t m_count;
  2624. std::string m_label;
  2625. };
  2626. }
  2627. // end catch_string_manip.h
  2628. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2629. // start catch_capture_matchers.h
  2630. // start catch_matchers.h
  2631. #include <string>
  2632. #include <vector>
  2633. namespace Catch {
  2634. namespace Matchers {
  2635. namespace Impl {
  2636. template<typename ArgT> struct MatchAllOf;
  2637. template<typename ArgT> struct MatchAnyOf;
  2638. template<typename ArgT> struct MatchNotOf;
  2639. class MatcherUntypedBase {
  2640. public:
  2641. MatcherUntypedBase() = default;
  2642. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2643. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2644. std::string toString() const;
  2645. protected:
  2646. virtual ~MatcherUntypedBase();
  2647. virtual std::string describe() const = 0;
  2648. mutable std::string m_cachedToString;
  2649. };
  2650. #ifdef __clang__
  2651. # pragma clang diagnostic push
  2652. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2653. #endif
  2654. template<typename ObjectT>
  2655. struct MatcherMethod {
  2656. virtual bool match( ObjectT const& arg ) const = 0;
  2657. };
  2658. #if defined(__OBJC__)
  2659. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2660. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2661. template<>
  2662. struct MatcherMethod<NSString*> {
  2663. virtual bool match( NSString* arg ) const = 0;
  2664. };
  2665. #endif
  2666. #ifdef __clang__
  2667. # pragma clang diagnostic pop
  2668. #endif
  2669. template<typename T>
  2670. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2671. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2672. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2673. MatchNotOf<T> operator ! () const;
  2674. };
  2675. template<typename ArgT>
  2676. struct MatchAllOf : MatcherBase<ArgT> {
  2677. bool match( ArgT const& arg ) const override {
  2678. for( auto matcher : m_matchers ) {
  2679. if (!matcher->match(arg))
  2680. return false;
  2681. }
  2682. return true;
  2683. }
  2684. std::string describe() const override {
  2685. std::string description;
  2686. description.reserve( 4 + m_matchers.size()*32 );
  2687. description += "( ";
  2688. bool first = true;
  2689. for( auto matcher : m_matchers ) {
  2690. if( first )
  2691. first = false;
  2692. else
  2693. description += " and ";
  2694. description += matcher->toString();
  2695. }
  2696. description += " )";
  2697. return description;
  2698. }
  2699. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2700. m_matchers.push_back( &other );
  2701. return *this;
  2702. }
  2703. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2704. };
  2705. template<typename ArgT>
  2706. struct MatchAnyOf : MatcherBase<ArgT> {
  2707. bool match( ArgT const& arg ) const override {
  2708. for( auto matcher : m_matchers ) {
  2709. if (matcher->match(arg))
  2710. return true;
  2711. }
  2712. return false;
  2713. }
  2714. std::string describe() const override {
  2715. std::string description;
  2716. description.reserve( 4 + m_matchers.size()*32 );
  2717. description += "( ";
  2718. bool first = true;
  2719. for( auto matcher : m_matchers ) {
  2720. if( first )
  2721. first = false;
  2722. else
  2723. description += " or ";
  2724. description += matcher->toString();
  2725. }
  2726. description += " )";
  2727. return description;
  2728. }
  2729. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2730. m_matchers.push_back( &other );
  2731. return *this;
  2732. }
  2733. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2734. };
  2735. template<typename ArgT>
  2736. struct MatchNotOf : MatcherBase<ArgT> {
  2737. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2738. bool match( ArgT const& arg ) const override {
  2739. return !m_underlyingMatcher.match( arg );
  2740. }
  2741. std::string describe() const override {
  2742. return "not " + m_underlyingMatcher.toString();
  2743. }
  2744. MatcherBase<ArgT> const& m_underlyingMatcher;
  2745. };
  2746. template<typename T>
  2747. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2748. return MatchAllOf<T>() && *this && other;
  2749. }
  2750. template<typename T>
  2751. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2752. return MatchAnyOf<T>() || *this || other;
  2753. }
  2754. template<typename T>
  2755. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2756. return MatchNotOf<T>( *this );
  2757. }
  2758. } // namespace Impl
  2759. } // namespace Matchers
  2760. using namespace Matchers;
  2761. using Matchers::Impl::MatcherBase;
  2762. } // namespace Catch
  2763. // end catch_matchers.h
  2764. // start catch_matchers_floating.h
  2765. #include <type_traits>
  2766. #include <cmath>
  2767. namespace Catch {
  2768. namespace Matchers {
  2769. namespace Floating {
  2770. enum class FloatingPointKind : uint8_t;
  2771. struct WithinAbsMatcher : MatcherBase<double> {
  2772. WithinAbsMatcher(double target, double margin);
  2773. bool match(double const& matchee) const override;
  2774. std::string describe() const override;
  2775. private:
  2776. double m_target;
  2777. double m_margin;
  2778. };
  2779. struct WithinUlpsMatcher : MatcherBase<double> {
  2780. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2781. bool match(double const& matchee) const override;
  2782. std::string describe() const override;
  2783. private:
  2784. double m_target;
  2785. int m_ulps;
  2786. FloatingPointKind m_type;
  2787. };
  2788. } // namespace Floating
  2789. // The following functions create the actual matcher objects.
  2790. // This allows the types to be inferred
  2791. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2792. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2793. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2794. } // namespace Matchers
  2795. } // namespace Catch
  2796. // end catch_matchers_floating.h
  2797. // start catch_matchers_generic.hpp
  2798. #include <functional>
  2799. #include <string>
  2800. namespace Catch {
  2801. namespace Matchers {
  2802. namespace Generic {
  2803. namespace Detail {
  2804. std::string finalizeDescription(const std::string& desc);
  2805. }
  2806. template <typename T>
  2807. class PredicateMatcher : public MatcherBase<T> {
  2808. std::function<bool(T const&)> m_predicate;
  2809. std::string m_description;
  2810. public:
  2811. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2812. :m_predicate(std::move(elem)),
  2813. m_description(Detail::finalizeDescription(descr))
  2814. {}
  2815. bool match( T const& item ) const override {
  2816. return m_predicate(item);
  2817. }
  2818. std::string describe() const override {
  2819. return m_description;
  2820. }
  2821. };
  2822. } // namespace Generic
  2823. // The following functions create the actual matcher objects.
  2824. // The user has to explicitly specify type to the function, because
  2825. // inferring std::function<bool(T const&)> is hard (but possible) and
  2826. // requires a lot of TMP.
  2827. template<typename T>
  2828. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2829. return Generic::PredicateMatcher<T>(predicate, description);
  2830. }
  2831. } // namespace Matchers
  2832. } // namespace Catch
  2833. // end catch_matchers_generic.hpp
  2834. // start catch_matchers_string.h
  2835. #include <string>
  2836. namespace Catch {
  2837. namespace Matchers {
  2838. namespace StdString {
  2839. struct CasedString
  2840. {
  2841. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2842. std::string adjustString( std::string const& str ) const;
  2843. std::string caseSensitivitySuffix() const;
  2844. CaseSensitive::Choice m_caseSensitivity;
  2845. std::string m_str;
  2846. };
  2847. struct StringMatcherBase : MatcherBase<std::string> {
  2848. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2849. std::string describe() const override;
  2850. CasedString m_comparator;
  2851. std::string m_operation;
  2852. };
  2853. struct EqualsMatcher : StringMatcherBase {
  2854. EqualsMatcher( CasedString const& comparator );
  2855. bool match( std::string const& source ) const override;
  2856. };
  2857. struct ContainsMatcher : StringMatcherBase {
  2858. ContainsMatcher( CasedString const& comparator );
  2859. bool match( std::string const& source ) const override;
  2860. };
  2861. struct StartsWithMatcher : StringMatcherBase {
  2862. StartsWithMatcher( CasedString const& comparator );
  2863. bool match( std::string const& source ) const override;
  2864. };
  2865. struct EndsWithMatcher : StringMatcherBase {
  2866. EndsWithMatcher( CasedString const& comparator );
  2867. bool match( std::string const& source ) const override;
  2868. };
  2869. struct RegexMatcher : MatcherBase<std::string> {
  2870. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2871. bool match( std::string const& matchee ) const override;
  2872. std::string describe() const override;
  2873. private:
  2874. std::string m_regex;
  2875. CaseSensitive::Choice m_caseSensitivity;
  2876. };
  2877. } // namespace StdString
  2878. // The following functions create the actual matcher objects.
  2879. // This allows the types to be inferred
  2880. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2881. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2882. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2883. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2884. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2885. } // namespace Matchers
  2886. } // namespace Catch
  2887. // end catch_matchers_string.h
  2888. // start catch_matchers_vector.h
  2889. #include <algorithm>
  2890. namespace Catch {
  2891. namespace Matchers {
  2892. namespace Vector {
  2893. template<typename T>
  2894. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2895. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2896. bool match(std::vector<T> const &v) const override {
  2897. for (auto const& el : v) {
  2898. if (el == m_comparator) {
  2899. return true;
  2900. }
  2901. }
  2902. return false;
  2903. }
  2904. std::string describe() const override {
  2905. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2906. }
  2907. T const& m_comparator;
  2908. };
  2909. template<typename T>
  2910. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2911. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2912. bool match(std::vector<T> const &v) const override {
  2913. // !TBD: see note in EqualsMatcher
  2914. if (m_comparator.size() > v.size())
  2915. return false;
  2916. for (auto const& comparator : m_comparator) {
  2917. auto present = false;
  2918. for (const auto& el : v) {
  2919. if (el == comparator) {
  2920. present = true;
  2921. break;
  2922. }
  2923. }
  2924. if (!present) {
  2925. return false;
  2926. }
  2927. }
  2928. return true;
  2929. }
  2930. std::string describe() const override {
  2931. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2932. }
  2933. std::vector<T> const& m_comparator;
  2934. };
  2935. template<typename T>
  2936. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2937. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2938. bool match(std::vector<T> const &v) const override {
  2939. // !TBD: This currently works if all elements can be compared using !=
  2940. // - a more general approach would be via a compare template that defaults
  2941. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2942. // - then just call that directly
  2943. if (m_comparator.size() != v.size())
  2944. return false;
  2945. for (std::size_t i = 0; i < v.size(); ++i)
  2946. if (m_comparator[i] != v[i])
  2947. return false;
  2948. return true;
  2949. }
  2950. std::string describe() const override {
  2951. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2952. }
  2953. std::vector<T> const& m_comparator;
  2954. };
  2955. template<typename T>
  2956. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  2957. ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
  2958. bool match(std::vector<T> const &v) const override {
  2959. if (m_comparator.size() != v.size())
  2960. return false;
  2961. for (std::size_t i = 0; i < v.size(); ++i)
  2962. if (m_comparator[i] != approx(v[i]))
  2963. return false;
  2964. return true;
  2965. }
  2966. std::string describe() const override {
  2967. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  2968. }
  2969. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2970. ApproxMatcher& epsilon( T const& newEpsilon ) {
  2971. approx.epsilon(newEpsilon);
  2972. return *this;
  2973. }
  2974. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2975. ApproxMatcher& margin( T const& newMargin ) {
  2976. approx.margin(newMargin);
  2977. return *this;
  2978. }
  2979. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2980. ApproxMatcher& scale( T const& newScale ) {
  2981. approx.scale(newScale);
  2982. return *this;
  2983. }
  2984. std::vector<T> const& m_comparator;
  2985. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  2986. };
  2987. template<typename T>
  2988. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2989. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2990. bool match(std::vector<T> const& vec) const override {
  2991. // Note: This is a reimplementation of std::is_permutation,
  2992. // because I don't want to include <algorithm> inside the common path
  2993. if (m_target.size() != vec.size()) {
  2994. return false;
  2995. }
  2996. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  2997. }
  2998. std::string describe() const override {
  2999. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3000. }
  3001. private:
  3002. std::vector<T> const& m_target;
  3003. };
  3004. } // namespace Vector
  3005. // The following functions create the actual matcher objects.
  3006. // This allows the types to be inferred
  3007. template<typename T>
  3008. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  3009. return Vector::ContainsMatcher<T>( comparator );
  3010. }
  3011. template<typename T>
  3012. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  3013. return Vector::ContainsElementMatcher<T>( comparator );
  3014. }
  3015. template<typename T>
  3016. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  3017. return Vector::EqualsMatcher<T>( comparator );
  3018. }
  3019. template<typename T>
  3020. Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
  3021. return Vector::ApproxMatcher<T>( comparator );
  3022. }
  3023. template<typename T>
  3024. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  3025. return Vector::UnorderedEqualsMatcher<T>(target);
  3026. }
  3027. } // namespace Matchers
  3028. } // namespace Catch
  3029. // end catch_matchers_vector.h
  3030. namespace Catch {
  3031. template<typename ArgT, typename MatcherT>
  3032. class MatchExpr : public ITransientExpression {
  3033. ArgT const& m_arg;
  3034. MatcherT m_matcher;
  3035. StringRef m_matcherString;
  3036. public:
  3037. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3038. : ITransientExpression{ true, matcher.match( arg ) },
  3039. m_arg( arg ),
  3040. m_matcher( matcher ),
  3041. m_matcherString( matcherString )
  3042. {}
  3043. void streamReconstructedExpression( std::ostream &os ) const override {
  3044. auto matcherAsString = m_matcher.toString();
  3045. os << Catch::Detail::stringify( m_arg ) << ' ';
  3046. if( matcherAsString == Detail::unprintableString )
  3047. os << m_matcherString;
  3048. else
  3049. os << matcherAsString;
  3050. }
  3051. };
  3052. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3053. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3054. template<typename ArgT, typename MatcherT>
  3055. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3056. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3057. }
  3058. } // namespace Catch
  3059. ///////////////////////////////////////////////////////////////////////////////
  3060. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3061. do { \
  3062. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3063. INTERNAL_CATCH_TRY { \
  3064. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3065. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3066. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3067. } while( false )
  3068. ///////////////////////////////////////////////////////////////////////////////
  3069. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3070. do { \
  3071. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3072. if( catchAssertionHandler.allowThrows() ) \
  3073. try { \
  3074. static_cast<void>(__VA_ARGS__ ); \
  3075. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3076. } \
  3077. catch( exceptionType const& ex ) { \
  3078. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3079. } \
  3080. catch( ... ) { \
  3081. catchAssertionHandler.handleUnexpectedInflightException(); \
  3082. } \
  3083. else \
  3084. catchAssertionHandler.handleThrowingCallSkipped(); \
  3085. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3086. } while( false )
  3087. // end catch_capture_matchers.h
  3088. #endif
  3089. // start catch_generators.hpp
  3090. // start catch_interfaces_generatortracker.h
  3091. #include <memory>
  3092. namespace Catch {
  3093. namespace Generators {
  3094. class GeneratorUntypedBase {
  3095. public:
  3096. GeneratorUntypedBase() = default;
  3097. virtual ~GeneratorUntypedBase();
  3098. // Attempts to move the generator to the next element
  3099. //
  3100. // Returns true iff the move succeeded (and a valid element
  3101. // can be retrieved).
  3102. virtual bool next() = 0;
  3103. };
  3104. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3105. } // namespace Generators
  3106. struct IGeneratorTracker {
  3107. virtual ~IGeneratorTracker();
  3108. virtual auto hasGenerator() const -> bool = 0;
  3109. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3110. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3111. };
  3112. } // namespace Catch
  3113. // end catch_interfaces_generatortracker.h
  3114. // start catch_enforce.h
  3115. #include <exception>
  3116. namespace Catch {
  3117. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3118. template <typename Ex>
  3119. [[noreturn]]
  3120. void throw_exception(Ex const& e) {
  3121. throw e;
  3122. }
  3123. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3124. [[noreturn]]
  3125. void throw_exception(std::exception const& e);
  3126. #endif
  3127. [[noreturn]]
  3128. void throw_logic_error(std::string const& msg);
  3129. [[noreturn]]
  3130. void throw_domain_error(std::string const& msg);
  3131. [[noreturn]]
  3132. void throw_runtime_error(std::string const& msg);
  3133. } // namespace Catch;
  3134. #define CATCH_MAKE_MSG(...) \
  3135. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3136. #define CATCH_INTERNAL_ERROR(...) \
  3137. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3138. #define CATCH_ERROR(...) \
  3139. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3140. #define CATCH_RUNTIME_ERROR(...) \
  3141. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3142. #define CATCH_ENFORCE( condition, ... ) \
  3143. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3144. // end catch_enforce.h
  3145. #include <memory>
  3146. #include <vector>
  3147. #include <cassert>
  3148. #include <utility>
  3149. #include <exception>
  3150. namespace Catch {
  3151. class GeneratorException : public std::exception {
  3152. const char* const m_msg = "";
  3153. public:
  3154. GeneratorException(const char* msg):
  3155. m_msg(msg)
  3156. {}
  3157. const char* what() const noexcept override final;
  3158. };
  3159. namespace Generators {
  3160. // !TBD move this into its own location?
  3161. namespace pf{
  3162. template<typename T, typename... Args>
  3163. std::unique_ptr<T> make_unique( Args&&... args ) {
  3164. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3165. }
  3166. }
  3167. template<typename T>
  3168. struct IGenerator : GeneratorUntypedBase {
  3169. virtual ~IGenerator() = default;
  3170. // Returns the current element of the generator
  3171. //
  3172. // \Precondition The generator is either freshly constructed,
  3173. // or the last call to `next()` returned true
  3174. virtual T const& get() const = 0;
  3175. using type = T;
  3176. };
  3177. template<typename T>
  3178. class SingleValueGenerator final : public IGenerator<T> {
  3179. T m_value;
  3180. public:
  3181. SingleValueGenerator(T const& value) : m_value( value ) {}
  3182. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3183. T const& get() const override {
  3184. return m_value;
  3185. }
  3186. bool next() override {
  3187. return false;
  3188. }
  3189. };
  3190. template<typename T>
  3191. class FixedValuesGenerator final : public IGenerator<T> {
  3192. static_assert(!std::is_same<T, bool>::value,
  3193. "ValuesGenerator does not support bools because of std::vector<bool>"
  3194. "specialization, use SingleValue Generator instead.");
  3195. std::vector<T> m_values;
  3196. size_t m_idx = 0;
  3197. public:
  3198. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3199. T const& get() const override {
  3200. return m_values[m_idx];
  3201. }
  3202. bool next() override {
  3203. ++m_idx;
  3204. return m_idx < m_values.size();
  3205. }
  3206. };
  3207. template <typename T>
  3208. class GeneratorWrapper final {
  3209. std::unique_ptr<IGenerator<T>> m_generator;
  3210. public:
  3211. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3212. m_generator(std::move(generator))
  3213. {}
  3214. T const& get() const {
  3215. return m_generator->get();
  3216. }
  3217. bool next() {
  3218. return m_generator->next();
  3219. }
  3220. };
  3221. template <typename T>
  3222. GeneratorWrapper<T> value(T&& value) {
  3223. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3224. }
  3225. template <typename T>
  3226. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3227. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3228. }
  3229. template<typename T>
  3230. class Generators : public IGenerator<T> {
  3231. std::vector<GeneratorWrapper<T>> m_generators;
  3232. size_t m_current = 0;
  3233. void populate(GeneratorWrapper<T>&& generator) {
  3234. m_generators.emplace_back(std::move(generator));
  3235. }
  3236. void populate(T&& val) {
  3237. m_generators.emplace_back(value(std::move(val)));
  3238. }
  3239. template<typename U>
  3240. void populate(U&& val) {
  3241. populate(T(std::move(val)));
  3242. }
  3243. template<typename U, typename... Gs>
  3244. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  3245. populate(std::forward<U>(valueOrGenerator));
  3246. populate(std::forward<Gs>(moreGenerators)...);
  3247. }
  3248. public:
  3249. template <typename... Gs>
  3250. Generators(Gs... moreGenerators) {
  3251. m_generators.reserve(sizeof...(Gs));
  3252. populate(std::forward<Gs>(moreGenerators)...);
  3253. }
  3254. T const& get() const override {
  3255. return m_generators[m_current].get();
  3256. }
  3257. bool next() override {
  3258. if (m_current >= m_generators.size()) {
  3259. return false;
  3260. }
  3261. const bool current_status = m_generators[m_current].next();
  3262. if (!current_status) {
  3263. ++m_current;
  3264. }
  3265. return m_current < m_generators.size();
  3266. }
  3267. };
  3268. template<typename... Ts>
  3269. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3270. return values<std::tuple<Ts...>>( tuples );
  3271. }
  3272. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3273. template <typename T>
  3274. struct as {};
  3275. template<typename T, typename... Gs>
  3276. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  3277. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3278. }
  3279. template<typename T>
  3280. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3281. return Generators<T>(std::move(generator));
  3282. }
  3283. template<typename T, typename... Gs>
  3284. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3285. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3286. }
  3287. template<typename T, typename U, typename... Gs>
  3288. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3289. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3290. }
  3291. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3292. template<typename L>
  3293. // Note: The type after -> is weird, because VS2015 cannot parse
  3294. // the expression used in the typedef inside, when it is in
  3295. // return type. Yeah.
  3296. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3297. using UnderlyingType = typename decltype(generatorExpression())::type;
  3298. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3299. if (!tracker.hasGenerator()) {
  3300. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3301. }
  3302. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3303. return generator.get();
  3304. }
  3305. } // namespace Generators
  3306. } // namespace Catch
  3307. #define GENERATE( ... ) \
  3308. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3309. #define GENERATE_COPY( ... ) \
  3310. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3311. #define GENERATE_REF( ... ) \
  3312. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3313. // end catch_generators.hpp
  3314. // start catch_generators_generic.hpp
  3315. namespace Catch {
  3316. namespace Generators {
  3317. template <typename T>
  3318. class TakeGenerator : public IGenerator<T> {
  3319. GeneratorWrapper<T> m_generator;
  3320. size_t m_returned = 0;
  3321. size_t m_target;
  3322. public:
  3323. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3324. m_generator(std::move(generator)),
  3325. m_target(target)
  3326. {
  3327. assert(target != 0 && "Empty generators are not allowed");
  3328. }
  3329. T const& get() const override {
  3330. return m_generator.get();
  3331. }
  3332. bool next() override {
  3333. ++m_returned;
  3334. if (m_returned >= m_target) {
  3335. return false;
  3336. }
  3337. const auto success = m_generator.next();
  3338. // If the underlying generator does not contain enough values
  3339. // then we cut short as well
  3340. if (!success) {
  3341. m_returned = m_target;
  3342. }
  3343. return success;
  3344. }
  3345. };
  3346. template <typename T>
  3347. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3348. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3349. }
  3350. template <typename T, typename Predicate>
  3351. class FilterGenerator : public IGenerator<T> {
  3352. GeneratorWrapper<T> m_generator;
  3353. Predicate m_predicate;
  3354. public:
  3355. template <typename P = Predicate>
  3356. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3357. m_generator(std::move(generator)),
  3358. m_predicate(std::forward<P>(pred))
  3359. {
  3360. if (!m_predicate(m_generator.get())) {
  3361. // It might happen that there are no values that pass the
  3362. // filter. In that case we throw an exception.
  3363. auto has_initial_value = next();
  3364. if (!has_initial_value) {
  3365. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3366. }
  3367. }
  3368. }
  3369. T const& get() const override {
  3370. return m_generator.get();
  3371. }
  3372. bool next() override {
  3373. bool success = m_generator.next();
  3374. if (!success) {
  3375. return false;
  3376. }
  3377. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3378. return success;
  3379. }
  3380. };
  3381. template <typename T, typename Predicate>
  3382. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3383. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3384. }
  3385. template <typename T>
  3386. class RepeatGenerator : public IGenerator<T> {
  3387. static_assert(!std::is_same<T, bool>::value,
  3388. "RepeatGenerator currently does not support bools"
  3389. "because of std::vector<bool> specialization");
  3390. GeneratorWrapper<T> m_generator;
  3391. mutable std::vector<T> m_returned;
  3392. size_t m_target_repeats;
  3393. size_t m_current_repeat = 0;
  3394. size_t m_repeat_index = 0;
  3395. public:
  3396. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3397. m_generator(std::move(generator)),
  3398. m_target_repeats(repeats)
  3399. {
  3400. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3401. }
  3402. T const& get() const override {
  3403. if (m_current_repeat == 0) {
  3404. m_returned.push_back(m_generator.get());
  3405. return m_returned.back();
  3406. }
  3407. return m_returned[m_repeat_index];
  3408. }
  3409. bool next() override {
  3410. // There are 2 basic cases:
  3411. // 1) We are still reading the generator
  3412. // 2) We are reading our own cache
  3413. // In the first case, we need to poke the underlying generator.
  3414. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3415. if (m_current_repeat == 0) {
  3416. const auto success = m_generator.next();
  3417. if (!success) {
  3418. ++m_current_repeat;
  3419. }
  3420. return m_current_repeat < m_target_repeats;
  3421. }
  3422. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3423. ++m_repeat_index;
  3424. if (m_repeat_index == m_returned.size()) {
  3425. m_repeat_index = 0;
  3426. ++m_current_repeat;
  3427. }
  3428. return m_current_repeat < m_target_repeats;
  3429. }
  3430. };
  3431. template <typename T>
  3432. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3433. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3434. }
  3435. template <typename T, typename U, typename Func>
  3436. class MapGenerator : public IGenerator<T> {
  3437. // TBD: provide static assert for mapping function, for friendly error message
  3438. GeneratorWrapper<U> m_generator;
  3439. Func m_function;
  3440. // To avoid returning dangling reference, we have to save the values
  3441. T m_cache;
  3442. public:
  3443. template <typename F2 = Func>
  3444. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3445. m_generator(std::move(generator)),
  3446. m_function(std::forward<F2>(function)),
  3447. m_cache(m_function(m_generator.get()))
  3448. {}
  3449. T const& get() const override {
  3450. return m_cache;
  3451. }
  3452. bool next() override {
  3453. const auto success = m_generator.next();
  3454. if (success) {
  3455. m_cache = m_function(m_generator.get());
  3456. }
  3457. return success;
  3458. }
  3459. };
  3460. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3461. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3462. // replaced with std::invoke_result here. Also *_t format is preferred over
  3463. // typename *::type format.
  3464. template <typename Func, typename U>
  3465. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3466. #else
  3467. template <typename Func, typename U>
  3468. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3469. #endif
  3470. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3471. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3472. return GeneratorWrapper<T>(
  3473. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3474. );
  3475. }
  3476. template <typename T, typename U, typename Func>
  3477. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3478. return GeneratorWrapper<T>(
  3479. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3480. );
  3481. }
  3482. template <typename T>
  3483. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3484. std::vector<T> m_chunk;
  3485. size_t m_chunk_size;
  3486. GeneratorWrapper<T> m_generator;
  3487. bool m_used_up = false;
  3488. public:
  3489. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3490. m_chunk_size(size), m_generator(std::move(generator))
  3491. {
  3492. m_chunk.reserve(m_chunk_size);
  3493. if (m_chunk_size != 0) {
  3494. m_chunk.push_back(m_generator.get());
  3495. for (size_t i = 1; i < m_chunk_size; ++i) {
  3496. if (!m_generator.next()) {
  3497. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3498. }
  3499. m_chunk.push_back(m_generator.get());
  3500. }
  3501. }
  3502. }
  3503. std::vector<T> const& get() const override {
  3504. return m_chunk;
  3505. }
  3506. bool next() override {
  3507. m_chunk.clear();
  3508. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3509. if (!m_generator.next()) {
  3510. return false;
  3511. }
  3512. m_chunk.push_back(m_generator.get());
  3513. }
  3514. return true;
  3515. }
  3516. };
  3517. template <typename T>
  3518. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3519. return GeneratorWrapper<std::vector<T>>(
  3520. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3521. );
  3522. }
  3523. } // namespace Generators
  3524. } // namespace Catch
  3525. // end catch_generators_generic.hpp
  3526. // start catch_generators_specific.hpp
  3527. // start catch_context.h
  3528. #include <memory>
  3529. namespace Catch {
  3530. struct IResultCapture;
  3531. struct IRunner;
  3532. struct IConfig;
  3533. struct IMutableContext;
  3534. using IConfigPtr = std::shared_ptr<IConfig const>;
  3535. struct IContext
  3536. {
  3537. virtual ~IContext();
  3538. virtual IResultCapture* getResultCapture() = 0;
  3539. virtual IRunner* getRunner() = 0;
  3540. virtual IConfigPtr const& getConfig() const = 0;
  3541. };
  3542. struct IMutableContext : IContext
  3543. {
  3544. virtual ~IMutableContext();
  3545. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3546. virtual void setRunner( IRunner* runner ) = 0;
  3547. virtual void setConfig( IConfigPtr const& config ) = 0;
  3548. private:
  3549. static IMutableContext *currentContext;
  3550. friend IMutableContext& getCurrentMutableContext();
  3551. friend void cleanUpContext();
  3552. static void createContext();
  3553. };
  3554. inline IMutableContext& getCurrentMutableContext()
  3555. {
  3556. if( !IMutableContext::currentContext )
  3557. IMutableContext::createContext();
  3558. return *IMutableContext::currentContext;
  3559. }
  3560. inline IContext& getCurrentContext()
  3561. {
  3562. return getCurrentMutableContext();
  3563. }
  3564. void cleanUpContext();
  3565. }
  3566. // end catch_context.h
  3567. // start catch_interfaces_config.h
  3568. // start catch_option.hpp
  3569. namespace Catch {
  3570. // An optional type
  3571. template<typename T>
  3572. class Option {
  3573. public:
  3574. Option() : nullableValue( nullptr ) {}
  3575. Option( T const& _value )
  3576. : nullableValue( new( storage ) T( _value ) )
  3577. {}
  3578. Option( Option const& _other )
  3579. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3580. {}
  3581. ~Option() {
  3582. reset();
  3583. }
  3584. Option& operator= ( Option const& _other ) {
  3585. if( &_other != this ) {
  3586. reset();
  3587. if( _other )
  3588. nullableValue = new( storage ) T( *_other );
  3589. }
  3590. return *this;
  3591. }
  3592. Option& operator = ( T const& _value ) {
  3593. reset();
  3594. nullableValue = new( storage ) T( _value );
  3595. return *this;
  3596. }
  3597. void reset() {
  3598. if( nullableValue )
  3599. nullableValue->~T();
  3600. nullableValue = nullptr;
  3601. }
  3602. T& operator*() { return *nullableValue; }
  3603. T const& operator*() const { return *nullableValue; }
  3604. T* operator->() { return nullableValue; }
  3605. const T* operator->() const { return nullableValue; }
  3606. T valueOr( T const& defaultValue ) const {
  3607. return nullableValue ? *nullableValue : defaultValue;
  3608. }
  3609. bool some() const { return nullableValue != nullptr; }
  3610. bool none() const { return nullableValue == nullptr; }
  3611. bool operator !() const { return nullableValue == nullptr; }
  3612. explicit operator bool() const {
  3613. return some();
  3614. }
  3615. private:
  3616. T *nullableValue;
  3617. alignas(alignof(T)) char storage[sizeof(T)];
  3618. };
  3619. } // end namespace Catch
  3620. // end catch_option.hpp
  3621. #include <iosfwd>
  3622. #include <string>
  3623. #include <vector>
  3624. #include <memory>
  3625. namespace Catch {
  3626. enum class Verbosity {
  3627. Quiet = 0,
  3628. Normal,
  3629. High
  3630. };
  3631. struct WarnAbout { enum What {
  3632. Nothing = 0x00,
  3633. NoAssertions = 0x01,
  3634. NoTests = 0x02
  3635. }; };
  3636. struct ShowDurations { enum OrNot {
  3637. DefaultForReporter,
  3638. Always,
  3639. Never
  3640. }; };
  3641. struct RunTests { enum InWhatOrder {
  3642. InDeclarationOrder,
  3643. InLexicographicalOrder,
  3644. InRandomOrder
  3645. }; };
  3646. struct UseColour { enum YesOrNo {
  3647. Auto,
  3648. Yes,
  3649. No
  3650. }; };
  3651. struct WaitForKeypress { enum When {
  3652. Never,
  3653. BeforeStart = 1,
  3654. BeforeExit = 2,
  3655. BeforeStartAndExit = BeforeStart | BeforeExit
  3656. }; };
  3657. class TestSpec;
  3658. struct IConfig : NonCopyable {
  3659. virtual ~IConfig();
  3660. virtual bool allowThrows() const = 0;
  3661. virtual std::ostream& stream() const = 0;
  3662. virtual std::string name() const = 0;
  3663. virtual bool includeSuccessfulResults() const = 0;
  3664. virtual bool shouldDebugBreak() const = 0;
  3665. virtual bool warnAboutMissingAssertions() const = 0;
  3666. virtual bool warnAboutNoTests() const = 0;
  3667. virtual int abortAfter() const = 0;
  3668. virtual bool showInvisibles() const = 0;
  3669. virtual ShowDurations::OrNot showDurations() const = 0;
  3670. virtual TestSpec const& testSpec() const = 0;
  3671. virtual bool hasTestFilters() const = 0;
  3672. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3673. virtual RunTests::InWhatOrder runOrder() const = 0;
  3674. virtual unsigned int rngSeed() const = 0;
  3675. virtual UseColour::YesOrNo useColour() const = 0;
  3676. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3677. virtual Verbosity verbosity() const = 0;
  3678. virtual bool benchmarkNoAnalysis() const = 0;
  3679. virtual int benchmarkSamples() const = 0;
  3680. virtual double benchmarkConfidenceInterval() const = 0;
  3681. virtual unsigned int benchmarkResamples() const = 0;
  3682. };
  3683. using IConfigPtr = std::shared_ptr<IConfig const>;
  3684. }
  3685. // end catch_interfaces_config.h
  3686. #include <random>
  3687. namespace Catch {
  3688. namespace Generators {
  3689. template <typename Float>
  3690. class RandomFloatingGenerator final : public IGenerator<Float> {
  3691. // FIXME: What is the right seed?
  3692. std::minstd_rand m_rand;
  3693. std::uniform_real_distribution<Float> m_dist;
  3694. Float m_current_number;
  3695. public:
  3696. RandomFloatingGenerator(Float a, Float b):
  3697. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3698. m_dist(a, b) {
  3699. static_cast<void>(next());
  3700. }
  3701. Float const& get() const override {
  3702. return m_current_number;
  3703. }
  3704. bool next() override {
  3705. m_current_number = m_dist(m_rand);
  3706. return true;
  3707. }
  3708. };
  3709. template <typename Integer>
  3710. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3711. std::minstd_rand m_rand;
  3712. std::uniform_int_distribution<Integer> m_dist;
  3713. Integer m_current_number;
  3714. public:
  3715. RandomIntegerGenerator(Integer a, Integer b):
  3716. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3717. m_dist(a, b) {
  3718. static_cast<void>(next());
  3719. }
  3720. Integer const& get() const override {
  3721. return m_current_number;
  3722. }
  3723. bool next() override {
  3724. m_current_number = m_dist(m_rand);
  3725. return true;
  3726. }
  3727. };
  3728. // TODO: Ideally this would be also constrained against the various char types,
  3729. // but I don't expect users to run into that in practice.
  3730. template <typename T>
  3731. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3732. GeneratorWrapper<T>>::type
  3733. random(T a, T b) {
  3734. return GeneratorWrapper<T>(
  3735. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3736. );
  3737. }
  3738. template <typename T>
  3739. typename std::enable_if<std::is_floating_point<T>::value,
  3740. GeneratorWrapper<T>>::type
  3741. random(T a, T b) {
  3742. return GeneratorWrapper<T>(
  3743. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3744. );
  3745. }
  3746. template <typename T>
  3747. class RangeGenerator final : public IGenerator<T> {
  3748. T m_current;
  3749. T m_end;
  3750. T m_step;
  3751. bool m_positive;
  3752. public:
  3753. RangeGenerator(T const& start, T const& end, T const& step):
  3754. m_current(start),
  3755. m_end(end),
  3756. m_step(step),
  3757. m_positive(m_step > T(0))
  3758. {
  3759. assert(m_current != m_end && "Range start and end cannot be equal");
  3760. assert(m_step != T(0) && "Step size cannot be zero");
  3761. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3762. }
  3763. RangeGenerator(T const& start, T const& end):
  3764. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3765. {}
  3766. T const& get() const override {
  3767. return m_current;
  3768. }
  3769. bool next() override {
  3770. m_current += m_step;
  3771. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3772. }
  3773. };
  3774. template <typename T>
  3775. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3776. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3777. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3778. }
  3779. template <typename T>
  3780. GeneratorWrapper<T> range(T const& start, T const& end) {
  3781. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3782. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3783. }
  3784. } // namespace Generators
  3785. } // namespace Catch
  3786. // end catch_generators_specific.hpp
  3787. // These files are included here so the single_include script doesn't put them
  3788. // in the conditionally compiled sections
  3789. // start catch_test_case_info.h
  3790. #include <string>
  3791. #include <vector>
  3792. #include <memory>
  3793. #ifdef __clang__
  3794. #pragma clang diagnostic push
  3795. #pragma clang diagnostic ignored "-Wpadded"
  3796. #endif
  3797. namespace Catch {
  3798. struct ITestInvoker;
  3799. struct TestCaseInfo {
  3800. enum SpecialProperties{
  3801. None = 0,
  3802. IsHidden = 1 << 1,
  3803. ShouldFail = 1 << 2,
  3804. MayFail = 1 << 3,
  3805. Throws = 1 << 4,
  3806. NonPortable = 1 << 5,
  3807. Benchmark = 1 << 6
  3808. };
  3809. TestCaseInfo( std::string const& _name,
  3810. std::string const& _className,
  3811. std::string const& _description,
  3812. std::vector<std::string> const& _tags,
  3813. SourceLineInfo const& _lineInfo );
  3814. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3815. bool isHidden() const;
  3816. bool throws() const;
  3817. bool okToFail() const;
  3818. bool expectedToFail() const;
  3819. std::string tagsAsString() const;
  3820. std::string name;
  3821. std::string className;
  3822. std::string description;
  3823. std::vector<std::string> tags;
  3824. std::vector<std::string> lcaseTags;
  3825. SourceLineInfo lineInfo;
  3826. SpecialProperties properties;
  3827. };
  3828. class TestCase : public TestCaseInfo {
  3829. public:
  3830. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3831. TestCase withName( std::string const& _newName ) const;
  3832. void invoke() const;
  3833. TestCaseInfo const& getTestCaseInfo() const;
  3834. bool operator == ( TestCase const& other ) const;
  3835. bool operator < ( TestCase const& other ) const;
  3836. private:
  3837. std::shared_ptr<ITestInvoker> test;
  3838. };
  3839. TestCase makeTestCase( ITestInvoker* testCase,
  3840. std::string const& className,
  3841. NameAndTags const& nameAndTags,
  3842. SourceLineInfo const& lineInfo );
  3843. }
  3844. #ifdef __clang__
  3845. #pragma clang diagnostic pop
  3846. #endif
  3847. // end catch_test_case_info.h
  3848. // start catch_interfaces_runner.h
  3849. namespace Catch {
  3850. struct IRunner {
  3851. virtual ~IRunner();
  3852. virtual bool aborting() const = 0;
  3853. };
  3854. }
  3855. // end catch_interfaces_runner.h
  3856. #ifdef __OBJC__
  3857. // start catch_objc.hpp
  3858. #import <objc/runtime.h>
  3859. #include <string>
  3860. // NB. Any general catch headers included here must be included
  3861. // in catch.hpp first to make sure they are included by the single
  3862. // header for non obj-usage
  3863. ///////////////////////////////////////////////////////////////////////////////
  3864. // This protocol is really only here for (self) documenting purposes, since
  3865. // all its methods are optional.
  3866. @protocol OcFixture
  3867. @optional
  3868. -(void) setUp;
  3869. -(void) tearDown;
  3870. @end
  3871. namespace Catch {
  3872. class OcMethod : public ITestInvoker {
  3873. public:
  3874. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3875. virtual void invoke() const {
  3876. id obj = [[m_cls alloc] init];
  3877. performOptionalSelector( obj, @selector(setUp) );
  3878. performOptionalSelector( obj, m_sel );
  3879. performOptionalSelector( obj, @selector(tearDown) );
  3880. arcSafeRelease( obj );
  3881. }
  3882. private:
  3883. virtual ~OcMethod() {}
  3884. Class m_cls;
  3885. SEL m_sel;
  3886. };
  3887. namespace Detail{
  3888. inline std::string getAnnotation( Class cls,
  3889. std::string const& annotationName,
  3890. std::string const& testCaseName ) {
  3891. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3892. SEL sel = NSSelectorFromString( selStr );
  3893. arcSafeRelease( selStr );
  3894. id value = performOptionalSelector( cls, sel );
  3895. if( value )
  3896. return [(NSString*)value UTF8String];
  3897. return "";
  3898. }
  3899. }
  3900. inline std::size_t registerTestMethods() {
  3901. std::size_t noTestMethods = 0;
  3902. int noClasses = objc_getClassList( nullptr, 0 );
  3903. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3904. objc_getClassList( classes, noClasses );
  3905. for( int c = 0; c < noClasses; c++ ) {
  3906. Class cls = classes[c];
  3907. {
  3908. u_int count;
  3909. Method* methods = class_copyMethodList( cls, &count );
  3910. for( u_int m = 0; m < count ; m++ ) {
  3911. SEL selector = method_getName(methods[m]);
  3912. std::string methodName = sel_getName(selector);
  3913. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3914. std::string testCaseName = methodName.substr( 15 );
  3915. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3916. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3917. const char* className = class_getName( cls );
  3918. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3919. noTestMethods++;
  3920. }
  3921. }
  3922. free(methods);
  3923. }
  3924. }
  3925. return noTestMethods;
  3926. }
  3927. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3928. namespace Matchers {
  3929. namespace Impl {
  3930. namespace NSStringMatchers {
  3931. struct StringHolder : MatcherBase<NSString*>{
  3932. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3933. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3934. StringHolder() {
  3935. arcSafeRelease( m_substr );
  3936. }
  3937. bool match( NSString* str ) const override {
  3938. return false;
  3939. }
  3940. NSString* CATCH_ARC_STRONG m_substr;
  3941. };
  3942. struct Equals : StringHolder {
  3943. Equals( NSString* substr ) : StringHolder( substr ){}
  3944. bool match( NSString* str ) const override {
  3945. return (str != nil || m_substr == nil ) &&
  3946. [str isEqualToString:m_substr];
  3947. }
  3948. std::string describe() const override {
  3949. return "equals string: " + Catch::Detail::stringify( m_substr );
  3950. }
  3951. };
  3952. struct Contains : StringHolder {
  3953. Contains( NSString* substr ) : StringHolder( substr ){}
  3954. bool match( NSString* str ) const override {
  3955. return (str != nil || m_substr == nil ) &&
  3956. [str rangeOfString:m_substr].location != NSNotFound;
  3957. }
  3958. std::string describe() const override {
  3959. return "contains string: " + Catch::Detail::stringify( m_substr );
  3960. }
  3961. };
  3962. struct StartsWith : StringHolder {
  3963. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3964. bool match( NSString* str ) const override {
  3965. return (str != nil || m_substr == nil ) &&
  3966. [str rangeOfString:m_substr].location == 0;
  3967. }
  3968. std::string describe() const override {
  3969. return "starts with: " + Catch::Detail::stringify( m_substr );
  3970. }
  3971. };
  3972. struct EndsWith : StringHolder {
  3973. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3974. bool match( NSString* str ) const override {
  3975. return (str != nil || m_substr == nil ) &&
  3976. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3977. }
  3978. std::string describe() const override {
  3979. return "ends with: " + Catch::Detail::stringify( m_substr );
  3980. }
  3981. };
  3982. } // namespace NSStringMatchers
  3983. } // namespace Impl
  3984. inline Impl::NSStringMatchers::Equals
  3985. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3986. inline Impl::NSStringMatchers::Contains
  3987. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3988. inline Impl::NSStringMatchers::StartsWith
  3989. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3990. inline Impl::NSStringMatchers::EndsWith
  3991. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3992. } // namespace Matchers
  3993. using namespace Matchers;
  3994. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3995. } // namespace Catch
  3996. ///////////////////////////////////////////////////////////////////////////////
  3997. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3998. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3999. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4000. { \
  4001. return @ name; \
  4002. } \
  4003. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4004. { \
  4005. return @ desc; \
  4006. } \
  4007. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4008. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4009. // end catch_objc.hpp
  4010. #endif
  4011. // Benchmarking needs the externally-facing parts of reporters to work
  4012. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4013. // start catch_external_interfaces.h
  4014. // start catch_reporter_bases.hpp
  4015. // start catch_interfaces_reporter.h
  4016. // start catch_config.hpp
  4017. // start catch_test_spec_parser.h
  4018. #ifdef __clang__
  4019. #pragma clang diagnostic push
  4020. #pragma clang diagnostic ignored "-Wpadded"
  4021. #endif
  4022. // start catch_test_spec.h
  4023. #ifdef __clang__
  4024. #pragma clang diagnostic push
  4025. #pragma clang diagnostic ignored "-Wpadded"
  4026. #endif
  4027. // start catch_wildcard_pattern.h
  4028. namespace Catch
  4029. {
  4030. class WildcardPattern {
  4031. enum WildcardPosition {
  4032. NoWildcard = 0,
  4033. WildcardAtStart = 1,
  4034. WildcardAtEnd = 2,
  4035. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4036. };
  4037. public:
  4038. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4039. virtual ~WildcardPattern() = default;
  4040. virtual bool matches( std::string const& str ) const;
  4041. private:
  4042. std::string adjustCase( std::string const& str ) const;
  4043. CaseSensitive::Choice m_caseSensitivity;
  4044. WildcardPosition m_wildcard = NoWildcard;
  4045. std::string m_pattern;
  4046. };
  4047. }
  4048. // end catch_wildcard_pattern.h
  4049. #include <string>
  4050. #include <vector>
  4051. #include <memory>
  4052. namespace Catch {
  4053. struct IConfig;
  4054. class TestSpec {
  4055. class Pattern {
  4056. public:
  4057. explicit Pattern( std::string const& name );
  4058. virtual ~Pattern();
  4059. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4060. std::string const& name() const;
  4061. private:
  4062. std::string const m_name;
  4063. };
  4064. using PatternPtr = std::shared_ptr<Pattern>;
  4065. class NamePattern : public Pattern {
  4066. public:
  4067. explicit NamePattern( std::string const& name, std::string const& filterString );
  4068. bool matches( TestCaseInfo const& testCase ) const override;
  4069. private:
  4070. WildcardPattern m_wildcardPattern;
  4071. };
  4072. class TagPattern : public Pattern {
  4073. public:
  4074. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4075. bool matches( TestCaseInfo const& testCase ) const override;
  4076. private:
  4077. std::string m_tag;
  4078. };
  4079. class ExcludedPattern : public Pattern {
  4080. public:
  4081. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4082. bool matches( TestCaseInfo const& testCase ) const override;
  4083. private:
  4084. PatternPtr m_underlyingPattern;
  4085. };
  4086. struct Filter {
  4087. std::vector<PatternPtr> m_patterns;
  4088. bool matches( TestCaseInfo const& testCase ) const;
  4089. std::string name() const;
  4090. };
  4091. public:
  4092. struct FilterMatch {
  4093. std::string name;
  4094. std::vector<TestCase const*> tests;
  4095. };
  4096. using Matches = std::vector<FilterMatch>;
  4097. bool hasFilters() const;
  4098. bool matches( TestCaseInfo const& testCase ) const;
  4099. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4100. private:
  4101. std::vector<Filter> m_filters;
  4102. friend class TestSpecParser;
  4103. };
  4104. }
  4105. #ifdef __clang__
  4106. #pragma clang diagnostic pop
  4107. #endif
  4108. // end catch_test_spec.h
  4109. // start catch_interfaces_tag_alias_registry.h
  4110. #include <string>
  4111. namespace Catch {
  4112. struct TagAlias;
  4113. struct ITagAliasRegistry {
  4114. virtual ~ITagAliasRegistry();
  4115. // Nullptr if not present
  4116. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4117. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4118. static ITagAliasRegistry const& get();
  4119. };
  4120. } // end namespace Catch
  4121. // end catch_interfaces_tag_alias_registry.h
  4122. namespace Catch {
  4123. class TestSpecParser {
  4124. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4125. Mode m_mode = None;
  4126. bool m_exclusion = false;
  4127. std::size_t m_pos = 0;
  4128. std::string m_arg;
  4129. std::string m_substring;
  4130. std::string m_patternName;
  4131. std::vector<std::size_t> m_escapeChars;
  4132. TestSpec::Filter m_currentFilter;
  4133. TestSpec m_testSpec;
  4134. ITagAliasRegistry const* m_tagAliases = nullptr;
  4135. public:
  4136. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4137. TestSpecParser& parse( std::string const& arg );
  4138. TestSpec testSpec();
  4139. private:
  4140. void visitChar( char c );
  4141. void startNewMode( Mode mode );
  4142. bool processNoneChar( char c );
  4143. void processNameChar( char c );
  4144. bool processOtherChar( char c );
  4145. void endMode();
  4146. void escape();
  4147. bool isControlChar( char c ) const;
  4148. template<typename T>
  4149. void addPattern() {
  4150. std::string token = m_patternName;
  4151. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4152. token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
  4153. m_escapeChars.clear();
  4154. if( startsWith( token, "exclude:" ) ) {
  4155. m_exclusion = true;
  4156. token = token.substr( 8 );
  4157. }
  4158. if( !token.empty() ) {
  4159. TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
  4160. if( m_exclusion )
  4161. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4162. m_currentFilter.m_patterns.push_back( pattern );
  4163. }
  4164. m_substring.clear();
  4165. m_patternName.clear();
  4166. m_exclusion = false;
  4167. m_mode = None;
  4168. }
  4169. void addFilter();
  4170. };
  4171. TestSpec parseTestSpec( std::string const& arg );
  4172. } // namespace Catch
  4173. #ifdef __clang__
  4174. #pragma clang diagnostic pop
  4175. #endif
  4176. // end catch_test_spec_parser.h
  4177. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4178. #include <memory>
  4179. #include <vector>
  4180. #include <string>
  4181. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4182. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4183. #endif
  4184. namespace Catch {
  4185. struct IStream;
  4186. struct ConfigData {
  4187. bool listTests = false;
  4188. bool listTags = false;
  4189. bool listReporters = false;
  4190. bool listTestNamesOnly = false;
  4191. bool showSuccessfulTests = false;
  4192. bool shouldDebugBreak = false;
  4193. bool noThrow = false;
  4194. bool showHelp = false;
  4195. bool showInvisibles = false;
  4196. bool filenamesAsTags = false;
  4197. bool libIdentify = false;
  4198. int abortAfter = -1;
  4199. unsigned int rngSeed = 0;
  4200. bool benchmarkNoAnalysis = false;
  4201. unsigned int benchmarkSamples = 100;
  4202. double benchmarkConfidenceInterval = 0.95;
  4203. unsigned int benchmarkResamples = 100000;
  4204. Verbosity verbosity = Verbosity::Normal;
  4205. WarnAbout::What warnings = WarnAbout::Nothing;
  4206. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4207. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4208. UseColour::YesOrNo useColour = UseColour::Auto;
  4209. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4210. std::string outputFilename;
  4211. std::string name;
  4212. std::string processName;
  4213. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4214. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4215. #endif
  4216. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4217. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4218. std::vector<std::string> testsOrTags;
  4219. std::vector<std::string> sectionsToRun;
  4220. };
  4221. class Config : public IConfig {
  4222. public:
  4223. Config() = default;
  4224. Config( ConfigData const& data );
  4225. virtual ~Config() = default;
  4226. std::string const& getFilename() const;
  4227. bool listTests() const;
  4228. bool listTestNamesOnly() const;
  4229. bool listTags() const;
  4230. bool listReporters() const;
  4231. std::string getProcessName() const;
  4232. std::string const& getReporterName() const;
  4233. std::vector<std::string> const& getTestsOrTags() const override;
  4234. std::vector<std::string> const& getSectionsToRun() const override;
  4235. TestSpec const& testSpec() const override;
  4236. bool hasTestFilters() const override;
  4237. bool showHelp() const;
  4238. // IConfig interface
  4239. bool allowThrows() const override;
  4240. std::ostream& stream() const override;
  4241. std::string name() const override;
  4242. bool includeSuccessfulResults() const override;
  4243. bool warnAboutMissingAssertions() const override;
  4244. bool warnAboutNoTests() const override;
  4245. ShowDurations::OrNot showDurations() const override;
  4246. RunTests::InWhatOrder runOrder() const override;
  4247. unsigned int rngSeed() const override;
  4248. UseColour::YesOrNo useColour() const override;
  4249. bool shouldDebugBreak() const override;
  4250. int abortAfter() const override;
  4251. bool showInvisibles() const override;
  4252. Verbosity verbosity() const override;
  4253. bool benchmarkNoAnalysis() const override;
  4254. int benchmarkSamples() const override;
  4255. double benchmarkConfidenceInterval() const override;
  4256. unsigned int benchmarkResamples() const override;
  4257. private:
  4258. IStream const* openStream();
  4259. ConfigData m_data;
  4260. std::unique_ptr<IStream const> m_stream;
  4261. TestSpec m_testSpec;
  4262. bool m_hasTestFilters = false;
  4263. };
  4264. } // end namespace Catch
  4265. // end catch_config.hpp
  4266. // start catch_assertionresult.h
  4267. #include <string>
  4268. namespace Catch {
  4269. struct AssertionResultData
  4270. {
  4271. AssertionResultData() = delete;
  4272. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4273. std::string message;
  4274. mutable std::string reconstructedExpression;
  4275. LazyExpression lazyExpression;
  4276. ResultWas::OfType resultType;
  4277. std::string reconstructExpression() const;
  4278. };
  4279. class AssertionResult {
  4280. public:
  4281. AssertionResult() = delete;
  4282. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4283. bool isOk() const;
  4284. bool succeeded() const;
  4285. ResultWas::OfType getResultType() const;
  4286. bool hasExpression() const;
  4287. bool hasMessage() const;
  4288. std::string getExpression() const;
  4289. std::string getExpressionInMacro() const;
  4290. bool hasExpandedExpression() const;
  4291. std::string getExpandedExpression() const;
  4292. std::string getMessage() const;
  4293. SourceLineInfo getSourceInfo() const;
  4294. StringRef getTestMacroName() const;
  4295. //protected:
  4296. AssertionInfo m_info;
  4297. AssertionResultData m_resultData;
  4298. };
  4299. } // end namespace Catch
  4300. // end catch_assertionresult.h
  4301. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4302. // start catch_estimate.hpp
  4303. // Statistics estimates
  4304. namespace Catch {
  4305. namespace Benchmark {
  4306. template <typename Duration>
  4307. struct Estimate {
  4308. Duration point;
  4309. Duration lower_bound;
  4310. Duration upper_bound;
  4311. double confidence_interval;
  4312. template <typename Duration2>
  4313. operator Estimate<Duration2>() const {
  4314. return { point, lower_bound, upper_bound, confidence_interval };
  4315. }
  4316. };
  4317. } // namespace Benchmark
  4318. } // namespace Catch
  4319. // end catch_estimate.hpp
  4320. // start catch_outlier_classification.hpp
  4321. // Outlier information
  4322. namespace Catch {
  4323. namespace Benchmark {
  4324. struct OutlierClassification {
  4325. int samples_seen = 0;
  4326. int low_severe = 0; // more than 3 times IQR below Q1
  4327. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4328. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4329. int high_severe = 0; // more than 3 times IQR above Q3
  4330. int total() const {
  4331. return low_severe + low_mild + high_mild + high_severe;
  4332. }
  4333. };
  4334. } // namespace Benchmark
  4335. } // namespace Catch
  4336. // end catch_outlier_classification.hpp
  4337. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4338. #include <string>
  4339. #include <iosfwd>
  4340. #include <map>
  4341. #include <set>
  4342. #include <memory>
  4343. #include <algorithm>
  4344. namespace Catch {
  4345. struct ReporterConfig {
  4346. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4347. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4348. std::ostream& stream() const;
  4349. IConfigPtr fullConfig() const;
  4350. private:
  4351. std::ostream* m_stream;
  4352. IConfigPtr m_fullConfig;
  4353. };
  4354. struct ReporterPreferences {
  4355. bool shouldRedirectStdOut = false;
  4356. bool shouldReportAllAssertions = false;
  4357. };
  4358. template<typename T>
  4359. struct LazyStat : Option<T> {
  4360. LazyStat& operator=( T const& _value ) {
  4361. Option<T>::operator=( _value );
  4362. used = false;
  4363. return *this;
  4364. }
  4365. void reset() {
  4366. Option<T>::reset();
  4367. used = false;
  4368. }
  4369. bool used = false;
  4370. };
  4371. struct TestRunInfo {
  4372. TestRunInfo( std::string const& _name );
  4373. std::string name;
  4374. };
  4375. struct GroupInfo {
  4376. GroupInfo( std::string const& _name,
  4377. std::size_t _groupIndex,
  4378. std::size_t _groupsCount );
  4379. std::string name;
  4380. std::size_t groupIndex;
  4381. std::size_t groupsCounts;
  4382. };
  4383. struct AssertionStats {
  4384. AssertionStats( AssertionResult const& _assertionResult,
  4385. std::vector<MessageInfo> const& _infoMessages,
  4386. Totals const& _totals );
  4387. AssertionStats( AssertionStats const& ) = default;
  4388. AssertionStats( AssertionStats && ) = default;
  4389. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4390. AssertionStats& operator = ( AssertionStats && ) = delete;
  4391. virtual ~AssertionStats();
  4392. AssertionResult assertionResult;
  4393. std::vector<MessageInfo> infoMessages;
  4394. Totals totals;
  4395. };
  4396. struct SectionStats {
  4397. SectionStats( SectionInfo const& _sectionInfo,
  4398. Counts const& _assertions,
  4399. double _durationInSeconds,
  4400. bool _missingAssertions );
  4401. SectionStats( SectionStats const& ) = default;
  4402. SectionStats( SectionStats && ) = default;
  4403. SectionStats& operator = ( SectionStats const& ) = default;
  4404. SectionStats& operator = ( SectionStats && ) = default;
  4405. virtual ~SectionStats();
  4406. SectionInfo sectionInfo;
  4407. Counts assertions;
  4408. double durationInSeconds;
  4409. bool missingAssertions;
  4410. };
  4411. struct TestCaseStats {
  4412. TestCaseStats( TestCaseInfo const& _testInfo,
  4413. Totals const& _totals,
  4414. std::string const& _stdOut,
  4415. std::string const& _stdErr,
  4416. bool _aborting );
  4417. TestCaseStats( TestCaseStats const& ) = default;
  4418. TestCaseStats( TestCaseStats && ) = default;
  4419. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4420. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4421. virtual ~TestCaseStats();
  4422. TestCaseInfo testInfo;
  4423. Totals totals;
  4424. std::string stdOut;
  4425. std::string stdErr;
  4426. bool aborting;
  4427. };
  4428. struct TestGroupStats {
  4429. TestGroupStats( GroupInfo const& _groupInfo,
  4430. Totals const& _totals,
  4431. bool _aborting );
  4432. TestGroupStats( GroupInfo const& _groupInfo );
  4433. TestGroupStats( TestGroupStats const& ) = default;
  4434. TestGroupStats( TestGroupStats && ) = default;
  4435. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4436. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4437. virtual ~TestGroupStats();
  4438. GroupInfo groupInfo;
  4439. Totals totals;
  4440. bool aborting;
  4441. };
  4442. struct TestRunStats {
  4443. TestRunStats( TestRunInfo const& _runInfo,
  4444. Totals const& _totals,
  4445. bool _aborting );
  4446. TestRunStats( TestRunStats const& ) = default;
  4447. TestRunStats( TestRunStats && ) = default;
  4448. TestRunStats& operator = ( TestRunStats const& ) = default;
  4449. TestRunStats& operator = ( TestRunStats && ) = default;
  4450. virtual ~TestRunStats();
  4451. TestRunInfo runInfo;
  4452. Totals totals;
  4453. bool aborting;
  4454. };
  4455. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4456. struct BenchmarkInfo {
  4457. std::string name;
  4458. double estimatedDuration;
  4459. int iterations;
  4460. int samples;
  4461. unsigned int resamples;
  4462. double clockResolution;
  4463. double clockCost;
  4464. };
  4465. template <class Duration>
  4466. struct BenchmarkStats {
  4467. BenchmarkInfo info;
  4468. std::vector<Duration> samples;
  4469. Benchmark::Estimate<Duration> mean;
  4470. Benchmark::Estimate<Duration> standardDeviation;
  4471. Benchmark::OutlierClassification outliers;
  4472. double outlierVariance;
  4473. template <typename Duration2>
  4474. operator BenchmarkStats<Duration2>() const {
  4475. std::vector<Duration2> samples2;
  4476. samples2.reserve(samples.size());
  4477. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4478. return {
  4479. info,
  4480. std::move(samples2),
  4481. mean,
  4482. standardDeviation,
  4483. outliers,
  4484. outlierVariance,
  4485. };
  4486. }
  4487. };
  4488. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4489. struct IStreamingReporter {
  4490. virtual ~IStreamingReporter() = default;
  4491. // Implementing class must also provide the following static methods:
  4492. // static std::string getDescription();
  4493. // static std::set<Verbosity> getSupportedVerbosities()
  4494. virtual ReporterPreferences getPreferences() const = 0;
  4495. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4496. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4497. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4498. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4499. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4500. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4501. virtual void benchmarkPreparing( std::string const& ) {}
  4502. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4503. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4504. virtual void benchmarkFailed( std::string const& ) {}
  4505. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4506. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4507. // The return value indicates if the messages buffer should be cleared:
  4508. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4509. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4510. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4511. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4512. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4513. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4514. // Default empty implementation provided
  4515. virtual void fatalErrorEncountered( StringRef name );
  4516. virtual bool isMulti() const;
  4517. };
  4518. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4519. struct IReporterFactory {
  4520. virtual ~IReporterFactory();
  4521. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4522. virtual std::string getDescription() const = 0;
  4523. };
  4524. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4525. struct IReporterRegistry {
  4526. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4527. using Listeners = std::vector<IReporterFactoryPtr>;
  4528. virtual ~IReporterRegistry();
  4529. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4530. virtual FactoryMap const& getFactories() const = 0;
  4531. virtual Listeners const& getListeners() const = 0;
  4532. };
  4533. } // end namespace Catch
  4534. // end catch_interfaces_reporter.h
  4535. #include <algorithm>
  4536. #include <cstring>
  4537. #include <cfloat>
  4538. #include <cstdio>
  4539. #include <cassert>
  4540. #include <memory>
  4541. #include <ostream>
  4542. namespace Catch {
  4543. void prepareExpandedExpression(AssertionResult& result);
  4544. // Returns double formatted as %.3f (format expected on output)
  4545. std::string getFormattedDuration( double duration );
  4546. std::string serializeFilters( std::vector<std::string> const& container );
  4547. template<typename DerivedT>
  4548. struct StreamingReporterBase : IStreamingReporter {
  4549. StreamingReporterBase( ReporterConfig const& _config )
  4550. : m_config( _config.fullConfig() ),
  4551. stream( _config.stream() )
  4552. {
  4553. m_reporterPrefs.shouldRedirectStdOut = false;
  4554. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4555. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4556. }
  4557. ReporterPreferences getPreferences() const override {
  4558. return m_reporterPrefs;
  4559. }
  4560. static std::set<Verbosity> getSupportedVerbosities() {
  4561. return { Verbosity::Normal };
  4562. }
  4563. ~StreamingReporterBase() override = default;
  4564. void noMatchingTestCases(std::string const&) override {}
  4565. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4566. currentTestRunInfo = _testRunInfo;
  4567. }
  4568. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4569. currentGroupInfo = _groupInfo;
  4570. }
  4571. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4572. currentTestCaseInfo = _testInfo;
  4573. }
  4574. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4575. m_sectionStack.push_back(_sectionInfo);
  4576. }
  4577. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4578. m_sectionStack.pop_back();
  4579. }
  4580. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4581. currentTestCaseInfo.reset();
  4582. }
  4583. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4584. currentGroupInfo.reset();
  4585. }
  4586. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4587. currentTestCaseInfo.reset();
  4588. currentGroupInfo.reset();
  4589. currentTestRunInfo.reset();
  4590. }
  4591. void skipTest(TestCaseInfo const&) override {
  4592. // Don't do anything with this by default.
  4593. // It can optionally be overridden in the derived class.
  4594. }
  4595. IConfigPtr m_config;
  4596. std::ostream& stream;
  4597. LazyStat<TestRunInfo> currentTestRunInfo;
  4598. LazyStat<GroupInfo> currentGroupInfo;
  4599. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4600. std::vector<SectionInfo> m_sectionStack;
  4601. ReporterPreferences m_reporterPrefs;
  4602. };
  4603. template<typename DerivedT>
  4604. struct CumulativeReporterBase : IStreamingReporter {
  4605. template<typename T, typename ChildNodeT>
  4606. struct Node {
  4607. explicit Node( T const& _value ) : value( _value ) {}
  4608. virtual ~Node() {}
  4609. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4610. T value;
  4611. ChildNodes children;
  4612. };
  4613. struct SectionNode {
  4614. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4615. virtual ~SectionNode() = default;
  4616. bool operator == (SectionNode const& other) const {
  4617. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4618. }
  4619. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4620. return operator==(*other);
  4621. }
  4622. SectionStats stats;
  4623. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4624. using Assertions = std::vector<AssertionStats>;
  4625. ChildSections childSections;
  4626. Assertions assertions;
  4627. std::string stdOut;
  4628. std::string stdErr;
  4629. };
  4630. struct BySectionInfo {
  4631. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4632. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4633. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4634. return ((node->stats.sectionInfo.name == m_other.name) &&
  4635. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4636. }
  4637. void operator=(BySectionInfo const&) = delete;
  4638. private:
  4639. SectionInfo const& m_other;
  4640. };
  4641. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4642. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4643. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4644. CumulativeReporterBase( ReporterConfig const& _config )
  4645. : m_config( _config.fullConfig() ),
  4646. stream( _config.stream() )
  4647. {
  4648. m_reporterPrefs.shouldRedirectStdOut = false;
  4649. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4650. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4651. }
  4652. ~CumulativeReporterBase() override = default;
  4653. ReporterPreferences getPreferences() const override {
  4654. return m_reporterPrefs;
  4655. }
  4656. static std::set<Verbosity> getSupportedVerbosities() {
  4657. return { Verbosity::Normal };
  4658. }
  4659. void testRunStarting( TestRunInfo const& ) override {}
  4660. void testGroupStarting( GroupInfo const& ) override {}
  4661. void testCaseStarting( TestCaseInfo const& ) override {}
  4662. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4663. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4664. std::shared_ptr<SectionNode> node;
  4665. if( m_sectionStack.empty() ) {
  4666. if( !m_rootSection )
  4667. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4668. node = m_rootSection;
  4669. }
  4670. else {
  4671. SectionNode& parentNode = *m_sectionStack.back();
  4672. auto it =
  4673. std::find_if( parentNode.childSections.begin(),
  4674. parentNode.childSections.end(),
  4675. BySectionInfo( sectionInfo ) );
  4676. if( it == parentNode.childSections.end() ) {
  4677. node = std::make_shared<SectionNode>( incompleteStats );
  4678. parentNode.childSections.push_back( node );
  4679. }
  4680. else
  4681. node = *it;
  4682. }
  4683. m_sectionStack.push_back( node );
  4684. m_deepestSection = std::move(node);
  4685. }
  4686. void assertionStarting(AssertionInfo const&) override {}
  4687. bool assertionEnded(AssertionStats const& assertionStats) override {
  4688. assert(!m_sectionStack.empty());
  4689. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4690. // which getExpandedExpression() calls to build the expression string.
  4691. // Our section stack copy of the assertionResult will likely outlive the
  4692. // temporary, so it must be expanded or discarded now to avoid calling
  4693. // a destroyed object later.
  4694. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4695. SectionNode& sectionNode = *m_sectionStack.back();
  4696. sectionNode.assertions.push_back(assertionStats);
  4697. return true;
  4698. }
  4699. void sectionEnded(SectionStats const& sectionStats) override {
  4700. assert(!m_sectionStack.empty());
  4701. SectionNode& node = *m_sectionStack.back();
  4702. node.stats = sectionStats;
  4703. m_sectionStack.pop_back();
  4704. }
  4705. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4706. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4707. assert(m_sectionStack.size() == 0);
  4708. node->children.push_back(m_rootSection);
  4709. m_testCases.push_back(node);
  4710. m_rootSection.reset();
  4711. assert(m_deepestSection);
  4712. m_deepestSection->stdOut = testCaseStats.stdOut;
  4713. m_deepestSection->stdErr = testCaseStats.stdErr;
  4714. }
  4715. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4716. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4717. node->children.swap(m_testCases);
  4718. m_testGroups.push_back(node);
  4719. }
  4720. void testRunEnded(TestRunStats const& testRunStats) override {
  4721. auto node = std::make_shared<TestRunNode>(testRunStats);
  4722. node->children.swap(m_testGroups);
  4723. m_testRuns.push_back(node);
  4724. testRunEndedCumulative();
  4725. }
  4726. virtual void testRunEndedCumulative() = 0;
  4727. void skipTest(TestCaseInfo const&) override {}
  4728. IConfigPtr m_config;
  4729. std::ostream& stream;
  4730. std::vector<AssertionStats> m_assertions;
  4731. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4732. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4733. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4734. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4735. std::shared_ptr<SectionNode> m_rootSection;
  4736. std::shared_ptr<SectionNode> m_deepestSection;
  4737. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4738. ReporterPreferences m_reporterPrefs;
  4739. };
  4740. template<char C>
  4741. char const* getLineOfChars() {
  4742. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4743. if( !*line ) {
  4744. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4745. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4746. }
  4747. return line;
  4748. }
  4749. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4750. TestEventListenerBase( ReporterConfig const& _config );
  4751. static std::set<Verbosity> getSupportedVerbosities();
  4752. void assertionStarting(AssertionInfo const&) override;
  4753. bool assertionEnded(AssertionStats const&) override;
  4754. };
  4755. } // end namespace Catch
  4756. // end catch_reporter_bases.hpp
  4757. // start catch_console_colour.h
  4758. namespace Catch {
  4759. struct Colour {
  4760. enum Code {
  4761. None = 0,
  4762. White,
  4763. Red,
  4764. Green,
  4765. Blue,
  4766. Cyan,
  4767. Yellow,
  4768. Grey,
  4769. Bright = 0x10,
  4770. BrightRed = Bright | Red,
  4771. BrightGreen = Bright | Green,
  4772. LightGrey = Bright | Grey,
  4773. BrightWhite = Bright | White,
  4774. BrightYellow = Bright | Yellow,
  4775. // By intention
  4776. FileName = LightGrey,
  4777. Warning = BrightYellow,
  4778. ResultError = BrightRed,
  4779. ResultSuccess = BrightGreen,
  4780. ResultExpectedFailure = Warning,
  4781. Error = BrightRed,
  4782. Success = Green,
  4783. OriginalExpression = Cyan,
  4784. ReconstructedExpression = BrightYellow,
  4785. SecondaryText = LightGrey,
  4786. Headers = White
  4787. };
  4788. // Use constructed object for RAII guard
  4789. Colour( Code _colourCode );
  4790. Colour( Colour&& other ) noexcept;
  4791. Colour& operator=( Colour&& other ) noexcept;
  4792. ~Colour();
  4793. // Use static method for one-shot changes
  4794. static void use( Code _colourCode );
  4795. private:
  4796. bool m_moved = false;
  4797. };
  4798. std::ostream& operator << ( std::ostream& os, Colour const& );
  4799. } // end namespace Catch
  4800. // end catch_console_colour.h
  4801. // start catch_reporter_registrars.hpp
  4802. namespace Catch {
  4803. template<typename T>
  4804. class ReporterRegistrar {
  4805. class ReporterFactory : public IReporterFactory {
  4806. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4807. return std::unique_ptr<T>( new T( config ) );
  4808. }
  4809. std::string getDescription() const override {
  4810. return T::getDescription();
  4811. }
  4812. };
  4813. public:
  4814. explicit ReporterRegistrar( std::string const& name ) {
  4815. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4816. }
  4817. };
  4818. template<typename T>
  4819. class ListenerRegistrar {
  4820. class ListenerFactory : public IReporterFactory {
  4821. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4822. return std::unique_ptr<T>( new T( config ) );
  4823. }
  4824. std::string getDescription() const override {
  4825. return std::string();
  4826. }
  4827. };
  4828. public:
  4829. ListenerRegistrar() {
  4830. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4831. }
  4832. };
  4833. }
  4834. #if !defined(CATCH_CONFIG_DISABLE)
  4835. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4836. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4837. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4838. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4839. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4840. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4841. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4842. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4843. #else // CATCH_CONFIG_DISABLE
  4844. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4845. #define CATCH_REGISTER_LISTENER(listenerType)
  4846. #endif // CATCH_CONFIG_DISABLE
  4847. // end catch_reporter_registrars.hpp
  4848. // Allow users to base their work off existing reporters
  4849. // start catch_reporter_compact.h
  4850. namespace Catch {
  4851. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4852. using StreamingReporterBase::StreamingReporterBase;
  4853. ~CompactReporter() override;
  4854. static std::string getDescription();
  4855. ReporterPreferences getPreferences() const override;
  4856. void noMatchingTestCases(std::string const& spec) override;
  4857. void assertionStarting(AssertionInfo const&) override;
  4858. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4859. void sectionEnded(SectionStats const& _sectionStats) override;
  4860. void testRunEnded(TestRunStats const& _testRunStats) override;
  4861. };
  4862. } // end namespace Catch
  4863. // end catch_reporter_compact.h
  4864. // start catch_reporter_console.h
  4865. #if defined(_MSC_VER)
  4866. #pragma warning(push)
  4867. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4868. // Note that 4062 (not all labels are handled
  4869. // and default is missing) is enabled
  4870. #endif
  4871. namespace Catch {
  4872. // Fwd decls
  4873. struct SummaryColumn;
  4874. class TablePrinter;
  4875. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4876. std::unique_ptr<TablePrinter> m_tablePrinter;
  4877. ConsoleReporter(ReporterConfig const& config);
  4878. ~ConsoleReporter() override;
  4879. static std::string getDescription();
  4880. void noMatchingTestCases(std::string const& spec) override;
  4881. void assertionStarting(AssertionInfo const&) override;
  4882. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4883. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4884. void sectionEnded(SectionStats const& _sectionStats) override;
  4885. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4886. void benchmarkPreparing(std::string const& name) override;
  4887. void benchmarkStarting(BenchmarkInfo const& info) override;
  4888. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  4889. void benchmarkFailed(std::string const& error) override;
  4890. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4891. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4892. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4893. void testRunEnded(TestRunStats const& _testRunStats) override;
  4894. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4895. private:
  4896. void lazyPrint();
  4897. void lazyPrintWithoutClosingBenchmarkTable();
  4898. void lazyPrintRunInfo();
  4899. void lazyPrintGroupInfo();
  4900. void printTestCaseAndSectionHeader();
  4901. void printClosedHeader(std::string const& _name);
  4902. void printOpenHeader(std::string const& _name);
  4903. // if string has a : in first line will set indent to follow it on
  4904. // subsequent lines
  4905. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4906. void printTotals(Totals const& totals);
  4907. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4908. void printTotalsDivider(Totals const& totals);
  4909. void printSummaryDivider();
  4910. void printTestFilters();
  4911. private:
  4912. bool m_headerPrinted = false;
  4913. };
  4914. } // end namespace Catch
  4915. #if defined(_MSC_VER)
  4916. #pragma warning(pop)
  4917. #endif
  4918. // end catch_reporter_console.h
  4919. // start catch_reporter_junit.h
  4920. // start catch_xmlwriter.h
  4921. #include <vector>
  4922. namespace Catch {
  4923. class XmlEncode {
  4924. public:
  4925. enum ForWhat { ForTextNodes, ForAttributes };
  4926. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4927. void encodeTo( std::ostream& os ) const;
  4928. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4929. private:
  4930. std::string m_str;
  4931. ForWhat m_forWhat;
  4932. };
  4933. class XmlWriter {
  4934. public:
  4935. class ScopedElement {
  4936. public:
  4937. ScopedElement( XmlWriter* writer );
  4938. ScopedElement( ScopedElement&& other ) noexcept;
  4939. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4940. ~ScopedElement();
  4941. ScopedElement& writeText( std::string const& text, bool indent = true );
  4942. template<typename T>
  4943. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4944. m_writer->writeAttribute( name, attribute );
  4945. return *this;
  4946. }
  4947. private:
  4948. mutable XmlWriter* m_writer = nullptr;
  4949. };
  4950. XmlWriter( std::ostream& os = Catch::cout() );
  4951. ~XmlWriter();
  4952. XmlWriter( XmlWriter const& ) = delete;
  4953. XmlWriter& operator=( XmlWriter const& ) = delete;
  4954. XmlWriter& startElement( std::string const& name );
  4955. ScopedElement scopedElement( std::string const& name );
  4956. XmlWriter& endElement();
  4957. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4958. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4959. template<typename T>
  4960. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4961. ReusableStringStream rss;
  4962. rss << attribute;
  4963. return writeAttribute( name, rss.str() );
  4964. }
  4965. XmlWriter& writeText( std::string const& text, bool indent = true );
  4966. XmlWriter& writeComment( std::string const& text );
  4967. void writeStylesheetRef( std::string const& url );
  4968. XmlWriter& writeBlankLine();
  4969. void ensureTagClosed();
  4970. private:
  4971. void writeDeclaration();
  4972. void newlineIfNecessary();
  4973. bool m_tagIsOpen = false;
  4974. bool m_needsNewline = false;
  4975. std::vector<std::string> m_tags;
  4976. std::string m_indent;
  4977. std::ostream& m_os;
  4978. };
  4979. }
  4980. // end catch_xmlwriter.h
  4981. namespace Catch {
  4982. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4983. public:
  4984. JunitReporter(ReporterConfig const& _config);
  4985. ~JunitReporter() override;
  4986. static std::string getDescription();
  4987. void noMatchingTestCases(std::string const& /*spec*/) override;
  4988. void testRunStarting(TestRunInfo const& runInfo) override;
  4989. void testGroupStarting(GroupInfo const& groupInfo) override;
  4990. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4991. bool assertionEnded(AssertionStats const& assertionStats) override;
  4992. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4993. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4994. void testRunEndedCumulative() override;
  4995. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4996. void writeTestCase(TestCaseNode const& testCaseNode);
  4997. void writeSection(std::string const& className,
  4998. std::string const& rootName,
  4999. SectionNode const& sectionNode);
  5000. void writeAssertions(SectionNode const& sectionNode);
  5001. void writeAssertion(AssertionStats const& stats);
  5002. XmlWriter xml;
  5003. Timer suiteTimer;
  5004. std::string stdOutForSuite;
  5005. std::string stdErrForSuite;
  5006. unsigned int unexpectedExceptions = 0;
  5007. bool m_okToFail = false;
  5008. };
  5009. } // end namespace Catch
  5010. // end catch_reporter_junit.h
  5011. // start catch_reporter_xml.h
  5012. namespace Catch {
  5013. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5014. public:
  5015. XmlReporter(ReporterConfig const& _config);
  5016. ~XmlReporter() override;
  5017. static std::string getDescription();
  5018. virtual std::string getStylesheetRef() const;
  5019. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5020. public: // StreamingReporterBase
  5021. void noMatchingTestCases(std::string const& s) override;
  5022. void testRunStarting(TestRunInfo const& testInfo) override;
  5023. void testGroupStarting(GroupInfo const& groupInfo) override;
  5024. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5025. void sectionStarting(SectionInfo const& sectionInfo) override;
  5026. void assertionStarting(AssertionInfo const&) override;
  5027. bool assertionEnded(AssertionStats const& assertionStats) override;
  5028. void sectionEnded(SectionStats const& sectionStats) override;
  5029. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5030. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5031. void testRunEnded(TestRunStats const& testRunStats) override;
  5032. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5033. void benchmarkPreparing(std::string const& name) override;
  5034. void benchmarkStarting(BenchmarkInfo const&) override;
  5035. void benchmarkEnded(BenchmarkStats<> const&) override;
  5036. void benchmarkFailed(std::string const&) override;
  5037. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5038. private:
  5039. Timer m_testCaseTimer;
  5040. XmlWriter m_xml;
  5041. int m_sectionDepth = 0;
  5042. };
  5043. } // end namespace Catch
  5044. // end catch_reporter_xml.h
  5045. // end catch_external_interfaces.h
  5046. #endif
  5047. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5048. // start catch_benchmark.hpp
  5049. // Benchmark
  5050. // start catch_chronometer.hpp
  5051. // User-facing chronometer
  5052. // start catch_clock.hpp
  5053. // Clocks
  5054. #include <chrono>
  5055. #include <ratio>
  5056. namespace Catch {
  5057. namespace Benchmark {
  5058. template <typename Clock>
  5059. using ClockDuration = typename Clock::duration;
  5060. template <typename Clock>
  5061. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5062. template <typename Clock>
  5063. using TimePoint = typename Clock::time_point;
  5064. using default_clock = std::chrono::steady_clock;
  5065. template <typename Clock>
  5066. struct now {
  5067. TimePoint<Clock> operator()() const {
  5068. return Clock::now();
  5069. }
  5070. };
  5071. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5072. } // namespace Benchmark
  5073. } // namespace Catch
  5074. // end catch_clock.hpp
  5075. // start catch_optimizer.hpp
  5076. // Hinting the optimizer
  5077. #if defined(_MSC_VER)
  5078. # include <atomic> // atomic_thread_fence
  5079. #endif
  5080. namespace Catch {
  5081. namespace Benchmark {
  5082. #if defined(__GNUC__) || defined(__clang__)
  5083. template <typename T>
  5084. inline void keep_memory(T* p) {
  5085. asm volatile("" : : "g"(p) : "memory");
  5086. }
  5087. inline void keep_memory() {
  5088. asm volatile("" : : : "memory");
  5089. }
  5090. namespace Detail {
  5091. inline void optimizer_barrier() { keep_memory(); }
  5092. } // namespace Detail
  5093. #elif defined(_MSC_VER)
  5094. #pragma optimize("", off)
  5095. template <typename T>
  5096. inline void keep_memory(T* p) {
  5097. // thanks @milleniumbug
  5098. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5099. }
  5100. // TODO equivalent keep_memory()
  5101. #pragma optimize("", on)
  5102. namespace Detail {
  5103. inline void optimizer_barrier() {
  5104. std::atomic_thread_fence(std::memory_order_seq_cst);
  5105. }
  5106. } // namespace Detail
  5107. #endif
  5108. template <typename T>
  5109. inline void deoptimize_value(T&& x) {
  5110. keep_memory(&x);
  5111. }
  5112. template <typename Fn, typename... Args>
  5113. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5114. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5115. }
  5116. template <typename Fn, typename... Args>
  5117. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5118. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5119. }
  5120. } // namespace Benchmark
  5121. } // namespace Catch
  5122. // end catch_optimizer.hpp
  5123. // start catch_complete_invoke.hpp
  5124. // Invoke with a special case for void
  5125. #include <type_traits>
  5126. #include <utility>
  5127. namespace Catch {
  5128. namespace Benchmark {
  5129. namespace Detail {
  5130. template <typename T>
  5131. struct CompleteType { using type = T; };
  5132. template <>
  5133. struct CompleteType<void> { struct type {}; };
  5134. template <typename T>
  5135. using CompleteType_t = typename CompleteType<T>::type;
  5136. template <typename Result>
  5137. struct CompleteInvoker {
  5138. template <typename Fun, typename... Args>
  5139. static Result invoke(Fun&& fun, Args&&... args) {
  5140. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5141. }
  5142. };
  5143. template <>
  5144. struct CompleteInvoker<void> {
  5145. template <typename Fun, typename... Args>
  5146. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5147. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5148. return {};
  5149. }
  5150. };
  5151. template <typename Sig>
  5152. using ResultOf_t = typename std::result_of<Sig>::type;
  5153. // invoke and not return void :(
  5154. template <typename Fun, typename... Args>
  5155. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5156. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5157. }
  5158. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5159. } // namespace Detail
  5160. template <typename Fun>
  5161. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5162. CATCH_TRY{
  5163. return Detail::complete_invoke(std::forward<Fun>(fun));
  5164. } CATCH_CATCH_ALL{
  5165. getResultCapture().benchmarkFailed(translateActiveException());
  5166. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5167. }
  5168. }
  5169. } // namespace Benchmark
  5170. } // namespace Catch
  5171. // end catch_complete_invoke.hpp
  5172. namespace Catch {
  5173. namespace Benchmark {
  5174. namespace Detail {
  5175. struct ChronometerConcept {
  5176. virtual void start() = 0;
  5177. virtual void finish() = 0;
  5178. virtual ~ChronometerConcept() = default;
  5179. };
  5180. template <typename Clock>
  5181. struct ChronometerModel final : public ChronometerConcept {
  5182. void start() override { started = Clock::now(); }
  5183. void finish() override { finished = Clock::now(); }
  5184. ClockDuration<Clock> elapsed() const { return finished - started; }
  5185. TimePoint<Clock> started;
  5186. TimePoint<Clock> finished;
  5187. };
  5188. } // namespace Detail
  5189. struct Chronometer {
  5190. public:
  5191. template <typename Fun>
  5192. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5193. int runs() const { return k; }
  5194. Chronometer(Detail::ChronometerConcept& meter, int k)
  5195. : impl(&meter)
  5196. , k(k) {}
  5197. private:
  5198. template <typename Fun>
  5199. void measure(Fun&& fun, std::false_type) {
  5200. measure([&fun](int) { return fun(); }, std::true_type());
  5201. }
  5202. template <typename Fun>
  5203. void measure(Fun&& fun, std::true_type) {
  5204. Detail::optimizer_barrier();
  5205. impl->start();
  5206. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5207. impl->finish();
  5208. Detail::optimizer_barrier();
  5209. }
  5210. Detail::ChronometerConcept* impl;
  5211. int k;
  5212. };
  5213. } // namespace Benchmark
  5214. } // namespace Catch
  5215. // end catch_chronometer.hpp
  5216. // start catch_environment.hpp
  5217. // Environment information
  5218. namespace Catch {
  5219. namespace Benchmark {
  5220. template <typename Duration>
  5221. struct EnvironmentEstimate {
  5222. Duration mean;
  5223. OutlierClassification outliers;
  5224. template <typename Duration2>
  5225. operator EnvironmentEstimate<Duration2>() const {
  5226. return { mean, outliers };
  5227. }
  5228. };
  5229. template <typename Clock>
  5230. struct Environment {
  5231. using clock_type = Clock;
  5232. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5233. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5234. };
  5235. } // namespace Benchmark
  5236. } // namespace Catch
  5237. // end catch_environment.hpp
  5238. // start catch_execution_plan.hpp
  5239. // Execution plan
  5240. // start catch_benchmark_function.hpp
  5241. // Dumb std::function implementation for consistent call overhead
  5242. #include <cassert>
  5243. #include <type_traits>
  5244. #include <utility>
  5245. #include <memory>
  5246. namespace Catch {
  5247. namespace Benchmark {
  5248. namespace Detail {
  5249. template <typename T>
  5250. using Decay = typename std::decay<T>::type;
  5251. template <typename T, typename U>
  5252. struct is_related
  5253. : std::is_same<Decay<T>, Decay<U>> {};
  5254. /// We need to reinvent std::function because every piece of code that might add overhead
  5255. /// in a measurement context needs to have consistent performance characteristics so that we
  5256. /// can account for it in the measurement.
  5257. /// Implementations of std::function with optimizations that aren't always applicable, like
  5258. /// small buffer optimizations, are not uncommon.
  5259. /// This is effectively an implementation of std::function without any such optimizations;
  5260. /// it may be slow, but it is consistently slow.
  5261. struct BenchmarkFunction {
  5262. private:
  5263. struct callable {
  5264. virtual void call(Chronometer meter) const = 0;
  5265. virtual callable* clone() const = 0;
  5266. virtual ~callable() = default;
  5267. };
  5268. template <typename Fun>
  5269. struct model : public callable {
  5270. model(Fun&& fun) : fun(std::move(fun)) {}
  5271. model(Fun const& fun) : fun(fun) {}
  5272. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5273. void call(Chronometer meter) const override {
  5274. call(meter, is_callable<Fun(Chronometer)>());
  5275. }
  5276. void call(Chronometer meter, std::true_type) const {
  5277. fun(meter);
  5278. }
  5279. void call(Chronometer meter, std::false_type) const {
  5280. meter.measure(fun);
  5281. }
  5282. Fun fun;
  5283. };
  5284. struct do_nothing { void operator()() const {} };
  5285. template <typename T>
  5286. BenchmarkFunction(model<T>* c) : f(c) {}
  5287. public:
  5288. BenchmarkFunction()
  5289. : f(new model<do_nothing>{ {} }) {}
  5290. template <typename Fun,
  5291. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5292. BenchmarkFunction(Fun&& fun)
  5293. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5294. BenchmarkFunction(BenchmarkFunction&& that)
  5295. : f(std::move(that.f)) {}
  5296. BenchmarkFunction(BenchmarkFunction const& that)
  5297. : f(that.f->clone()) {}
  5298. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5299. f = std::move(that.f);
  5300. return *this;
  5301. }
  5302. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5303. f.reset(that.f->clone());
  5304. return *this;
  5305. }
  5306. void operator()(Chronometer meter) const { f->call(meter); }
  5307. private:
  5308. std::unique_ptr<callable> f;
  5309. };
  5310. } // namespace Detail
  5311. } // namespace Benchmark
  5312. } // namespace Catch
  5313. // end catch_benchmark_function.hpp
  5314. // start catch_repeat.hpp
  5315. // repeat algorithm
  5316. #include <type_traits>
  5317. #include <utility>
  5318. namespace Catch {
  5319. namespace Benchmark {
  5320. namespace Detail {
  5321. template <typename Fun>
  5322. struct repeater {
  5323. void operator()(int k) const {
  5324. for (int i = 0; i < k; ++i) {
  5325. fun();
  5326. }
  5327. }
  5328. Fun fun;
  5329. };
  5330. template <typename Fun>
  5331. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5332. return { std::forward<Fun>(fun) };
  5333. }
  5334. } // namespace Detail
  5335. } // namespace Benchmark
  5336. } // namespace Catch
  5337. // end catch_repeat.hpp
  5338. // start catch_run_for_at_least.hpp
  5339. // Run a function for a minimum amount of time
  5340. // start catch_measure.hpp
  5341. // Measure
  5342. // start catch_timing.hpp
  5343. // Timing
  5344. #include <tuple>
  5345. #include <type_traits>
  5346. namespace Catch {
  5347. namespace Benchmark {
  5348. template <typename Duration, typename Result>
  5349. struct Timing {
  5350. Duration elapsed;
  5351. Result result;
  5352. int iterations;
  5353. };
  5354. template <typename Clock, typename Sig>
  5355. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5356. } // namespace Benchmark
  5357. } // namespace Catch
  5358. // end catch_timing.hpp
  5359. #include <utility>
  5360. namespace Catch {
  5361. namespace Benchmark {
  5362. namespace Detail {
  5363. template <typename Clock, typename Fun, typename... Args>
  5364. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5365. auto start = Clock::now();
  5366. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5367. auto end = Clock::now();
  5368. auto delta = end - start;
  5369. return { delta, std::forward<decltype(r)>(r), 1 };
  5370. }
  5371. } // namespace Detail
  5372. } // namespace Benchmark
  5373. } // namespace Catch
  5374. // end catch_measure.hpp
  5375. #include <utility>
  5376. #include <type_traits>
  5377. namespace Catch {
  5378. namespace Benchmark {
  5379. namespace Detail {
  5380. template <typename Clock, typename Fun>
  5381. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5382. return Detail::measure<Clock>(fun, iters);
  5383. }
  5384. template <typename Clock, typename Fun>
  5385. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5386. Detail::ChronometerModel<Clock> meter;
  5387. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5388. return { meter.elapsed(), std::move(result), iters };
  5389. }
  5390. template <typename Clock, typename Fun>
  5391. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5392. struct optimized_away_error : std::exception {
  5393. const char* what() const noexcept override {
  5394. return "could not measure benchmark, maybe it was optimized away";
  5395. }
  5396. };
  5397. template <typename Clock, typename Fun>
  5398. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5399. auto iters = seed;
  5400. while (iters < (1 << 30)) {
  5401. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5402. if (Timing.elapsed >= how_long) {
  5403. return { Timing.elapsed, std::move(Timing.result), iters };
  5404. }
  5405. iters *= 2;
  5406. }
  5407. throw optimized_away_error{};
  5408. }
  5409. } // namespace Detail
  5410. } // namespace Benchmark
  5411. } // namespace Catch
  5412. // end catch_run_for_at_least.hpp
  5413. #include <algorithm>
  5414. namespace Catch {
  5415. namespace Benchmark {
  5416. template <typename Duration>
  5417. struct ExecutionPlan {
  5418. int iterations_per_sample;
  5419. Duration estimated_duration;
  5420. Detail::BenchmarkFunction benchmark;
  5421. Duration warmup_time;
  5422. int warmup_iterations;
  5423. template <typename Duration2>
  5424. operator ExecutionPlan<Duration2>() const {
  5425. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5426. }
  5427. template <typename Clock>
  5428. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5429. // warmup a bit
  5430. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5431. std::vector<FloatDuration<Clock>> times;
  5432. times.reserve(cfg.benchmarkSamples());
  5433. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5434. Detail::ChronometerModel<Clock> model;
  5435. this->benchmark(Chronometer(model, iterations_per_sample));
  5436. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5437. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5438. return sample_time / iterations_per_sample;
  5439. });
  5440. return times;
  5441. }
  5442. };
  5443. } // namespace Benchmark
  5444. } // namespace Catch
  5445. // end catch_execution_plan.hpp
  5446. // start catch_estimate_clock.hpp
  5447. // Environment measurement
  5448. // start catch_stats.hpp
  5449. // Statistical analysis tools
  5450. #include <algorithm>
  5451. #include <functional>
  5452. #include <vector>
  5453. #include <numeric>
  5454. #include <tuple>
  5455. #include <cmath>
  5456. #include <utility>
  5457. #include <cstddef>
  5458. namespace Catch {
  5459. namespace Benchmark {
  5460. namespace Detail {
  5461. using sample = std::vector<double>;
  5462. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5463. template <typename Iterator>
  5464. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5465. std::vector<double> copy(first, last);
  5466. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5467. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5468. auto iqr = q3 - q1;
  5469. auto los = q1 - (iqr * 3.);
  5470. auto lom = q1 - (iqr * 1.5);
  5471. auto him = q3 + (iqr * 1.5);
  5472. auto his = q3 + (iqr * 3.);
  5473. OutlierClassification o;
  5474. for (; first != last; ++first) {
  5475. auto&& t = *first;
  5476. if (t < los) ++o.low_severe;
  5477. else if (t < lom) ++o.low_mild;
  5478. else if (t > his) ++o.high_severe;
  5479. else if (t > him) ++o.high_mild;
  5480. ++o.samples_seen;
  5481. }
  5482. return o;
  5483. }
  5484. template <typename Iterator>
  5485. double mean(Iterator first, Iterator last) {
  5486. auto count = last - first;
  5487. double sum = std::accumulate(first, last, 0.);
  5488. return sum / count;
  5489. }
  5490. template <typename URng, typename Iterator, typename Estimator>
  5491. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5492. auto n = last - first;
  5493. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5494. sample out;
  5495. out.reserve(resamples);
  5496. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5497. std::vector<double> resampled;
  5498. resampled.reserve(n);
  5499. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5500. return estimator(resampled.begin(), resampled.end());
  5501. });
  5502. std::sort(out.begin(), out.end());
  5503. return out;
  5504. }
  5505. template <typename Estimator, typename Iterator>
  5506. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5507. auto n = last - first;
  5508. auto second = std::next(first);
  5509. sample results;
  5510. results.reserve(n);
  5511. for (auto it = first; it != last; ++it) {
  5512. std::iter_swap(it, first);
  5513. results.push_back(estimator(second, last));
  5514. }
  5515. return results;
  5516. }
  5517. inline double normal_cdf(double x) {
  5518. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5519. }
  5520. double erfc_inv(double x);
  5521. double normal_quantile(double p);
  5522. template <typename Iterator, typename Estimator>
  5523. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5524. auto n_samples = last - first;
  5525. double point = estimator(first, last);
  5526. // Degenerate case with a single sample
  5527. if (n_samples == 1) return { point, point, point, confidence_level };
  5528. sample jack = jackknife(estimator, first, last);
  5529. double jack_mean = mean(jack.begin(), jack.end());
  5530. double sum_squares, sum_cubes;
  5531. 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> {
  5532. auto d = jack_mean - x;
  5533. auto d2 = d * d;
  5534. auto d3 = d2 * d;
  5535. return { sqcb.first + d2, sqcb.second + d3 };
  5536. });
  5537. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5538. int n = static_cast<int>(resample.size());
  5539. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5540. // degenerate case with uniform samples
  5541. if (prob_n == 0) return { point, point, point, confidence_level };
  5542. double bias = normal_quantile(prob_n);
  5543. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5544. auto cumn = [n](double x) -> int {
  5545. return std::lround(normal_cdf(x) * n); };
  5546. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5547. double b1 = bias + z1;
  5548. double b2 = bias - z1;
  5549. double a1 = a(b1);
  5550. double a2 = a(b2);
  5551. auto lo = std::max(cumn(a1), 0);
  5552. auto hi = std::min(cumn(a2), n - 1);
  5553. return { point, resample[lo], resample[hi], confidence_level };
  5554. }
  5555. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5556. struct bootstrap_analysis {
  5557. Estimate<double> mean;
  5558. Estimate<double> standard_deviation;
  5559. double outlier_variance;
  5560. };
  5561. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5562. } // namespace Detail
  5563. } // namespace Benchmark
  5564. } // namespace Catch
  5565. // end catch_stats.hpp
  5566. #include <algorithm>
  5567. #include <iterator>
  5568. #include <tuple>
  5569. #include <vector>
  5570. #include <cmath>
  5571. namespace Catch {
  5572. namespace Benchmark {
  5573. namespace Detail {
  5574. template <typename Clock>
  5575. std::vector<double> resolution(int k) {
  5576. std::vector<TimePoint<Clock>> times;
  5577. times.reserve(k + 1);
  5578. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5579. std::vector<double> deltas;
  5580. deltas.reserve(k);
  5581. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5582. std::back_inserter(deltas),
  5583. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5584. return deltas;
  5585. }
  5586. const auto warmup_iterations = 10000;
  5587. const auto warmup_time = std::chrono::milliseconds(100);
  5588. const auto minimum_ticks = 1000;
  5589. const auto warmup_seed = 10000;
  5590. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5591. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5592. const auto clock_cost_estimation_tick_limit = 100000;
  5593. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5594. const auto clock_cost_estimation_iterations = 10000;
  5595. template <typename Clock>
  5596. int warmup() {
  5597. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5598. .iterations;
  5599. }
  5600. template <typename Clock>
  5601. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5602. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5603. .result;
  5604. return {
  5605. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5606. classify_outliers(r.begin(), r.end()),
  5607. };
  5608. }
  5609. template <typename Clock>
  5610. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5611. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5612. auto time_clock = [](int k) {
  5613. return Detail::measure<Clock>([k] {
  5614. for (int i = 0; i < k; ++i) {
  5615. volatile auto ignored = Clock::now();
  5616. (void)ignored;
  5617. }
  5618. }).elapsed;
  5619. };
  5620. time_clock(1);
  5621. int iters = clock_cost_estimation_iterations;
  5622. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5623. std::vector<double> times;
  5624. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5625. times.reserve(nsamples);
  5626. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5627. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5628. });
  5629. return {
  5630. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5631. classify_outliers(times.begin(), times.end()),
  5632. };
  5633. }
  5634. template <typename Clock>
  5635. Environment<FloatDuration<Clock>> measure_environment() {
  5636. static Environment<FloatDuration<Clock>>* env = nullptr;
  5637. if (env) {
  5638. return *env;
  5639. }
  5640. auto iters = Detail::warmup<Clock>();
  5641. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5642. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5643. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5644. return *env;
  5645. }
  5646. } // namespace Detail
  5647. } // namespace Benchmark
  5648. } // namespace Catch
  5649. // end catch_estimate_clock.hpp
  5650. // start catch_analyse.hpp
  5651. // Run and analyse one benchmark
  5652. // start catch_sample_analysis.hpp
  5653. // Benchmark results
  5654. #include <algorithm>
  5655. #include <vector>
  5656. #include <string>
  5657. #include <iterator>
  5658. namespace Catch {
  5659. namespace Benchmark {
  5660. template <typename Duration>
  5661. struct SampleAnalysis {
  5662. std::vector<Duration> samples;
  5663. Estimate<Duration> mean;
  5664. Estimate<Duration> standard_deviation;
  5665. OutlierClassification outliers;
  5666. double outlier_variance;
  5667. template <typename Duration2>
  5668. operator SampleAnalysis<Duration2>() const {
  5669. std::vector<Duration2> samples2;
  5670. samples2.reserve(samples.size());
  5671. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5672. return {
  5673. std::move(samples2),
  5674. mean,
  5675. standard_deviation,
  5676. outliers,
  5677. outlier_variance,
  5678. };
  5679. }
  5680. };
  5681. } // namespace Benchmark
  5682. } // namespace Catch
  5683. // end catch_sample_analysis.hpp
  5684. #include <algorithm>
  5685. #include <iterator>
  5686. #include <vector>
  5687. namespace Catch {
  5688. namespace Benchmark {
  5689. namespace Detail {
  5690. template <typename Duration, typename Iterator>
  5691. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5692. if (!cfg.benchmarkNoAnalysis()) {
  5693. std::vector<double> samples;
  5694. samples.reserve(last - first);
  5695. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5696. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5697. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5698. auto wrap_estimate = [](Estimate<double> e) {
  5699. return Estimate<Duration> {
  5700. Duration(e.point),
  5701. Duration(e.lower_bound),
  5702. Duration(e.upper_bound),
  5703. e.confidence_interval,
  5704. };
  5705. };
  5706. std::vector<Duration> samples2;
  5707. samples2.reserve(samples.size());
  5708. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5709. return {
  5710. std::move(samples2),
  5711. wrap_estimate(analysis.mean),
  5712. wrap_estimate(analysis.standard_deviation),
  5713. outliers,
  5714. analysis.outlier_variance,
  5715. };
  5716. } else {
  5717. std::vector<Duration> samples;
  5718. samples.reserve(last - first);
  5719. Duration mean = Duration(0);
  5720. int i = 0;
  5721. for (auto it = first; it < last; ++it, ++i) {
  5722. samples.push_back(Duration(*it));
  5723. mean += Duration(*it);
  5724. }
  5725. mean /= i;
  5726. return {
  5727. std::move(samples),
  5728. Estimate<Duration>{mean, mean, mean, 0.0},
  5729. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5730. OutlierClassification{},
  5731. 0.0
  5732. };
  5733. }
  5734. }
  5735. } // namespace Detail
  5736. } // namespace Benchmark
  5737. } // namespace Catch
  5738. // end catch_analyse.hpp
  5739. #include <algorithm>
  5740. #include <functional>
  5741. #include <string>
  5742. #include <vector>
  5743. #include <cmath>
  5744. namespace Catch {
  5745. namespace Benchmark {
  5746. struct Benchmark {
  5747. Benchmark(std::string &&name)
  5748. : name(std::move(name)) {}
  5749. template <class FUN>
  5750. Benchmark(std::string &&name, FUN &&func)
  5751. : fun(std::move(func)), name(std::move(name)) {}
  5752. template <typename Clock>
  5753. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5754. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5755. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  5756. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5757. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5758. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  5759. }
  5760. template <typename Clock = default_clock>
  5761. void run() {
  5762. IConfigPtr cfg = getCurrentContext().getConfig();
  5763. auto env = Detail::measure_environment<Clock>();
  5764. getResultCapture().benchmarkPreparing(name);
  5765. CATCH_TRY{
  5766. auto plan = user_code([&] {
  5767. return prepare<Clock>(*cfg, env);
  5768. });
  5769. BenchmarkInfo info {
  5770. name,
  5771. plan.estimated_duration.count(),
  5772. plan.iterations_per_sample,
  5773. cfg->benchmarkSamples(),
  5774. cfg->benchmarkResamples(),
  5775. env.clock_resolution.mean.count(),
  5776. env.clock_cost.mean.count()
  5777. };
  5778. getResultCapture().benchmarkStarting(info);
  5779. auto samples = user_code([&] {
  5780. return plan.template run<Clock>(*cfg, env);
  5781. });
  5782. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5783. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5784. getResultCapture().benchmarkEnded(stats);
  5785. } CATCH_CATCH_ALL{
  5786. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5787. std::rethrow_exception(std::current_exception());
  5788. }
  5789. }
  5790. // sets lambda to be used in fun *and* executes benchmark!
  5791. template <typename Fun,
  5792. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5793. Benchmark & operator=(Fun func) {
  5794. fun = Detail::BenchmarkFunction(func);
  5795. run();
  5796. return *this;
  5797. }
  5798. explicit operator bool() {
  5799. return true;
  5800. }
  5801. private:
  5802. Detail::BenchmarkFunction fun;
  5803. std::string name;
  5804. };
  5805. }
  5806. } // namespace Catch
  5807. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5808. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5809. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5810. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5811. BenchmarkName = [&](int benchmarkIndex)
  5812. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5813. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5814. BenchmarkName = [&]
  5815. // end catch_benchmark.hpp
  5816. #endif
  5817. #endif // ! CATCH_CONFIG_IMPL_ONLY
  5818. #ifdef CATCH_IMPL
  5819. // start catch_impl.hpp
  5820. #ifdef __clang__
  5821. #pragma clang diagnostic push
  5822. #pragma clang diagnostic ignored "-Wweak-vtables"
  5823. #endif
  5824. // Keep these here for external reporters
  5825. // start catch_test_case_tracker.h
  5826. #include <string>
  5827. #include <vector>
  5828. #include <memory>
  5829. namespace Catch {
  5830. namespace TestCaseTracking {
  5831. struct NameAndLocation {
  5832. std::string name;
  5833. SourceLineInfo location;
  5834. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  5835. };
  5836. struct ITracker;
  5837. using ITrackerPtr = std::shared_ptr<ITracker>;
  5838. struct ITracker {
  5839. virtual ~ITracker();
  5840. // static queries
  5841. virtual NameAndLocation const& nameAndLocation() const = 0;
  5842. // dynamic queries
  5843. virtual bool isComplete() const = 0; // Successfully completed or failed
  5844. virtual bool isSuccessfullyCompleted() const = 0;
  5845. virtual bool isOpen() const = 0; // Started but not complete
  5846. virtual bool hasChildren() const = 0;
  5847. virtual ITracker& parent() = 0;
  5848. // actions
  5849. virtual void close() = 0; // Successfully complete
  5850. virtual void fail() = 0;
  5851. virtual void markAsNeedingAnotherRun() = 0;
  5852. virtual void addChild( ITrackerPtr const& child ) = 0;
  5853. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  5854. virtual void openChild() = 0;
  5855. // Debug/ checking
  5856. virtual bool isSectionTracker() const = 0;
  5857. virtual bool isGeneratorTracker() const = 0;
  5858. };
  5859. class TrackerContext {
  5860. enum RunState {
  5861. NotStarted,
  5862. Executing,
  5863. CompletedCycle
  5864. };
  5865. ITrackerPtr m_rootTracker;
  5866. ITracker* m_currentTracker = nullptr;
  5867. RunState m_runState = NotStarted;
  5868. public:
  5869. ITracker& startRun();
  5870. void endRun();
  5871. void startCycle();
  5872. void completeCycle();
  5873. bool completedCycle() const;
  5874. ITracker& currentTracker();
  5875. void setCurrentTracker( ITracker* tracker );
  5876. };
  5877. class TrackerBase : public ITracker {
  5878. protected:
  5879. enum CycleState {
  5880. NotStarted,
  5881. Executing,
  5882. ExecutingChildren,
  5883. NeedsAnotherRun,
  5884. CompletedSuccessfully,
  5885. Failed
  5886. };
  5887. using Children = std::vector<ITrackerPtr>;
  5888. NameAndLocation m_nameAndLocation;
  5889. TrackerContext& m_ctx;
  5890. ITracker* m_parent;
  5891. Children m_children;
  5892. CycleState m_runState = NotStarted;
  5893. public:
  5894. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5895. NameAndLocation const& nameAndLocation() const override;
  5896. bool isComplete() const override;
  5897. bool isSuccessfullyCompleted() const override;
  5898. bool isOpen() const override;
  5899. bool hasChildren() const override;
  5900. void addChild( ITrackerPtr const& child ) override;
  5901. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  5902. ITracker& parent() override;
  5903. void openChild() override;
  5904. bool isSectionTracker() const override;
  5905. bool isGeneratorTracker() const override;
  5906. void open();
  5907. void close() override;
  5908. void fail() override;
  5909. void markAsNeedingAnotherRun() override;
  5910. private:
  5911. void moveToParent();
  5912. void moveToThis();
  5913. };
  5914. class SectionTracker : public TrackerBase {
  5915. std::vector<std::string> m_filters;
  5916. public:
  5917. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5918. bool isSectionTracker() const override;
  5919. bool isComplete() const override;
  5920. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  5921. void tryOpen();
  5922. void addInitialFilters( std::vector<std::string> const& filters );
  5923. void addNextFilters( std::vector<std::string> const& filters );
  5924. };
  5925. } // namespace TestCaseTracking
  5926. using TestCaseTracking::ITracker;
  5927. using TestCaseTracking::TrackerContext;
  5928. using TestCaseTracking::SectionTracker;
  5929. } // namespace Catch
  5930. // end catch_test_case_tracker.h
  5931. // start catch_leak_detector.h
  5932. namespace Catch {
  5933. struct LeakDetector {
  5934. LeakDetector();
  5935. ~LeakDetector();
  5936. };
  5937. }
  5938. // end catch_leak_detector.h
  5939. // Cpp files will be included in the single-header file here
  5940. // start catch_stats.cpp
  5941. // Statistical analysis tools
  5942. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5943. #include <cassert>
  5944. #include <random>
  5945. #if defined(CATCH_CONFIG_USE_ASYNC)
  5946. #include <future>
  5947. #endif
  5948. namespace {
  5949. double erf_inv(double x) {
  5950. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  5951. double w, p;
  5952. w = -log((1.0 - x) * (1.0 + x));
  5953. if (w < 6.250000) {
  5954. w = w - 3.125000;
  5955. p = -3.6444120640178196996e-21;
  5956. p = -1.685059138182016589e-19 + p * w;
  5957. p = 1.2858480715256400167e-18 + p * w;
  5958. p = 1.115787767802518096e-17 + p * w;
  5959. p = -1.333171662854620906e-16 + p * w;
  5960. p = 2.0972767875968561637e-17 + p * w;
  5961. p = 6.6376381343583238325e-15 + p * w;
  5962. p = -4.0545662729752068639e-14 + p * w;
  5963. p = -8.1519341976054721522e-14 + p * w;
  5964. p = 2.6335093153082322977e-12 + p * w;
  5965. p = -1.2975133253453532498e-11 + p * w;
  5966. p = -5.4154120542946279317e-11 + p * w;
  5967. p = 1.051212273321532285e-09 + p * w;
  5968. p = -4.1126339803469836976e-09 + p * w;
  5969. p = -2.9070369957882005086e-08 + p * w;
  5970. p = 4.2347877827932403518e-07 + p * w;
  5971. p = -1.3654692000834678645e-06 + p * w;
  5972. p = -1.3882523362786468719e-05 + p * w;
  5973. p = 0.0001867342080340571352 + p * w;
  5974. p = -0.00074070253416626697512 + p * w;
  5975. p = -0.0060336708714301490533 + p * w;
  5976. p = 0.24015818242558961693 + p * w;
  5977. p = 1.6536545626831027356 + p * w;
  5978. } else if (w < 16.000000) {
  5979. w = sqrt(w) - 3.250000;
  5980. p = 2.2137376921775787049e-09;
  5981. p = 9.0756561938885390979e-08 + p * w;
  5982. p = -2.7517406297064545428e-07 + p * w;
  5983. p = 1.8239629214389227755e-08 + p * w;
  5984. p = 1.5027403968909827627e-06 + p * w;
  5985. p = -4.013867526981545969e-06 + p * w;
  5986. p = 2.9234449089955446044e-06 + p * w;
  5987. p = 1.2475304481671778723e-05 + p * w;
  5988. p = -4.7318229009055733981e-05 + p * w;
  5989. p = 6.8284851459573175448e-05 + p * w;
  5990. p = 2.4031110387097893999e-05 + p * w;
  5991. p = -0.0003550375203628474796 + p * w;
  5992. p = 0.00095328937973738049703 + p * w;
  5993. p = -0.0016882755560235047313 + p * w;
  5994. p = 0.0024914420961078508066 + p * w;
  5995. p = -0.0037512085075692412107 + p * w;
  5996. p = 0.005370914553590063617 + p * w;
  5997. p = 1.0052589676941592334 + p * w;
  5998. p = 3.0838856104922207635 + p * w;
  5999. } else {
  6000. w = sqrt(w) - 5.000000;
  6001. p = -2.7109920616438573243e-11;
  6002. p = -2.5556418169965252055e-10 + p * w;
  6003. p = 1.5076572693500548083e-09 + p * w;
  6004. p = -3.7894654401267369937e-09 + p * w;
  6005. p = 7.6157012080783393804e-09 + p * w;
  6006. p = -1.4960026627149240478e-08 + p * w;
  6007. p = 2.9147953450901080826e-08 + p * w;
  6008. p = -6.7711997758452339498e-08 + p * w;
  6009. p = 2.2900482228026654717e-07 + p * w;
  6010. p = -9.9298272942317002539e-07 + p * w;
  6011. p = 4.5260625972231537039e-06 + p * w;
  6012. p = -1.9681778105531670567e-05 + p * w;
  6013. p = 7.5995277030017761139e-05 + p * w;
  6014. p = -0.00021503011930044477347 + p * w;
  6015. p = -0.00013871931833623122026 + p * w;
  6016. p = 1.0103004648645343977 + p * w;
  6017. p = 4.8499064014085844221 + p * w;
  6018. }
  6019. return p * x;
  6020. }
  6021. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6022. auto m = Catch::Benchmark::Detail::mean(first, last);
  6023. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6024. double diff = b - m;
  6025. return a + diff * diff;
  6026. }) / (last - first);
  6027. return std::sqrt(variance);
  6028. }
  6029. }
  6030. namespace Catch {
  6031. namespace Benchmark {
  6032. namespace Detail {
  6033. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6034. auto count = last - first;
  6035. double idx = (count - 1) * k / static_cast<double>(q);
  6036. int j = static_cast<int>(idx);
  6037. double g = idx - j;
  6038. std::nth_element(first, first + j, last);
  6039. auto xj = first[j];
  6040. if (g == 0) return xj;
  6041. auto xj1 = *std::min_element(first + (j + 1), last);
  6042. return xj + g * (xj1 - xj);
  6043. }
  6044. double erfc_inv(double x) {
  6045. return erf_inv(1.0 - x);
  6046. }
  6047. double normal_quantile(double p) {
  6048. static const double ROOT_TWO = std::sqrt(2.0);
  6049. double result = 0.0;
  6050. assert(p >= 0 && p <= 1);
  6051. if (p < 0 || p > 1) {
  6052. return result;
  6053. }
  6054. result = -erfc_inv(2.0 * p);
  6055. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6056. result *= /*sd * */ ROOT_TWO;
  6057. // result += normal disttribution mean (0)
  6058. return result;
  6059. }
  6060. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6061. double sb = stddev.point;
  6062. double mn = mean.point / n;
  6063. double mg_min = mn / 2.;
  6064. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6065. double sg2 = sg * sg;
  6066. double sb2 = sb * sb;
  6067. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6068. double k = mn - x;
  6069. double d = k * k;
  6070. double nd = n * d;
  6071. double k0 = -n * nd;
  6072. double k1 = sb2 - n * sg2 + nd;
  6073. double det = k1 * k1 - 4 * sg2 * k0;
  6074. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6075. };
  6076. auto var_out = [n, sb2, sg2](double c) {
  6077. double nc = n - c;
  6078. return (nc / n) * (sb2 - nc * sg2);
  6079. };
  6080. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6081. }
  6082. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6083. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6084. static std::random_device entropy;
  6085. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6086. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6087. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6088. auto stddev = &standard_deviation;
  6089. #if defined(CATCH_CONFIG_USE_ASYNC)
  6090. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6091. auto seed = entropy();
  6092. return std::async(std::launch::async, [=] {
  6093. std::mt19937 rng(seed);
  6094. auto resampled = resample(rng, n_resamples, first, last, f);
  6095. return bootstrap(confidence_level, first, last, resampled, f);
  6096. });
  6097. };
  6098. auto mean_future = Estimate(mean);
  6099. auto stddev_future = Estimate(stddev);
  6100. auto mean_estimate = mean_future.get();
  6101. auto stddev_estimate = stddev_future.get();
  6102. #else
  6103. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6104. auto seed = entropy();
  6105. std::mt19937 rng(seed);
  6106. auto resampled = resample(rng, n_resamples, first, last, f);
  6107. return bootstrap(confidence_level, first, last, resampled, f);
  6108. };
  6109. auto mean_estimate = Estimate(mean);
  6110. auto stddev_estimate = Estimate(stddev);
  6111. #endif // CATCH_USE_ASYNC
  6112. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6113. return { mean_estimate, stddev_estimate, outlier_variance };
  6114. }
  6115. } // namespace Detail
  6116. } // namespace Benchmark
  6117. } // namespace Catch
  6118. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6119. // end catch_stats.cpp
  6120. // start catch_approx.cpp
  6121. #include <cmath>
  6122. #include <limits>
  6123. namespace {
  6124. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6125. // But without the subtraction to allow for INFINITY in comparison
  6126. bool marginComparison(double lhs, double rhs, double margin) {
  6127. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6128. }
  6129. }
  6130. namespace Catch {
  6131. namespace Detail {
  6132. Approx::Approx ( double value )
  6133. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6134. m_margin( 0.0 ),
  6135. m_scale( 0.0 ),
  6136. m_value( value )
  6137. {}
  6138. Approx Approx::custom() {
  6139. return Approx( 0 );
  6140. }
  6141. Approx Approx::operator-() const {
  6142. auto temp(*this);
  6143. temp.m_value = -temp.m_value;
  6144. return temp;
  6145. }
  6146. std::string Approx::toString() const {
  6147. ReusableStringStream rss;
  6148. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6149. return rss.str();
  6150. }
  6151. bool Approx::equalityComparisonImpl(const double other) const {
  6152. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6153. // Thanks to Richard Harris for his help refining the scaled margin value
  6154. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6155. }
  6156. void Approx::setMargin(double newMargin) {
  6157. CATCH_ENFORCE(newMargin >= 0,
  6158. "Invalid Approx::margin: " << newMargin << '.'
  6159. << " Approx::Margin has to be non-negative.");
  6160. m_margin = newMargin;
  6161. }
  6162. void Approx::setEpsilon(double newEpsilon) {
  6163. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6164. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6165. << " Approx::epsilon has to be in [0, 1]");
  6166. m_epsilon = newEpsilon;
  6167. }
  6168. } // end namespace Detail
  6169. namespace literals {
  6170. Detail::Approx operator "" _a(long double val) {
  6171. return Detail::Approx(val);
  6172. }
  6173. Detail::Approx operator "" _a(unsigned long long val) {
  6174. return Detail::Approx(val);
  6175. }
  6176. } // end namespace literals
  6177. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6178. return value.toString();
  6179. }
  6180. } // end namespace Catch
  6181. // end catch_approx.cpp
  6182. // start catch_assertionhandler.cpp
  6183. // start catch_debugger.h
  6184. namespace Catch {
  6185. bool isDebuggerActive();
  6186. }
  6187. #ifdef CATCH_PLATFORM_MAC
  6188. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6189. #elif defined(CATCH_PLATFORM_LINUX)
  6190. // If we can use inline assembler, do it because this allows us to break
  6191. // directly at the location of the failing check instead of breaking inside
  6192. // raise() called from it, i.e. one stack frame below.
  6193. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6194. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6195. #else // Fall back to the generic way.
  6196. #include <signal.h>
  6197. #define CATCH_TRAP() raise(SIGTRAP)
  6198. #endif
  6199. #elif defined(_MSC_VER)
  6200. #define CATCH_TRAP() __debugbreak()
  6201. #elif defined(__MINGW32__)
  6202. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6203. #define CATCH_TRAP() DebugBreak()
  6204. #endif
  6205. #ifdef CATCH_TRAP
  6206. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6207. #else
  6208. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6209. #endif
  6210. // end catch_debugger.h
  6211. // start catch_run_context.h
  6212. // start catch_fatal_condition.h
  6213. // start catch_windows_h_proxy.h
  6214. #if defined(CATCH_PLATFORM_WINDOWS)
  6215. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6216. # define CATCH_DEFINED_NOMINMAX
  6217. # define NOMINMAX
  6218. #endif
  6219. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6220. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6221. # define WIN32_LEAN_AND_MEAN
  6222. #endif
  6223. #ifdef __AFXDLL
  6224. #include <AfxWin.h>
  6225. #else
  6226. #include <windows.h>
  6227. #endif
  6228. #ifdef CATCH_DEFINED_NOMINMAX
  6229. # undef NOMINMAX
  6230. #endif
  6231. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6232. # undef WIN32_LEAN_AND_MEAN
  6233. #endif
  6234. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6235. // end catch_windows_h_proxy.h
  6236. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6237. namespace Catch {
  6238. struct FatalConditionHandler {
  6239. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6240. FatalConditionHandler();
  6241. static void reset();
  6242. ~FatalConditionHandler();
  6243. private:
  6244. static bool isSet;
  6245. static ULONG guaranteeSize;
  6246. static PVOID exceptionHandlerHandle;
  6247. };
  6248. } // namespace Catch
  6249. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6250. #include <signal.h>
  6251. namespace Catch {
  6252. struct FatalConditionHandler {
  6253. static bool isSet;
  6254. static struct sigaction oldSigActions[];
  6255. static stack_t oldSigStack;
  6256. static char altStackMem[];
  6257. static void handleSignal( int sig );
  6258. FatalConditionHandler();
  6259. ~FatalConditionHandler();
  6260. static void reset();
  6261. };
  6262. } // namespace Catch
  6263. #else
  6264. namespace Catch {
  6265. struct FatalConditionHandler {
  6266. void reset();
  6267. };
  6268. }
  6269. #endif
  6270. // end catch_fatal_condition.h
  6271. #include <string>
  6272. namespace Catch {
  6273. struct IMutableContext;
  6274. ///////////////////////////////////////////////////////////////////////////
  6275. class RunContext : public IResultCapture, public IRunner {
  6276. public:
  6277. RunContext( RunContext const& ) = delete;
  6278. RunContext& operator =( RunContext const& ) = delete;
  6279. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6280. ~RunContext() override;
  6281. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6282. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6283. Totals runTest(TestCase const& testCase);
  6284. IConfigPtr config() const;
  6285. IStreamingReporter& reporter() const;
  6286. public: // IResultCapture
  6287. // Assertion handlers
  6288. void handleExpr
  6289. ( AssertionInfo const& info,
  6290. ITransientExpression const& expr,
  6291. AssertionReaction& reaction ) override;
  6292. void handleMessage
  6293. ( AssertionInfo const& info,
  6294. ResultWas::OfType resultType,
  6295. StringRef const& message,
  6296. AssertionReaction& reaction ) override;
  6297. void handleUnexpectedExceptionNotThrown
  6298. ( AssertionInfo const& info,
  6299. AssertionReaction& reaction ) override;
  6300. void handleUnexpectedInflightException
  6301. ( AssertionInfo const& info,
  6302. std::string const& message,
  6303. AssertionReaction& reaction ) override;
  6304. void handleIncomplete
  6305. ( AssertionInfo const& info ) override;
  6306. void handleNonExpr
  6307. ( AssertionInfo const &info,
  6308. ResultWas::OfType resultType,
  6309. AssertionReaction &reaction ) override;
  6310. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6311. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6312. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6313. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6314. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6315. void benchmarkPreparing( std::string const& name ) override;
  6316. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6317. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6318. void benchmarkFailed( std::string const& error ) override;
  6319. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6320. void pushScopedMessage( MessageInfo const& message ) override;
  6321. void popScopedMessage( MessageInfo const& message ) override;
  6322. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6323. std::string getCurrentTestName() const override;
  6324. const AssertionResult* getLastResult() const override;
  6325. void exceptionEarlyReported() override;
  6326. void handleFatalErrorCondition( StringRef message ) override;
  6327. bool lastAssertionPassed() override;
  6328. void assertionPassed() override;
  6329. public:
  6330. // !TBD We need to do this another way!
  6331. bool aborting() const final;
  6332. private:
  6333. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6334. void invokeActiveTestCase();
  6335. void resetAssertionInfo();
  6336. bool testForMissingAssertions( Counts& assertions );
  6337. void assertionEnded( AssertionResult const& result );
  6338. void reportExpr
  6339. ( AssertionInfo const &info,
  6340. ResultWas::OfType resultType,
  6341. ITransientExpression const *expr,
  6342. bool negated );
  6343. void populateReaction( AssertionReaction& reaction );
  6344. private:
  6345. void handleUnfinishedSections();
  6346. TestRunInfo m_runInfo;
  6347. IMutableContext& m_context;
  6348. TestCase const* m_activeTestCase = nullptr;
  6349. ITracker* m_testCaseTracker = nullptr;
  6350. Option<AssertionResult> m_lastResult;
  6351. IConfigPtr m_config;
  6352. Totals m_totals;
  6353. IStreamingReporterPtr m_reporter;
  6354. std::vector<MessageInfo> m_messages;
  6355. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6356. AssertionInfo m_lastAssertionInfo;
  6357. std::vector<SectionEndInfo> m_unfinishedSections;
  6358. std::vector<ITracker*> m_activeSections;
  6359. TrackerContext m_trackerContext;
  6360. bool m_lastAssertionPassed = false;
  6361. bool m_shouldReportUnexpected = true;
  6362. bool m_includeSuccessfulResults;
  6363. };
  6364. } // end namespace Catch
  6365. // end catch_run_context.h
  6366. namespace Catch {
  6367. namespace {
  6368. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6369. expr.streamReconstructedExpression( os );
  6370. return os;
  6371. }
  6372. }
  6373. LazyExpression::LazyExpression( bool isNegated )
  6374. : m_isNegated( isNegated )
  6375. {}
  6376. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6377. LazyExpression::operator bool() const {
  6378. return m_transientExpression != nullptr;
  6379. }
  6380. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6381. if( lazyExpr.m_isNegated )
  6382. os << "!";
  6383. if( lazyExpr ) {
  6384. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6385. os << "(" << *lazyExpr.m_transientExpression << ")";
  6386. else
  6387. os << *lazyExpr.m_transientExpression;
  6388. }
  6389. else {
  6390. os << "{** error - unchecked empty expression requested **}";
  6391. }
  6392. return os;
  6393. }
  6394. AssertionHandler::AssertionHandler
  6395. ( StringRef const& macroName,
  6396. SourceLineInfo const& lineInfo,
  6397. StringRef capturedExpression,
  6398. ResultDisposition::Flags resultDisposition )
  6399. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6400. m_resultCapture( getResultCapture() )
  6401. {}
  6402. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6403. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6404. }
  6405. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6406. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6407. }
  6408. auto AssertionHandler::allowThrows() const -> bool {
  6409. return getCurrentContext().getConfig()->allowThrows();
  6410. }
  6411. void AssertionHandler::complete() {
  6412. setCompleted();
  6413. if( m_reaction.shouldDebugBreak ) {
  6414. // If you find your debugger stopping you here then go one level up on the
  6415. // call-stack for the code that caused it (typically a failed assertion)
  6416. // (To go back to the test and change execution, jump over the throw, next)
  6417. CATCH_BREAK_INTO_DEBUGGER();
  6418. }
  6419. if (m_reaction.shouldThrow) {
  6420. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6421. throw Catch::TestFailureException();
  6422. #else
  6423. CATCH_ERROR( "Test failure requires aborting test!" );
  6424. #endif
  6425. }
  6426. }
  6427. void AssertionHandler::setCompleted() {
  6428. m_completed = true;
  6429. }
  6430. void AssertionHandler::handleUnexpectedInflightException() {
  6431. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6432. }
  6433. void AssertionHandler::handleExceptionThrownAsExpected() {
  6434. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6435. }
  6436. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6437. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6438. }
  6439. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6440. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6441. }
  6442. void AssertionHandler::handleThrowingCallSkipped() {
  6443. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6444. }
  6445. // This is the overload that takes a string and infers the Equals matcher from it
  6446. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6447. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6448. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6449. }
  6450. } // namespace Catch
  6451. // end catch_assertionhandler.cpp
  6452. // start catch_assertionresult.cpp
  6453. namespace Catch {
  6454. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6455. lazyExpression(_lazyExpression),
  6456. resultType(_resultType) {}
  6457. std::string AssertionResultData::reconstructExpression() const {
  6458. if( reconstructedExpression.empty() ) {
  6459. if( lazyExpression ) {
  6460. ReusableStringStream rss;
  6461. rss << lazyExpression;
  6462. reconstructedExpression = rss.str();
  6463. }
  6464. }
  6465. return reconstructedExpression;
  6466. }
  6467. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6468. : m_info( info ),
  6469. m_resultData( data )
  6470. {}
  6471. // Result was a success
  6472. bool AssertionResult::succeeded() const {
  6473. return Catch::isOk( m_resultData.resultType );
  6474. }
  6475. // Result was a success, or failure is suppressed
  6476. bool AssertionResult::isOk() const {
  6477. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6478. }
  6479. ResultWas::OfType AssertionResult::getResultType() const {
  6480. return m_resultData.resultType;
  6481. }
  6482. bool AssertionResult::hasExpression() const {
  6483. return m_info.capturedExpression[0] != 0;
  6484. }
  6485. bool AssertionResult::hasMessage() const {
  6486. return !m_resultData.message.empty();
  6487. }
  6488. std::string AssertionResult::getExpression() const {
  6489. if( isFalseTest( m_info.resultDisposition ) )
  6490. return "!(" + m_info.capturedExpression + ")";
  6491. else
  6492. return m_info.capturedExpression;
  6493. }
  6494. std::string AssertionResult::getExpressionInMacro() const {
  6495. std::string expr;
  6496. if( m_info.macroName[0] == 0 )
  6497. expr = m_info.capturedExpression;
  6498. else {
  6499. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6500. expr += m_info.macroName;
  6501. expr += "( ";
  6502. expr += m_info.capturedExpression;
  6503. expr += " )";
  6504. }
  6505. return expr;
  6506. }
  6507. bool AssertionResult::hasExpandedExpression() const {
  6508. return hasExpression() && getExpandedExpression() != getExpression();
  6509. }
  6510. std::string AssertionResult::getExpandedExpression() const {
  6511. std::string expr = m_resultData.reconstructExpression();
  6512. return expr.empty()
  6513. ? getExpression()
  6514. : expr;
  6515. }
  6516. std::string AssertionResult::getMessage() const {
  6517. return m_resultData.message;
  6518. }
  6519. SourceLineInfo AssertionResult::getSourceInfo() const {
  6520. return m_info.lineInfo;
  6521. }
  6522. StringRef AssertionResult::getTestMacroName() const {
  6523. return m_info.macroName;
  6524. }
  6525. } // end namespace Catch
  6526. // end catch_assertionresult.cpp
  6527. // start catch_capture_matchers.cpp
  6528. namespace Catch {
  6529. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6530. // This is the general overload that takes a any string matcher
  6531. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6532. // the Equals matcher (so the header does not mention matchers)
  6533. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6534. std::string exceptionMessage = Catch::translateActiveException();
  6535. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6536. handler.handleExpr( expr );
  6537. }
  6538. } // namespace Catch
  6539. // end catch_capture_matchers.cpp
  6540. // start catch_commandline.cpp
  6541. // start catch_commandline.h
  6542. // start catch_clara.h
  6543. // Use Catch's value for console width (store Clara's off to the side, if present)
  6544. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6545. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6546. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6547. #endif
  6548. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6549. #ifdef __clang__
  6550. #pragma clang diagnostic push
  6551. #pragma clang diagnostic ignored "-Wweak-vtables"
  6552. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6553. #pragma clang diagnostic ignored "-Wshadow"
  6554. #endif
  6555. // start clara.hpp
  6556. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6557. //
  6558. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6559. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6560. //
  6561. // See https://github.com/philsquared/Clara for more details
  6562. // Clara v1.1.5
  6563. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6564. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6565. #endif
  6566. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6567. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6568. #endif
  6569. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6570. #ifdef __has_include
  6571. #if __has_include(<optional>) && __cplusplus >= 201703L
  6572. #include <optional>
  6573. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6574. #endif
  6575. #endif
  6576. #endif
  6577. // ----------- #included from clara_textflow.hpp -----------
  6578. // TextFlowCpp
  6579. //
  6580. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6581. //
  6582. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6583. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6584. //
  6585. // This project is hosted at https://github.com/philsquared/textflowcpp
  6586. #include <cassert>
  6587. #include <ostream>
  6588. #include <sstream>
  6589. #include <vector>
  6590. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6591. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6592. #endif
  6593. namespace Catch {
  6594. namespace clara {
  6595. namespace TextFlow {
  6596. inline auto isWhitespace(char c) -> bool {
  6597. static std::string chars = " \t\n\r";
  6598. return chars.find(c) != std::string::npos;
  6599. }
  6600. inline auto isBreakableBefore(char c) -> bool {
  6601. static std::string chars = "[({<|";
  6602. return chars.find(c) != std::string::npos;
  6603. }
  6604. inline auto isBreakableAfter(char c) -> bool {
  6605. static std::string chars = "])}>.,:;*+-=&/\\";
  6606. return chars.find(c) != std::string::npos;
  6607. }
  6608. class Columns;
  6609. class Column {
  6610. std::vector<std::string> m_strings;
  6611. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6612. size_t m_indent = 0;
  6613. size_t m_initialIndent = std::string::npos;
  6614. public:
  6615. class iterator {
  6616. friend Column;
  6617. Column const& m_column;
  6618. size_t m_stringIndex = 0;
  6619. size_t m_pos = 0;
  6620. size_t m_len = 0;
  6621. size_t m_end = 0;
  6622. bool m_suffix = false;
  6623. iterator(Column const& column, size_t stringIndex)
  6624. : m_column(column),
  6625. m_stringIndex(stringIndex) {}
  6626. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6627. auto isBoundary(size_t at) const -> bool {
  6628. assert(at > 0);
  6629. assert(at <= line().size());
  6630. return at == line().size() ||
  6631. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6632. isBreakableBefore(line()[at]) ||
  6633. isBreakableAfter(line()[at - 1]);
  6634. }
  6635. void calcLength() {
  6636. assert(m_stringIndex < m_column.m_strings.size());
  6637. m_suffix = false;
  6638. auto width = m_column.m_width - indent();
  6639. m_end = m_pos;
  6640. if (line()[m_pos] == '\n') {
  6641. ++m_end;
  6642. }
  6643. while (m_end < line().size() && line()[m_end] != '\n')
  6644. ++m_end;
  6645. if (m_end < m_pos + width) {
  6646. m_len = m_end - m_pos;
  6647. } else {
  6648. size_t len = width;
  6649. while (len > 0 && !isBoundary(m_pos + len))
  6650. --len;
  6651. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6652. --len;
  6653. if (len > 0) {
  6654. m_len = len;
  6655. } else {
  6656. m_suffix = true;
  6657. m_len = width - 1;
  6658. }
  6659. }
  6660. }
  6661. auto indent() const -> size_t {
  6662. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6663. return initial == std::string::npos ? m_column.m_indent : initial;
  6664. }
  6665. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6666. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6667. }
  6668. public:
  6669. using difference_type = std::ptrdiff_t;
  6670. using value_type = std::string;
  6671. using pointer = value_type * ;
  6672. using reference = value_type & ;
  6673. using iterator_category = std::forward_iterator_tag;
  6674. explicit iterator(Column const& column) : m_column(column) {
  6675. assert(m_column.m_width > m_column.m_indent);
  6676. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6677. calcLength();
  6678. if (m_len == 0)
  6679. m_stringIndex++; // Empty string
  6680. }
  6681. auto operator *() const -> std::string {
  6682. assert(m_stringIndex < m_column.m_strings.size());
  6683. assert(m_pos <= m_end);
  6684. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6685. }
  6686. auto operator ++() -> iterator& {
  6687. m_pos += m_len;
  6688. if (m_pos < line().size() && line()[m_pos] == '\n')
  6689. m_pos += 1;
  6690. else
  6691. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6692. ++m_pos;
  6693. if (m_pos == line().size()) {
  6694. m_pos = 0;
  6695. ++m_stringIndex;
  6696. }
  6697. if (m_stringIndex < m_column.m_strings.size())
  6698. calcLength();
  6699. return *this;
  6700. }
  6701. auto operator ++(int) -> iterator {
  6702. iterator prev(*this);
  6703. operator++();
  6704. return prev;
  6705. }
  6706. auto operator ==(iterator const& other) const -> bool {
  6707. return
  6708. m_pos == other.m_pos &&
  6709. m_stringIndex == other.m_stringIndex &&
  6710. &m_column == &other.m_column;
  6711. }
  6712. auto operator !=(iterator const& other) const -> bool {
  6713. return !operator==(other);
  6714. }
  6715. };
  6716. using const_iterator = iterator;
  6717. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6718. auto width(size_t newWidth) -> Column& {
  6719. assert(newWidth > 0);
  6720. m_width = newWidth;
  6721. return *this;
  6722. }
  6723. auto indent(size_t newIndent) -> Column& {
  6724. m_indent = newIndent;
  6725. return *this;
  6726. }
  6727. auto initialIndent(size_t newIndent) -> Column& {
  6728. m_initialIndent = newIndent;
  6729. return *this;
  6730. }
  6731. auto width() const -> size_t { return m_width; }
  6732. auto begin() const -> iterator { return iterator(*this); }
  6733. auto end() const -> iterator { return { *this, m_strings.size() }; }
  6734. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  6735. bool first = true;
  6736. for (auto line : col) {
  6737. if (first)
  6738. first = false;
  6739. else
  6740. os << "\n";
  6741. os << line;
  6742. }
  6743. return os;
  6744. }
  6745. auto operator + (Column const& other)->Columns;
  6746. auto toString() const -> std::string {
  6747. std::ostringstream oss;
  6748. oss << *this;
  6749. return oss.str();
  6750. }
  6751. };
  6752. class Spacer : public Column {
  6753. public:
  6754. explicit Spacer(size_t spaceWidth) : Column("") {
  6755. width(spaceWidth);
  6756. }
  6757. };
  6758. class Columns {
  6759. std::vector<Column> m_columns;
  6760. public:
  6761. class iterator {
  6762. friend Columns;
  6763. struct EndTag {};
  6764. std::vector<Column> const& m_columns;
  6765. std::vector<Column::iterator> m_iterators;
  6766. size_t m_activeIterators;
  6767. iterator(Columns const& columns, EndTag)
  6768. : m_columns(columns.m_columns),
  6769. m_activeIterators(0) {
  6770. m_iterators.reserve(m_columns.size());
  6771. for (auto const& col : m_columns)
  6772. m_iterators.push_back(col.end());
  6773. }
  6774. public:
  6775. using difference_type = std::ptrdiff_t;
  6776. using value_type = std::string;
  6777. using pointer = value_type * ;
  6778. using reference = value_type & ;
  6779. using iterator_category = std::forward_iterator_tag;
  6780. explicit iterator(Columns const& columns)
  6781. : m_columns(columns.m_columns),
  6782. m_activeIterators(m_columns.size()) {
  6783. m_iterators.reserve(m_columns.size());
  6784. for (auto const& col : m_columns)
  6785. m_iterators.push_back(col.begin());
  6786. }
  6787. auto operator ==(iterator const& other) const -> bool {
  6788. return m_iterators == other.m_iterators;
  6789. }
  6790. auto operator !=(iterator const& other) const -> bool {
  6791. return m_iterators != other.m_iterators;
  6792. }
  6793. auto operator *() const -> std::string {
  6794. std::string row, padding;
  6795. for (size_t i = 0; i < m_columns.size(); ++i) {
  6796. auto width = m_columns[i].width();
  6797. if (m_iterators[i] != m_columns[i].end()) {
  6798. std::string col = *m_iterators[i];
  6799. row += padding + col;
  6800. if (col.size() < width)
  6801. padding = std::string(width - col.size(), ' ');
  6802. else
  6803. padding = "";
  6804. } else {
  6805. padding += std::string(width, ' ');
  6806. }
  6807. }
  6808. return row;
  6809. }
  6810. auto operator ++() -> iterator& {
  6811. for (size_t i = 0; i < m_columns.size(); ++i) {
  6812. if (m_iterators[i] != m_columns[i].end())
  6813. ++m_iterators[i];
  6814. }
  6815. return *this;
  6816. }
  6817. auto operator ++(int) -> iterator {
  6818. iterator prev(*this);
  6819. operator++();
  6820. return prev;
  6821. }
  6822. };
  6823. using const_iterator = iterator;
  6824. auto begin() const -> iterator { return iterator(*this); }
  6825. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  6826. auto operator += (Column const& col) -> Columns& {
  6827. m_columns.push_back(col);
  6828. return *this;
  6829. }
  6830. auto operator + (Column const& col) -> Columns {
  6831. Columns combined = *this;
  6832. combined += col;
  6833. return combined;
  6834. }
  6835. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  6836. bool first = true;
  6837. for (auto line : cols) {
  6838. if (first)
  6839. first = false;
  6840. else
  6841. os << "\n";
  6842. os << line;
  6843. }
  6844. return os;
  6845. }
  6846. auto toString() const -> std::string {
  6847. std::ostringstream oss;
  6848. oss << *this;
  6849. return oss.str();
  6850. }
  6851. };
  6852. inline auto Column::operator + (Column const& other) -> Columns {
  6853. Columns cols;
  6854. cols += *this;
  6855. cols += other;
  6856. return cols;
  6857. }
  6858. }
  6859. }
  6860. }
  6861. // ----------- end of #include from clara_textflow.hpp -----------
  6862. // ........... back in clara.hpp
  6863. #include <cctype>
  6864. #include <string>
  6865. #include <memory>
  6866. #include <set>
  6867. #include <algorithm>
  6868. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  6869. #define CATCH_PLATFORM_WINDOWS
  6870. #endif
  6871. namespace Catch { namespace clara {
  6872. namespace detail {
  6873. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  6874. template<typename L>
  6875. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  6876. template<typename ClassT, typename ReturnT, typename... Args>
  6877. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  6878. static const bool isValid = false;
  6879. };
  6880. template<typename ClassT, typename ReturnT, typename ArgT>
  6881. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  6882. static const bool isValid = true;
  6883. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  6884. using ReturnType = ReturnT;
  6885. };
  6886. class TokenStream;
  6887. // Transport for raw args (copied from main args, or supplied via init list for testing)
  6888. class Args {
  6889. friend TokenStream;
  6890. std::string m_exeName;
  6891. std::vector<std::string> m_args;
  6892. public:
  6893. Args( int argc, char const* const* argv )
  6894. : m_exeName(argv[0]),
  6895. m_args(argv + 1, argv + argc) {}
  6896. Args( std::initializer_list<std::string> args )
  6897. : m_exeName( *args.begin() ),
  6898. m_args( args.begin()+1, args.end() )
  6899. {}
  6900. auto exeName() const -> std::string {
  6901. return m_exeName;
  6902. }
  6903. };
  6904. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  6905. // may encode an option + its argument if the : or = form is used
  6906. enum class TokenType {
  6907. Option, Argument
  6908. };
  6909. struct Token {
  6910. TokenType type;
  6911. std::string token;
  6912. };
  6913. inline auto isOptPrefix( char c ) -> bool {
  6914. return c == '-'
  6915. #ifdef CATCH_PLATFORM_WINDOWS
  6916. || c == '/'
  6917. #endif
  6918. ;
  6919. }
  6920. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  6921. class TokenStream {
  6922. using Iterator = std::vector<std::string>::const_iterator;
  6923. Iterator it;
  6924. Iterator itEnd;
  6925. std::vector<Token> m_tokenBuffer;
  6926. void loadBuffer() {
  6927. m_tokenBuffer.resize( 0 );
  6928. // Skip any empty strings
  6929. while( it != itEnd && it->empty() )
  6930. ++it;
  6931. if( it != itEnd ) {
  6932. auto const &next = *it;
  6933. if( isOptPrefix( next[0] ) ) {
  6934. auto delimiterPos = next.find_first_of( " :=" );
  6935. if( delimiterPos != std::string::npos ) {
  6936. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  6937. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  6938. } else {
  6939. if( next[1] != '-' && next.size() > 2 ) {
  6940. std::string opt = "- ";
  6941. for( size_t i = 1; i < next.size(); ++i ) {
  6942. opt[1] = next[i];
  6943. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  6944. }
  6945. } else {
  6946. m_tokenBuffer.push_back( { TokenType::Option, next } );
  6947. }
  6948. }
  6949. } else {
  6950. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  6951. }
  6952. }
  6953. }
  6954. public:
  6955. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  6956. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  6957. loadBuffer();
  6958. }
  6959. explicit operator bool() const {
  6960. return !m_tokenBuffer.empty() || it != itEnd;
  6961. }
  6962. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  6963. auto operator*() const -> Token {
  6964. assert( !m_tokenBuffer.empty() );
  6965. return m_tokenBuffer.front();
  6966. }
  6967. auto operator->() const -> Token const * {
  6968. assert( !m_tokenBuffer.empty() );
  6969. return &m_tokenBuffer.front();
  6970. }
  6971. auto operator++() -> TokenStream & {
  6972. if( m_tokenBuffer.size() >= 2 ) {
  6973. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  6974. } else {
  6975. if( it != itEnd )
  6976. ++it;
  6977. loadBuffer();
  6978. }
  6979. return *this;
  6980. }
  6981. };
  6982. class ResultBase {
  6983. public:
  6984. enum Type {
  6985. Ok, LogicError, RuntimeError
  6986. };
  6987. protected:
  6988. ResultBase( Type type ) : m_type( type ) {}
  6989. virtual ~ResultBase() = default;
  6990. virtual void enforceOk() const = 0;
  6991. Type m_type;
  6992. };
  6993. template<typename T>
  6994. class ResultValueBase : public ResultBase {
  6995. public:
  6996. auto value() const -> T const & {
  6997. enforceOk();
  6998. return m_value;
  6999. }
  7000. protected:
  7001. ResultValueBase( Type type ) : ResultBase( type ) {}
  7002. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7003. if( m_type == ResultBase::Ok )
  7004. new( &m_value ) T( other.m_value );
  7005. }
  7006. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7007. new( &m_value ) T( value );
  7008. }
  7009. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7010. if( m_type == ResultBase::Ok )
  7011. m_value.~T();
  7012. ResultBase::operator=(other);
  7013. if( m_type == ResultBase::Ok )
  7014. new( &m_value ) T( other.m_value );
  7015. return *this;
  7016. }
  7017. ~ResultValueBase() override {
  7018. if( m_type == Ok )
  7019. m_value.~T();
  7020. }
  7021. union {
  7022. T m_value;
  7023. };
  7024. };
  7025. template<>
  7026. class ResultValueBase<void> : public ResultBase {
  7027. protected:
  7028. using ResultBase::ResultBase;
  7029. };
  7030. template<typename T = void>
  7031. class BasicResult : public ResultValueBase<T> {
  7032. public:
  7033. template<typename U>
  7034. explicit BasicResult( BasicResult<U> const &other )
  7035. : ResultValueBase<T>( other.type() ),
  7036. m_errorMessage( other.errorMessage() )
  7037. {
  7038. assert( type() != ResultBase::Ok );
  7039. }
  7040. template<typename U>
  7041. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7042. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7043. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7044. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7045. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7046. auto type() const -> ResultBase::Type { return m_type; }
  7047. auto errorMessage() const -> std::string { return m_errorMessage; }
  7048. protected:
  7049. void enforceOk() const override {
  7050. // Errors shouldn't reach this point, but if they do
  7051. // the actual error message will be in m_errorMessage
  7052. assert( m_type != ResultBase::LogicError );
  7053. assert( m_type != ResultBase::RuntimeError );
  7054. if( m_type != ResultBase::Ok )
  7055. std::abort();
  7056. }
  7057. std::string m_errorMessage; // Only populated if resultType is an error
  7058. BasicResult( ResultBase::Type type, std::string const &message )
  7059. : ResultValueBase<T>(type),
  7060. m_errorMessage(message)
  7061. {
  7062. assert( m_type != ResultBase::Ok );
  7063. }
  7064. using ResultValueBase<T>::ResultValueBase;
  7065. using ResultBase::m_type;
  7066. };
  7067. enum class ParseResultType {
  7068. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7069. };
  7070. class ParseState {
  7071. public:
  7072. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7073. : m_type(type),
  7074. m_remainingTokens( remainingTokens )
  7075. {}
  7076. auto type() const -> ParseResultType { return m_type; }
  7077. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7078. private:
  7079. ParseResultType m_type;
  7080. TokenStream m_remainingTokens;
  7081. };
  7082. using Result = BasicResult<void>;
  7083. using ParserResult = BasicResult<ParseResultType>;
  7084. using InternalParseResult = BasicResult<ParseState>;
  7085. struct HelpColumns {
  7086. std::string left;
  7087. std::string right;
  7088. };
  7089. template<typename T>
  7090. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7091. std::stringstream ss;
  7092. ss << source;
  7093. ss >> target;
  7094. if( ss.fail() )
  7095. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7096. else
  7097. return ParserResult::ok( ParseResultType::Matched );
  7098. }
  7099. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7100. target = source;
  7101. return ParserResult::ok( ParseResultType::Matched );
  7102. }
  7103. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7104. std::string srcLC = source;
  7105. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7106. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7107. target = true;
  7108. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7109. target = false;
  7110. else
  7111. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7112. return ParserResult::ok( ParseResultType::Matched );
  7113. }
  7114. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7115. template<typename T>
  7116. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7117. T temp;
  7118. auto result = convertInto( source, temp );
  7119. if( result )
  7120. target = std::move(temp);
  7121. return result;
  7122. }
  7123. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7124. struct NonCopyable {
  7125. NonCopyable() = default;
  7126. NonCopyable( NonCopyable const & ) = delete;
  7127. NonCopyable( NonCopyable && ) = delete;
  7128. NonCopyable &operator=( NonCopyable const & ) = delete;
  7129. NonCopyable &operator=( NonCopyable && ) = delete;
  7130. };
  7131. struct BoundRef : NonCopyable {
  7132. virtual ~BoundRef() = default;
  7133. virtual auto isContainer() const -> bool { return false; }
  7134. virtual auto isFlag() const -> bool { return false; }
  7135. };
  7136. struct BoundValueRefBase : BoundRef {
  7137. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7138. };
  7139. struct BoundFlagRefBase : BoundRef {
  7140. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7141. virtual auto isFlag() const -> bool { return true; }
  7142. };
  7143. template<typename T>
  7144. struct BoundValueRef : BoundValueRefBase {
  7145. T &m_ref;
  7146. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7147. auto setValue( std::string const &arg ) -> ParserResult override {
  7148. return convertInto( arg, m_ref );
  7149. }
  7150. };
  7151. template<typename T>
  7152. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7153. std::vector<T> &m_ref;
  7154. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7155. auto isContainer() const -> bool override { return true; }
  7156. auto setValue( std::string const &arg ) -> ParserResult override {
  7157. T temp;
  7158. auto result = convertInto( arg, temp );
  7159. if( result )
  7160. m_ref.push_back( temp );
  7161. return result;
  7162. }
  7163. };
  7164. struct BoundFlagRef : BoundFlagRefBase {
  7165. bool &m_ref;
  7166. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7167. auto setFlag( bool flag ) -> ParserResult override {
  7168. m_ref = flag;
  7169. return ParserResult::ok( ParseResultType::Matched );
  7170. }
  7171. };
  7172. template<typename ReturnType>
  7173. struct LambdaInvoker {
  7174. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7175. template<typename L, typename ArgType>
  7176. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7177. return lambda( arg );
  7178. }
  7179. };
  7180. template<>
  7181. struct LambdaInvoker<void> {
  7182. template<typename L, typename ArgType>
  7183. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7184. lambda( arg );
  7185. return ParserResult::ok( ParseResultType::Matched );
  7186. }
  7187. };
  7188. template<typename ArgType, typename L>
  7189. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7190. ArgType temp{};
  7191. auto result = convertInto( arg, temp );
  7192. return !result
  7193. ? result
  7194. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7195. }
  7196. template<typename L>
  7197. struct BoundLambda : BoundValueRefBase {
  7198. L m_lambda;
  7199. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7200. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7201. auto setValue( std::string const &arg ) -> ParserResult override {
  7202. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7203. }
  7204. };
  7205. template<typename L>
  7206. struct BoundFlagLambda : BoundFlagRefBase {
  7207. L m_lambda;
  7208. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7209. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7210. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7211. auto setFlag( bool flag ) -> ParserResult override {
  7212. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7213. }
  7214. };
  7215. enum class Optionality { Optional, Required };
  7216. struct Parser;
  7217. class ParserBase {
  7218. public:
  7219. virtual ~ParserBase() = default;
  7220. virtual auto validate() const -> Result { return Result::ok(); }
  7221. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7222. virtual auto cardinality() const -> size_t { return 1; }
  7223. auto parse( Args const &args ) const -> InternalParseResult {
  7224. return parse( args.exeName(), TokenStream( args ) );
  7225. }
  7226. };
  7227. template<typename DerivedT>
  7228. class ComposableParserImpl : public ParserBase {
  7229. public:
  7230. template<typename T>
  7231. auto operator|( T const &other ) const -> Parser;
  7232. template<typename T>
  7233. auto operator+( T const &other ) const -> Parser;
  7234. };
  7235. // Common code and state for Args and Opts
  7236. template<typename DerivedT>
  7237. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7238. protected:
  7239. Optionality m_optionality = Optionality::Optional;
  7240. std::shared_ptr<BoundRef> m_ref;
  7241. std::string m_hint;
  7242. std::string m_description;
  7243. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7244. public:
  7245. template<typename T>
  7246. ParserRefImpl( T &ref, std::string const &hint )
  7247. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7248. m_hint( hint )
  7249. {}
  7250. template<typename LambdaT>
  7251. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7252. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7253. m_hint(hint)
  7254. {}
  7255. auto operator()( std::string const &description ) -> DerivedT & {
  7256. m_description = description;
  7257. return static_cast<DerivedT &>( *this );
  7258. }
  7259. auto optional() -> DerivedT & {
  7260. m_optionality = Optionality::Optional;
  7261. return static_cast<DerivedT &>( *this );
  7262. };
  7263. auto required() -> DerivedT & {
  7264. m_optionality = Optionality::Required;
  7265. return static_cast<DerivedT &>( *this );
  7266. };
  7267. auto isOptional() const -> bool {
  7268. return m_optionality == Optionality::Optional;
  7269. }
  7270. auto cardinality() const -> size_t override {
  7271. if( m_ref->isContainer() )
  7272. return 0;
  7273. else
  7274. return 1;
  7275. }
  7276. auto hint() const -> std::string { return m_hint; }
  7277. };
  7278. class ExeName : public ComposableParserImpl<ExeName> {
  7279. std::shared_ptr<std::string> m_name;
  7280. std::shared_ptr<BoundValueRefBase> m_ref;
  7281. template<typename LambdaT>
  7282. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7283. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7284. }
  7285. public:
  7286. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7287. explicit ExeName( std::string &ref ) : ExeName() {
  7288. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7289. }
  7290. template<typename LambdaT>
  7291. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7292. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7293. }
  7294. // The exe name is not parsed out of the normal tokens, but is handled specially
  7295. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7296. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7297. }
  7298. auto name() const -> std::string { return *m_name; }
  7299. auto set( std::string const& newName ) -> ParserResult {
  7300. auto lastSlash = newName.find_last_of( "\\/" );
  7301. auto filename = ( lastSlash == std::string::npos )
  7302. ? newName
  7303. : newName.substr( lastSlash+1 );
  7304. *m_name = filename;
  7305. if( m_ref )
  7306. return m_ref->setValue( filename );
  7307. else
  7308. return ParserResult::ok( ParseResultType::Matched );
  7309. }
  7310. };
  7311. class Arg : public ParserRefImpl<Arg> {
  7312. public:
  7313. using ParserRefImpl::ParserRefImpl;
  7314. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7315. auto validationResult = validate();
  7316. if( !validationResult )
  7317. return InternalParseResult( validationResult );
  7318. auto remainingTokens = tokens;
  7319. auto const &token = *remainingTokens;
  7320. if( token.type != TokenType::Argument )
  7321. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7322. assert( !m_ref->isFlag() );
  7323. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7324. auto result = valueRef->setValue( remainingTokens->token );
  7325. if( !result )
  7326. return InternalParseResult( result );
  7327. else
  7328. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7329. }
  7330. };
  7331. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7332. #ifdef CATCH_PLATFORM_WINDOWS
  7333. if( optName[0] == '/' )
  7334. return "-" + optName.substr( 1 );
  7335. else
  7336. #endif
  7337. return optName;
  7338. }
  7339. class Opt : public ParserRefImpl<Opt> {
  7340. protected:
  7341. std::vector<std::string> m_optNames;
  7342. public:
  7343. template<typename LambdaT>
  7344. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7345. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7346. template<typename LambdaT>
  7347. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7348. template<typename T>
  7349. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7350. auto operator[]( std::string const &optName ) -> Opt & {
  7351. m_optNames.push_back( optName );
  7352. return *this;
  7353. }
  7354. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7355. std::ostringstream oss;
  7356. bool first = true;
  7357. for( auto const &opt : m_optNames ) {
  7358. if (first)
  7359. first = false;
  7360. else
  7361. oss << ", ";
  7362. oss << opt;
  7363. }
  7364. if( !m_hint.empty() )
  7365. oss << " <" << m_hint << ">";
  7366. return { { oss.str(), m_description } };
  7367. }
  7368. auto isMatch( std::string const &optToken ) const -> bool {
  7369. auto normalisedToken = normaliseOpt( optToken );
  7370. for( auto const &name : m_optNames ) {
  7371. if( normaliseOpt( name ) == normalisedToken )
  7372. return true;
  7373. }
  7374. return false;
  7375. }
  7376. using ParserBase::parse;
  7377. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7378. auto validationResult = validate();
  7379. if( !validationResult )
  7380. return InternalParseResult( validationResult );
  7381. auto remainingTokens = tokens;
  7382. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7383. auto const &token = *remainingTokens;
  7384. if( isMatch(token.token ) ) {
  7385. if( m_ref->isFlag() ) {
  7386. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7387. auto result = flagRef->setFlag( true );
  7388. if( !result )
  7389. return InternalParseResult( result );
  7390. if( result.value() == ParseResultType::ShortCircuitAll )
  7391. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7392. } else {
  7393. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7394. ++remainingTokens;
  7395. if( !remainingTokens )
  7396. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7397. auto const &argToken = *remainingTokens;
  7398. if( argToken.type != TokenType::Argument )
  7399. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7400. auto result = valueRef->setValue( argToken.token );
  7401. if( !result )
  7402. return InternalParseResult( result );
  7403. if( result.value() == ParseResultType::ShortCircuitAll )
  7404. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7405. }
  7406. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7407. }
  7408. }
  7409. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7410. }
  7411. auto validate() const -> Result override {
  7412. if( m_optNames.empty() )
  7413. return Result::logicError( "No options supplied to Opt" );
  7414. for( auto const &name : m_optNames ) {
  7415. if( name.empty() )
  7416. return Result::logicError( "Option name cannot be empty" );
  7417. #ifdef CATCH_PLATFORM_WINDOWS
  7418. if( name[0] != '-' && name[0] != '/' )
  7419. return Result::logicError( "Option name must begin with '-' or '/'" );
  7420. #else
  7421. if( name[0] != '-' )
  7422. return Result::logicError( "Option name must begin with '-'" );
  7423. #endif
  7424. }
  7425. return ParserRefImpl::validate();
  7426. }
  7427. };
  7428. struct Help : Opt {
  7429. Help( bool &showHelpFlag )
  7430. : Opt([&]( bool flag ) {
  7431. showHelpFlag = flag;
  7432. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7433. })
  7434. {
  7435. static_cast<Opt &>( *this )
  7436. ("display usage information")
  7437. ["-?"]["-h"]["--help"]
  7438. .optional();
  7439. }
  7440. };
  7441. struct Parser : ParserBase {
  7442. mutable ExeName m_exeName;
  7443. std::vector<Opt> m_options;
  7444. std::vector<Arg> m_args;
  7445. auto operator|=( ExeName const &exeName ) -> Parser & {
  7446. m_exeName = exeName;
  7447. return *this;
  7448. }
  7449. auto operator|=( Arg const &arg ) -> Parser & {
  7450. m_args.push_back(arg);
  7451. return *this;
  7452. }
  7453. auto operator|=( Opt const &opt ) -> Parser & {
  7454. m_options.push_back(opt);
  7455. return *this;
  7456. }
  7457. auto operator|=( Parser const &other ) -> Parser & {
  7458. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7459. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7460. return *this;
  7461. }
  7462. template<typename T>
  7463. auto operator|( T const &other ) const -> Parser {
  7464. return Parser( *this ) |= other;
  7465. }
  7466. // Forward deprecated interface with '+' instead of '|'
  7467. template<typename T>
  7468. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7469. template<typename T>
  7470. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7471. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7472. std::vector<HelpColumns> cols;
  7473. for (auto const &o : m_options) {
  7474. auto childCols = o.getHelpColumns();
  7475. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7476. }
  7477. return cols;
  7478. }
  7479. void writeToStream( std::ostream &os ) const {
  7480. if (!m_exeName.name().empty()) {
  7481. os << "usage:\n" << " " << m_exeName.name() << " ";
  7482. bool required = true, first = true;
  7483. for( auto const &arg : m_args ) {
  7484. if (first)
  7485. first = false;
  7486. else
  7487. os << " ";
  7488. if( arg.isOptional() && required ) {
  7489. os << "[";
  7490. required = false;
  7491. }
  7492. os << "<" << arg.hint() << ">";
  7493. if( arg.cardinality() == 0 )
  7494. os << " ... ";
  7495. }
  7496. if( !required )
  7497. os << "]";
  7498. if( !m_options.empty() )
  7499. os << " options";
  7500. os << "\n\nwhere options are:" << std::endl;
  7501. }
  7502. auto rows = getHelpColumns();
  7503. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7504. size_t optWidth = 0;
  7505. for( auto const &cols : rows )
  7506. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7507. optWidth = (std::min)(optWidth, consoleWidth/2);
  7508. for( auto const &cols : rows ) {
  7509. auto row =
  7510. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7511. TextFlow::Spacer(4) +
  7512. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7513. os << row << std::endl;
  7514. }
  7515. }
  7516. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7517. parser.writeToStream( os );
  7518. return os;
  7519. }
  7520. auto validate() const -> Result override {
  7521. for( auto const &opt : m_options ) {
  7522. auto result = opt.validate();
  7523. if( !result )
  7524. return result;
  7525. }
  7526. for( auto const &arg : m_args ) {
  7527. auto result = arg.validate();
  7528. if( !result )
  7529. return result;
  7530. }
  7531. return Result::ok();
  7532. }
  7533. using ParserBase::parse;
  7534. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7535. struct ParserInfo {
  7536. ParserBase const* parser = nullptr;
  7537. size_t count = 0;
  7538. };
  7539. const size_t totalParsers = m_options.size() + m_args.size();
  7540. assert( totalParsers < 512 );
  7541. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7542. ParserInfo parseInfos[512];
  7543. {
  7544. size_t i = 0;
  7545. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7546. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7547. }
  7548. m_exeName.set( exeName );
  7549. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7550. while( result.value().remainingTokens() ) {
  7551. bool tokenParsed = false;
  7552. for( size_t i = 0; i < totalParsers; ++i ) {
  7553. auto& parseInfo = parseInfos[i];
  7554. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7555. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7556. if (!result)
  7557. return result;
  7558. if (result.value().type() != ParseResultType::NoMatch) {
  7559. tokenParsed = true;
  7560. ++parseInfo.count;
  7561. break;
  7562. }
  7563. }
  7564. }
  7565. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7566. return result;
  7567. if( !tokenParsed )
  7568. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7569. }
  7570. // !TBD Check missing required options
  7571. return result;
  7572. }
  7573. };
  7574. template<typename DerivedT>
  7575. template<typename T>
  7576. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7577. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7578. }
  7579. } // namespace detail
  7580. // A Combined parser
  7581. using detail::Parser;
  7582. // A parser for options
  7583. using detail::Opt;
  7584. // A parser for arguments
  7585. using detail::Arg;
  7586. // Wrapper for argc, argv from main()
  7587. using detail::Args;
  7588. // Specifies the name of the executable
  7589. using detail::ExeName;
  7590. // Convenience wrapper for option parser that specifies the help option
  7591. using detail::Help;
  7592. // enum of result types from a parse
  7593. using detail::ParseResultType;
  7594. // Result type for parser operation
  7595. using detail::ParserResult;
  7596. }} // namespace Catch::clara
  7597. // end clara.hpp
  7598. #ifdef __clang__
  7599. #pragma clang diagnostic pop
  7600. #endif
  7601. // Restore Clara's value for console width, if present
  7602. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7603. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7604. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7605. #endif
  7606. // end catch_clara.h
  7607. namespace Catch {
  7608. clara::Parser makeCommandLineParser( ConfigData& config );
  7609. } // end namespace Catch
  7610. // end catch_commandline.h
  7611. #include <fstream>
  7612. #include <ctime>
  7613. namespace Catch {
  7614. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7615. using namespace clara;
  7616. auto const setWarning = [&]( std::string const& warning ) {
  7617. auto warningSet = [&]() {
  7618. if( warning == "NoAssertions" )
  7619. return WarnAbout::NoAssertions;
  7620. if ( warning == "NoTests" )
  7621. return WarnAbout::NoTests;
  7622. return WarnAbout::Nothing;
  7623. }();
  7624. if (warningSet == WarnAbout::Nothing)
  7625. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7626. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7627. return ParserResult::ok( ParseResultType::Matched );
  7628. };
  7629. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7630. std::ifstream f( filename.c_str() );
  7631. if( !f.is_open() )
  7632. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7633. std::string line;
  7634. while( std::getline( f, line ) ) {
  7635. line = trim(line);
  7636. if( !line.empty() && !startsWith( line, '#' ) ) {
  7637. if( !startsWith( line, '"' ) )
  7638. line = '"' + line + '"';
  7639. config.testsOrTags.push_back( line + ',' );
  7640. }
  7641. }
  7642. return ParserResult::ok( ParseResultType::Matched );
  7643. };
  7644. auto const setTestOrder = [&]( std::string const& order ) {
  7645. if( startsWith( "declared", order ) )
  7646. config.runOrder = RunTests::InDeclarationOrder;
  7647. else if( startsWith( "lexical", order ) )
  7648. config.runOrder = RunTests::InLexicographicalOrder;
  7649. else if( startsWith( "random", order ) )
  7650. config.runOrder = RunTests::InRandomOrder;
  7651. else
  7652. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7653. return ParserResult::ok( ParseResultType::Matched );
  7654. };
  7655. auto const setRngSeed = [&]( std::string const& seed ) {
  7656. if( seed != "time" )
  7657. return clara::detail::convertInto( seed, config.rngSeed );
  7658. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7659. return ParserResult::ok( ParseResultType::Matched );
  7660. };
  7661. auto const setColourUsage = [&]( std::string const& useColour ) {
  7662. auto mode = toLower( useColour );
  7663. if( mode == "yes" )
  7664. config.useColour = UseColour::Yes;
  7665. else if( mode == "no" )
  7666. config.useColour = UseColour::No;
  7667. else if( mode == "auto" )
  7668. config.useColour = UseColour::Auto;
  7669. else
  7670. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7671. return ParserResult::ok( ParseResultType::Matched );
  7672. };
  7673. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7674. auto keypressLc = toLower( keypress );
  7675. if( keypressLc == "start" )
  7676. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7677. else if( keypressLc == "exit" )
  7678. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7679. else if( keypressLc == "both" )
  7680. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7681. else
  7682. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  7683. return ParserResult::ok( ParseResultType::Matched );
  7684. };
  7685. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7686. auto lcVerbosity = toLower( verbosity );
  7687. if( lcVerbosity == "quiet" )
  7688. config.verbosity = Verbosity::Quiet;
  7689. else if( lcVerbosity == "normal" )
  7690. config.verbosity = Verbosity::Normal;
  7691. else if( lcVerbosity == "high" )
  7692. config.verbosity = Verbosity::High;
  7693. else
  7694. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7695. return ParserResult::ok( ParseResultType::Matched );
  7696. };
  7697. auto const setReporter = [&]( std::string const& reporter ) {
  7698. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7699. auto lcReporter = toLower( reporter );
  7700. auto result = factories.find( lcReporter );
  7701. if( factories.end() != result )
  7702. config.reporterName = lcReporter;
  7703. else
  7704. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7705. return ParserResult::ok( ParseResultType::Matched );
  7706. };
  7707. auto cli
  7708. = ExeName( config.processName )
  7709. | Help( config.showHelp )
  7710. | Opt( config.listTests )
  7711. ["-l"]["--list-tests"]
  7712. ( "list all/matching test cases" )
  7713. | Opt( config.listTags )
  7714. ["-t"]["--list-tags"]
  7715. ( "list all/matching tags" )
  7716. | Opt( config.showSuccessfulTests )
  7717. ["-s"]["--success"]
  7718. ( "include successful tests in output" )
  7719. | Opt( config.shouldDebugBreak )
  7720. ["-b"]["--break"]
  7721. ( "break into debugger on failure" )
  7722. | Opt( config.noThrow )
  7723. ["-e"]["--nothrow"]
  7724. ( "skip exception tests" )
  7725. | Opt( config.showInvisibles )
  7726. ["-i"]["--invisibles"]
  7727. ( "show invisibles (tabs, newlines)" )
  7728. | Opt( config.outputFilename, "filename" )
  7729. ["-o"]["--out"]
  7730. ( "output filename" )
  7731. | Opt( setReporter, "name" )
  7732. ["-r"]["--reporter"]
  7733. ( "reporter to use (defaults to console)" )
  7734. | Opt( config.name, "name" )
  7735. ["-n"]["--name"]
  7736. ( "suite name" )
  7737. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  7738. ["-a"]["--abort"]
  7739. ( "abort at first failure" )
  7740. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  7741. ["-x"]["--abortx"]
  7742. ( "abort after x failures" )
  7743. | Opt( setWarning, "warning name" )
  7744. ["-w"]["--warn"]
  7745. ( "enable warnings" )
  7746. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  7747. ["-d"]["--durations"]
  7748. ( "show test durations" )
  7749. | Opt( loadTestNamesFromFile, "filename" )
  7750. ["-f"]["--input-file"]
  7751. ( "load test names to run from a file" )
  7752. | Opt( config.filenamesAsTags )
  7753. ["-#"]["--filenames-as-tags"]
  7754. ( "adds a tag for the filename" )
  7755. | Opt( config.sectionsToRun, "section name" )
  7756. ["-c"]["--section"]
  7757. ( "specify section to run" )
  7758. | Opt( setVerbosity, "quiet|normal|high" )
  7759. ["-v"]["--verbosity"]
  7760. ( "set output verbosity" )
  7761. | Opt( config.listTestNamesOnly )
  7762. ["--list-test-names-only"]
  7763. ( "list all/matching test cases names only" )
  7764. | Opt( config.listReporters )
  7765. ["--list-reporters"]
  7766. ( "list all reporters" )
  7767. | Opt( setTestOrder, "decl|lex|rand" )
  7768. ["--order"]
  7769. ( "test case order (defaults to decl)" )
  7770. | Opt( setRngSeed, "'time'|number" )
  7771. ["--rng-seed"]
  7772. ( "set a specific seed for random numbers" )
  7773. | Opt( setColourUsage, "yes|no" )
  7774. ["--use-colour"]
  7775. ( "should output be colourised" )
  7776. | Opt( config.libIdentify )
  7777. ["--libidentify"]
  7778. ( "report name and version according to libidentify standard" )
  7779. | Opt( setWaitForKeypress, "start|exit|both" )
  7780. ["--wait-for-keypress"]
  7781. ( "waits for a keypress before exiting" )
  7782. | Opt( config.benchmarkSamples, "samples" )
  7783. ["--benchmark-samples"]
  7784. ( "number of samples to collect (default: 100)" )
  7785. | Opt( config.benchmarkResamples, "resamples" )
  7786. ["--benchmark-resamples"]
  7787. ( "number of resamples for the bootstrap (default: 100000)" )
  7788. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  7789. ["--benchmark-confidence-interval"]
  7790. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  7791. | Opt( config.benchmarkNoAnalysis )
  7792. ["--benchmark-no-analysis"]
  7793. ( "perform only measurements; do not perform any analysis" )
  7794. | Arg( config.testsOrTags, "test name|pattern|tags" )
  7795. ( "which test or tests to use" );
  7796. return cli;
  7797. }
  7798. } // end namespace Catch
  7799. // end catch_commandline.cpp
  7800. // start catch_common.cpp
  7801. #include <cstring>
  7802. #include <ostream>
  7803. namespace Catch {
  7804. bool SourceLineInfo::empty() const noexcept {
  7805. return file[0] == '\0';
  7806. }
  7807. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  7808. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  7809. }
  7810. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  7811. // We can assume that the same file will usually have the same pointer.
  7812. // Thus, if the pointers are the same, there is no point in calling the strcmp
  7813. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  7814. }
  7815. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  7816. #ifndef __GNUG__
  7817. os << info.file << '(' << info.line << ')';
  7818. #else
  7819. os << info.file << ':' << info.line;
  7820. #endif
  7821. return os;
  7822. }
  7823. std::string StreamEndStop::operator+() const {
  7824. return std::string();
  7825. }
  7826. NonCopyable::NonCopyable() = default;
  7827. NonCopyable::~NonCopyable() = default;
  7828. }
  7829. // end catch_common.cpp
  7830. // start catch_config.cpp
  7831. namespace Catch {
  7832. Config::Config( ConfigData const& data )
  7833. : m_data( data ),
  7834. m_stream( openStream() )
  7835. {
  7836. TestSpecParser parser(ITagAliasRegistry::get());
  7837. if (!data.testsOrTags.empty()) {
  7838. m_hasTestFilters = true;
  7839. for( auto const& testOrTags : data.testsOrTags )
  7840. parser.parse( testOrTags );
  7841. }
  7842. m_testSpec = parser.testSpec();
  7843. }
  7844. std::string const& Config::getFilename() const {
  7845. return m_data.outputFilename ;
  7846. }
  7847. bool Config::listTests() const { return m_data.listTests; }
  7848. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  7849. bool Config::listTags() const { return m_data.listTags; }
  7850. bool Config::listReporters() const { return m_data.listReporters; }
  7851. std::string Config::getProcessName() const { return m_data.processName; }
  7852. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  7853. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  7854. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  7855. TestSpec const& Config::testSpec() const { return m_testSpec; }
  7856. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  7857. bool Config::showHelp() const { return m_data.showHelp; }
  7858. // IConfig interface
  7859. bool Config::allowThrows() const { return !m_data.noThrow; }
  7860. std::ostream& Config::stream() const { return m_stream->stream(); }
  7861. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  7862. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  7863. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  7864. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  7865. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  7866. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  7867. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  7868. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  7869. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  7870. int Config::abortAfter() const { return m_data.abortAfter; }
  7871. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  7872. Verbosity Config::verbosity() const { return m_data.verbosity; }
  7873. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  7874. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  7875. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  7876. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  7877. IStream const* Config::openStream() {
  7878. return Catch::makeStream(m_data.outputFilename);
  7879. }
  7880. } // end namespace Catch
  7881. // end catch_config.cpp
  7882. // start catch_console_colour.cpp
  7883. #if defined(__clang__)
  7884. # pragma clang diagnostic push
  7885. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7886. #endif
  7887. // start catch_errno_guard.h
  7888. namespace Catch {
  7889. class ErrnoGuard {
  7890. public:
  7891. ErrnoGuard();
  7892. ~ErrnoGuard();
  7893. private:
  7894. int m_oldErrno;
  7895. };
  7896. }
  7897. // end catch_errno_guard.h
  7898. #include <sstream>
  7899. namespace Catch {
  7900. namespace {
  7901. struct IColourImpl {
  7902. virtual ~IColourImpl() = default;
  7903. virtual void use( Colour::Code _colourCode ) = 0;
  7904. };
  7905. struct NoColourImpl : IColourImpl {
  7906. void use( Colour::Code ) {}
  7907. static IColourImpl* instance() {
  7908. static NoColourImpl s_instance;
  7909. return &s_instance;
  7910. }
  7911. };
  7912. } // anon namespace
  7913. } // namespace Catch
  7914. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  7915. # ifdef CATCH_PLATFORM_WINDOWS
  7916. # define CATCH_CONFIG_COLOUR_WINDOWS
  7917. # else
  7918. # define CATCH_CONFIG_COLOUR_ANSI
  7919. # endif
  7920. #endif
  7921. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  7922. namespace Catch {
  7923. namespace {
  7924. class Win32ColourImpl : public IColourImpl {
  7925. public:
  7926. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  7927. {
  7928. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  7929. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  7930. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  7931. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  7932. }
  7933. void use( Colour::Code _colourCode ) override {
  7934. switch( _colourCode ) {
  7935. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  7936. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7937. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  7938. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  7939. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  7940. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  7941. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  7942. case Colour::Grey: return setTextAttribute( 0 );
  7943. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  7944. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  7945. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  7946. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7947. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  7948. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7949. default:
  7950. CATCH_ERROR( "Unknown colour requested" );
  7951. }
  7952. }
  7953. private:
  7954. void setTextAttribute( WORD _textAttribute ) {
  7955. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  7956. }
  7957. HANDLE stdoutHandle;
  7958. WORD originalForegroundAttributes;
  7959. WORD originalBackgroundAttributes;
  7960. };
  7961. IColourImpl* platformColourInstance() {
  7962. static Win32ColourImpl s_instance;
  7963. IConfigPtr config = getCurrentContext().getConfig();
  7964. UseColour::YesOrNo colourMode = config
  7965. ? config->useColour()
  7966. : UseColour::Auto;
  7967. if( colourMode == UseColour::Auto )
  7968. colourMode = UseColour::Yes;
  7969. return colourMode == UseColour::Yes
  7970. ? &s_instance
  7971. : NoColourImpl::instance();
  7972. }
  7973. } // end anon namespace
  7974. } // end namespace Catch
  7975. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  7976. #include <unistd.h>
  7977. namespace Catch {
  7978. namespace {
  7979. // use POSIX/ ANSI console terminal codes
  7980. // Thanks to Adam Strzelecki for original contribution
  7981. // (http://github.com/nanoant)
  7982. // https://github.com/philsquared/Catch/pull/131
  7983. class PosixColourImpl : public IColourImpl {
  7984. public:
  7985. void use( Colour::Code _colourCode ) override {
  7986. switch( _colourCode ) {
  7987. case Colour::None:
  7988. case Colour::White: return setColour( "[0m" );
  7989. case Colour::Red: return setColour( "[0;31m" );
  7990. case Colour::Green: return setColour( "[0;32m" );
  7991. case Colour::Blue: return setColour( "[0;34m" );
  7992. case Colour::Cyan: return setColour( "[0;36m" );
  7993. case Colour::Yellow: return setColour( "[0;33m" );
  7994. case Colour::Grey: return setColour( "[1;30m" );
  7995. case Colour::LightGrey: return setColour( "[0;37m" );
  7996. case Colour::BrightRed: return setColour( "[1;31m" );
  7997. case Colour::BrightGreen: return setColour( "[1;32m" );
  7998. case Colour::BrightWhite: return setColour( "[1;37m" );
  7999. case Colour::BrightYellow: return setColour( "[1;33m" );
  8000. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8001. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8002. }
  8003. }
  8004. static IColourImpl* instance() {
  8005. static PosixColourImpl s_instance;
  8006. return &s_instance;
  8007. }
  8008. private:
  8009. void setColour( const char* _escapeCode ) {
  8010. getCurrentContext().getConfig()->stream()
  8011. << '\033' << _escapeCode;
  8012. }
  8013. };
  8014. bool useColourOnPlatform() {
  8015. return
  8016. #ifdef CATCH_PLATFORM_MAC
  8017. !isDebuggerActive() &&
  8018. #endif
  8019. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8020. isatty(STDOUT_FILENO)
  8021. #else
  8022. false
  8023. #endif
  8024. ;
  8025. }
  8026. IColourImpl* platformColourInstance() {
  8027. ErrnoGuard guard;
  8028. IConfigPtr config = getCurrentContext().getConfig();
  8029. UseColour::YesOrNo colourMode = config
  8030. ? config->useColour()
  8031. : UseColour::Auto;
  8032. if( colourMode == UseColour::Auto )
  8033. colourMode = useColourOnPlatform()
  8034. ? UseColour::Yes
  8035. : UseColour::No;
  8036. return colourMode == UseColour::Yes
  8037. ? PosixColourImpl::instance()
  8038. : NoColourImpl::instance();
  8039. }
  8040. } // end anon namespace
  8041. } // end namespace Catch
  8042. #else // not Windows or ANSI ///////////////////////////////////////////////
  8043. namespace Catch {
  8044. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8045. } // end namespace Catch
  8046. #endif // Windows/ ANSI/ None
  8047. namespace Catch {
  8048. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8049. Colour::Colour( Colour&& rhs ) noexcept {
  8050. m_moved = rhs.m_moved;
  8051. rhs.m_moved = true;
  8052. }
  8053. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  8054. m_moved = rhs.m_moved;
  8055. rhs.m_moved = true;
  8056. return *this;
  8057. }
  8058. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8059. void Colour::use( Code _colourCode ) {
  8060. static IColourImpl* impl = platformColourInstance();
  8061. // Strictly speaking, this cannot possibly happen.
  8062. // However, under some conditions it does happen (see #1626),
  8063. // and this change is small enough that we can let practicality
  8064. // triumph over purity in this case.
  8065. if (impl != NULL) {
  8066. impl->use( _colourCode );
  8067. }
  8068. }
  8069. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8070. return os;
  8071. }
  8072. } // end namespace Catch
  8073. #if defined(__clang__)
  8074. # pragma clang diagnostic pop
  8075. #endif
  8076. // end catch_console_colour.cpp
  8077. // start catch_context.cpp
  8078. namespace Catch {
  8079. class Context : public IMutableContext, NonCopyable {
  8080. public: // IContext
  8081. IResultCapture* getResultCapture() override {
  8082. return m_resultCapture;
  8083. }
  8084. IRunner* getRunner() override {
  8085. return m_runner;
  8086. }
  8087. IConfigPtr const& getConfig() const override {
  8088. return m_config;
  8089. }
  8090. ~Context() override;
  8091. public: // IMutableContext
  8092. void setResultCapture( IResultCapture* resultCapture ) override {
  8093. m_resultCapture = resultCapture;
  8094. }
  8095. void setRunner( IRunner* runner ) override {
  8096. m_runner = runner;
  8097. }
  8098. void setConfig( IConfigPtr const& config ) override {
  8099. m_config = config;
  8100. }
  8101. friend IMutableContext& getCurrentMutableContext();
  8102. private:
  8103. IConfigPtr m_config;
  8104. IRunner* m_runner = nullptr;
  8105. IResultCapture* m_resultCapture = nullptr;
  8106. };
  8107. IMutableContext *IMutableContext::currentContext = nullptr;
  8108. void IMutableContext::createContext()
  8109. {
  8110. currentContext = new Context();
  8111. }
  8112. void cleanUpContext() {
  8113. delete IMutableContext::currentContext;
  8114. IMutableContext::currentContext = nullptr;
  8115. }
  8116. IContext::~IContext() = default;
  8117. IMutableContext::~IMutableContext() = default;
  8118. Context::~Context() = default;
  8119. }
  8120. // end catch_context.cpp
  8121. // start catch_debug_console.cpp
  8122. // start catch_debug_console.h
  8123. #include <string>
  8124. namespace Catch {
  8125. void writeToDebugConsole( std::string const& text );
  8126. }
  8127. // end catch_debug_console.h
  8128. #if defined(__ANDROID__)
  8129. #include <android/log.h>
  8130. namespace Catch {
  8131. void writeToDebugConsole( std::string const& text ) {
  8132. __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8133. }
  8134. }
  8135. #elif defined(CATCH_PLATFORM_WINDOWS)
  8136. namespace Catch {
  8137. void writeToDebugConsole( std::string const& text ) {
  8138. ::OutputDebugStringA( text.c_str() );
  8139. }
  8140. }
  8141. #else
  8142. namespace Catch {
  8143. void writeToDebugConsole( std::string const& text ) {
  8144. // !TBD: Need a version for Mac/ XCode and other IDEs
  8145. Catch::cout() << text;
  8146. }
  8147. }
  8148. #endif // Platform
  8149. // end catch_debug_console.cpp
  8150. // start catch_debugger.cpp
  8151. #ifdef CATCH_PLATFORM_MAC
  8152. # include <assert.h>
  8153. # include <stdbool.h>
  8154. # include <sys/types.h>
  8155. # include <unistd.h>
  8156. # include <cstddef>
  8157. # include <ostream>
  8158. #ifdef __apple_build_version__
  8159. // These headers will only compile with AppleClang (XCode)
  8160. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8161. # include <sys/sysctl.h>
  8162. #endif
  8163. namespace Catch {
  8164. #ifdef __apple_build_version__
  8165. // The following function is taken directly from the following technical note:
  8166. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8167. // Returns true if the current process is being debugged (either
  8168. // running under the debugger or has a debugger attached post facto).
  8169. bool isDebuggerActive(){
  8170. int mib[4];
  8171. struct kinfo_proc info;
  8172. std::size_t size;
  8173. // Initialize the flags so that, if sysctl fails for some bizarre
  8174. // reason, we get a predictable result.
  8175. info.kp_proc.p_flag = 0;
  8176. // Initialize mib, which tells sysctl the info we want, in this case
  8177. // we're looking for information about a specific process ID.
  8178. mib[0] = CTL_KERN;
  8179. mib[1] = KERN_PROC;
  8180. mib[2] = KERN_PROC_PID;
  8181. mib[3] = getpid();
  8182. // Call sysctl.
  8183. size = sizeof(info);
  8184. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8185. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8186. return false;
  8187. }
  8188. // We're being debugged if the P_TRACED flag is set.
  8189. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8190. }
  8191. #else
  8192. bool isDebuggerActive() {
  8193. // We need to find another way to determine this for non-appleclang compilers on macOS
  8194. return false;
  8195. }
  8196. #endif
  8197. } // namespace Catch
  8198. #elif defined(CATCH_PLATFORM_LINUX)
  8199. #include <fstream>
  8200. #include <string>
  8201. namespace Catch{
  8202. // The standard POSIX way of detecting a debugger is to attempt to
  8203. // ptrace() the process, but this needs to be done from a child and not
  8204. // this process itself to still allow attaching to this process later
  8205. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8206. // "debugger" (which doesn't need to be gdb, of course, it could also
  8207. // be strace, for example) in /proc/$PID/status, so just get it from
  8208. // there instead.
  8209. bool isDebuggerActive(){
  8210. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8211. // This way our users can properly assert over errno values
  8212. ErrnoGuard guard;
  8213. std::ifstream in("/proc/self/status");
  8214. for( std::string line; std::getline(in, line); ) {
  8215. static const int PREFIX_LEN = 11;
  8216. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8217. // We're traced if the PID is not 0 and no other PID starts
  8218. // with 0 digit, so it's enough to check for just a single
  8219. // character.
  8220. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8221. }
  8222. }
  8223. return false;
  8224. }
  8225. } // namespace Catch
  8226. #elif defined(_MSC_VER)
  8227. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8228. namespace Catch {
  8229. bool isDebuggerActive() {
  8230. return IsDebuggerPresent() != 0;
  8231. }
  8232. }
  8233. #elif defined(__MINGW32__)
  8234. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8235. namespace Catch {
  8236. bool isDebuggerActive() {
  8237. return IsDebuggerPresent() != 0;
  8238. }
  8239. }
  8240. #else
  8241. namespace Catch {
  8242. bool isDebuggerActive() { return false; }
  8243. }
  8244. #endif // Platform
  8245. // end catch_debugger.cpp
  8246. // start catch_decomposer.cpp
  8247. namespace Catch {
  8248. ITransientExpression::~ITransientExpression() = default;
  8249. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8250. if( lhs.size() + rhs.size() < 40 &&
  8251. lhs.find('\n') == std::string::npos &&
  8252. rhs.find('\n') == std::string::npos )
  8253. os << lhs << " " << op << " " << rhs;
  8254. else
  8255. os << lhs << "\n" << op << "\n" << rhs;
  8256. }
  8257. }
  8258. // end catch_decomposer.cpp
  8259. // start catch_enforce.cpp
  8260. #include <stdexcept>
  8261. namespace Catch {
  8262. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8263. [[noreturn]]
  8264. void throw_exception(std::exception const& e) {
  8265. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8266. << "The message was: " << e.what() << '\n';
  8267. std::terminate();
  8268. }
  8269. #endif
  8270. [[noreturn]]
  8271. void throw_logic_error(std::string const& msg) {
  8272. throw_exception(std::logic_error(msg));
  8273. }
  8274. [[noreturn]]
  8275. void throw_domain_error(std::string const& msg) {
  8276. throw_exception(std::domain_error(msg));
  8277. }
  8278. [[noreturn]]
  8279. void throw_runtime_error(std::string const& msg) {
  8280. throw_exception(std::runtime_error(msg));
  8281. }
  8282. } // namespace Catch;
  8283. // end catch_enforce.cpp
  8284. // start catch_enum_values_registry.cpp
  8285. // start catch_enum_values_registry.h
  8286. #include <vector>
  8287. #include <memory>
  8288. namespace Catch {
  8289. namespace Detail {
  8290. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8291. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8292. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8293. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8294. };
  8295. std::vector<std::string> parseEnums( StringRef enums );
  8296. } // Detail
  8297. } // Catch
  8298. // end catch_enum_values_registry.h
  8299. #include <map>
  8300. #include <cassert>
  8301. namespace Catch {
  8302. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8303. namespace Detail {
  8304. std::vector<std::string> parseEnums( StringRef enums ) {
  8305. auto enumValues = splitStringRef( enums, ',' );
  8306. std::vector<std::string> parsed;
  8307. parsed.reserve( enumValues.size() );
  8308. for( auto const& enumValue : enumValues ) {
  8309. auto identifiers = splitStringRef( enumValue, ':' );
  8310. parsed.push_back( Catch::trim( identifiers.back() ) );
  8311. }
  8312. return parsed;
  8313. }
  8314. EnumInfo::~EnumInfo() {}
  8315. StringRef EnumInfo::lookup( int value ) const {
  8316. for( auto const& valueToName : m_values ) {
  8317. if( valueToName.first == value )
  8318. return valueToName.second;
  8319. }
  8320. return "{** unexpected enum value **}";
  8321. }
  8322. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8323. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8324. enumInfo->m_name = enumName;
  8325. enumInfo->m_values.reserve( values.size() );
  8326. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8327. assert( valueNames.size() == values.size() );
  8328. std::size_t i = 0;
  8329. for( auto value : values )
  8330. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8331. return enumInfo;
  8332. }
  8333. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8334. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8335. EnumInfo* raw = enumInfo.get();
  8336. m_enumInfos.push_back( std::move( enumInfo ) );
  8337. return *raw;
  8338. }
  8339. } // Detail
  8340. } // Catch
  8341. // end catch_enum_values_registry.cpp
  8342. // start catch_errno_guard.cpp
  8343. #include <cerrno>
  8344. namespace Catch {
  8345. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8346. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8347. }
  8348. // end catch_errno_guard.cpp
  8349. // start catch_exception_translator_registry.cpp
  8350. // start catch_exception_translator_registry.h
  8351. #include <vector>
  8352. #include <string>
  8353. #include <memory>
  8354. namespace Catch {
  8355. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8356. public:
  8357. ~ExceptionTranslatorRegistry();
  8358. virtual void registerTranslator( const IExceptionTranslator* translator );
  8359. std::string translateActiveException() const override;
  8360. std::string tryTranslators() const;
  8361. private:
  8362. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8363. };
  8364. }
  8365. // end catch_exception_translator_registry.h
  8366. #ifdef __OBJC__
  8367. #import "Foundation/Foundation.h"
  8368. #endif
  8369. namespace Catch {
  8370. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8371. }
  8372. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8373. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8374. }
  8375. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8376. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8377. try {
  8378. #ifdef __OBJC__
  8379. // In Objective-C try objective-c exceptions first
  8380. @try {
  8381. return tryTranslators();
  8382. }
  8383. @catch (NSException *exception) {
  8384. return Catch::Detail::stringify( [exception description] );
  8385. }
  8386. #else
  8387. // Compiling a mixed mode project with MSVC means that CLR
  8388. // exceptions will be caught in (...) as well. However, these
  8389. // do not fill-in std::current_exception and thus lead to crash
  8390. // when attempting rethrow.
  8391. // /EHa switch also causes structured exceptions to be caught
  8392. // here, but they fill-in current_exception properly, so
  8393. // at worst the output should be a little weird, instead of
  8394. // causing a crash.
  8395. if (std::current_exception() == nullptr) {
  8396. return "Non C++ exception. Possibly a CLR exception.";
  8397. }
  8398. return tryTranslators();
  8399. #endif
  8400. }
  8401. catch( TestFailureException& ) {
  8402. std::rethrow_exception(std::current_exception());
  8403. }
  8404. catch( std::exception& ex ) {
  8405. return ex.what();
  8406. }
  8407. catch( std::string& msg ) {
  8408. return msg;
  8409. }
  8410. catch( const char* msg ) {
  8411. return msg;
  8412. }
  8413. catch(...) {
  8414. return "Unknown exception";
  8415. }
  8416. }
  8417. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8418. if (m_translators.empty()) {
  8419. std::rethrow_exception(std::current_exception());
  8420. } else {
  8421. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8422. }
  8423. }
  8424. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8425. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8426. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8427. }
  8428. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8429. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8430. }
  8431. #endif
  8432. }
  8433. // end catch_exception_translator_registry.cpp
  8434. // start catch_fatal_condition.cpp
  8435. #if defined(__GNUC__)
  8436. # pragma GCC diagnostic push
  8437. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8438. #endif
  8439. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8440. namespace {
  8441. // Report the error condition
  8442. void reportFatal( char const * const message ) {
  8443. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8444. }
  8445. }
  8446. #endif // signals/SEH handling
  8447. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8448. namespace Catch {
  8449. struct SignalDefs { DWORD id; const char* name; };
  8450. // There is no 1-1 mapping between signals and windows exceptions.
  8451. // Windows can easily distinguish between SO and SigSegV,
  8452. // but SigInt, SigTerm, etc are handled differently.
  8453. static SignalDefs signalDefs[] = {
  8454. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8455. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8456. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8457. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8458. };
  8459. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8460. for (auto const& def : signalDefs) {
  8461. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8462. reportFatal(def.name);
  8463. }
  8464. }
  8465. // If its not an exception we care about, pass it along.
  8466. // This stops us from eating debugger breaks etc.
  8467. return EXCEPTION_CONTINUE_SEARCH;
  8468. }
  8469. FatalConditionHandler::FatalConditionHandler() {
  8470. isSet = true;
  8471. // 32k seems enough for Catch to handle stack overflow,
  8472. // but the value was found experimentally, so there is no strong guarantee
  8473. guaranteeSize = 32 * 1024;
  8474. exceptionHandlerHandle = nullptr;
  8475. // Register as first handler in current chain
  8476. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8477. // Pass in guarantee size to be filled
  8478. SetThreadStackGuarantee(&guaranteeSize);
  8479. }
  8480. void FatalConditionHandler::reset() {
  8481. if (isSet) {
  8482. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8483. SetThreadStackGuarantee(&guaranteeSize);
  8484. exceptionHandlerHandle = nullptr;
  8485. isSet = false;
  8486. }
  8487. }
  8488. FatalConditionHandler::~FatalConditionHandler() {
  8489. reset();
  8490. }
  8491. bool FatalConditionHandler::isSet = false;
  8492. ULONG FatalConditionHandler::guaranteeSize = 0;
  8493. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8494. } // namespace Catch
  8495. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8496. namespace Catch {
  8497. struct SignalDefs {
  8498. int id;
  8499. const char* name;
  8500. };
  8501. // 32kb for the alternate stack seems to be sufficient. However, this value
  8502. // is experimentally determined, so that's not guaranteed.
  8503. static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8504. static SignalDefs signalDefs[] = {
  8505. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8506. { SIGILL, "SIGILL - Illegal instruction signal" },
  8507. { SIGFPE, "SIGFPE - Floating point error signal" },
  8508. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8509. { SIGTERM, "SIGTERM - Termination request signal" },
  8510. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8511. };
  8512. void FatalConditionHandler::handleSignal( int sig ) {
  8513. char const * name = "<unknown signal>";
  8514. for (auto const& def : signalDefs) {
  8515. if (sig == def.id) {
  8516. name = def.name;
  8517. break;
  8518. }
  8519. }
  8520. reset();
  8521. reportFatal(name);
  8522. raise( sig );
  8523. }
  8524. FatalConditionHandler::FatalConditionHandler() {
  8525. isSet = true;
  8526. stack_t sigStack;
  8527. sigStack.ss_sp = altStackMem;
  8528. sigStack.ss_size = sigStackSize;
  8529. sigStack.ss_flags = 0;
  8530. sigaltstack(&sigStack, &oldSigStack);
  8531. struct sigaction sa = { };
  8532. sa.sa_handler = handleSignal;
  8533. sa.sa_flags = SA_ONSTACK;
  8534. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8535. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8536. }
  8537. }
  8538. FatalConditionHandler::~FatalConditionHandler() {
  8539. reset();
  8540. }
  8541. void FatalConditionHandler::reset() {
  8542. if( isSet ) {
  8543. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8544. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8545. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8546. }
  8547. // Return the old stack
  8548. sigaltstack(&oldSigStack, nullptr);
  8549. isSet = false;
  8550. }
  8551. }
  8552. bool FatalConditionHandler::isSet = false;
  8553. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8554. stack_t FatalConditionHandler::oldSigStack = {};
  8555. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8556. } // namespace Catch
  8557. #else
  8558. namespace Catch {
  8559. void FatalConditionHandler::reset() {}
  8560. }
  8561. #endif // signals/SEH handling
  8562. #if defined(__GNUC__)
  8563. # pragma GCC diagnostic pop
  8564. #endif
  8565. // end catch_fatal_condition.cpp
  8566. // start catch_generators.cpp
  8567. // start catch_random_number_generator.h
  8568. #include <algorithm>
  8569. #include <random>
  8570. namespace Catch {
  8571. struct IConfig;
  8572. std::mt19937& rng();
  8573. void seedRng( IConfig const& config );
  8574. unsigned int rngSeed();
  8575. }
  8576. // end catch_random_number_generator.h
  8577. #include <limits>
  8578. #include <set>
  8579. namespace Catch {
  8580. IGeneratorTracker::~IGeneratorTracker() {}
  8581. const char* GeneratorException::what() const noexcept {
  8582. return m_msg;
  8583. }
  8584. namespace Generators {
  8585. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8586. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8587. return getResultCapture().acquireGeneratorTracker( lineInfo );
  8588. }
  8589. } // namespace Generators
  8590. } // namespace Catch
  8591. // end catch_generators.cpp
  8592. // start catch_interfaces_capture.cpp
  8593. namespace Catch {
  8594. IResultCapture::~IResultCapture() = default;
  8595. }
  8596. // end catch_interfaces_capture.cpp
  8597. // start catch_interfaces_config.cpp
  8598. namespace Catch {
  8599. IConfig::~IConfig() = default;
  8600. }
  8601. // end catch_interfaces_config.cpp
  8602. // start catch_interfaces_exception.cpp
  8603. namespace Catch {
  8604. IExceptionTranslator::~IExceptionTranslator() = default;
  8605. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8606. }
  8607. // end catch_interfaces_exception.cpp
  8608. // start catch_interfaces_registry_hub.cpp
  8609. namespace Catch {
  8610. IRegistryHub::~IRegistryHub() = default;
  8611. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8612. }
  8613. // end catch_interfaces_registry_hub.cpp
  8614. // start catch_interfaces_reporter.cpp
  8615. // start catch_reporter_listening.h
  8616. namespace Catch {
  8617. class ListeningReporter : public IStreamingReporter {
  8618. using Reporters = std::vector<IStreamingReporterPtr>;
  8619. Reporters m_listeners;
  8620. IStreamingReporterPtr m_reporter = nullptr;
  8621. ReporterPreferences m_preferences;
  8622. public:
  8623. ListeningReporter();
  8624. void addListener( IStreamingReporterPtr&& listener );
  8625. void addReporter( IStreamingReporterPtr&& reporter );
  8626. public: // IStreamingReporter
  8627. ReporterPreferences getPreferences() const override;
  8628. void noMatchingTestCases( std::string const& spec ) override;
  8629. static std::set<Verbosity> getSupportedVerbosities();
  8630. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8631. void benchmarkPreparing(std::string const& name) override;
  8632. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8633. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8634. void benchmarkFailed(std::string const&) override;
  8635. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8636. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8637. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8638. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8639. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8640. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8641. // The return value indicates if the messages buffer should be cleared:
  8642. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8643. void sectionEnded( SectionStats const& sectionStats ) override;
  8644. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8645. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8646. void testRunEnded( TestRunStats const& testRunStats ) override;
  8647. void skipTest( TestCaseInfo const& testInfo ) override;
  8648. bool isMulti() const override;
  8649. };
  8650. } // end namespace Catch
  8651. // end catch_reporter_listening.h
  8652. namespace Catch {
  8653. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8654. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8655. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8656. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8657. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8658. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8659. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8660. GroupInfo::GroupInfo( std::string const& _name,
  8661. std::size_t _groupIndex,
  8662. std::size_t _groupsCount )
  8663. : name( _name ),
  8664. groupIndex( _groupIndex ),
  8665. groupsCounts( _groupsCount )
  8666. {}
  8667. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8668. std::vector<MessageInfo> const& _infoMessages,
  8669. Totals const& _totals )
  8670. : assertionResult( _assertionResult ),
  8671. infoMessages( _infoMessages ),
  8672. totals( _totals )
  8673. {
  8674. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8675. if( assertionResult.hasMessage() ) {
  8676. // Copy message into messages list.
  8677. // !TBD This should have been done earlier, somewhere
  8678. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8679. builder << assertionResult.getMessage();
  8680. builder.m_info.message = builder.m_stream.str();
  8681. infoMessages.push_back( builder.m_info );
  8682. }
  8683. }
  8684. AssertionStats::~AssertionStats() = default;
  8685. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8686. Counts const& _assertions,
  8687. double _durationInSeconds,
  8688. bool _missingAssertions )
  8689. : sectionInfo( _sectionInfo ),
  8690. assertions( _assertions ),
  8691. durationInSeconds( _durationInSeconds ),
  8692. missingAssertions( _missingAssertions )
  8693. {}
  8694. SectionStats::~SectionStats() = default;
  8695. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8696. Totals const& _totals,
  8697. std::string const& _stdOut,
  8698. std::string const& _stdErr,
  8699. bool _aborting )
  8700. : testInfo( _testInfo ),
  8701. totals( _totals ),
  8702. stdOut( _stdOut ),
  8703. stdErr( _stdErr ),
  8704. aborting( _aborting )
  8705. {}
  8706. TestCaseStats::~TestCaseStats() = default;
  8707. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  8708. Totals const& _totals,
  8709. bool _aborting )
  8710. : groupInfo( _groupInfo ),
  8711. totals( _totals ),
  8712. aborting( _aborting )
  8713. {}
  8714. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  8715. : groupInfo( _groupInfo ),
  8716. aborting( false )
  8717. {}
  8718. TestGroupStats::~TestGroupStats() = default;
  8719. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  8720. Totals const& _totals,
  8721. bool _aborting )
  8722. : runInfo( _runInfo ),
  8723. totals( _totals ),
  8724. aborting( _aborting )
  8725. {}
  8726. TestRunStats::~TestRunStats() = default;
  8727. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  8728. bool IStreamingReporter::isMulti() const { return false; }
  8729. IReporterFactory::~IReporterFactory() = default;
  8730. IReporterRegistry::~IReporterRegistry() = default;
  8731. } // end namespace Catch
  8732. // end catch_interfaces_reporter.cpp
  8733. // start catch_interfaces_runner.cpp
  8734. namespace Catch {
  8735. IRunner::~IRunner() = default;
  8736. }
  8737. // end catch_interfaces_runner.cpp
  8738. // start catch_interfaces_testcase.cpp
  8739. namespace Catch {
  8740. ITestInvoker::~ITestInvoker() = default;
  8741. ITestCaseRegistry::~ITestCaseRegistry() = default;
  8742. }
  8743. // end catch_interfaces_testcase.cpp
  8744. // start catch_leak_detector.cpp
  8745. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  8746. #include <crtdbg.h>
  8747. namespace Catch {
  8748. LeakDetector::LeakDetector() {
  8749. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8750. flag |= _CRTDBG_LEAK_CHECK_DF;
  8751. flag |= _CRTDBG_ALLOC_MEM_DF;
  8752. _CrtSetDbgFlag(flag);
  8753. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  8754. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  8755. // Change this to leaking allocation's number to break there
  8756. _CrtSetBreakAlloc(-1);
  8757. }
  8758. }
  8759. #else
  8760. Catch::LeakDetector::LeakDetector() {}
  8761. #endif
  8762. Catch::LeakDetector::~LeakDetector() {
  8763. Catch::cleanUp();
  8764. }
  8765. // end catch_leak_detector.cpp
  8766. // start catch_list.cpp
  8767. // start catch_list.h
  8768. #include <set>
  8769. namespace Catch {
  8770. std::size_t listTests( Config const& config );
  8771. std::size_t listTestsNamesOnly( Config const& config );
  8772. struct TagInfo {
  8773. void add( std::string const& spelling );
  8774. std::string all() const;
  8775. std::set<std::string> spellings;
  8776. std::size_t count = 0;
  8777. };
  8778. std::size_t listTags( Config const& config );
  8779. std::size_t listReporters();
  8780. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  8781. } // end namespace Catch
  8782. // end catch_list.h
  8783. // start catch_text.h
  8784. namespace Catch {
  8785. using namespace clara::TextFlow;
  8786. }
  8787. // end catch_text.h
  8788. #include <limits>
  8789. #include <algorithm>
  8790. #include <iomanip>
  8791. namespace Catch {
  8792. std::size_t listTests( Config const& config ) {
  8793. TestSpec testSpec = config.testSpec();
  8794. if( config.hasTestFilters() )
  8795. Catch::cout() << "Matching test cases:\n";
  8796. else {
  8797. Catch::cout() << "All available test cases:\n";
  8798. }
  8799. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8800. for( auto const& testCaseInfo : matchedTestCases ) {
  8801. Colour::Code colour = testCaseInfo.isHidden()
  8802. ? Colour::SecondaryText
  8803. : Colour::None;
  8804. Colour colourGuard( colour );
  8805. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  8806. if( config.verbosity() >= Verbosity::High ) {
  8807. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  8808. std::string description = testCaseInfo.description;
  8809. if( description.empty() )
  8810. description = "(NO DESCRIPTION)";
  8811. Catch::cout() << Column( description ).indent(4) << std::endl;
  8812. }
  8813. if( !testCaseInfo.tags.empty() )
  8814. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  8815. }
  8816. if( !config.hasTestFilters() )
  8817. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  8818. else
  8819. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  8820. return matchedTestCases.size();
  8821. }
  8822. std::size_t listTestsNamesOnly( Config const& config ) {
  8823. TestSpec testSpec = config.testSpec();
  8824. std::size_t matchedTests = 0;
  8825. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8826. for( auto const& testCaseInfo : matchedTestCases ) {
  8827. matchedTests++;
  8828. if( startsWith( testCaseInfo.name, '#' ) )
  8829. Catch::cout() << '"' << testCaseInfo.name << '"';
  8830. else
  8831. Catch::cout() << testCaseInfo.name;
  8832. if ( config.verbosity() >= Verbosity::High )
  8833. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  8834. Catch::cout() << std::endl;
  8835. }
  8836. return matchedTests;
  8837. }
  8838. void TagInfo::add( std::string const& spelling ) {
  8839. ++count;
  8840. spellings.insert( spelling );
  8841. }
  8842. std::string TagInfo::all() const {
  8843. size_t size = 0;
  8844. for (auto const& spelling : spellings) {
  8845. // Add 2 for the brackes
  8846. size += spelling.size() + 2;
  8847. }
  8848. std::string out; out.reserve(size);
  8849. for (auto const& spelling : spellings) {
  8850. out += '[';
  8851. out += spelling;
  8852. out += ']';
  8853. }
  8854. return out;
  8855. }
  8856. std::size_t listTags( Config const& config ) {
  8857. TestSpec testSpec = config.testSpec();
  8858. if( config.hasTestFilters() )
  8859. Catch::cout() << "Tags for matching test cases:\n";
  8860. else {
  8861. Catch::cout() << "All available tags:\n";
  8862. }
  8863. std::map<std::string, TagInfo> tagCounts;
  8864. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8865. for( auto const& testCase : matchedTestCases ) {
  8866. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  8867. std::string lcaseTagName = toLower( tagName );
  8868. auto countIt = tagCounts.find( lcaseTagName );
  8869. if( countIt == tagCounts.end() )
  8870. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  8871. countIt->second.add( tagName );
  8872. }
  8873. }
  8874. for( auto const& tagCount : tagCounts ) {
  8875. ReusableStringStream rss;
  8876. rss << " " << std::setw(2) << tagCount.second.count << " ";
  8877. auto str = rss.str();
  8878. auto wrapper = Column( tagCount.second.all() )
  8879. .initialIndent( 0 )
  8880. .indent( str.size() )
  8881. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  8882. Catch::cout() << str << wrapper << '\n';
  8883. }
  8884. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  8885. return tagCounts.size();
  8886. }
  8887. std::size_t listReporters() {
  8888. Catch::cout() << "Available reporters:\n";
  8889. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8890. std::size_t maxNameLen = 0;
  8891. for( auto const& factoryKvp : factories )
  8892. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  8893. for( auto const& factoryKvp : factories ) {
  8894. Catch::cout()
  8895. << Column( factoryKvp.first + ":" )
  8896. .indent(2)
  8897. .width( 5+maxNameLen )
  8898. + Column( factoryKvp.second->getDescription() )
  8899. .initialIndent(0)
  8900. .indent(2)
  8901. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  8902. << "\n";
  8903. }
  8904. Catch::cout() << std::endl;
  8905. return factories.size();
  8906. }
  8907. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  8908. Option<std::size_t> listedCount;
  8909. getCurrentMutableContext().setConfig( config );
  8910. if( config->listTests() )
  8911. listedCount = listedCount.valueOr(0) + listTests( *config );
  8912. if( config->listTestNamesOnly() )
  8913. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  8914. if( config->listTags() )
  8915. listedCount = listedCount.valueOr(0) + listTags( *config );
  8916. if( config->listReporters() )
  8917. listedCount = listedCount.valueOr(0) + listReporters();
  8918. return listedCount;
  8919. }
  8920. } // end namespace Catch
  8921. // end catch_list.cpp
  8922. // start catch_matchers.cpp
  8923. namespace Catch {
  8924. namespace Matchers {
  8925. namespace Impl {
  8926. std::string MatcherUntypedBase::toString() const {
  8927. if( m_cachedToString.empty() )
  8928. m_cachedToString = describe();
  8929. return m_cachedToString;
  8930. }
  8931. MatcherUntypedBase::~MatcherUntypedBase() = default;
  8932. } // namespace Impl
  8933. } // namespace Matchers
  8934. using namespace Matchers;
  8935. using Matchers::Impl::MatcherBase;
  8936. } // namespace Catch
  8937. // end catch_matchers.cpp
  8938. // start catch_matchers_floating.cpp
  8939. // start catch_polyfills.hpp
  8940. namespace Catch {
  8941. bool isnan(float f);
  8942. bool isnan(double d);
  8943. }
  8944. // end catch_polyfills.hpp
  8945. // start catch_to_string.hpp
  8946. #include <string>
  8947. namespace Catch {
  8948. template <typename T>
  8949. std::string to_string(T const& t) {
  8950. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  8951. return std::to_string(t);
  8952. #else
  8953. ReusableStringStream rss;
  8954. rss << t;
  8955. return rss.str();
  8956. #endif
  8957. }
  8958. } // end namespace Catch
  8959. // end catch_to_string.hpp
  8960. #include <cstdlib>
  8961. #include <cstdint>
  8962. #include <cstring>
  8963. #include <sstream>
  8964. #include <iomanip>
  8965. #include <limits>
  8966. namespace Catch {
  8967. namespace Matchers {
  8968. namespace Floating {
  8969. enum class FloatingPointKind : uint8_t {
  8970. Float,
  8971. Double
  8972. };
  8973. }
  8974. }
  8975. }
  8976. namespace {
  8977. template <typename T>
  8978. struct Converter;
  8979. template <>
  8980. struct Converter<float> {
  8981. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  8982. Converter(float f) {
  8983. std::memcpy(&i, &f, sizeof(f));
  8984. }
  8985. int32_t i;
  8986. };
  8987. template <>
  8988. struct Converter<double> {
  8989. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  8990. Converter(double d) {
  8991. std::memcpy(&i, &d, sizeof(d));
  8992. }
  8993. int64_t i;
  8994. };
  8995. template <typename T>
  8996. auto convert(T t) -> Converter<T> {
  8997. return Converter<T>(t);
  8998. }
  8999. template <typename FP>
  9000. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  9001. // Comparison with NaN should always be false.
  9002. // This way we can rule it out before getting into the ugly details
  9003. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9004. return false;
  9005. }
  9006. auto lc = convert(lhs);
  9007. auto rc = convert(rhs);
  9008. if ((lc.i < 0) != (rc.i < 0)) {
  9009. // Potentially we can have +0 and -0
  9010. return lhs == rhs;
  9011. }
  9012. auto ulpDiff = std::abs(lc.i - rc.i);
  9013. return ulpDiff <= maxUlpDiff;
  9014. }
  9015. template <typename FP>
  9016. FP step(FP start, FP direction, int steps) {
  9017. for (int i = 0; i < steps; ++i) {
  9018. start = std::nextafter(start, direction);
  9019. }
  9020. return start;
  9021. }
  9022. } // end anonymous namespace
  9023. namespace Catch {
  9024. namespace Matchers {
  9025. namespace Floating {
  9026. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9027. :m_target{ target }, m_margin{ margin } {
  9028. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9029. << " Margin has to be non-negative.");
  9030. }
  9031. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9032. // But without the subtraction to allow for INFINITY in comparison
  9033. bool WithinAbsMatcher::match(double const& matchee) const {
  9034. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9035. }
  9036. std::string WithinAbsMatcher::describe() const {
  9037. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9038. }
  9039. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  9040. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9041. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  9042. << " ULPs have to be non-negative.");
  9043. }
  9044. #if defined(__clang__)
  9045. #pragma clang diagnostic push
  9046. // Clang <3.5 reports on the default branch in the switch below
  9047. #pragma clang diagnostic ignored "-Wunreachable-code"
  9048. #endif
  9049. bool WithinUlpsMatcher::match(double const& matchee) const {
  9050. switch (m_type) {
  9051. case FloatingPointKind::Float:
  9052. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9053. case FloatingPointKind::Double:
  9054. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9055. default:
  9056. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9057. }
  9058. }
  9059. #if defined(__clang__)
  9060. #pragma clang diagnostic pop
  9061. #endif
  9062. std::string WithinUlpsMatcher::describe() const {
  9063. std::stringstream ret;
  9064. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  9065. if (m_type == FloatingPointKind::Float) {
  9066. ret << 'f';
  9067. }
  9068. ret << " ([";
  9069. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  9070. if (m_type == FloatingPointKind::Double) {
  9071. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  9072. << ", "
  9073. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  9074. } else {
  9075. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  9076. << ", "
  9077. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9078. }
  9079. ret << "])";
  9080. return ret.str();
  9081. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9082. }
  9083. }// namespace Floating
  9084. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9085. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9086. }
  9087. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9088. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9089. }
  9090. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9091. return Floating::WithinAbsMatcher(target, margin);
  9092. }
  9093. } // namespace Matchers
  9094. } // namespace Catch
  9095. // end catch_matchers_floating.cpp
  9096. // start catch_matchers_generic.cpp
  9097. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9098. if (desc.empty()) {
  9099. return "matches undescribed predicate";
  9100. } else {
  9101. return "matches predicate: \"" + desc + '"';
  9102. }
  9103. }
  9104. // end catch_matchers_generic.cpp
  9105. // start catch_matchers_string.cpp
  9106. #include <regex>
  9107. namespace Catch {
  9108. namespace Matchers {
  9109. namespace StdString {
  9110. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9111. : m_caseSensitivity( caseSensitivity ),
  9112. m_str( adjustString( str ) )
  9113. {}
  9114. std::string CasedString::adjustString( std::string const& str ) const {
  9115. return m_caseSensitivity == CaseSensitive::No
  9116. ? toLower( str )
  9117. : str;
  9118. }
  9119. std::string CasedString::caseSensitivitySuffix() const {
  9120. return m_caseSensitivity == CaseSensitive::No
  9121. ? " (case insensitive)"
  9122. : std::string();
  9123. }
  9124. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9125. : m_comparator( comparator ),
  9126. m_operation( operation ) {
  9127. }
  9128. std::string StringMatcherBase::describe() const {
  9129. std::string description;
  9130. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9131. m_comparator.caseSensitivitySuffix().size());
  9132. description += m_operation;
  9133. description += ": \"";
  9134. description += m_comparator.m_str;
  9135. description += "\"";
  9136. description += m_comparator.caseSensitivitySuffix();
  9137. return description;
  9138. }
  9139. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9140. bool EqualsMatcher::match( std::string const& source ) const {
  9141. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9142. }
  9143. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9144. bool ContainsMatcher::match( std::string const& source ) const {
  9145. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9146. }
  9147. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9148. bool StartsWithMatcher::match( std::string const& source ) const {
  9149. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9150. }
  9151. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9152. bool EndsWithMatcher::match( std::string const& source ) const {
  9153. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9154. }
  9155. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9156. bool RegexMatcher::match(std::string const& matchee) const {
  9157. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9158. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9159. flags |= std::regex::icase;
  9160. }
  9161. auto reg = std::regex(m_regex, flags);
  9162. return std::regex_match(matchee, reg);
  9163. }
  9164. std::string RegexMatcher::describe() const {
  9165. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9166. }
  9167. } // namespace StdString
  9168. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9169. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9170. }
  9171. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9172. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9173. }
  9174. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9175. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9176. }
  9177. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9178. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9179. }
  9180. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9181. return StdString::RegexMatcher(regex, caseSensitivity);
  9182. }
  9183. } // namespace Matchers
  9184. } // namespace Catch
  9185. // end catch_matchers_string.cpp
  9186. // start catch_message.cpp
  9187. // start catch_uncaught_exceptions.h
  9188. namespace Catch {
  9189. bool uncaught_exceptions();
  9190. } // end namespace Catch
  9191. // end catch_uncaught_exceptions.h
  9192. #include <cassert>
  9193. #include <stack>
  9194. namespace Catch {
  9195. MessageInfo::MessageInfo( StringRef const& _macroName,
  9196. SourceLineInfo const& _lineInfo,
  9197. ResultWas::OfType _type )
  9198. : macroName( _macroName ),
  9199. lineInfo( _lineInfo ),
  9200. type( _type ),
  9201. sequence( ++globalCount )
  9202. {}
  9203. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9204. return sequence == other.sequence;
  9205. }
  9206. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9207. return sequence < other.sequence;
  9208. }
  9209. // This may need protecting if threading support is added
  9210. unsigned int MessageInfo::globalCount = 0;
  9211. ////////////////////////////////////////////////////////////////////////////
  9212. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9213. SourceLineInfo const& lineInfo,
  9214. ResultWas::OfType type )
  9215. :m_info(macroName, lineInfo, type) {}
  9216. ////////////////////////////////////////////////////////////////////////////
  9217. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9218. : m_info( builder.m_info ), m_moved()
  9219. {
  9220. m_info.message = builder.m_stream.str();
  9221. getResultCapture().pushScopedMessage( m_info );
  9222. }
  9223. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9224. : m_info( old.m_info ), m_moved()
  9225. {
  9226. old.m_moved = true;
  9227. }
  9228. ScopedMessage::~ScopedMessage() {
  9229. if ( !uncaught_exceptions() && !m_moved ){
  9230. getResultCapture().popScopedMessage(m_info);
  9231. }
  9232. }
  9233. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9234. auto trimmed = [&] (size_t start, size_t end) {
  9235. while (names[start] == ',' || isspace(names[start])) {
  9236. ++start;
  9237. }
  9238. while (names[end] == ',' || isspace(names[end])) {
  9239. --end;
  9240. }
  9241. return names.substr(start, end - start + 1);
  9242. };
  9243. auto skipq = [&] (size_t start, char quote) {
  9244. for (auto i = start + 1; i < names.size() ; ++i) {
  9245. if (names[i] == quote)
  9246. return i;
  9247. if (names[i] == '\\')
  9248. ++i;
  9249. }
  9250. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9251. };
  9252. size_t start = 0;
  9253. std::stack<char> openings;
  9254. for (size_t pos = 0; pos < names.size(); ++pos) {
  9255. char c = names[pos];
  9256. switch (c) {
  9257. case '[':
  9258. case '{':
  9259. case '(':
  9260. // It is basically impossible to disambiguate between
  9261. // comparison and start of template args in this context
  9262. // case '<':
  9263. openings.push(c);
  9264. break;
  9265. case ']':
  9266. case '}':
  9267. case ')':
  9268. // case '>':
  9269. openings.pop();
  9270. break;
  9271. case '"':
  9272. case '\'':
  9273. pos = skipq(pos, c);
  9274. break;
  9275. case ',':
  9276. if (start != pos && openings.size() == 0) {
  9277. m_messages.emplace_back(macroName, lineInfo, resultType);
  9278. m_messages.back().message = trimmed(start, pos);
  9279. m_messages.back().message += " := ";
  9280. start = pos;
  9281. }
  9282. }
  9283. }
  9284. assert(openings.size() == 0 && "Mismatched openings");
  9285. m_messages.emplace_back(macroName, lineInfo, resultType);
  9286. m_messages.back().message = trimmed(start, names.size() - 1);
  9287. m_messages.back().message += " := ";
  9288. }
  9289. Capturer::~Capturer() {
  9290. if ( !uncaught_exceptions() ){
  9291. assert( m_captured == m_messages.size() );
  9292. for( size_t i = 0; i < m_captured; ++i )
  9293. m_resultCapture.popScopedMessage( m_messages[i] );
  9294. }
  9295. }
  9296. void Capturer::captureValue( size_t index, std::string const& value ) {
  9297. assert( index < m_messages.size() );
  9298. m_messages[index].message += value;
  9299. m_resultCapture.pushScopedMessage( m_messages[index] );
  9300. m_captured++;
  9301. }
  9302. } // end namespace Catch
  9303. // end catch_message.cpp
  9304. // start catch_output_redirect.cpp
  9305. // start catch_output_redirect.h
  9306. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9307. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9308. #include <cstdio>
  9309. #include <iosfwd>
  9310. #include <string>
  9311. namespace Catch {
  9312. class RedirectedStream {
  9313. std::ostream& m_originalStream;
  9314. std::ostream& m_redirectionStream;
  9315. std::streambuf* m_prevBuf;
  9316. public:
  9317. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9318. ~RedirectedStream();
  9319. };
  9320. class RedirectedStdOut {
  9321. ReusableStringStream m_rss;
  9322. RedirectedStream m_cout;
  9323. public:
  9324. RedirectedStdOut();
  9325. auto str() const -> std::string;
  9326. };
  9327. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9328. // This means that we need to redirect 2 streams into 1 to keep proper
  9329. // order of writes
  9330. class RedirectedStdErr {
  9331. ReusableStringStream m_rss;
  9332. RedirectedStream m_cerr;
  9333. RedirectedStream m_clog;
  9334. public:
  9335. RedirectedStdErr();
  9336. auto str() const -> std::string;
  9337. };
  9338. class RedirectedStreams {
  9339. public:
  9340. RedirectedStreams(RedirectedStreams const&) = delete;
  9341. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9342. RedirectedStreams(RedirectedStreams&&) = delete;
  9343. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9344. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9345. ~RedirectedStreams();
  9346. private:
  9347. std::string& m_redirectedCout;
  9348. std::string& m_redirectedCerr;
  9349. RedirectedStdOut m_redirectedStdOut;
  9350. RedirectedStdErr m_redirectedStdErr;
  9351. };
  9352. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9353. // Windows's implementation of std::tmpfile is terrible (it tries
  9354. // to create a file inside system folder, thus requiring elevated
  9355. // privileges for the binary), so we have to use tmpnam(_s) and
  9356. // create the file ourselves there.
  9357. class TempFile {
  9358. public:
  9359. TempFile(TempFile const&) = delete;
  9360. TempFile& operator=(TempFile const&) = delete;
  9361. TempFile(TempFile&&) = delete;
  9362. TempFile& operator=(TempFile&&) = delete;
  9363. TempFile();
  9364. ~TempFile();
  9365. std::FILE* getFile();
  9366. std::string getContents();
  9367. private:
  9368. std::FILE* m_file = nullptr;
  9369. #if defined(_MSC_VER)
  9370. char m_buffer[L_tmpnam] = { 0 };
  9371. #endif
  9372. };
  9373. class OutputRedirect {
  9374. public:
  9375. OutputRedirect(OutputRedirect const&) = delete;
  9376. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9377. OutputRedirect(OutputRedirect&&) = delete;
  9378. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9379. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9380. ~OutputRedirect();
  9381. private:
  9382. int m_originalStdout = -1;
  9383. int m_originalStderr = -1;
  9384. TempFile m_stdoutFile;
  9385. TempFile m_stderrFile;
  9386. std::string& m_stdoutDest;
  9387. std::string& m_stderrDest;
  9388. };
  9389. #endif
  9390. } // end namespace Catch
  9391. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9392. // end catch_output_redirect.h
  9393. #include <cstdio>
  9394. #include <cstring>
  9395. #include <fstream>
  9396. #include <sstream>
  9397. #include <stdexcept>
  9398. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9399. #if defined(_MSC_VER)
  9400. #include <io.h> //_dup and _dup2
  9401. #define dup _dup
  9402. #define dup2 _dup2
  9403. #define fileno _fileno
  9404. #else
  9405. #include <unistd.h> // dup and dup2
  9406. #endif
  9407. #endif
  9408. namespace Catch {
  9409. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9410. : m_originalStream( originalStream ),
  9411. m_redirectionStream( redirectionStream ),
  9412. m_prevBuf( m_originalStream.rdbuf() )
  9413. {
  9414. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9415. }
  9416. RedirectedStream::~RedirectedStream() {
  9417. m_originalStream.rdbuf( m_prevBuf );
  9418. }
  9419. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9420. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9421. RedirectedStdErr::RedirectedStdErr()
  9422. : m_cerr( Catch::cerr(), m_rss.get() ),
  9423. m_clog( Catch::clog(), m_rss.get() )
  9424. {}
  9425. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9426. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9427. : m_redirectedCout(redirectedCout),
  9428. m_redirectedCerr(redirectedCerr)
  9429. {}
  9430. RedirectedStreams::~RedirectedStreams() {
  9431. m_redirectedCout += m_redirectedStdOut.str();
  9432. m_redirectedCerr += m_redirectedStdErr.str();
  9433. }
  9434. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9435. #if defined(_MSC_VER)
  9436. TempFile::TempFile() {
  9437. if (tmpnam_s(m_buffer)) {
  9438. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9439. }
  9440. if (fopen_s(&m_file, m_buffer, "w")) {
  9441. char buffer[100];
  9442. if (strerror_s(buffer, errno)) {
  9443. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9444. }
  9445. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9446. }
  9447. }
  9448. #else
  9449. TempFile::TempFile() {
  9450. m_file = std::tmpfile();
  9451. if (!m_file) {
  9452. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9453. }
  9454. }
  9455. #endif
  9456. TempFile::~TempFile() {
  9457. // TBD: What to do about errors here?
  9458. std::fclose(m_file);
  9459. // We manually create the file on Windows only, on Linux
  9460. // it will be autodeleted
  9461. #if defined(_MSC_VER)
  9462. std::remove(m_buffer);
  9463. #endif
  9464. }
  9465. FILE* TempFile::getFile() {
  9466. return m_file;
  9467. }
  9468. std::string TempFile::getContents() {
  9469. std::stringstream sstr;
  9470. char buffer[100] = {};
  9471. std::rewind(m_file);
  9472. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9473. sstr << buffer;
  9474. }
  9475. return sstr.str();
  9476. }
  9477. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9478. m_originalStdout(dup(1)),
  9479. m_originalStderr(dup(2)),
  9480. m_stdoutDest(stdout_dest),
  9481. m_stderrDest(stderr_dest) {
  9482. dup2(fileno(m_stdoutFile.getFile()), 1);
  9483. dup2(fileno(m_stderrFile.getFile()), 2);
  9484. }
  9485. OutputRedirect::~OutputRedirect() {
  9486. Catch::cout() << std::flush;
  9487. fflush(stdout);
  9488. // Since we support overriding these streams, we flush cerr
  9489. // even though std::cerr is unbuffered
  9490. Catch::cerr() << std::flush;
  9491. Catch::clog() << std::flush;
  9492. fflush(stderr);
  9493. dup2(m_originalStdout, 1);
  9494. dup2(m_originalStderr, 2);
  9495. m_stdoutDest += m_stdoutFile.getContents();
  9496. m_stderrDest += m_stderrFile.getContents();
  9497. }
  9498. #endif // CATCH_CONFIG_NEW_CAPTURE
  9499. } // namespace Catch
  9500. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9501. #if defined(_MSC_VER)
  9502. #undef dup
  9503. #undef dup2
  9504. #undef fileno
  9505. #endif
  9506. #endif
  9507. // end catch_output_redirect.cpp
  9508. // start catch_polyfills.cpp
  9509. #include <cmath>
  9510. namespace Catch {
  9511. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9512. bool isnan(float f) {
  9513. return std::isnan(f);
  9514. }
  9515. bool isnan(double d) {
  9516. return std::isnan(d);
  9517. }
  9518. #else
  9519. // For now we only use this for embarcadero
  9520. bool isnan(float f) {
  9521. return std::_isnan(f);
  9522. }
  9523. bool isnan(double d) {
  9524. return std::_isnan(d);
  9525. }
  9526. #endif
  9527. } // end namespace Catch
  9528. // end catch_polyfills.cpp
  9529. // start catch_random_number_generator.cpp
  9530. namespace Catch {
  9531. std::mt19937& rng() {
  9532. static std::mt19937 s_rng;
  9533. return s_rng;
  9534. }
  9535. void seedRng( IConfig const& config ) {
  9536. if( config.rngSeed() != 0 ) {
  9537. std::srand( config.rngSeed() );
  9538. rng().seed( config.rngSeed() );
  9539. }
  9540. }
  9541. unsigned int rngSeed() {
  9542. return getCurrentContext().getConfig()->rngSeed();
  9543. }
  9544. }
  9545. // end catch_random_number_generator.cpp
  9546. // start catch_registry_hub.cpp
  9547. // start catch_test_case_registry_impl.h
  9548. #include <vector>
  9549. #include <set>
  9550. #include <algorithm>
  9551. #include <ios>
  9552. namespace Catch {
  9553. class TestCase;
  9554. struct IConfig;
  9555. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9556. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  9557. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9558. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9559. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9560. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9561. class TestRegistry : public ITestCaseRegistry {
  9562. public:
  9563. virtual ~TestRegistry() = default;
  9564. virtual void registerTest( TestCase const& testCase );
  9565. std::vector<TestCase> const& getAllTests() const override;
  9566. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9567. private:
  9568. std::vector<TestCase> m_functions;
  9569. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9570. mutable std::vector<TestCase> m_sortedFunctions;
  9571. std::size_t m_unnamedCount = 0;
  9572. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9573. };
  9574. ///////////////////////////////////////////////////////////////////////////
  9575. class TestInvokerAsFunction : public ITestInvoker {
  9576. void(*m_testAsFunction)();
  9577. public:
  9578. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9579. void invoke() const override;
  9580. };
  9581. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9582. ///////////////////////////////////////////////////////////////////////////
  9583. } // end namespace Catch
  9584. // end catch_test_case_registry_impl.h
  9585. // start catch_reporter_registry.h
  9586. #include <map>
  9587. namespace Catch {
  9588. class ReporterRegistry : public IReporterRegistry {
  9589. public:
  9590. ~ReporterRegistry() override;
  9591. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9592. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9593. void registerListener( IReporterFactoryPtr const& factory );
  9594. FactoryMap const& getFactories() const override;
  9595. Listeners const& getListeners() const override;
  9596. private:
  9597. FactoryMap m_factories;
  9598. Listeners m_listeners;
  9599. };
  9600. }
  9601. // end catch_reporter_registry.h
  9602. // start catch_tag_alias_registry.h
  9603. // start catch_tag_alias.h
  9604. #include <string>
  9605. namespace Catch {
  9606. struct TagAlias {
  9607. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9608. std::string tag;
  9609. SourceLineInfo lineInfo;
  9610. };
  9611. } // end namespace Catch
  9612. // end catch_tag_alias.h
  9613. #include <map>
  9614. namespace Catch {
  9615. class TagAliasRegistry : public ITagAliasRegistry {
  9616. public:
  9617. ~TagAliasRegistry() override;
  9618. TagAlias const* find( std::string const& alias ) const override;
  9619. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  9620. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  9621. private:
  9622. std::map<std::string, TagAlias> m_registry;
  9623. };
  9624. } // end namespace Catch
  9625. // end catch_tag_alias_registry.h
  9626. // start catch_startup_exception_registry.h
  9627. #include <vector>
  9628. #include <exception>
  9629. namespace Catch {
  9630. class StartupExceptionRegistry {
  9631. public:
  9632. void add(std::exception_ptr const& exception) noexcept;
  9633. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  9634. private:
  9635. std::vector<std::exception_ptr> m_exceptions;
  9636. };
  9637. } // end namespace Catch
  9638. // end catch_startup_exception_registry.h
  9639. // start catch_singletons.hpp
  9640. namespace Catch {
  9641. struct ISingleton {
  9642. virtual ~ISingleton();
  9643. };
  9644. void addSingleton( ISingleton* singleton );
  9645. void cleanupSingletons();
  9646. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  9647. class Singleton : SingletonImplT, public ISingleton {
  9648. static auto getInternal() -> Singleton* {
  9649. static Singleton* s_instance = nullptr;
  9650. if( !s_instance ) {
  9651. s_instance = new Singleton;
  9652. addSingleton( s_instance );
  9653. }
  9654. return s_instance;
  9655. }
  9656. public:
  9657. static auto get() -> InterfaceT const& {
  9658. return *getInternal();
  9659. }
  9660. static auto getMutable() -> MutableInterfaceT& {
  9661. return *getInternal();
  9662. }
  9663. };
  9664. } // namespace Catch
  9665. // end catch_singletons.hpp
  9666. namespace Catch {
  9667. namespace {
  9668. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  9669. private NonCopyable {
  9670. public: // IRegistryHub
  9671. RegistryHub() = default;
  9672. IReporterRegistry const& getReporterRegistry() const override {
  9673. return m_reporterRegistry;
  9674. }
  9675. ITestCaseRegistry const& getTestCaseRegistry() const override {
  9676. return m_testCaseRegistry;
  9677. }
  9678. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  9679. return m_exceptionTranslatorRegistry;
  9680. }
  9681. ITagAliasRegistry const& getTagAliasRegistry() const override {
  9682. return m_tagAliasRegistry;
  9683. }
  9684. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  9685. return m_exceptionRegistry;
  9686. }
  9687. public: // IMutableRegistryHub
  9688. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  9689. m_reporterRegistry.registerReporter( name, factory );
  9690. }
  9691. void registerListener( IReporterFactoryPtr const& factory ) override {
  9692. m_reporterRegistry.registerListener( factory );
  9693. }
  9694. void registerTest( TestCase const& testInfo ) override {
  9695. m_testCaseRegistry.registerTest( testInfo );
  9696. }
  9697. void registerTranslator( const IExceptionTranslator* translator ) override {
  9698. m_exceptionTranslatorRegistry.registerTranslator( translator );
  9699. }
  9700. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  9701. m_tagAliasRegistry.add( alias, tag, lineInfo );
  9702. }
  9703. void registerStartupException() noexcept override {
  9704. m_exceptionRegistry.add(std::current_exception());
  9705. }
  9706. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  9707. return m_enumValuesRegistry;
  9708. }
  9709. private:
  9710. TestRegistry m_testCaseRegistry;
  9711. ReporterRegistry m_reporterRegistry;
  9712. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  9713. TagAliasRegistry m_tagAliasRegistry;
  9714. StartupExceptionRegistry m_exceptionRegistry;
  9715. Detail::EnumValuesRegistry m_enumValuesRegistry;
  9716. };
  9717. }
  9718. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  9719. IRegistryHub const& getRegistryHub() {
  9720. return RegistryHubSingleton::get();
  9721. }
  9722. IMutableRegistryHub& getMutableRegistryHub() {
  9723. return RegistryHubSingleton::getMutable();
  9724. }
  9725. void cleanUp() {
  9726. cleanupSingletons();
  9727. cleanUpContext();
  9728. }
  9729. std::string translateActiveException() {
  9730. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  9731. }
  9732. } // end namespace Catch
  9733. // end catch_registry_hub.cpp
  9734. // start catch_reporter_registry.cpp
  9735. namespace Catch {
  9736. ReporterRegistry::~ReporterRegistry() = default;
  9737. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  9738. auto it = m_factories.find( name );
  9739. if( it == m_factories.end() )
  9740. return nullptr;
  9741. return it->second->create( ReporterConfig( config ) );
  9742. }
  9743. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  9744. m_factories.emplace(name, factory);
  9745. }
  9746. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  9747. m_listeners.push_back( factory );
  9748. }
  9749. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  9750. return m_factories;
  9751. }
  9752. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  9753. return m_listeners;
  9754. }
  9755. }
  9756. // end catch_reporter_registry.cpp
  9757. // start catch_result_type.cpp
  9758. namespace Catch {
  9759. bool isOk( ResultWas::OfType resultType ) {
  9760. return ( resultType & ResultWas::FailureBit ) == 0;
  9761. }
  9762. bool isJustInfo( int flags ) {
  9763. return flags == ResultWas::Info;
  9764. }
  9765. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  9766. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  9767. }
  9768. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  9769. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  9770. } // end namespace Catch
  9771. // end catch_result_type.cpp
  9772. // start catch_run_context.cpp
  9773. #include <cassert>
  9774. #include <algorithm>
  9775. #include <sstream>
  9776. namespace Catch {
  9777. namespace Generators {
  9778. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  9779. GeneratorBasePtr m_generator;
  9780. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9781. : TrackerBase( nameAndLocation, ctx, parent )
  9782. {}
  9783. ~GeneratorTracker();
  9784. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  9785. std::shared_ptr<GeneratorTracker> tracker;
  9786. ITracker& currentTracker = ctx.currentTracker();
  9787. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9788. assert( childTracker );
  9789. assert( childTracker->isGeneratorTracker() );
  9790. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  9791. }
  9792. else {
  9793. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  9794. currentTracker.addChild( tracker );
  9795. }
  9796. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9797. tracker->open();
  9798. }
  9799. return *tracker;
  9800. }
  9801. // TrackerBase interface
  9802. bool isGeneratorTracker() const override { return true; }
  9803. auto hasGenerator() const -> bool override {
  9804. return !!m_generator;
  9805. }
  9806. void close() override {
  9807. TrackerBase::close();
  9808. // Generator interface only finds out if it has another item on atual move
  9809. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  9810. m_children.clear();
  9811. m_runState = Executing;
  9812. }
  9813. }
  9814. // IGeneratorTracker interface
  9815. auto getGenerator() const -> GeneratorBasePtr const& override {
  9816. return m_generator;
  9817. }
  9818. void setGenerator( GeneratorBasePtr&& generator ) override {
  9819. m_generator = std::move( generator );
  9820. }
  9821. };
  9822. GeneratorTracker::~GeneratorTracker() {}
  9823. }
  9824. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  9825. : m_runInfo(_config->name()),
  9826. m_context(getCurrentMutableContext()),
  9827. m_config(_config),
  9828. m_reporter(std::move(reporter)),
  9829. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  9830. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  9831. {
  9832. m_context.setRunner(this);
  9833. m_context.setConfig(m_config);
  9834. m_context.setResultCapture(this);
  9835. m_reporter->testRunStarting(m_runInfo);
  9836. }
  9837. RunContext::~RunContext() {
  9838. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  9839. }
  9840. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  9841. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  9842. }
  9843. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  9844. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  9845. }
  9846. Totals RunContext::runTest(TestCase const& testCase) {
  9847. Totals prevTotals = m_totals;
  9848. std::string redirectedCout;
  9849. std::string redirectedCerr;
  9850. auto const& testInfo = testCase.getTestCaseInfo();
  9851. m_reporter->testCaseStarting(testInfo);
  9852. m_activeTestCase = &testCase;
  9853. ITracker& rootTracker = m_trackerContext.startRun();
  9854. assert(rootTracker.isSectionTracker());
  9855. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  9856. do {
  9857. m_trackerContext.startCycle();
  9858. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  9859. runCurrentTest(redirectedCout, redirectedCerr);
  9860. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  9861. Totals deltaTotals = m_totals.delta(prevTotals);
  9862. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  9863. deltaTotals.assertions.failed++;
  9864. deltaTotals.testCases.passed--;
  9865. deltaTotals.testCases.failed++;
  9866. }
  9867. m_totals.testCases += deltaTotals.testCases;
  9868. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9869. deltaTotals,
  9870. redirectedCout,
  9871. redirectedCerr,
  9872. aborting()));
  9873. m_activeTestCase = nullptr;
  9874. m_testCaseTracker = nullptr;
  9875. return deltaTotals;
  9876. }
  9877. IConfigPtr RunContext::config() const {
  9878. return m_config;
  9879. }
  9880. IStreamingReporter& RunContext::reporter() const {
  9881. return *m_reporter;
  9882. }
  9883. void RunContext::assertionEnded(AssertionResult const & result) {
  9884. if (result.getResultType() == ResultWas::Ok) {
  9885. m_totals.assertions.passed++;
  9886. m_lastAssertionPassed = true;
  9887. } else if (!result.isOk()) {
  9888. m_lastAssertionPassed = false;
  9889. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  9890. m_totals.assertions.failedButOk++;
  9891. else
  9892. m_totals.assertions.failed++;
  9893. }
  9894. else {
  9895. m_lastAssertionPassed = true;
  9896. }
  9897. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  9898. // and should be let to clear themselves out.
  9899. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  9900. if (result.getResultType() != ResultWas::Warning)
  9901. m_messageScopes.clear();
  9902. // Reset working state
  9903. resetAssertionInfo();
  9904. m_lastResult = result;
  9905. }
  9906. void RunContext::resetAssertionInfo() {
  9907. m_lastAssertionInfo.macroName = StringRef();
  9908. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  9909. }
  9910. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  9911. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  9912. if (!sectionTracker.isOpen())
  9913. return false;
  9914. m_activeSections.push_back(&sectionTracker);
  9915. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  9916. m_reporter->sectionStarting(sectionInfo);
  9917. assertions = m_totals.assertions;
  9918. return true;
  9919. }
  9920. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9921. using namespace Generators;
  9922. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  9923. assert( tracker.isOpen() );
  9924. m_lastAssertionInfo.lineInfo = lineInfo;
  9925. return tracker;
  9926. }
  9927. bool RunContext::testForMissingAssertions(Counts& assertions) {
  9928. if (assertions.total() != 0)
  9929. return false;
  9930. if (!m_config->warnAboutMissingAssertions())
  9931. return false;
  9932. if (m_trackerContext.currentTracker().hasChildren())
  9933. return false;
  9934. m_totals.assertions.failed++;
  9935. assertions.failed++;
  9936. return true;
  9937. }
  9938. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  9939. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  9940. bool missingAssertions = testForMissingAssertions(assertions);
  9941. if (!m_activeSections.empty()) {
  9942. m_activeSections.back()->close();
  9943. m_activeSections.pop_back();
  9944. }
  9945. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  9946. m_messages.clear();
  9947. m_messageScopes.clear();
  9948. }
  9949. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  9950. if (m_unfinishedSections.empty())
  9951. m_activeSections.back()->fail();
  9952. else
  9953. m_activeSections.back()->close();
  9954. m_activeSections.pop_back();
  9955. m_unfinishedSections.push_back(endInfo);
  9956. }
  9957. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  9958. void RunContext::benchmarkPreparing(std::string const& name) {
  9959. m_reporter->benchmarkPreparing(name);
  9960. }
  9961. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  9962. m_reporter->benchmarkStarting( info );
  9963. }
  9964. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  9965. m_reporter->benchmarkEnded( stats );
  9966. }
  9967. void RunContext::benchmarkFailed(std::string const & error) {
  9968. m_reporter->benchmarkFailed(error);
  9969. }
  9970. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9971. void RunContext::pushScopedMessage(MessageInfo const & message) {
  9972. m_messages.push_back(message);
  9973. }
  9974. void RunContext::popScopedMessage(MessageInfo const & message) {
  9975. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  9976. }
  9977. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  9978. m_messageScopes.emplace_back( builder );
  9979. }
  9980. std::string RunContext::getCurrentTestName() const {
  9981. return m_activeTestCase
  9982. ? m_activeTestCase->getTestCaseInfo().name
  9983. : std::string();
  9984. }
  9985. const AssertionResult * RunContext::getLastResult() const {
  9986. return &(*m_lastResult);
  9987. }
  9988. void RunContext::exceptionEarlyReported() {
  9989. m_shouldReportUnexpected = false;
  9990. }
  9991. void RunContext::handleFatalErrorCondition( StringRef message ) {
  9992. // First notify reporter that bad things happened
  9993. m_reporter->fatalErrorEncountered(message);
  9994. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  9995. // Instead, fake a result data.
  9996. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  9997. tempResult.message = message;
  9998. AssertionResult result(m_lastAssertionInfo, tempResult);
  9999. assertionEnded(result);
  10000. handleUnfinishedSections();
  10001. // Recreate section for test case (as we will lose the one that was in scope)
  10002. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10003. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10004. Counts assertions;
  10005. assertions.failed = 1;
  10006. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10007. m_reporter->sectionEnded(testCaseSectionStats);
  10008. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10009. Totals deltaTotals;
  10010. deltaTotals.testCases.failed = 1;
  10011. deltaTotals.assertions.failed = 1;
  10012. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10013. deltaTotals,
  10014. std::string(),
  10015. std::string(),
  10016. false));
  10017. m_totals.testCases.failed++;
  10018. testGroupEnded(std::string(), m_totals, 1, 1);
  10019. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10020. }
  10021. bool RunContext::lastAssertionPassed() {
  10022. return m_lastAssertionPassed;
  10023. }
  10024. void RunContext::assertionPassed() {
  10025. m_lastAssertionPassed = true;
  10026. ++m_totals.assertions.passed;
  10027. resetAssertionInfo();
  10028. m_messageScopes.clear();
  10029. }
  10030. bool RunContext::aborting() const {
  10031. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10032. }
  10033. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10034. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10035. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10036. m_reporter->sectionStarting(testCaseSection);
  10037. Counts prevAssertions = m_totals.assertions;
  10038. double duration = 0;
  10039. m_shouldReportUnexpected = true;
  10040. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10041. seedRng(*m_config);
  10042. Timer timer;
  10043. CATCH_TRY {
  10044. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10045. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10046. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10047. timer.start();
  10048. invokeActiveTestCase();
  10049. #else
  10050. OutputRedirect r(redirectedCout, redirectedCerr);
  10051. timer.start();
  10052. invokeActiveTestCase();
  10053. #endif
  10054. } else {
  10055. timer.start();
  10056. invokeActiveTestCase();
  10057. }
  10058. duration = timer.getElapsedSeconds();
  10059. } CATCH_CATCH_ANON (TestFailureException&) {
  10060. // This just means the test was aborted due to failure
  10061. } CATCH_CATCH_ALL {
  10062. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10063. // are reported without translation at the point of origin.
  10064. if( m_shouldReportUnexpected ) {
  10065. AssertionReaction dummyReaction;
  10066. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10067. }
  10068. }
  10069. Counts assertions = m_totals.assertions - prevAssertions;
  10070. bool missingAssertions = testForMissingAssertions(assertions);
  10071. m_testCaseTracker->close();
  10072. handleUnfinishedSections();
  10073. m_messages.clear();
  10074. m_messageScopes.clear();
  10075. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10076. m_reporter->sectionEnded(testCaseSectionStats);
  10077. }
  10078. void RunContext::invokeActiveTestCase() {
  10079. FatalConditionHandler fatalConditionHandler; // Handle signals
  10080. m_activeTestCase->invoke();
  10081. fatalConditionHandler.reset();
  10082. }
  10083. void RunContext::handleUnfinishedSections() {
  10084. // If sections ended prematurely due to an exception we stored their
  10085. // infos here so we can tear them down outside the unwind process.
  10086. for (auto it = m_unfinishedSections.rbegin(),
  10087. itEnd = m_unfinishedSections.rend();
  10088. it != itEnd;
  10089. ++it)
  10090. sectionEnded(*it);
  10091. m_unfinishedSections.clear();
  10092. }
  10093. void RunContext::handleExpr(
  10094. AssertionInfo const& info,
  10095. ITransientExpression const& expr,
  10096. AssertionReaction& reaction
  10097. ) {
  10098. m_reporter->assertionStarting( info );
  10099. bool negated = isFalseTest( info.resultDisposition );
  10100. bool result = expr.getResult() != negated;
  10101. if( result ) {
  10102. if (!m_includeSuccessfulResults) {
  10103. assertionPassed();
  10104. }
  10105. else {
  10106. reportExpr(info, ResultWas::Ok, &expr, negated);
  10107. }
  10108. }
  10109. else {
  10110. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10111. populateReaction( reaction );
  10112. }
  10113. }
  10114. void RunContext::reportExpr(
  10115. AssertionInfo const &info,
  10116. ResultWas::OfType resultType,
  10117. ITransientExpression const *expr,
  10118. bool negated ) {
  10119. m_lastAssertionInfo = info;
  10120. AssertionResultData data( resultType, LazyExpression( negated ) );
  10121. AssertionResult assertionResult{ info, data };
  10122. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10123. assertionEnded( assertionResult );
  10124. }
  10125. void RunContext::handleMessage(
  10126. AssertionInfo const& info,
  10127. ResultWas::OfType resultType,
  10128. StringRef const& message,
  10129. AssertionReaction& reaction
  10130. ) {
  10131. m_reporter->assertionStarting( info );
  10132. m_lastAssertionInfo = info;
  10133. AssertionResultData data( resultType, LazyExpression( false ) );
  10134. data.message = message;
  10135. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10136. assertionEnded( assertionResult );
  10137. if( !assertionResult.isOk() )
  10138. populateReaction( reaction );
  10139. }
  10140. void RunContext::handleUnexpectedExceptionNotThrown(
  10141. AssertionInfo const& info,
  10142. AssertionReaction& reaction
  10143. ) {
  10144. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10145. }
  10146. void RunContext::handleUnexpectedInflightException(
  10147. AssertionInfo const& info,
  10148. std::string const& message,
  10149. AssertionReaction& reaction
  10150. ) {
  10151. m_lastAssertionInfo = info;
  10152. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10153. data.message = message;
  10154. AssertionResult assertionResult{ info, data };
  10155. assertionEnded( assertionResult );
  10156. populateReaction( reaction );
  10157. }
  10158. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10159. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10160. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10161. }
  10162. void RunContext::handleIncomplete(
  10163. AssertionInfo const& info
  10164. ) {
  10165. m_lastAssertionInfo = info;
  10166. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10167. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10168. AssertionResult assertionResult{ info, data };
  10169. assertionEnded( assertionResult );
  10170. }
  10171. void RunContext::handleNonExpr(
  10172. AssertionInfo const &info,
  10173. ResultWas::OfType resultType,
  10174. AssertionReaction &reaction
  10175. ) {
  10176. m_lastAssertionInfo = info;
  10177. AssertionResultData data( resultType, LazyExpression( false ) );
  10178. AssertionResult assertionResult{ info, data };
  10179. assertionEnded( assertionResult );
  10180. if( !assertionResult.isOk() )
  10181. populateReaction( reaction );
  10182. }
  10183. IResultCapture& getResultCapture() {
  10184. if (auto* capture = getCurrentContext().getResultCapture())
  10185. return *capture;
  10186. else
  10187. CATCH_INTERNAL_ERROR("No result capture instance");
  10188. }
  10189. }
  10190. // end catch_run_context.cpp
  10191. // start catch_section.cpp
  10192. namespace Catch {
  10193. Section::Section( SectionInfo const& info )
  10194. : m_info( info ),
  10195. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10196. {
  10197. m_timer.start();
  10198. }
  10199. Section::~Section() {
  10200. if( m_sectionIncluded ) {
  10201. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10202. if( uncaught_exceptions() )
  10203. getResultCapture().sectionEndedEarly( endInfo );
  10204. else
  10205. getResultCapture().sectionEnded( endInfo );
  10206. }
  10207. }
  10208. // This indicates whether the section should be executed or not
  10209. Section::operator bool() const {
  10210. return m_sectionIncluded;
  10211. }
  10212. } // end namespace Catch
  10213. // end catch_section.cpp
  10214. // start catch_section_info.cpp
  10215. namespace Catch {
  10216. SectionInfo::SectionInfo
  10217. ( SourceLineInfo const& _lineInfo,
  10218. std::string const& _name )
  10219. : name( _name ),
  10220. lineInfo( _lineInfo )
  10221. {}
  10222. } // end namespace Catch
  10223. // end catch_section_info.cpp
  10224. // start catch_session.cpp
  10225. // start catch_session.h
  10226. #include <memory>
  10227. namespace Catch {
  10228. class Session : NonCopyable {
  10229. public:
  10230. Session();
  10231. ~Session() override;
  10232. void showHelp() const;
  10233. void libIdentify();
  10234. int applyCommandLine( int argc, char const * const * argv );
  10235. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10236. int applyCommandLine( int argc, wchar_t const * const * argv );
  10237. #endif
  10238. void useConfigData( ConfigData const& configData );
  10239. template<typename CharT>
  10240. int run(int argc, CharT const * const argv[]) {
  10241. if (m_startupExceptions)
  10242. return 1;
  10243. int returnCode = applyCommandLine(argc, argv);
  10244. if (returnCode == 0)
  10245. returnCode = run();
  10246. return returnCode;
  10247. }
  10248. int run();
  10249. clara::Parser const& cli() const;
  10250. void cli( clara::Parser const& newParser );
  10251. ConfigData& configData();
  10252. Config& config();
  10253. private:
  10254. int runInternal();
  10255. clara::Parser m_cli;
  10256. ConfigData m_configData;
  10257. std::shared_ptr<Config> m_config;
  10258. bool m_startupExceptions = false;
  10259. };
  10260. } // end namespace Catch
  10261. // end catch_session.h
  10262. // start catch_version.h
  10263. #include <iosfwd>
  10264. namespace Catch {
  10265. // Versioning information
  10266. struct Version {
  10267. Version( Version const& ) = delete;
  10268. Version& operator=( Version const& ) = delete;
  10269. Version( unsigned int _majorVersion,
  10270. unsigned int _minorVersion,
  10271. unsigned int _patchNumber,
  10272. char const * const _branchName,
  10273. unsigned int _buildNumber );
  10274. unsigned int const majorVersion;
  10275. unsigned int const minorVersion;
  10276. unsigned int const patchNumber;
  10277. // buildNumber is only used if branchName is not null
  10278. char const * const branchName;
  10279. unsigned int const buildNumber;
  10280. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10281. };
  10282. Version const& libraryVersion();
  10283. }
  10284. // end catch_version.h
  10285. #include <cstdlib>
  10286. #include <iomanip>
  10287. #include <set>
  10288. #include <iterator>
  10289. namespace Catch {
  10290. namespace {
  10291. const int MaxExitCode = 255;
  10292. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10293. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10294. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10295. return reporter;
  10296. }
  10297. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10298. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10299. return createReporter(config->getReporterName(), config);
  10300. }
  10301. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10302. // when the return type is std::unique_ptr<IStreamingReporter>
  10303. // doesn't compile without a std::move call. However, this causes
  10304. // a warning on newer platforms. Thus, we have to work around
  10305. // it a bit and downcast the pointer manually.
  10306. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10307. auto& multi = static_cast<ListeningReporter&>(*ret);
  10308. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10309. for (auto const& listener : listeners) {
  10310. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10311. }
  10312. multi.addReporter(createReporter(config->getReporterName(), config));
  10313. return ret;
  10314. }
  10315. class TestGroup {
  10316. public:
  10317. explicit TestGroup(std::shared_ptr<Config> const& config)
  10318. : m_config{config}
  10319. , m_context{config, makeReporter(config)}
  10320. {
  10321. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10322. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10323. if (m_matches.empty()) {
  10324. for (auto const& test : allTestCases)
  10325. if (!test.isHidden())
  10326. m_tests.emplace(&test);
  10327. } else {
  10328. for (auto const& match : m_matches)
  10329. m_tests.insert(match.tests.begin(), match.tests.end());
  10330. }
  10331. }
  10332. Totals execute() {
  10333. Totals totals;
  10334. m_context.testGroupStarting(m_config->name(), 1, 1);
  10335. for (auto const& testCase : m_tests) {
  10336. if (!m_context.aborting())
  10337. totals += m_context.runTest(*testCase);
  10338. else
  10339. m_context.reporter().skipTest(*testCase);
  10340. }
  10341. for (auto const& match : m_matches) {
  10342. if (match.tests.empty()) {
  10343. m_context.reporter().noMatchingTestCases(match.name);
  10344. totals.error = -1;
  10345. }
  10346. }
  10347. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10348. return totals;
  10349. }
  10350. private:
  10351. using Tests = std::set<TestCase const*>;
  10352. std::shared_ptr<Config> m_config;
  10353. RunContext m_context;
  10354. Tests m_tests;
  10355. TestSpec::Matches m_matches;
  10356. };
  10357. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10358. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10359. for (auto& testCase : tests) {
  10360. auto tags = testCase.tags;
  10361. std::string filename = testCase.lineInfo.file;
  10362. auto lastSlash = filename.find_last_of("\\/");
  10363. if (lastSlash != std::string::npos) {
  10364. filename.erase(0, lastSlash);
  10365. filename[0] = '#';
  10366. }
  10367. auto lastDot = filename.find_last_of('.');
  10368. if (lastDot != std::string::npos) {
  10369. filename.erase(lastDot);
  10370. }
  10371. tags.push_back(std::move(filename));
  10372. setTags(testCase, tags);
  10373. }
  10374. }
  10375. } // anon namespace
  10376. Session::Session() {
  10377. static bool alreadyInstantiated = false;
  10378. if( alreadyInstantiated ) {
  10379. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10380. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10381. }
  10382. // There cannot be exceptions at startup in no-exception mode.
  10383. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10384. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10385. if ( !exceptions.empty() ) {
  10386. config();
  10387. getCurrentMutableContext().setConfig(m_config);
  10388. m_startupExceptions = true;
  10389. Colour colourGuard( Colour::Red );
  10390. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10391. // iterate over all exceptions and notify user
  10392. for ( const auto& ex_ptr : exceptions ) {
  10393. try {
  10394. std::rethrow_exception(ex_ptr);
  10395. } catch ( std::exception const& ex ) {
  10396. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10397. }
  10398. }
  10399. }
  10400. #endif
  10401. alreadyInstantiated = true;
  10402. m_cli = makeCommandLineParser( m_configData );
  10403. }
  10404. Session::~Session() {
  10405. Catch::cleanUp();
  10406. }
  10407. void Session::showHelp() const {
  10408. Catch::cout()
  10409. << "\nCatch v" << libraryVersion() << "\n"
  10410. << m_cli << std::endl
  10411. << "For more detailed usage please see the project docs\n" << std::endl;
  10412. }
  10413. void Session::libIdentify() {
  10414. Catch::cout()
  10415. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10416. << std::left << std::setw(16) << "category: " << "testframework\n"
  10417. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10418. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10419. }
  10420. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10421. if( m_startupExceptions )
  10422. return 1;
  10423. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10424. if( !result ) {
  10425. config();
  10426. getCurrentMutableContext().setConfig(m_config);
  10427. Catch::cerr()
  10428. << Colour( Colour::Red )
  10429. << "\nError(s) in input:\n"
  10430. << Column( result.errorMessage() ).indent( 2 )
  10431. << "\n\n";
  10432. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10433. return MaxExitCode;
  10434. }
  10435. if( m_configData.showHelp )
  10436. showHelp();
  10437. if( m_configData.libIdentify )
  10438. libIdentify();
  10439. m_config.reset();
  10440. return 0;
  10441. }
  10442. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10443. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10444. char **utf8Argv = new char *[ argc ];
  10445. for ( int i = 0; i < argc; ++i ) {
  10446. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10447. utf8Argv[ i ] = new char[ bufSize ];
  10448. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10449. }
  10450. int returnCode = applyCommandLine( argc, utf8Argv );
  10451. for ( int i = 0; i < argc; ++i )
  10452. delete [] utf8Argv[ i ];
  10453. delete [] utf8Argv;
  10454. return returnCode;
  10455. }
  10456. #endif
  10457. void Session::useConfigData( ConfigData const& configData ) {
  10458. m_configData = configData;
  10459. m_config.reset();
  10460. }
  10461. int Session::run() {
  10462. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10463. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10464. static_cast<void>(std::getchar());
  10465. }
  10466. int exitCode = runInternal();
  10467. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10468. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10469. static_cast<void>(std::getchar());
  10470. }
  10471. return exitCode;
  10472. }
  10473. clara::Parser const& Session::cli() const {
  10474. return m_cli;
  10475. }
  10476. void Session::cli( clara::Parser const& newParser ) {
  10477. m_cli = newParser;
  10478. }
  10479. ConfigData& Session::configData() {
  10480. return m_configData;
  10481. }
  10482. Config& Session::config() {
  10483. if( !m_config )
  10484. m_config = std::make_shared<Config>( m_configData );
  10485. return *m_config;
  10486. }
  10487. int Session::runInternal() {
  10488. if( m_startupExceptions )
  10489. return 1;
  10490. if (m_configData.showHelp || m_configData.libIdentify) {
  10491. return 0;
  10492. }
  10493. CATCH_TRY {
  10494. config(); // Force config to be constructed
  10495. seedRng( *m_config );
  10496. if( m_configData.filenamesAsTags )
  10497. applyFilenamesAsTags( *m_config );
  10498. // Handle list request
  10499. if( Option<std::size_t> listed = list( m_config ) )
  10500. return static_cast<int>( *listed );
  10501. TestGroup tests { m_config };
  10502. auto const totals = tests.execute();
  10503. if( m_config->warnAboutNoTests() && totals.error == -1 )
  10504. return 2;
  10505. // Note that on unices only the lower 8 bits are usually used, clamping
  10506. // the return value to 255 prevents false negative when some multiple
  10507. // of 256 tests has failed
  10508. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10509. }
  10510. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10511. catch( std::exception& ex ) {
  10512. Catch::cerr() << ex.what() << std::endl;
  10513. return MaxExitCode;
  10514. }
  10515. #endif
  10516. }
  10517. } // end namespace Catch
  10518. // end catch_session.cpp
  10519. // start catch_singletons.cpp
  10520. #include <vector>
  10521. namespace Catch {
  10522. namespace {
  10523. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10524. static std::vector<ISingleton*>* g_singletons = nullptr;
  10525. if( !g_singletons )
  10526. g_singletons = new std::vector<ISingleton*>();
  10527. return g_singletons;
  10528. }
  10529. }
  10530. ISingleton::~ISingleton() {}
  10531. void addSingleton(ISingleton* singleton ) {
  10532. getSingletons()->push_back( singleton );
  10533. }
  10534. void cleanupSingletons() {
  10535. auto& singletons = getSingletons();
  10536. for( auto singleton : *singletons )
  10537. delete singleton;
  10538. delete singletons;
  10539. singletons = nullptr;
  10540. }
  10541. } // namespace Catch
  10542. // end catch_singletons.cpp
  10543. // start catch_startup_exception_registry.cpp
  10544. namespace Catch {
  10545. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10546. CATCH_TRY {
  10547. m_exceptions.push_back(exception);
  10548. } CATCH_CATCH_ALL {
  10549. // If we run out of memory during start-up there's really not a lot more we can do about it
  10550. std::terminate();
  10551. }
  10552. }
  10553. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10554. return m_exceptions;
  10555. }
  10556. } // end namespace Catch
  10557. // end catch_startup_exception_registry.cpp
  10558. // start catch_stream.cpp
  10559. #include <cstdio>
  10560. #include <iostream>
  10561. #include <fstream>
  10562. #include <sstream>
  10563. #include <vector>
  10564. #include <memory>
  10565. namespace Catch {
  10566. Catch::IStream::~IStream() = default;
  10567. namespace Detail { namespace {
  10568. template<typename WriterF, std::size_t bufferSize=256>
  10569. class StreamBufImpl : public std::streambuf {
  10570. char data[bufferSize];
  10571. WriterF m_writer;
  10572. public:
  10573. StreamBufImpl() {
  10574. setp( data, data + sizeof(data) );
  10575. }
  10576. ~StreamBufImpl() noexcept {
  10577. StreamBufImpl::sync();
  10578. }
  10579. private:
  10580. int overflow( int c ) override {
  10581. sync();
  10582. if( c != EOF ) {
  10583. if( pbase() == epptr() )
  10584. m_writer( std::string( 1, static_cast<char>( c ) ) );
  10585. else
  10586. sputc( static_cast<char>( c ) );
  10587. }
  10588. return 0;
  10589. }
  10590. int sync() override {
  10591. if( pbase() != pptr() ) {
  10592. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  10593. setp( pbase(), epptr() );
  10594. }
  10595. return 0;
  10596. }
  10597. };
  10598. ///////////////////////////////////////////////////////////////////////////
  10599. struct OutputDebugWriter {
  10600. void operator()( std::string const&str ) {
  10601. writeToDebugConsole( str );
  10602. }
  10603. };
  10604. ///////////////////////////////////////////////////////////////////////////
  10605. class FileStream : public IStream {
  10606. mutable std::ofstream m_ofs;
  10607. public:
  10608. FileStream( StringRef filename ) {
  10609. m_ofs.open( filename.c_str() );
  10610. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  10611. }
  10612. ~FileStream() override = default;
  10613. public: // IStream
  10614. std::ostream& stream() const override {
  10615. return m_ofs;
  10616. }
  10617. };
  10618. ///////////////////////////////////////////////////////////////////////////
  10619. class CoutStream : public IStream {
  10620. mutable std::ostream m_os;
  10621. public:
  10622. // Store the streambuf from cout up-front because
  10623. // cout may get redirected when running tests
  10624. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  10625. ~CoutStream() override = default;
  10626. public: // IStream
  10627. std::ostream& stream() const override { return m_os; }
  10628. };
  10629. ///////////////////////////////////////////////////////////////////////////
  10630. class DebugOutStream : public IStream {
  10631. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  10632. mutable std::ostream m_os;
  10633. public:
  10634. DebugOutStream()
  10635. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  10636. m_os( m_streamBuf.get() )
  10637. {}
  10638. ~DebugOutStream() override = default;
  10639. public: // IStream
  10640. std::ostream& stream() const override { return m_os; }
  10641. };
  10642. }} // namespace anon::detail
  10643. ///////////////////////////////////////////////////////////////////////////
  10644. auto makeStream( StringRef const &filename ) -> IStream const* {
  10645. if( filename.empty() )
  10646. return new Detail::CoutStream();
  10647. else if( filename[0] == '%' ) {
  10648. if( filename == "%debug" )
  10649. return new Detail::DebugOutStream();
  10650. else
  10651. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  10652. }
  10653. else
  10654. return new Detail::FileStream( filename );
  10655. }
  10656. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  10657. struct StringStreams {
  10658. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  10659. std::vector<std::size_t> m_unused;
  10660. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  10661. auto add() -> std::size_t {
  10662. if( m_unused.empty() ) {
  10663. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  10664. return m_streams.size()-1;
  10665. }
  10666. else {
  10667. auto index = m_unused.back();
  10668. m_unused.pop_back();
  10669. return index;
  10670. }
  10671. }
  10672. void release( std::size_t index ) {
  10673. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  10674. m_unused.push_back(index);
  10675. }
  10676. };
  10677. ReusableStringStream::ReusableStringStream()
  10678. : m_index( Singleton<StringStreams>::getMutable().add() ),
  10679. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  10680. {}
  10681. ReusableStringStream::~ReusableStringStream() {
  10682. static_cast<std::ostringstream*>( m_oss )->str("");
  10683. m_oss->clear();
  10684. Singleton<StringStreams>::getMutable().release( m_index );
  10685. }
  10686. auto ReusableStringStream::str() const -> std::string {
  10687. return static_cast<std::ostringstream*>( m_oss )->str();
  10688. }
  10689. ///////////////////////////////////////////////////////////////////////////
  10690. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  10691. std::ostream& cout() { return std::cout; }
  10692. std::ostream& cerr() { return std::cerr; }
  10693. std::ostream& clog() { return std::clog; }
  10694. #endif
  10695. }
  10696. // end catch_stream.cpp
  10697. // start catch_string_manip.cpp
  10698. #include <algorithm>
  10699. #include <ostream>
  10700. #include <cstring>
  10701. #include <cctype>
  10702. #include <vector>
  10703. namespace Catch {
  10704. namespace {
  10705. char toLowerCh(char c) {
  10706. return static_cast<char>( std::tolower( c ) );
  10707. }
  10708. }
  10709. bool startsWith( std::string const& s, std::string const& prefix ) {
  10710. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  10711. }
  10712. bool startsWith( std::string const& s, char prefix ) {
  10713. return !s.empty() && s[0] == prefix;
  10714. }
  10715. bool endsWith( std::string const& s, std::string const& suffix ) {
  10716. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  10717. }
  10718. bool endsWith( std::string const& s, char suffix ) {
  10719. return !s.empty() && s[s.size()-1] == suffix;
  10720. }
  10721. bool contains( std::string const& s, std::string const& infix ) {
  10722. return s.find( infix ) != std::string::npos;
  10723. }
  10724. void toLowerInPlace( std::string& s ) {
  10725. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  10726. }
  10727. std::string toLower( std::string const& s ) {
  10728. std::string lc = s;
  10729. toLowerInPlace( lc );
  10730. return lc;
  10731. }
  10732. std::string trim( std::string const& str ) {
  10733. static char const* whitespaceChars = "\n\r\t ";
  10734. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  10735. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  10736. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  10737. }
  10738. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  10739. bool replaced = false;
  10740. std::size_t i = str.find( replaceThis );
  10741. while( i != std::string::npos ) {
  10742. replaced = true;
  10743. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  10744. if( i < str.size()-withThis.size() )
  10745. i = str.find( replaceThis, i+withThis.size() );
  10746. else
  10747. i = std::string::npos;
  10748. }
  10749. return replaced;
  10750. }
  10751. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  10752. std::vector<StringRef> subStrings;
  10753. std::size_t start = 0;
  10754. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  10755. if( str[pos] == delimiter ) {
  10756. if( pos - start > 1 )
  10757. subStrings.push_back( str.substr( start, pos-start ) );
  10758. start = pos+1;
  10759. }
  10760. }
  10761. if( start < str.size() )
  10762. subStrings.push_back( str.substr( start, str.size()-start ) );
  10763. return subStrings;
  10764. }
  10765. pluralise::pluralise( std::size_t count, std::string const& label )
  10766. : m_count( count ),
  10767. m_label( label )
  10768. {}
  10769. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  10770. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  10771. if( pluraliser.m_count != 1 )
  10772. os << 's';
  10773. return os;
  10774. }
  10775. }
  10776. // end catch_string_manip.cpp
  10777. // start catch_stringref.cpp
  10778. #if defined(__clang__)
  10779. # pragma clang diagnostic push
  10780. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10781. #endif
  10782. #include <ostream>
  10783. #include <cstring>
  10784. #include <cstdint>
  10785. namespace {
  10786. const uint32_t byte_2_lead = 0xC0;
  10787. const uint32_t byte_3_lead = 0xE0;
  10788. const uint32_t byte_4_lead = 0xF0;
  10789. }
  10790. namespace Catch {
  10791. StringRef::StringRef( char const* rawChars ) noexcept
  10792. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  10793. {}
  10794. StringRef::operator std::string() const {
  10795. return std::string( m_start, m_size );
  10796. }
  10797. void StringRef::swap( StringRef& other ) noexcept {
  10798. std::swap( m_start, other.m_start );
  10799. std::swap( m_size, other.m_size );
  10800. std::swap( m_data, other.m_data );
  10801. }
  10802. auto StringRef::c_str() const -> char const* {
  10803. if( !isSubstring() )
  10804. return m_start;
  10805. const_cast<StringRef *>( this )->takeOwnership();
  10806. return m_data;
  10807. }
  10808. auto StringRef::currentData() const noexcept -> char const* {
  10809. return m_start;
  10810. }
  10811. auto StringRef::isOwned() const noexcept -> bool {
  10812. return m_data != nullptr;
  10813. }
  10814. auto StringRef::isSubstring() const noexcept -> bool {
  10815. return m_start[m_size] != '\0';
  10816. }
  10817. void StringRef::takeOwnership() {
  10818. if( !isOwned() ) {
  10819. m_data = new char[m_size+1];
  10820. memcpy( m_data, m_start, m_size );
  10821. m_data[m_size] = '\0';
  10822. }
  10823. }
  10824. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  10825. if( start < m_size )
  10826. return StringRef( m_start+start, size );
  10827. else
  10828. return StringRef();
  10829. }
  10830. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  10831. return
  10832. size() == other.size() &&
  10833. (std::strncmp( m_start, other.m_start, size() ) == 0);
  10834. }
  10835. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  10836. return !operator==( other );
  10837. }
  10838. auto StringRef::operator[](size_type index) const noexcept -> char {
  10839. return m_start[index];
  10840. }
  10841. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  10842. size_type noChars = m_size;
  10843. // Make adjustments for uft encodings
  10844. for( size_type i=0; i < m_size; ++i ) {
  10845. char c = m_start[i];
  10846. if( ( c & byte_2_lead ) == byte_2_lead ) {
  10847. noChars--;
  10848. if (( c & byte_3_lead ) == byte_3_lead )
  10849. noChars--;
  10850. if( ( c & byte_4_lead ) == byte_4_lead )
  10851. noChars--;
  10852. }
  10853. }
  10854. return noChars;
  10855. }
  10856. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  10857. std::string str;
  10858. str.reserve( lhs.size() + rhs.size() );
  10859. str += lhs;
  10860. str += rhs;
  10861. return str;
  10862. }
  10863. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  10864. return std::string( lhs ) + std::string( rhs );
  10865. }
  10866. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  10867. return std::string( lhs ) + std::string( rhs );
  10868. }
  10869. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  10870. return os.write(str.currentData(), str.size());
  10871. }
  10872. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  10873. lhs.append(rhs.currentData(), rhs.size());
  10874. return lhs;
  10875. }
  10876. } // namespace Catch
  10877. #if defined(__clang__)
  10878. # pragma clang diagnostic pop
  10879. #endif
  10880. // end catch_stringref.cpp
  10881. // start catch_tag_alias.cpp
  10882. namespace Catch {
  10883. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  10884. }
  10885. // end catch_tag_alias.cpp
  10886. // start catch_tag_alias_autoregistrar.cpp
  10887. namespace Catch {
  10888. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  10889. CATCH_TRY {
  10890. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  10891. } CATCH_CATCH_ALL {
  10892. // Do not throw when constructing global objects, instead register the exception to be processed later
  10893. getMutableRegistryHub().registerStartupException();
  10894. }
  10895. }
  10896. }
  10897. // end catch_tag_alias_autoregistrar.cpp
  10898. // start catch_tag_alias_registry.cpp
  10899. #include <sstream>
  10900. namespace Catch {
  10901. TagAliasRegistry::~TagAliasRegistry() {}
  10902. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  10903. auto it = m_registry.find( alias );
  10904. if( it != m_registry.end() )
  10905. return &(it->second);
  10906. else
  10907. return nullptr;
  10908. }
  10909. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  10910. std::string expandedTestSpec = unexpandedTestSpec;
  10911. for( auto const& registryKvp : m_registry ) {
  10912. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  10913. if( pos != std::string::npos ) {
  10914. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  10915. registryKvp.second.tag +
  10916. expandedTestSpec.substr( pos + registryKvp.first.size() );
  10917. }
  10918. }
  10919. return expandedTestSpec;
  10920. }
  10921. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  10922. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  10923. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  10924. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  10925. "error: tag alias, '" << alias << "' already registered.\n"
  10926. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  10927. << "\tRedefined at: " << lineInfo );
  10928. }
  10929. ITagAliasRegistry::~ITagAliasRegistry() {}
  10930. ITagAliasRegistry const& ITagAliasRegistry::get() {
  10931. return getRegistryHub().getTagAliasRegistry();
  10932. }
  10933. } // end namespace Catch
  10934. // end catch_tag_alias_registry.cpp
  10935. // start catch_test_case_info.cpp
  10936. #include <cctype>
  10937. #include <exception>
  10938. #include <algorithm>
  10939. #include <sstream>
  10940. namespace Catch {
  10941. namespace {
  10942. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  10943. if( startsWith( tag, '.' ) ||
  10944. tag == "!hide" )
  10945. return TestCaseInfo::IsHidden;
  10946. else if( tag == "!throws" )
  10947. return TestCaseInfo::Throws;
  10948. else if( tag == "!shouldfail" )
  10949. return TestCaseInfo::ShouldFail;
  10950. else if( tag == "!mayfail" )
  10951. return TestCaseInfo::MayFail;
  10952. else if( tag == "!nonportable" )
  10953. return TestCaseInfo::NonPortable;
  10954. else if( tag == "!benchmark" )
  10955. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  10956. else
  10957. return TestCaseInfo::None;
  10958. }
  10959. bool isReservedTag( std::string const& tag ) {
  10960. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  10961. }
  10962. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  10963. CATCH_ENFORCE( !isReservedTag(tag),
  10964. "Tag name: [" << tag << "] is not allowed.\n"
  10965. << "Tag names starting with non alphanumeric characters are reserved\n"
  10966. << _lineInfo );
  10967. }
  10968. }
  10969. TestCase makeTestCase( ITestInvoker* _testCase,
  10970. std::string const& _className,
  10971. NameAndTags const& nameAndTags,
  10972. SourceLineInfo const& _lineInfo )
  10973. {
  10974. bool isHidden = false;
  10975. // Parse out tags
  10976. std::vector<std::string> tags;
  10977. std::string desc, tag;
  10978. bool inTag = false;
  10979. std::string _descOrTags = nameAndTags.tags;
  10980. for (char c : _descOrTags) {
  10981. if( !inTag ) {
  10982. if( c == '[' )
  10983. inTag = true;
  10984. else
  10985. desc += c;
  10986. }
  10987. else {
  10988. if( c == ']' ) {
  10989. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  10990. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  10991. isHidden = true;
  10992. else if( prop == TestCaseInfo::None )
  10993. enforceNotReservedTag( tag, _lineInfo );
  10994. // Merged hide tags like `[.approvals]` should be added as
  10995. // `[.][approvals]`. The `[.]` is added at later point, so
  10996. // we only strip the prefix
  10997. if (startsWith(tag, '.') && tag.size() > 1) {
  10998. tag.erase(0, 1);
  10999. }
  11000. tags.push_back( tag );
  11001. tag.clear();
  11002. inTag = false;
  11003. }
  11004. else
  11005. tag += c;
  11006. }
  11007. }
  11008. if( isHidden ) {
  11009. tags.push_back( "." );
  11010. }
  11011. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  11012. return TestCase( _testCase, std::move(info) );
  11013. }
  11014. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11015. std::sort(begin(tags), end(tags));
  11016. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11017. testCaseInfo.lcaseTags.clear();
  11018. for( auto const& tag : tags ) {
  11019. std::string lcaseTag = toLower( tag );
  11020. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11021. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11022. }
  11023. testCaseInfo.tags = std::move(tags);
  11024. }
  11025. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11026. std::string const& _className,
  11027. std::string const& _description,
  11028. std::vector<std::string> const& _tags,
  11029. SourceLineInfo const& _lineInfo )
  11030. : name( _name ),
  11031. className( _className ),
  11032. description( _description ),
  11033. lineInfo( _lineInfo ),
  11034. properties( None )
  11035. {
  11036. setTags( *this, _tags );
  11037. }
  11038. bool TestCaseInfo::isHidden() const {
  11039. return ( properties & IsHidden ) != 0;
  11040. }
  11041. bool TestCaseInfo::throws() const {
  11042. return ( properties & Throws ) != 0;
  11043. }
  11044. bool TestCaseInfo::okToFail() const {
  11045. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11046. }
  11047. bool TestCaseInfo::expectedToFail() const {
  11048. return ( properties & (ShouldFail ) ) != 0;
  11049. }
  11050. std::string TestCaseInfo::tagsAsString() const {
  11051. std::string ret;
  11052. // '[' and ']' per tag
  11053. std::size_t full_size = 2 * tags.size();
  11054. for (const auto& tag : tags) {
  11055. full_size += tag.size();
  11056. }
  11057. ret.reserve(full_size);
  11058. for (const auto& tag : tags) {
  11059. ret.push_back('[');
  11060. ret.append(tag);
  11061. ret.push_back(']');
  11062. }
  11063. return ret;
  11064. }
  11065. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11066. TestCase TestCase::withName( std::string const& _newName ) const {
  11067. TestCase other( *this );
  11068. other.name = _newName;
  11069. return other;
  11070. }
  11071. void TestCase::invoke() const {
  11072. test->invoke();
  11073. }
  11074. bool TestCase::operator == ( TestCase const& other ) const {
  11075. return test.get() == other.test.get() &&
  11076. name == other.name &&
  11077. className == other.className;
  11078. }
  11079. bool TestCase::operator < ( TestCase const& other ) const {
  11080. return name < other.name;
  11081. }
  11082. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11083. {
  11084. return *this;
  11085. }
  11086. } // end namespace Catch
  11087. // end catch_test_case_info.cpp
  11088. // start catch_test_case_registry_impl.cpp
  11089. #include <sstream>
  11090. namespace Catch {
  11091. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11092. std::vector<TestCase> sorted = unsortedTestCases;
  11093. switch( config.runOrder() ) {
  11094. case RunTests::InLexicographicalOrder:
  11095. std::sort( sorted.begin(), sorted.end() );
  11096. break;
  11097. case RunTests::InRandomOrder:
  11098. seedRng( config );
  11099. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11100. break;
  11101. case RunTests::InDeclarationOrder:
  11102. // already in declaration order
  11103. break;
  11104. }
  11105. return sorted;
  11106. }
  11107. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11108. return !testCase.throws() || config.allowThrows();
  11109. }
  11110. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11111. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11112. }
  11113. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11114. std::set<TestCase> seenFunctions;
  11115. for( auto const& function : functions ) {
  11116. auto prev = seenFunctions.insert( function );
  11117. CATCH_ENFORCE( prev.second,
  11118. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11119. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11120. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11121. }
  11122. }
  11123. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11124. std::vector<TestCase> filtered;
  11125. filtered.reserve( testCases.size() );
  11126. for (auto const& testCase : testCases) {
  11127. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11128. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11129. filtered.push_back(testCase);
  11130. }
  11131. }
  11132. return filtered;
  11133. }
  11134. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11135. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11136. }
  11137. void TestRegistry::registerTest( TestCase const& testCase ) {
  11138. std::string name = testCase.getTestCaseInfo().name;
  11139. if( name.empty() ) {
  11140. ReusableStringStream rss;
  11141. rss << "Anonymous test case " << ++m_unnamedCount;
  11142. return registerTest( testCase.withName( rss.str() ) );
  11143. }
  11144. m_functions.push_back( testCase );
  11145. }
  11146. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11147. return m_functions;
  11148. }
  11149. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11150. if( m_sortedFunctions.empty() )
  11151. enforceNoDuplicateTestCases( m_functions );
  11152. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11153. m_sortedFunctions = sortTests( config, m_functions );
  11154. m_currentSortOrder = config.runOrder();
  11155. }
  11156. return m_sortedFunctions;
  11157. }
  11158. ///////////////////////////////////////////////////////////////////////////
  11159. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11160. void TestInvokerAsFunction::invoke() const {
  11161. m_testAsFunction();
  11162. }
  11163. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11164. std::string className = classOrQualifiedMethodName;
  11165. if( startsWith( className, '&' ) )
  11166. {
  11167. std::size_t lastColons = className.rfind( "::" );
  11168. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11169. if( penultimateColons == std::string::npos )
  11170. penultimateColons = 1;
  11171. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11172. }
  11173. return className;
  11174. }
  11175. } // end namespace Catch
  11176. // end catch_test_case_registry_impl.cpp
  11177. // start catch_test_case_tracker.cpp
  11178. #include <algorithm>
  11179. #include <cassert>
  11180. #include <stdexcept>
  11181. #include <memory>
  11182. #include <sstream>
  11183. #if defined(__clang__)
  11184. # pragma clang diagnostic push
  11185. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11186. #endif
  11187. namespace Catch {
  11188. namespace TestCaseTracking {
  11189. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11190. : name( _name ),
  11191. location( _location )
  11192. {}
  11193. ITracker::~ITracker() = default;
  11194. ITracker& TrackerContext::startRun() {
  11195. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11196. m_currentTracker = nullptr;
  11197. m_runState = Executing;
  11198. return *m_rootTracker;
  11199. }
  11200. void TrackerContext::endRun() {
  11201. m_rootTracker.reset();
  11202. m_currentTracker = nullptr;
  11203. m_runState = NotStarted;
  11204. }
  11205. void TrackerContext::startCycle() {
  11206. m_currentTracker = m_rootTracker.get();
  11207. m_runState = Executing;
  11208. }
  11209. void TrackerContext::completeCycle() {
  11210. m_runState = CompletedCycle;
  11211. }
  11212. bool TrackerContext::completedCycle() const {
  11213. return m_runState == CompletedCycle;
  11214. }
  11215. ITracker& TrackerContext::currentTracker() {
  11216. return *m_currentTracker;
  11217. }
  11218. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11219. m_currentTracker = tracker;
  11220. }
  11221. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11222. : m_nameAndLocation( nameAndLocation ),
  11223. m_ctx( ctx ),
  11224. m_parent( parent )
  11225. {}
  11226. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11227. return m_nameAndLocation;
  11228. }
  11229. bool TrackerBase::isComplete() const {
  11230. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11231. }
  11232. bool TrackerBase::isSuccessfullyCompleted() const {
  11233. return m_runState == CompletedSuccessfully;
  11234. }
  11235. bool TrackerBase::isOpen() const {
  11236. return m_runState != NotStarted && !isComplete();
  11237. }
  11238. bool TrackerBase::hasChildren() const {
  11239. return !m_children.empty();
  11240. }
  11241. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11242. m_children.push_back( child );
  11243. }
  11244. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11245. auto it = std::find_if( m_children.begin(), m_children.end(),
  11246. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11247. return
  11248. tracker->nameAndLocation().location == nameAndLocation.location &&
  11249. tracker->nameAndLocation().name == nameAndLocation.name;
  11250. } );
  11251. return( it != m_children.end() )
  11252. ? *it
  11253. : nullptr;
  11254. }
  11255. ITracker& TrackerBase::parent() {
  11256. assert( m_parent ); // Should always be non-null except for root
  11257. return *m_parent;
  11258. }
  11259. void TrackerBase::openChild() {
  11260. if( m_runState != ExecutingChildren ) {
  11261. m_runState = ExecutingChildren;
  11262. if( m_parent )
  11263. m_parent->openChild();
  11264. }
  11265. }
  11266. bool TrackerBase::isSectionTracker() const { return false; }
  11267. bool TrackerBase::isGeneratorTracker() const { return false; }
  11268. void TrackerBase::open() {
  11269. m_runState = Executing;
  11270. moveToThis();
  11271. if( m_parent )
  11272. m_parent->openChild();
  11273. }
  11274. void TrackerBase::close() {
  11275. // Close any still open children (e.g. generators)
  11276. while( &m_ctx.currentTracker() != this )
  11277. m_ctx.currentTracker().close();
  11278. switch( m_runState ) {
  11279. case NeedsAnotherRun:
  11280. break;
  11281. case Executing:
  11282. m_runState = CompletedSuccessfully;
  11283. break;
  11284. case ExecutingChildren:
  11285. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11286. m_runState = CompletedSuccessfully;
  11287. break;
  11288. case NotStarted:
  11289. case CompletedSuccessfully:
  11290. case Failed:
  11291. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11292. default:
  11293. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11294. }
  11295. moveToParent();
  11296. m_ctx.completeCycle();
  11297. }
  11298. void TrackerBase::fail() {
  11299. m_runState = Failed;
  11300. if( m_parent )
  11301. m_parent->markAsNeedingAnotherRun();
  11302. moveToParent();
  11303. m_ctx.completeCycle();
  11304. }
  11305. void TrackerBase::markAsNeedingAnotherRun() {
  11306. m_runState = NeedsAnotherRun;
  11307. }
  11308. void TrackerBase::moveToParent() {
  11309. assert( m_parent );
  11310. m_ctx.setCurrentTracker( m_parent );
  11311. }
  11312. void TrackerBase::moveToThis() {
  11313. m_ctx.setCurrentTracker( this );
  11314. }
  11315. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11316. : TrackerBase( nameAndLocation, ctx, parent )
  11317. {
  11318. if( parent ) {
  11319. while( !parent->isSectionTracker() )
  11320. parent = &parent->parent();
  11321. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11322. addNextFilters( parentSection.m_filters );
  11323. }
  11324. }
  11325. bool SectionTracker::isComplete() const {
  11326. bool complete = true;
  11327. if ((m_filters.empty() || m_filters[0] == "") ||
  11328. std::find(m_filters.begin(), m_filters.end(),
  11329. m_nameAndLocation.name) != m_filters.end())
  11330. complete = TrackerBase::isComplete();
  11331. return complete;
  11332. }
  11333. bool SectionTracker::isSectionTracker() const { return true; }
  11334. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11335. std::shared_ptr<SectionTracker> section;
  11336. ITracker& currentTracker = ctx.currentTracker();
  11337. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11338. assert( childTracker );
  11339. assert( childTracker->isSectionTracker() );
  11340. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11341. }
  11342. else {
  11343. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11344. currentTracker.addChild( section );
  11345. }
  11346. if( !ctx.completedCycle() )
  11347. section->tryOpen();
  11348. return *section;
  11349. }
  11350. void SectionTracker::tryOpen() {
  11351. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11352. open();
  11353. }
  11354. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11355. if( !filters.empty() ) {
  11356. m_filters.push_back(""); // Root - should never be consulted
  11357. m_filters.push_back(""); // Test Case - not a section filter
  11358. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11359. }
  11360. }
  11361. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11362. if( filters.size() > 1 )
  11363. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11364. }
  11365. } // namespace TestCaseTracking
  11366. using TestCaseTracking::ITracker;
  11367. using TestCaseTracking::TrackerContext;
  11368. using TestCaseTracking::SectionTracker;
  11369. } // namespace Catch
  11370. #if defined(__clang__)
  11371. # pragma clang diagnostic pop
  11372. #endif
  11373. // end catch_test_case_tracker.cpp
  11374. // start catch_test_registry.cpp
  11375. namespace Catch {
  11376. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11377. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11378. }
  11379. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11380. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11381. CATCH_TRY {
  11382. getMutableRegistryHub()
  11383. .registerTest(
  11384. makeTestCase(
  11385. invoker,
  11386. extractClassName( classOrMethod ),
  11387. nameAndTags,
  11388. lineInfo));
  11389. } CATCH_CATCH_ALL {
  11390. // Do not throw when constructing global objects, instead register the exception to be processed later
  11391. getMutableRegistryHub().registerStartupException();
  11392. }
  11393. }
  11394. AutoReg::~AutoReg() = default;
  11395. }
  11396. // end catch_test_registry.cpp
  11397. // start catch_test_spec.cpp
  11398. #include <algorithm>
  11399. #include <string>
  11400. #include <vector>
  11401. #include <memory>
  11402. namespace Catch {
  11403. TestSpec::Pattern::Pattern( std::string const& name )
  11404. : m_name( name )
  11405. {}
  11406. TestSpec::Pattern::~Pattern() = default;
  11407. std::string const& TestSpec::Pattern::name() const {
  11408. return m_name;
  11409. }
  11410. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11411. : Pattern( filterString )
  11412. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11413. {}
  11414. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11415. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11416. }
  11417. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11418. : Pattern( filterString )
  11419. , m_tag( toLower( tag ) )
  11420. {}
  11421. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11422. return std::find(begin(testCase.lcaseTags),
  11423. end(testCase.lcaseTags),
  11424. m_tag) != end(testCase.lcaseTags);
  11425. }
  11426. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11427. : Pattern( underlyingPattern->name() )
  11428. , m_underlyingPattern( underlyingPattern )
  11429. {}
  11430. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11431. return !m_underlyingPattern->matches( testCase );
  11432. }
  11433. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11434. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11435. }
  11436. std::string TestSpec::Filter::name() const {
  11437. std::string name;
  11438. for( auto const& p : m_patterns )
  11439. name += p->name();
  11440. return name;
  11441. }
  11442. bool TestSpec::hasFilters() const {
  11443. return !m_filters.empty();
  11444. }
  11445. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11446. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11447. }
  11448. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11449. {
  11450. Matches matches( m_filters.size() );
  11451. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11452. std::vector<TestCase const*> currentMatches;
  11453. for( auto const& test : testCases )
  11454. if( isThrowSafe( test, config ) && filter.matches( test ) )
  11455. currentMatches.emplace_back( &test );
  11456. return FilterMatch{ filter.name(), currentMatches };
  11457. } );
  11458. return matches;
  11459. }
  11460. }
  11461. // end catch_test_spec.cpp
  11462. // start catch_test_spec_parser.cpp
  11463. namespace Catch {
  11464. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11465. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11466. m_mode = None;
  11467. m_exclusion = false;
  11468. m_arg = m_tagAliases->expandAliases( arg );
  11469. m_escapeChars.clear();
  11470. m_substring.reserve(m_arg.size());
  11471. m_patternName.reserve(m_arg.size());
  11472. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11473. visitChar( m_arg[m_pos] );
  11474. endMode();
  11475. return *this;
  11476. }
  11477. TestSpec TestSpecParser::testSpec() {
  11478. addFilter();
  11479. return m_testSpec;
  11480. }
  11481. void TestSpecParser::visitChar( char c ) {
  11482. if( c == ',' ) {
  11483. endMode();
  11484. addFilter();
  11485. return;
  11486. }
  11487. switch( m_mode ) {
  11488. case None:
  11489. if( processNoneChar( c ) )
  11490. return;
  11491. break;
  11492. case Name:
  11493. processNameChar( c );
  11494. break;
  11495. case EscapedName:
  11496. endMode();
  11497. break;
  11498. default:
  11499. case Tag:
  11500. case QuotedName:
  11501. if( processOtherChar( c ) )
  11502. return;
  11503. break;
  11504. }
  11505. m_substring += c;
  11506. if( !isControlChar( c ) )
  11507. m_patternName += c;
  11508. }
  11509. // Two of the processing methods return true to signal the caller to return
  11510. // without adding the given character to the current pattern strings
  11511. bool TestSpecParser::processNoneChar( char c ) {
  11512. switch( c ) {
  11513. case ' ':
  11514. return true;
  11515. case '~':
  11516. m_exclusion = true;
  11517. return false;
  11518. case '[':
  11519. startNewMode( Tag );
  11520. return false;
  11521. case '"':
  11522. startNewMode( QuotedName );
  11523. return false;
  11524. case '\\':
  11525. escape();
  11526. return true;
  11527. default:
  11528. startNewMode( Name );
  11529. return false;
  11530. }
  11531. }
  11532. void TestSpecParser::processNameChar( char c ) {
  11533. if( c == '[' ) {
  11534. if( m_substring == "exclude:" )
  11535. m_exclusion = true;
  11536. else
  11537. endMode();
  11538. startNewMode( Tag );
  11539. }
  11540. }
  11541. bool TestSpecParser::processOtherChar( char c ) {
  11542. if( !isControlChar( c ) )
  11543. return false;
  11544. m_substring += c;
  11545. endMode();
  11546. return true;
  11547. }
  11548. void TestSpecParser::startNewMode( Mode mode ) {
  11549. m_mode = mode;
  11550. }
  11551. void TestSpecParser::endMode() {
  11552. switch( m_mode ) {
  11553. case Name:
  11554. case QuotedName:
  11555. return addPattern<TestSpec::NamePattern>();
  11556. case Tag:
  11557. return addPattern<TestSpec::TagPattern>();
  11558. case EscapedName:
  11559. return startNewMode( Name );
  11560. case None:
  11561. default:
  11562. return startNewMode( None );
  11563. }
  11564. }
  11565. void TestSpecParser::escape() {
  11566. m_mode = EscapedName;
  11567. m_escapeChars.push_back( m_pos );
  11568. }
  11569. bool TestSpecParser::isControlChar( char c ) const {
  11570. switch( m_mode ) {
  11571. default:
  11572. return false;
  11573. case None:
  11574. return c == '~';
  11575. case Name:
  11576. return c == '[';
  11577. case EscapedName:
  11578. return true;
  11579. case QuotedName:
  11580. return c == '"';
  11581. case Tag:
  11582. return c == '[' || c == ']';
  11583. }
  11584. }
  11585. void TestSpecParser::addFilter() {
  11586. if( !m_currentFilter.m_patterns.empty() ) {
  11587. m_testSpec.m_filters.push_back( m_currentFilter );
  11588. m_currentFilter = TestSpec::Filter();
  11589. }
  11590. }
  11591. TestSpec parseTestSpec( std::string const& arg ) {
  11592. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  11593. }
  11594. } // namespace Catch
  11595. // end catch_test_spec_parser.cpp
  11596. // start catch_timer.cpp
  11597. #include <chrono>
  11598. static const uint64_t nanosecondsInSecond = 1000000000;
  11599. namespace Catch {
  11600. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  11601. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  11602. }
  11603. namespace {
  11604. auto estimateClockResolution() -> uint64_t {
  11605. uint64_t sum = 0;
  11606. static const uint64_t iterations = 1000000;
  11607. auto startTime = getCurrentNanosecondsSinceEpoch();
  11608. for( std::size_t i = 0; i < iterations; ++i ) {
  11609. uint64_t ticks;
  11610. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  11611. do {
  11612. ticks = getCurrentNanosecondsSinceEpoch();
  11613. } while( ticks == baseTicks );
  11614. auto delta = ticks - baseTicks;
  11615. sum += delta;
  11616. // If we have been calibrating for over 3 seconds -- the clock
  11617. // is terrible and we should move on.
  11618. // TBD: How to signal that the measured resolution is probably wrong?
  11619. if (ticks > startTime + 3 * nanosecondsInSecond) {
  11620. return sum / ( i + 1u );
  11621. }
  11622. }
  11623. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  11624. // - and potentially do more iterations if there's a high variance.
  11625. return sum/iterations;
  11626. }
  11627. }
  11628. auto getEstimatedClockResolution() -> uint64_t {
  11629. static auto s_resolution = estimateClockResolution();
  11630. return s_resolution;
  11631. }
  11632. void Timer::start() {
  11633. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  11634. }
  11635. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  11636. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  11637. }
  11638. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  11639. return getElapsedNanoseconds()/1000;
  11640. }
  11641. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  11642. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  11643. }
  11644. auto Timer::getElapsedSeconds() const -> double {
  11645. return getElapsedMicroseconds()/1000000.0;
  11646. }
  11647. } // namespace Catch
  11648. // end catch_timer.cpp
  11649. // start catch_tostring.cpp
  11650. #if defined(__clang__)
  11651. # pragma clang diagnostic push
  11652. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11653. # pragma clang diagnostic ignored "-Wglobal-constructors"
  11654. #endif
  11655. // Enable specific decls locally
  11656. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  11657. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  11658. #endif
  11659. #include <cmath>
  11660. #include <iomanip>
  11661. namespace Catch {
  11662. namespace Detail {
  11663. const std::string unprintableString = "{?}";
  11664. namespace {
  11665. const int hexThreshold = 255;
  11666. struct Endianness {
  11667. enum Arch { Big, Little };
  11668. static Arch which() {
  11669. union _{
  11670. int asInt;
  11671. char asChar[sizeof (int)];
  11672. } u;
  11673. u.asInt = 1;
  11674. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  11675. }
  11676. };
  11677. }
  11678. std::string rawMemoryToString( const void *object, std::size_t size ) {
  11679. // Reverse order for little endian architectures
  11680. int i = 0, end = static_cast<int>( size ), inc = 1;
  11681. if( Endianness::which() == Endianness::Little ) {
  11682. i = end-1;
  11683. end = inc = -1;
  11684. }
  11685. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  11686. ReusableStringStream rss;
  11687. rss << "0x" << std::setfill('0') << std::hex;
  11688. for( ; i != end; i += inc )
  11689. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  11690. return rss.str();
  11691. }
  11692. }
  11693. template<typename T>
  11694. std::string fpToString( T value, int precision ) {
  11695. if (Catch::isnan(value)) {
  11696. return "nan";
  11697. }
  11698. ReusableStringStream rss;
  11699. rss << std::setprecision( precision )
  11700. << std::fixed
  11701. << value;
  11702. std::string d = rss.str();
  11703. std::size_t i = d.find_last_not_of( '0' );
  11704. if( i != std::string::npos && i != d.size()-1 ) {
  11705. if( d[i] == '.' )
  11706. i++;
  11707. d = d.substr( 0, i+1 );
  11708. }
  11709. return d;
  11710. }
  11711. //// ======================================================= ////
  11712. //
  11713. // Out-of-line defs for full specialization of StringMaker
  11714. //
  11715. //// ======================================================= ////
  11716. std::string StringMaker<std::string>::convert(const std::string& str) {
  11717. if (!getCurrentContext().getConfig()->showInvisibles()) {
  11718. return '"' + str + '"';
  11719. }
  11720. std::string s("\"");
  11721. for (char c : str) {
  11722. switch (c) {
  11723. case '\n':
  11724. s.append("\\n");
  11725. break;
  11726. case '\t':
  11727. s.append("\\t");
  11728. break;
  11729. default:
  11730. s.push_back(c);
  11731. break;
  11732. }
  11733. }
  11734. s.append("\"");
  11735. return s;
  11736. }
  11737. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11738. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  11739. return ::Catch::Detail::stringify(std::string{ str });
  11740. }
  11741. #endif
  11742. std::string StringMaker<char const*>::convert(char const* str) {
  11743. if (str) {
  11744. return ::Catch::Detail::stringify(std::string{ str });
  11745. } else {
  11746. return{ "{null string}" };
  11747. }
  11748. }
  11749. std::string StringMaker<char*>::convert(char* str) {
  11750. if (str) {
  11751. return ::Catch::Detail::stringify(std::string{ str });
  11752. } else {
  11753. return{ "{null string}" };
  11754. }
  11755. }
  11756. #ifdef CATCH_CONFIG_WCHAR
  11757. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  11758. std::string s;
  11759. s.reserve(wstr.size());
  11760. for (auto c : wstr) {
  11761. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  11762. }
  11763. return ::Catch::Detail::stringify(s);
  11764. }
  11765. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11766. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  11767. return StringMaker<std::wstring>::convert(std::wstring(str));
  11768. }
  11769. # endif
  11770. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  11771. if (str) {
  11772. return ::Catch::Detail::stringify(std::wstring{ str });
  11773. } else {
  11774. return{ "{null string}" };
  11775. }
  11776. }
  11777. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  11778. if (str) {
  11779. return ::Catch::Detail::stringify(std::wstring{ str });
  11780. } else {
  11781. return{ "{null string}" };
  11782. }
  11783. }
  11784. #endif
  11785. #if defined(CATCH_CONFIG_CPP17_BYTE)
  11786. #include <cstddef>
  11787. std::string StringMaker<std::byte>::convert(std::byte value) {
  11788. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  11789. }
  11790. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  11791. std::string StringMaker<int>::convert(int value) {
  11792. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11793. }
  11794. std::string StringMaker<long>::convert(long value) {
  11795. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11796. }
  11797. std::string StringMaker<long long>::convert(long long value) {
  11798. ReusableStringStream rss;
  11799. rss << value;
  11800. if (value > Detail::hexThreshold) {
  11801. rss << " (0x" << std::hex << value << ')';
  11802. }
  11803. return rss.str();
  11804. }
  11805. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  11806. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11807. }
  11808. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  11809. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11810. }
  11811. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  11812. ReusableStringStream rss;
  11813. rss << value;
  11814. if (value > Detail::hexThreshold) {
  11815. rss << " (0x" << std::hex << value << ')';
  11816. }
  11817. return rss.str();
  11818. }
  11819. std::string StringMaker<bool>::convert(bool b) {
  11820. return b ? "true" : "false";
  11821. }
  11822. std::string StringMaker<signed char>::convert(signed char value) {
  11823. if (value == '\r') {
  11824. return "'\\r'";
  11825. } else if (value == '\f') {
  11826. return "'\\f'";
  11827. } else if (value == '\n') {
  11828. return "'\\n'";
  11829. } else if (value == '\t') {
  11830. return "'\\t'";
  11831. } else if ('\0' <= value && value < ' ') {
  11832. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  11833. } else {
  11834. char chstr[] = "' '";
  11835. chstr[1] = value;
  11836. return chstr;
  11837. }
  11838. }
  11839. std::string StringMaker<char>::convert(char c) {
  11840. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  11841. }
  11842. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  11843. return ::Catch::Detail::stringify(static_cast<char>(c));
  11844. }
  11845. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  11846. return "nullptr";
  11847. }
  11848. int StringMaker<float>::precision = 5;
  11849. std::string StringMaker<float>::convert(float value) {
  11850. return fpToString(value, precision) + 'f';
  11851. }
  11852. int StringMaker<double>::precision = 10;
  11853. std::string StringMaker<double>::convert(double value) {
  11854. return fpToString(value, precision);
  11855. }
  11856. std::string ratio_string<std::atto>::symbol() { return "a"; }
  11857. std::string ratio_string<std::femto>::symbol() { return "f"; }
  11858. std::string ratio_string<std::pico>::symbol() { return "p"; }
  11859. std::string ratio_string<std::nano>::symbol() { return "n"; }
  11860. std::string ratio_string<std::micro>::symbol() { return "u"; }
  11861. std::string ratio_string<std::milli>::symbol() { return "m"; }
  11862. } // end namespace Catch
  11863. #if defined(__clang__)
  11864. # pragma clang diagnostic pop
  11865. #endif
  11866. // end catch_tostring.cpp
  11867. // start catch_totals.cpp
  11868. namespace Catch {
  11869. Counts Counts::operator - ( Counts const& other ) const {
  11870. Counts diff;
  11871. diff.passed = passed - other.passed;
  11872. diff.failed = failed - other.failed;
  11873. diff.failedButOk = failedButOk - other.failedButOk;
  11874. return diff;
  11875. }
  11876. Counts& Counts::operator += ( Counts const& other ) {
  11877. passed += other.passed;
  11878. failed += other.failed;
  11879. failedButOk += other.failedButOk;
  11880. return *this;
  11881. }
  11882. std::size_t Counts::total() const {
  11883. return passed + failed + failedButOk;
  11884. }
  11885. bool Counts::allPassed() const {
  11886. return failed == 0 && failedButOk == 0;
  11887. }
  11888. bool Counts::allOk() const {
  11889. return failed == 0;
  11890. }
  11891. Totals Totals::operator - ( Totals const& other ) const {
  11892. Totals diff;
  11893. diff.assertions = assertions - other.assertions;
  11894. diff.testCases = testCases - other.testCases;
  11895. return diff;
  11896. }
  11897. Totals& Totals::operator += ( Totals const& other ) {
  11898. assertions += other.assertions;
  11899. testCases += other.testCases;
  11900. return *this;
  11901. }
  11902. Totals Totals::delta( Totals const& prevTotals ) const {
  11903. Totals diff = *this - prevTotals;
  11904. if( diff.assertions.failed > 0 )
  11905. ++diff.testCases.failed;
  11906. else if( diff.assertions.failedButOk > 0 )
  11907. ++diff.testCases.failedButOk;
  11908. else
  11909. ++diff.testCases.passed;
  11910. return diff;
  11911. }
  11912. }
  11913. // end catch_totals.cpp
  11914. // start catch_uncaught_exceptions.cpp
  11915. #include <exception>
  11916. namespace Catch {
  11917. bool uncaught_exceptions() {
  11918. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  11919. return std::uncaught_exceptions() > 0;
  11920. #else
  11921. return std::uncaught_exception();
  11922. #endif
  11923. }
  11924. } // end namespace Catch
  11925. // end catch_uncaught_exceptions.cpp
  11926. // start catch_version.cpp
  11927. #include <ostream>
  11928. namespace Catch {
  11929. Version::Version
  11930. ( unsigned int _majorVersion,
  11931. unsigned int _minorVersion,
  11932. unsigned int _patchNumber,
  11933. char const * const _branchName,
  11934. unsigned int _buildNumber )
  11935. : majorVersion( _majorVersion ),
  11936. minorVersion( _minorVersion ),
  11937. patchNumber( _patchNumber ),
  11938. branchName( _branchName ),
  11939. buildNumber( _buildNumber )
  11940. {}
  11941. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  11942. os << version.majorVersion << '.'
  11943. << version.minorVersion << '.'
  11944. << version.patchNumber;
  11945. // branchName is never null -> 0th char is \0 if it is empty
  11946. if (version.branchName[0]) {
  11947. os << '-' << version.branchName
  11948. << '.' << version.buildNumber;
  11949. }
  11950. return os;
  11951. }
  11952. Version const& libraryVersion() {
  11953. static Version version( 2, 9, 2, "", 0 );
  11954. return version;
  11955. }
  11956. }
  11957. // end catch_version.cpp
  11958. // start catch_wildcard_pattern.cpp
  11959. #include <sstream>
  11960. namespace Catch {
  11961. WildcardPattern::WildcardPattern( std::string const& pattern,
  11962. CaseSensitive::Choice caseSensitivity )
  11963. : m_caseSensitivity( caseSensitivity ),
  11964. m_pattern( adjustCase( pattern ) )
  11965. {
  11966. if( startsWith( m_pattern, '*' ) ) {
  11967. m_pattern = m_pattern.substr( 1 );
  11968. m_wildcard = WildcardAtStart;
  11969. }
  11970. if( endsWith( m_pattern, '*' ) ) {
  11971. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  11972. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  11973. }
  11974. }
  11975. bool WildcardPattern::matches( std::string const& str ) const {
  11976. switch( m_wildcard ) {
  11977. case NoWildcard:
  11978. return m_pattern == adjustCase( str );
  11979. case WildcardAtStart:
  11980. return endsWith( adjustCase( str ), m_pattern );
  11981. case WildcardAtEnd:
  11982. return startsWith( adjustCase( str ), m_pattern );
  11983. case WildcardAtBothEnds:
  11984. return contains( adjustCase( str ), m_pattern );
  11985. default:
  11986. CATCH_INTERNAL_ERROR( "Unknown enum" );
  11987. }
  11988. }
  11989. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  11990. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  11991. }
  11992. }
  11993. // end catch_wildcard_pattern.cpp
  11994. // start catch_xmlwriter.cpp
  11995. #include <iomanip>
  11996. using uchar = unsigned char;
  11997. namespace Catch {
  11998. namespace {
  11999. size_t trailingBytes(unsigned char c) {
  12000. if ((c & 0xE0) == 0xC0) {
  12001. return 2;
  12002. }
  12003. if ((c & 0xF0) == 0xE0) {
  12004. return 3;
  12005. }
  12006. if ((c & 0xF8) == 0xF0) {
  12007. return 4;
  12008. }
  12009. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12010. }
  12011. uint32_t headerValue(unsigned char c) {
  12012. if ((c & 0xE0) == 0xC0) {
  12013. return c & 0x1F;
  12014. }
  12015. if ((c & 0xF0) == 0xE0) {
  12016. return c & 0x0F;
  12017. }
  12018. if ((c & 0xF8) == 0xF0) {
  12019. return c & 0x07;
  12020. }
  12021. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12022. }
  12023. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12024. std::ios_base::fmtflags f(os.flags());
  12025. os << "\\x"
  12026. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12027. << static_cast<int>(c);
  12028. os.flags(f);
  12029. }
  12030. } // anonymous namespace
  12031. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12032. : m_str( str ),
  12033. m_forWhat( forWhat )
  12034. {}
  12035. void XmlEncode::encodeTo( std::ostream& os ) const {
  12036. // Apostrophe escaping not necessary if we always use " to write attributes
  12037. // (see: http://www.w3.org/TR/xml/#syntax)
  12038. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12039. uchar c = m_str[idx];
  12040. switch (c) {
  12041. case '<': os << "&lt;"; break;
  12042. case '&': os << "&amp;"; break;
  12043. case '>':
  12044. // See: http://www.w3.org/TR/xml/#syntax
  12045. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12046. os << "&gt;";
  12047. else
  12048. os << c;
  12049. break;
  12050. case '\"':
  12051. if (m_forWhat == ForAttributes)
  12052. os << "&quot;";
  12053. else
  12054. os << c;
  12055. break;
  12056. default:
  12057. // Check for control characters and invalid utf-8
  12058. // Escape control characters in standard ascii
  12059. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12060. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12061. hexEscapeChar(os, c);
  12062. break;
  12063. }
  12064. // Plain ASCII: Write it to stream
  12065. if (c < 0x7F) {
  12066. os << c;
  12067. break;
  12068. }
  12069. // UTF-8 territory
  12070. // Check if the encoding is valid and if it is not, hex escape bytes.
  12071. // Important: We do not check the exact decoded values for validity, only the encoding format
  12072. // First check that this bytes is a valid lead byte:
  12073. // This means that it is not encoded as 1111 1XXX
  12074. // Or as 10XX XXXX
  12075. if (c < 0xC0 ||
  12076. c >= 0xF8) {
  12077. hexEscapeChar(os, c);
  12078. break;
  12079. }
  12080. auto encBytes = trailingBytes(c);
  12081. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12082. if (idx + encBytes - 1 >= m_str.size()) {
  12083. hexEscapeChar(os, c);
  12084. break;
  12085. }
  12086. // The header is valid, check data
  12087. // The next encBytes bytes must together be a valid utf-8
  12088. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12089. bool valid = true;
  12090. uint32_t value = headerValue(c);
  12091. for (std::size_t n = 1; n < encBytes; ++n) {
  12092. uchar nc = m_str[idx + n];
  12093. valid &= ((nc & 0xC0) == 0x80);
  12094. value = (value << 6) | (nc & 0x3F);
  12095. }
  12096. if (
  12097. // Wrong bit pattern of following bytes
  12098. (!valid) ||
  12099. // Overlong encodings
  12100. (value < 0x80) ||
  12101. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12102. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12103. // Encoded value out of range
  12104. (value >= 0x110000)
  12105. ) {
  12106. hexEscapeChar(os, c);
  12107. break;
  12108. }
  12109. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12110. for (std::size_t n = 0; n < encBytes; ++n) {
  12111. os << m_str[idx + n];
  12112. }
  12113. idx += encBytes - 1;
  12114. break;
  12115. }
  12116. }
  12117. }
  12118. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12119. xmlEncode.encodeTo( os );
  12120. return os;
  12121. }
  12122. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  12123. : m_writer( writer )
  12124. {}
  12125. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12126. : m_writer( other.m_writer ){
  12127. other.m_writer = nullptr;
  12128. }
  12129. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12130. if ( m_writer ) {
  12131. m_writer->endElement();
  12132. }
  12133. m_writer = other.m_writer;
  12134. other.m_writer = nullptr;
  12135. return *this;
  12136. }
  12137. XmlWriter::ScopedElement::~ScopedElement() {
  12138. if( m_writer )
  12139. m_writer->endElement();
  12140. }
  12141. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  12142. m_writer->writeText( text, indent );
  12143. return *this;
  12144. }
  12145. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12146. {
  12147. writeDeclaration();
  12148. }
  12149. XmlWriter::~XmlWriter() {
  12150. while( !m_tags.empty() )
  12151. endElement();
  12152. }
  12153. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  12154. ensureTagClosed();
  12155. newlineIfNecessary();
  12156. m_os << m_indent << '<' << name;
  12157. m_tags.push_back( name );
  12158. m_indent += " ";
  12159. m_tagIsOpen = true;
  12160. return *this;
  12161. }
  12162. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  12163. ScopedElement scoped( this );
  12164. startElement( name );
  12165. return scoped;
  12166. }
  12167. XmlWriter& XmlWriter::endElement() {
  12168. newlineIfNecessary();
  12169. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  12170. if( m_tagIsOpen ) {
  12171. m_os << "/>";
  12172. m_tagIsOpen = false;
  12173. }
  12174. else {
  12175. m_os << m_indent << "</" << m_tags.back() << ">";
  12176. }
  12177. m_os << std::endl;
  12178. m_tags.pop_back();
  12179. return *this;
  12180. }
  12181. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12182. if( !name.empty() && !attribute.empty() )
  12183. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12184. return *this;
  12185. }
  12186. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12187. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12188. return *this;
  12189. }
  12190. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12191. if( !text.empty() ){
  12192. bool tagWasOpen = m_tagIsOpen;
  12193. ensureTagClosed();
  12194. if( tagWasOpen && indent )
  12195. m_os << m_indent;
  12196. m_os << XmlEncode( text );
  12197. m_needsNewline = true;
  12198. }
  12199. return *this;
  12200. }
  12201. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12202. ensureTagClosed();
  12203. m_os << m_indent << "<!--" << text << "-->";
  12204. m_needsNewline = true;
  12205. return *this;
  12206. }
  12207. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12208. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12209. }
  12210. XmlWriter& XmlWriter::writeBlankLine() {
  12211. ensureTagClosed();
  12212. m_os << '\n';
  12213. return *this;
  12214. }
  12215. void XmlWriter::ensureTagClosed() {
  12216. if( m_tagIsOpen ) {
  12217. m_os << ">" << std::endl;
  12218. m_tagIsOpen = false;
  12219. }
  12220. }
  12221. void XmlWriter::writeDeclaration() {
  12222. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12223. }
  12224. void XmlWriter::newlineIfNecessary() {
  12225. if( m_needsNewline ) {
  12226. m_os << std::endl;
  12227. m_needsNewline = false;
  12228. }
  12229. }
  12230. }
  12231. // end catch_xmlwriter.cpp
  12232. // start catch_reporter_bases.cpp
  12233. #include <cstring>
  12234. #include <cfloat>
  12235. #include <cstdio>
  12236. #include <cassert>
  12237. #include <memory>
  12238. namespace Catch {
  12239. void prepareExpandedExpression(AssertionResult& result) {
  12240. result.getExpandedExpression();
  12241. }
  12242. // Because formatting using c++ streams is stateful, drop down to C is required
  12243. // Alternatively we could use stringstream, but its performance is... not good.
  12244. std::string getFormattedDuration( double duration ) {
  12245. // Max exponent + 1 is required to represent the whole part
  12246. // + 1 for decimal point
  12247. // + 3 for the 3 decimal places
  12248. // + 1 for null terminator
  12249. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12250. char buffer[maxDoubleSize];
  12251. // Save previous errno, to prevent sprintf from overwriting it
  12252. ErrnoGuard guard;
  12253. #ifdef _MSC_VER
  12254. sprintf_s(buffer, "%.3f", duration);
  12255. #else
  12256. std::sprintf(buffer, "%.3f", duration);
  12257. #endif
  12258. return std::string(buffer);
  12259. }
  12260. std::string serializeFilters( std::vector<std::string> const& container ) {
  12261. ReusableStringStream oss;
  12262. bool first = true;
  12263. for (auto&& filter : container)
  12264. {
  12265. if (!first)
  12266. oss << ' ';
  12267. else
  12268. first = false;
  12269. oss << filter;
  12270. }
  12271. return oss.str();
  12272. }
  12273. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12274. :StreamingReporterBase(_config) {}
  12275. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12276. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12277. }
  12278. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12279. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12280. return false;
  12281. }
  12282. } // end namespace Catch
  12283. // end catch_reporter_bases.cpp
  12284. // start catch_reporter_compact.cpp
  12285. namespace {
  12286. #ifdef CATCH_PLATFORM_MAC
  12287. const char* failedString() { return "FAILED"; }
  12288. const char* passedString() { return "PASSED"; }
  12289. #else
  12290. const char* failedString() { return "failed"; }
  12291. const char* passedString() { return "passed"; }
  12292. #endif
  12293. // Colour::LightGrey
  12294. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12295. std::string bothOrAll( std::size_t count ) {
  12296. return count == 1 ? std::string() :
  12297. count == 2 ? "both " : "all " ;
  12298. }
  12299. } // anon namespace
  12300. namespace Catch {
  12301. namespace {
  12302. // Colour, message variants:
  12303. // - white: No tests ran.
  12304. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12305. // - white: Passed [both/all] N test cases (no assertions).
  12306. // - red: Failed N tests cases, failed M assertions.
  12307. // - green: Passed [both/all] N tests cases with M assertions.
  12308. void printTotals(std::ostream& out, const Totals& totals) {
  12309. if (totals.testCases.total() == 0) {
  12310. out << "No tests ran.";
  12311. } else if (totals.testCases.failed == totals.testCases.total()) {
  12312. Colour colour(Colour::ResultError);
  12313. const std::string qualify_assertions_failed =
  12314. totals.assertions.failed == totals.assertions.total() ?
  12315. bothOrAll(totals.assertions.failed) : std::string();
  12316. out <<
  12317. "Failed " << bothOrAll(totals.testCases.failed)
  12318. << pluralise(totals.testCases.failed, "test case") << ", "
  12319. "failed " << qualify_assertions_failed <<
  12320. pluralise(totals.assertions.failed, "assertion") << '.';
  12321. } else if (totals.assertions.total() == 0) {
  12322. out <<
  12323. "Passed " << bothOrAll(totals.testCases.total())
  12324. << pluralise(totals.testCases.total(), "test case")
  12325. << " (no assertions).";
  12326. } else if (totals.assertions.failed) {
  12327. Colour colour(Colour::ResultError);
  12328. out <<
  12329. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12330. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12331. } else {
  12332. Colour colour(Colour::ResultSuccess);
  12333. out <<
  12334. "Passed " << bothOrAll(totals.testCases.passed)
  12335. << pluralise(totals.testCases.passed, "test case") <<
  12336. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12337. }
  12338. }
  12339. // Implementation of CompactReporter formatting
  12340. class AssertionPrinter {
  12341. public:
  12342. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12343. AssertionPrinter(AssertionPrinter const&) = delete;
  12344. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12345. : stream(_stream)
  12346. , result(_stats.assertionResult)
  12347. , messages(_stats.infoMessages)
  12348. , itMessage(_stats.infoMessages.begin())
  12349. , printInfoMessages(_printInfoMessages) {}
  12350. void print() {
  12351. printSourceInfo();
  12352. itMessage = messages.begin();
  12353. switch (result.getResultType()) {
  12354. case ResultWas::Ok:
  12355. printResultType(Colour::ResultSuccess, passedString());
  12356. printOriginalExpression();
  12357. printReconstructedExpression();
  12358. if (!result.hasExpression())
  12359. printRemainingMessages(Colour::None);
  12360. else
  12361. printRemainingMessages();
  12362. break;
  12363. case ResultWas::ExpressionFailed:
  12364. if (result.isOk())
  12365. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12366. else
  12367. printResultType(Colour::Error, failedString());
  12368. printOriginalExpression();
  12369. printReconstructedExpression();
  12370. printRemainingMessages();
  12371. break;
  12372. case ResultWas::ThrewException:
  12373. printResultType(Colour::Error, failedString());
  12374. printIssue("unexpected exception with message:");
  12375. printMessage();
  12376. printExpressionWas();
  12377. printRemainingMessages();
  12378. break;
  12379. case ResultWas::FatalErrorCondition:
  12380. printResultType(Colour::Error, failedString());
  12381. printIssue("fatal error condition with message:");
  12382. printMessage();
  12383. printExpressionWas();
  12384. printRemainingMessages();
  12385. break;
  12386. case ResultWas::DidntThrowException:
  12387. printResultType(Colour::Error, failedString());
  12388. printIssue("expected exception, got none");
  12389. printExpressionWas();
  12390. printRemainingMessages();
  12391. break;
  12392. case ResultWas::Info:
  12393. printResultType(Colour::None, "info");
  12394. printMessage();
  12395. printRemainingMessages();
  12396. break;
  12397. case ResultWas::Warning:
  12398. printResultType(Colour::None, "warning");
  12399. printMessage();
  12400. printRemainingMessages();
  12401. break;
  12402. case ResultWas::ExplicitFailure:
  12403. printResultType(Colour::Error, failedString());
  12404. printIssue("explicitly");
  12405. printRemainingMessages(Colour::None);
  12406. break;
  12407. // These cases are here to prevent compiler warnings
  12408. case ResultWas::Unknown:
  12409. case ResultWas::FailureBit:
  12410. case ResultWas::Exception:
  12411. printResultType(Colour::Error, "** internal error **");
  12412. break;
  12413. }
  12414. }
  12415. private:
  12416. void printSourceInfo() const {
  12417. Colour colourGuard(Colour::FileName);
  12418. stream << result.getSourceInfo() << ':';
  12419. }
  12420. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12421. if (!passOrFail.empty()) {
  12422. {
  12423. Colour colourGuard(colour);
  12424. stream << ' ' << passOrFail;
  12425. }
  12426. stream << ':';
  12427. }
  12428. }
  12429. void printIssue(std::string const& issue) const {
  12430. stream << ' ' << issue;
  12431. }
  12432. void printExpressionWas() {
  12433. if (result.hasExpression()) {
  12434. stream << ';';
  12435. {
  12436. Colour colour(dimColour());
  12437. stream << " expression was:";
  12438. }
  12439. printOriginalExpression();
  12440. }
  12441. }
  12442. void printOriginalExpression() const {
  12443. if (result.hasExpression()) {
  12444. stream << ' ' << result.getExpression();
  12445. }
  12446. }
  12447. void printReconstructedExpression() const {
  12448. if (result.hasExpandedExpression()) {
  12449. {
  12450. Colour colour(dimColour());
  12451. stream << " for: ";
  12452. }
  12453. stream << result.getExpandedExpression();
  12454. }
  12455. }
  12456. void printMessage() {
  12457. if (itMessage != messages.end()) {
  12458. stream << " '" << itMessage->message << '\'';
  12459. ++itMessage;
  12460. }
  12461. }
  12462. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12463. if (itMessage == messages.end())
  12464. return;
  12465. const auto itEnd = messages.cend();
  12466. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12467. {
  12468. Colour colourGuard(colour);
  12469. stream << " with " << pluralise(N, "message") << ':';
  12470. }
  12471. while (itMessage != itEnd) {
  12472. // If this assertion is a warning ignore any INFO messages
  12473. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12474. printMessage();
  12475. if (itMessage != itEnd) {
  12476. Colour colourGuard(dimColour());
  12477. stream << " and";
  12478. }
  12479. continue;
  12480. }
  12481. ++itMessage;
  12482. }
  12483. }
  12484. private:
  12485. std::ostream& stream;
  12486. AssertionResult const& result;
  12487. std::vector<MessageInfo> messages;
  12488. std::vector<MessageInfo>::const_iterator itMessage;
  12489. bool printInfoMessages;
  12490. };
  12491. } // anon namespace
  12492. std::string CompactReporter::getDescription() {
  12493. return "Reports test results on a single line, suitable for IDEs";
  12494. }
  12495. ReporterPreferences CompactReporter::getPreferences() const {
  12496. return m_reporterPrefs;
  12497. }
  12498. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12499. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12500. }
  12501. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12502. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12503. AssertionResult const& result = _assertionStats.assertionResult;
  12504. bool printInfoMessages = true;
  12505. // Drop out if result was successful and we're not printing those
  12506. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12507. if( result.getResultType() != ResultWas::Warning )
  12508. return false;
  12509. printInfoMessages = false;
  12510. }
  12511. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12512. printer.print();
  12513. stream << std::endl;
  12514. return true;
  12515. }
  12516. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12517. if (m_config->showDurations() == ShowDurations::Always) {
  12518. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12519. }
  12520. }
  12521. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12522. printTotals( stream, _testRunStats.totals );
  12523. stream << '\n' << std::endl;
  12524. StreamingReporterBase::testRunEnded( _testRunStats );
  12525. }
  12526. CompactReporter::~CompactReporter() {}
  12527. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12528. } // end namespace Catch
  12529. // end catch_reporter_compact.cpp
  12530. // start catch_reporter_console.cpp
  12531. #include <cfloat>
  12532. #include <cstdio>
  12533. #if defined(_MSC_VER)
  12534. #pragma warning(push)
  12535. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12536. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12537. #endif
  12538. #if defined(__clang__)
  12539. # pragma clang diagnostic push
  12540. // For simplicity, benchmarking-only helpers are always enabled
  12541. # pragma clang diagnostic ignored "-Wunused-function"
  12542. #endif
  12543. namespace Catch {
  12544. namespace {
  12545. // Formatter impl for ConsoleReporter
  12546. class ConsoleAssertionPrinter {
  12547. public:
  12548. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12549. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12550. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12551. : stream(_stream),
  12552. stats(_stats),
  12553. result(_stats.assertionResult),
  12554. colour(Colour::None),
  12555. message(result.getMessage()),
  12556. messages(_stats.infoMessages),
  12557. printInfoMessages(_printInfoMessages) {
  12558. switch (result.getResultType()) {
  12559. case ResultWas::Ok:
  12560. colour = Colour::Success;
  12561. passOrFail = "PASSED";
  12562. //if( result.hasMessage() )
  12563. if (_stats.infoMessages.size() == 1)
  12564. messageLabel = "with message";
  12565. if (_stats.infoMessages.size() > 1)
  12566. messageLabel = "with messages";
  12567. break;
  12568. case ResultWas::ExpressionFailed:
  12569. if (result.isOk()) {
  12570. colour = Colour::Success;
  12571. passOrFail = "FAILED - but was ok";
  12572. } else {
  12573. colour = Colour::Error;
  12574. passOrFail = "FAILED";
  12575. }
  12576. if (_stats.infoMessages.size() == 1)
  12577. messageLabel = "with message";
  12578. if (_stats.infoMessages.size() > 1)
  12579. messageLabel = "with messages";
  12580. break;
  12581. case ResultWas::ThrewException:
  12582. colour = Colour::Error;
  12583. passOrFail = "FAILED";
  12584. messageLabel = "due to unexpected exception with ";
  12585. if (_stats.infoMessages.size() == 1)
  12586. messageLabel += "message";
  12587. if (_stats.infoMessages.size() > 1)
  12588. messageLabel += "messages";
  12589. break;
  12590. case ResultWas::FatalErrorCondition:
  12591. colour = Colour::Error;
  12592. passOrFail = "FAILED";
  12593. messageLabel = "due to a fatal error condition";
  12594. break;
  12595. case ResultWas::DidntThrowException:
  12596. colour = Colour::Error;
  12597. passOrFail = "FAILED";
  12598. messageLabel = "because no exception was thrown where one was expected";
  12599. break;
  12600. case ResultWas::Info:
  12601. messageLabel = "info";
  12602. break;
  12603. case ResultWas::Warning:
  12604. messageLabel = "warning";
  12605. break;
  12606. case ResultWas::ExplicitFailure:
  12607. passOrFail = "FAILED";
  12608. colour = Colour::Error;
  12609. if (_stats.infoMessages.size() == 1)
  12610. messageLabel = "explicitly with message";
  12611. if (_stats.infoMessages.size() > 1)
  12612. messageLabel = "explicitly with messages";
  12613. break;
  12614. // These cases are here to prevent compiler warnings
  12615. case ResultWas::Unknown:
  12616. case ResultWas::FailureBit:
  12617. case ResultWas::Exception:
  12618. passOrFail = "** internal error **";
  12619. colour = Colour::Error;
  12620. break;
  12621. }
  12622. }
  12623. void print() const {
  12624. printSourceInfo();
  12625. if (stats.totals.assertions.total() > 0) {
  12626. printResultType();
  12627. printOriginalExpression();
  12628. printReconstructedExpression();
  12629. } else {
  12630. stream << '\n';
  12631. }
  12632. printMessage();
  12633. }
  12634. private:
  12635. void printResultType() const {
  12636. if (!passOrFail.empty()) {
  12637. Colour colourGuard(colour);
  12638. stream << passOrFail << ":\n";
  12639. }
  12640. }
  12641. void printOriginalExpression() const {
  12642. if (result.hasExpression()) {
  12643. Colour colourGuard(Colour::OriginalExpression);
  12644. stream << " ";
  12645. stream << result.getExpressionInMacro();
  12646. stream << '\n';
  12647. }
  12648. }
  12649. void printReconstructedExpression() const {
  12650. if (result.hasExpandedExpression()) {
  12651. stream << "with expansion:\n";
  12652. Colour colourGuard(Colour::ReconstructedExpression);
  12653. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  12654. }
  12655. }
  12656. void printMessage() const {
  12657. if (!messageLabel.empty())
  12658. stream << messageLabel << ':' << '\n';
  12659. for (auto const& msg : messages) {
  12660. // If this assertion is a warning ignore any INFO messages
  12661. if (printInfoMessages || msg.type != ResultWas::Info)
  12662. stream << Column(msg.message).indent(2) << '\n';
  12663. }
  12664. }
  12665. void printSourceInfo() const {
  12666. Colour colourGuard(Colour::FileName);
  12667. stream << result.getSourceInfo() << ": ";
  12668. }
  12669. std::ostream& stream;
  12670. AssertionStats const& stats;
  12671. AssertionResult const& result;
  12672. Colour::Code colour;
  12673. std::string passOrFail;
  12674. std::string messageLabel;
  12675. std::string message;
  12676. std::vector<MessageInfo> messages;
  12677. bool printInfoMessages;
  12678. };
  12679. std::size_t makeRatio(std::size_t number, std::size_t total) {
  12680. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  12681. return (ratio == 0 && number > 0) ? 1 : ratio;
  12682. }
  12683. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  12684. if (i > j && i > k)
  12685. return i;
  12686. else if (j > k)
  12687. return j;
  12688. else
  12689. return k;
  12690. }
  12691. struct ColumnInfo {
  12692. enum Justification { Left, Right };
  12693. std::string name;
  12694. int width;
  12695. Justification justification;
  12696. };
  12697. struct ColumnBreak {};
  12698. struct RowBreak {};
  12699. class Duration {
  12700. enum class Unit {
  12701. Auto,
  12702. Nanoseconds,
  12703. Microseconds,
  12704. Milliseconds,
  12705. Seconds,
  12706. Minutes
  12707. };
  12708. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  12709. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  12710. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  12711. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  12712. uint64_t m_inNanoseconds;
  12713. Unit m_units;
  12714. public:
  12715. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  12716. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  12717. }
  12718. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  12719. : m_inNanoseconds(inNanoseconds),
  12720. m_units(units) {
  12721. if (m_units == Unit::Auto) {
  12722. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  12723. m_units = Unit::Nanoseconds;
  12724. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  12725. m_units = Unit::Microseconds;
  12726. else if (m_inNanoseconds < s_nanosecondsInASecond)
  12727. m_units = Unit::Milliseconds;
  12728. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  12729. m_units = Unit::Seconds;
  12730. else
  12731. m_units = Unit::Minutes;
  12732. }
  12733. }
  12734. auto value() const -> double {
  12735. switch (m_units) {
  12736. case Unit::Microseconds:
  12737. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  12738. case Unit::Milliseconds:
  12739. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  12740. case Unit::Seconds:
  12741. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  12742. case Unit::Minutes:
  12743. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  12744. default:
  12745. return static_cast<double>(m_inNanoseconds);
  12746. }
  12747. }
  12748. auto unitsAsString() const -> std::string {
  12749. switch (m_units) {
  12750. case Unit::Nanoseconds:
  12751. return "ns";
  12752. case Unit::Microseconds:
  12753. return "us";
  12754. case Unit::Milliseconds:
  12755. return "ms";
  12756. case Unit::Seconds:
  12757. return "s";
  12758. case Unit::Minutes:
  12759. return "m";
  12760. default:
  12761. return "** internal error **";
  12762. }
  12763. }
  12764. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  12765. return os << duration.value() << " " << duration.unitsAsString();
  12766. }
  12767. };
  12768. } // end anon namespace
  12769. class TablePrinter {
  12770. std::ostream& m_os;
  12771. std::vector<ColumnInfo> m_columnInfos;
  12772. std::ostringstream m_oss;
  12773. int m_currentColumn = -1;
  12774. bool m_isOpen = false;
  12775. public:
  12776. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  12777. : m_os( os ),
  12778. m_columnInfos( std::move( columnInfos ) ) {}
  12779. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  12780. return m_columnInfos;
  12781. }
  12782. void open() {
  12783. if (!m_isOpen) {
  12784. m_isOpen = true;
  12785. *this << RowBreak();
  12786. Columns headerCols;
  12787. Spacer spacer(2);
  12788. for (auto const& info : m_columnInfos) {
  12789. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  12790. headerCols += spacer;
  12791. }
  12792. m_os << headerCols << "\n";
  12793. m_os << Catch::getLineOfChars<'-'>() << "\n";
  12794. }
  12795. }
  12796. void close() {
  12797. if (m_isOpen) {
  12798. *this << RowBreak();
  12799. m_os << std::endl;
  12800. m_isOpen = false;
  12801. }
  12802. }
  12803. template<typename T>
  12804. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  12805. tp.m_oss << value;
  12806. return tp;
  12807. }
  12808. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  12809. auto colStr = tp.m_oss.str();
  12810. // This takes account of utf8 encodings
  12811. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  12812. tp.m_oss.str("");
  12813. tp.open();
  12814. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  12815. tp.m_currentColumn = -1;
  12816. tp.m_os << "\n";
  12817. }
  12818. tp.m_currentColumn++;
  12819. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  12820. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  12821. ? std::string(colInfo.width - (strSize + 2), ' ')
  12822. : std::string();
  12823. if (colInfo.justification == ColumnInfo::Left)
  12824. tp.m_os << colStr << padding << " ";
  12825. else
  12826. tp.m_os << padding << colStr << " ";
  12827. return tp;
  12828. }
  12829. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  12830. if (tp.m_currentColumn > 0) {
  12831. tp.m_os << "\n";
  12832. tp.m_currentColumn = -1;
  12833. }
  12834. return tp;
  12835. }
  12836. };
  12837. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  12838. : StreamingReporterBase(config),
  12839. m_tablePrinter(new TablePrinter(config.stream(),
  12840. {
  12841. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  12842. { "samples mean std dev", 14, ColumnInfo::Right },
  12843. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  12844. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  12845. })) {}
  12846. ConsoleReporter::~ConsoleReporter() = default;
  12847. std::string ConsoleReporter::getDescription() {
  12848. return "Reports test results as plain lines of text";
  12849. }
  12850. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  12851. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12852. }
  12853. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  12854. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  12855. AssertionResult const& result = _assertionStats.assertionResult;
  12856. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  12857. // Drop out if result was successful but we're not printing them.
  12858. if (!includeResults && result.getResultType() != ResultWas::Warning)
  12859. return false;
  12860. lazyPrint();
  12861. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  12862. printer.print();
  12863. stream << std::endl;
  12864. return true;
  12865. }
  12866. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  12867. m_tablePrinter->close();
  12868. m_headerPrinted = false;
  12869. StreamingReporterBase::sectionStarting(_sectionInfo);
  12870. }
  12871. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  12872. m_tablePrinter->close();
  12873. if (_sectionStats.missingAssertions) {
  12874. lazyPrint();
  12875. Colour colour(Colour::ResultError);
  12876. if (m_sectionStack.size() > 1)
  12877. stream << "\nNo assertions in section";
  12878. else
  12879. stream << "\nNo assertions in test case";
  12880. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  12881. }
  12882. if (m_config->showDurations() == ShowDurations::Always) {
  12883. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12884. }
  12885. if (m_headerPrinted) {
  12886. m_headerPrinted = false;
  12887. }
  12888. StreamingReporterBase::sectionEnded(_sectionStats);
  12889. }
  12890. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  12891. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  12892. lazyPrintWithoutClosingBenchmarkTable();
  12893. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  12894. bool firstLine = true;
  12895. for (auto line : nameCol) {
  12896. if (!firstLine)
  12897. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12898. else
  12899. firstLine = false;
  12900. (*m_tablePrinter) << line << ColumnBreak();
  12901. }
  12902. }
  12903. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  12904. (*m_tablePrinter) << info.samples << ColumnBreak()
  12905. << info.iterations << ColumnBreak()
  12906. << Duration(info.estimatedDuration) << ColumnBreak();
  12907. }
  12908. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  12909. (*m_tablePrinter) << ColumnBreak()
  12910. << Duration(stats.mean.point.count()) << ColumnBreak()
  12911. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  12912. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  12913. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  12914. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  12915. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12916. }
  12917. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  12918. Colour colour(Colour::Red);
  12919. (*m_tablePrinter)
  12920. << "Benchmark failed (" << error << ")"
  12921. << ColumnBreak() << RowBreak();
  12922. }
  12923. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  12924. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  12925. m_tablePrinter->close();
  12926. StreamingReporterBase::testCaseEnded(_testCaseStats);
  12927. m_headerPrinted = false;
  12928. }
  12929. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  12930. if (currentGroupInfo.used) {
  12931. printSummaryDivider();
  12932. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  12933. printTotals(_testGroupStats.totals);
  12934. stream << '\n' << std::endl;
  12935. }
  12936. StreamingReporterBase::testGroupEnded(_testGroupStats);
  12937. }
  12938. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  12939. printTotalsDivider(_testRunStats.totals);
  12940. printTotals(_testRunStats.totals);
  12941. stream << std::endl;
  12942. StreamingReporterBase::testRunEnded(_testRunStats);
  12943. }
  12944. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  12945. StreamingReporterBase::testRunStarting(_testInfo);
  12946. printTestFilters();
  12947. }
  12948. void ConsoleReporter::lazyPrint() {
  12949. m_tablePrinter->close();
  12950. lazyPrintWithoutClosingBenchmarkTable();
  12951. }
  12952. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  12953. if (!currentTestRunInfo.used)
  12954. lazyPrintRunInfo();
  12955. if (!currentGroupInfo.used)
  12956. lazyPrintGroupInfo();
  12957. if (!m_headerPrinted) {
  12958. printTestCaseAndSectionHeader();
  12959. m_headerPrinted = true;
  12960. }
  12961. }
  12962. void ConsoleReporter::lazyPrintRunInfo() {
  12963. stream << '\n' << getLineOfChars<'~'>() << '\n';
  12964. Colour colour(Colour::SecondaryText);
  12965. stream << currentTestRunInfo->name
  12966. << " is a Catch v" << libraryVersion() << " host application.\n"
  12967. << "Run with -? for options\n\n";
  12968. if (m_config->rngSeed() != 0)
  12969. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  12970. currentTestRunInfo.used = true;
  12971. }
  12972. void ConsoleReporter::lazyPrintGroupInfo() {
  12973. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  12974. printClosedHeader("Group: " + currentGroupInfo->name);
  12975. currentGroupInfo.used = true;
  12976. }
  12977. }
  12978. void ConsoleReporter::printTestCaseAndSectionHeader() {
  12979. assert(!m_sectionStack.empty());
  12980. printOpenHeader(currentTestCaseInfo->name);
  12981. if (m_sectionStack.size() > 1) {
  12982. Colour colourGuard(Colour::Headers);
  12983. auto
  12984. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  12985. itEnd = m_sectionStack.end();
  12986. for (; it != itEnd; ++it)
  12987. printHeaderString(it->name, 2);
  12988. }
  12989. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  12990. if (!lineInfo.empty()) {
  12991. stream << getLineOfChars<'-'>() << '\n';
  12992. Colour colourGuard(Colour::FileName);
  12993. stream << lineInfo << '\n';
  12994. }
  12995. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  12996. }
  12997. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  12998. printOpenHeader(_name);
  12999. stream << getLineOfChars<'.'>() << '\n';
  13000. }
  13001. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13002. stream << getLineOfChars<'-'>() << '\n';
  13003. {
  13004. Colour colourGuard(Colour::Headers);
  13005. printHeaderString(_name);
  13006. }
  13007. }
  13008. // if string has a : in first line will set indent to follow it on
  13009. // subsequent lines
  13010. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13011. std::size_t i = _string.find(": ");
  13012. if (i != std::string::npos)
  13013. i += 2;
  13014. else
  13015. i = 0;
  13016. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13017. }
  13018. struct SummaryColumn {
  13019. SummaryColumn( std::string _label, Colour::Code _colour )
  13020. : label( std::move( _label ) ),
  13021. colour( _colour ) {}
  13022. SummaryColumn addRow( std::size_t count ) {
  13023. ReusableStringStream rss;
  13024. rss << count;
  13025. std::string row = rss.str();
  13026. for (auto& oldRow : rows) {
  13027. while (oldRow.size() < row.size())
  13028. oldRow = ' ' + oldRow;
  13029. while (oldRow.size() > row.size())
  13030. row = ' ' + row;
  13031. }
  13032. rows.push_back(row);
  13033. return *this;
  13034. }
  13035. std::string label;
  13036. Colour::Code colour;
  13037. std::vector<std::string> rows;
  13038. };
  13039. void ConsoleReporter::printTotals( Totals const& totals ) {
  13040. if (totals.testCases.total() == 0) {
  13041. stream << Colour(Colour::Warning) << "No tests ran\n";
  13042. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13043. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13044. stream << " ("
  13045. << pluralise(totals.assertions.passed, "assertion") << " in "
  13046. << pluralise(totals.testCases.passed, "test case") << ')'
  13047. << '\n';
  13048. } else {
  13049. std::vector<SummaryColumn> columns;
  13050. columns.push_back(SummaryColumn("", Colour::None)
  13051. .addRow(totals.testCases.total())
  13052. .addRow(totals.assertions.total()));
  13053. columns.push_back(SummaryColumn("passed", Colour::Success)
  13054. .addRow(totals.testCases.passed)
  13055. .addRow(totals.assertions.passed));
  13056. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13057. .addRow(totals.testCases.failed)
  13058. .addRow(totals.assertions.failed));
  13059. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13060. .addRow(totals.testCases.failedButOk)
  13061. .addRow(totals.assertions.failedButOk));
  13062. printSummaryRow("test cases", columns, 0);
  13063. printSummaryRow("assertions", columns, 1);
  13064. }
  13065. }
  13066. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13067. for (auto col : cols) {
  13068. std::string value = col.rows[row];
  13069. if (col.label.empty()) {
  13070. stream << label << ": ";
  13071. if (value != "0")
  13072. stream << value;
  13073. else
  13074. stream << Colour(Colour::Warning) << "- none -";
  13075. } else if (value != "0") {
  13076. stream << Colour(Colour::LightGrey) << " | ";
  13077. stream << Colour(col.colour)
  13078. << value << ' ' << col.label;
  13079. }
  13080. }
  13081. stream << '\n';
  13082. }
  13083. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13084. if (totals.testCases.total() > 0) {
  13085. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13086. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13087. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13088. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13089. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13090. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13091. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13092. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13093. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13094. if (totals.testCases.allPassed())
  13095. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13096. else
  13097. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13098. } else {
  13099. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13100. }
  13101. stream << '\n';
  13102. }
  13103. void ConsoleReporter::printSummaryDivider() {
  13104. stream << getLineOfChars<'-'>() << '\n';
  13105. }
  13106. void ConsoleReporter::printTestFilters() {
  13107. if (m_config->testSpec().hasFilters())
  13108. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  13109. }
  13110. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13111. } // end namespace Catch
  13112. #if defined(_MSC_VER)
  13113. #pragma warning(pop)
  13114. #endif
  13115. #if defined(__clang__)
  13116. # pragma clang diagnostic pop
  13117. #endif
  13118. // end catch_reporter_console.cpp
  13119. // start catch_reporter_junit.cpp
  13120. #include <cassert>
  13121. #include <sstream>
  13122. #include <ctime>
  13123. #include <algorithm>
  13124. namespace Catch {
  13125. namespace {
  13126. std::string getCurrentTimestamp() {
  13127. // Beware, this is not reentrant because of backward compatibility issues
  13128. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13129. time_t rawtime;
  13130. std::time(&rawtime);
  13131. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13132. #ifdef _MSC_VER
  13133. std::tm timeInfo = {};
  13134. gmtime_s(&timeInfo, &rawtime);
  13135. #else
  13136. std::tm* timeInfo;
  13137. timeInfo = std::gmtime(&rawtime);
  13138. #endif
  13139. char timeStamp[timeStampSize];
  13140. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13141. #ifdef _MSC_VER
  13142. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13143. #else
  13144. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13145. #endif
  13146. return std::string(timeStamp);
  13147. }
  13148. std::string fileNameTag(const std::vector<std::string> &tags) {
  13149. auto it = std::find_if(begin(tags),
  13150. end(tags),
  13151. [] (std::string const& tag) {return tag.front() == '#'; });
  13152. if (it != tags.end())
  13153. return it->substr(1);
  13154. return std::string();
  13155. }
  13156. } // anonymous namespace
  13157. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13158. : CumulativeReporterBase( _config ),
  13159. xml( _config.stream() )
  13160. {
  13161. m_reporterPrefs.shouldRedirectStdOut = true;
  13162. m_reporterPrefs.shouldReportAllAssertions = true;
  13163. }
  13164. JunitReporter::~JunitReporter() {}
  13165. std::string JunitReporter::getDescription() {
  13166. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13167. }
  13168. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13169. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13170. CumulativeReporterBase::testRunStarting( runInfo );
  13171. xml.startElement( "testsuites" );
  13172. }
  13173. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13174. suiteTimer.start();
  13175. stdOutForSuite.clear();
  13176. stdErrForSuite.clear();
  13177. unexpectedExceptions = 0;
  13178. CumulativeReporterBase::testGroupStarting( groupInfo );
  13179. }
  13180. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13181. m_okToFail = testCaseInfo.okToFail();
  13182. }
  13183. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13184. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13185. unexpectedExceptions++;
  13186. return CumulativeReporterBase::assertionEnded( assertionStats );
  13187. }
  13188. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13189. stdOutForSuite += testCaseStats.stdOut;
  13190. stdErrForSuite += testCaseStats.stdErr;
  13191. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13192. }
  13193. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13194. double suiteTime = suiteTimer.getElapsedSeconds();
  13195. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13196. writeGroup( *m_testGroups.back(), suiteTime );
  13197. }
  13198. void JunitReporter::testRunEndedCumulative() {
  13199. xml.endElement();
  13200. }
  13201. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13202. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13203. TestGroupStats const& stats = groupNode.value;
  13204. xml.writeAttribute( "name", stats.groupInfo.name );
  13205. xml.writeAttribute( "errors", unexpectedExceptions );
  13206. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13207. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13208. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13209. if( m_config->showDurations() == ShowDurations::Never )
  13210. xml.writeAttribute( "time", "" );
  13211. else
  13212. xml.writeAttribute( "time", suiteTime );
  13213. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13214. // Write properties if there are any
  13215. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13216. auto properties = xml.scopedElement("properties");
  13217. if (m_config->hasTestFilters()) {
  13218. xml.scopedElement("property")
  13219. .writeAttribute("name", "filters")
  13220. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13221. }
  13222. if (m_config->rngSeed() != 0) {
  13223. xml.scopedElement("property")
  13224. .writeAttribute("name", "random-seed")
  13225. .writeAttribute("value", m_config->rngSeed());
  13226. }
  13227. }
  13228. // Write test cases
  13229. for( auto const& child : groupNode.children )
  13230. writeTestCase( *child );
  13231. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13232. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13233. }
  13234. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13235. TestCaseStats const& stats = testCaseNode.value;
  13236. // All test cases have exactly one section - which represents the
  13237. // test case itself. That section may have 0-n nested sections
  13238. assert( testCaseNode.children.size() == 1 );
  13239. SectionNode const& rootSection = *testCaseNode.children.front();
  13240. std::string className = stats.testInfo.className;
  13241. if( className.empty() ) {
  13242. className = fileNameTag(stats.testInfo.tags);
  13243. if ( className.empty() )
  13244. className = "global";
  13245. }
  13246. if ( !m_config->name().empty() )
  13247. className = m_config->name() + "." + className;
  13248. writeSection( className, "", rootSection );
  13249. }
  13250. void JunitReporter::writeSection( std::string const& className,
  13251. std::string const& rootName,
  13252. SectionNode const& sectionNode ) {
  13253. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13254. if( !rootName.empty() )
  13255. name = rootName + '/' + name;
  13256. if( !sectionNode.assertions.empty() ||
  13257. !sectionNode.stdOut.empty() ||
  13258. !sectionNode.stdErr.empty() ) {
  13259. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13260. if( className.empty() ) {
  13261. xml.writeAttribute( "classname", name );
  13262. xml.writeAttribute( "name", "root" );
  13263. }
  13264. else {
  13265. xml.writeAttribute( "classname", className );
  13266. xml.writeAttribute( "name", name );
  13267. }
  13268. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13269. writeAssertions( sectionNode );
  13270. if( !sectionNode.stdOut.empty() )
  13271. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13272. if( !sectionNode.stdErr.empty() )
  13273. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13274. }
  13275. for( auto const& childNode : sectionNode.childSections )
  13276. if( className.empty() )
  13277. writeSection( name, "", *childNode );
  13278. else
  13279. writeSection( className, name, *childNode );
  13280. }
  13281. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13282. for( auto const& assertion : sectionNode.assertions )
  13283. writeAssertion( assertion );
  13284. }
  13285. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13286. AssertionResult const& result = stats.assertionResult;
  13287. if( !result.isOk() ) {
  13288. std::string elementName;
  13289. switch( result.getResultType() ) {
  13290. case ResultWas::ThrewException:
  13291. case ResultWas::FatalErrorCondition:
  13292. elementName = "error";
  13293. break;
  13294. case ResultWas::ExplicitFailure:
  13295. elementName = "failure";
  13296. break;
  13297. case ResultWas::ExpressionFailed:
  13298. elementName = "failure";
  13299. break;
  13300. case ResultWas::DidntThrowException:
  13301. elementName = "failure";
  13302. break;
  13303. // We should never see these here:
  13304. case ResultWas::Info:
  13305. case ResultWas::Warning:
  13306. case ResultWas::Ok:
  13307. case ResultWas::Unknown:
  13308. case ResultWas::FailureBit:
  13309. case ResultWas::Exception:
  13310. elementName = "internalError";
  13311. break;
  13312. }
  13313. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13314. xml.writeAttribute( "message", result.getExpandedExpression() );
  13315. xml.writeAttribute( "type", result.getTestMacroName() );
  13316. ReusableStringStream rss;
  13317. if( !result.getMessage().empty() )
  13318. rss << result.getMessage() << '\n';
  13319. for( auto const& msg : stats.infoMessages )
  13320. if( msg.type == ResultWas::Info )
  13321. rss << msg.message << '\n';
  13322. rss << "at " << result.getSourceInfo();
  13323. xml.writeText( rss.str(), false );
  13324. }
  13325. }
  13326. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13327. } // end namespace Catch
  13328. // end catch_reporter_junit.cpp
  13329. // start catch_reporter_listening.cpp
  13330. #include <cassert>
  13331. namespace Catch {
  13332. ListeningReporter::ListeningReporter() {
  13333. // We will assume that listeners will always want all assertions
  13334. m_preferences.shouldReportAllAssertions = true;
  13335. }
  13336. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13337. m_listeners.push_back( std::move( listener ) );
  13338. }
  13339. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13340. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13341. m_reporter = std::move( reporter );
  13342. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13343. }
  13344. ReporterPreferences ListeningReporter::getPreferences() const {
  13345. return m_preferences;
  13346. }
  13347. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13348. return std::set<Verbosity>{ };
  13349. }
  13350. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13351. for ( auto const& listener : m_listeners ) {
  13352. listener->noMatchingTestCases( spec );
  13353. }
  13354. m_reporter->noMatchingTestCases( spec );
  13355. }
  13356. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13357. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13358. for (auto const& listener : m_listeners) {
  13359. listener->benchmarkPreparing(name);
  13360. }
  13361. m_reporter->benchmarkPreparing(name);
  13362. }
  13363. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13364. for ( auto const& listener : m_listeners ) {
  13365. listener->benchmarkStarting( benchmarkInfo );
  13366. }
  13367. m_reporter->benchmarkStarting( benchmarkInfo );
  13368. }
  13369. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13370. for ( auto const& listener : m_listeners ) {
  13371. listener->benchmarkEnded( benchmarkStats );
  13372. }
  13373. m_reporter->benchmarkEnded( benchmarkStats );
  13374. }
  13375. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13376. for (auto const& listener : m_listeners) {
  13377. listener->benchmarkFailed(error);
  13378. }
  13379. m_reporter->benchmarkFailed(error);
  13380. }
  13381. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13382. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13383. for ( auto const& listener : m_listeners ) {
  13384. listener->testRunStarting( testRunInfo );
  13385. }
  13386. m_reporter->testRunStarting( testRunInfo );
  13387. }
  13388. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13389. for ( auto const& listener : m_listeners ) {
  13390. listener->testGroupStarting( groupInfo );
  13391. }
  13392. m_reporter->testGroupStarting( groupInfo );
  13393. }
  13394. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13395. for ( auto const& listener : m_listeners ) {
  13396. listener->testCaseStarting( testInfo );
  13397. }
  13398. m_reporter->testCaseStarting( testInfo );
  13399. }
  13400. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13401. for ( auto const& listener : m_listeners ) {
  13402. listener->sectionStarting( sectionInfo );
  13403. }
  13404. m_reporter->sectionStarting( sectionInfo );
  13405. }
  13406. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13407. for ( auto const& listener : m_listeners ) {
  13408. listener->assertionStarting( assertionInfo );
  13409. }
  13410. m_reporter->assertionStarting( assertionInfo );
  13411. }
  13412. // The return value indicates if the messages buffer should be cleared:
  13413. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13414. for( auto const& listener : m_listeners ) {
  13415. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13416. }
  13417. return m_reporter->assertionEnded( assertionStats );
  13418. }
  13419. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13420. for ( auto const& listener : m_listeners ) {
  13421. listener->sectionEnded( sectionStats );
  13422. }
  13423. m_reporter->sectionEnded( sectionStats );
  13424. }
  13425. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13426. for ( auto const& listener : m_listeners ) {
  13427. listener->testCaseEnded( testCaseStats );
  13428. }
  13429. m_reporter->testCaseEnded( testCaseStats );
  13430. }
  13431. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13432. for ( auto const& listener : m_listeners ) {
  13433. listener->testGroupEnded( testGroupStats );
  13434. }
  13435. m_reporter->testGroupEnded( testGroupStats );
  13436. }
  13437. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13438. for ( auto const& listener : m_listeners ) {
  13439. listener->testRunEnded( testRunStats );
  13440. }
  13441. m_reporter->testRunEnded( testRunStats );
  13442. }
  13443. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13444. for ( auto const& listener : m_listeners ) {
  13445. listener->skipTest( testInfo );
  13446. }
  13447. m_reporter->skipTest( testInfo );
  13448. }
  13449. bool ListeningReporter::isMulti() const {
  13450. return true;
  13451. }
  13452. } // end namespace Catch
  13453. // end catch_reporter_listening.cpp
  13454. // start catch_reporter_xml.cpp
  13455. #if defined(_MSC_VER)
  13456. #pragma warning(push)
  13457. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13458. // Note that 4062 (not all labels are handled
  13459. // and default is missing) is enabled
  13460. #endif
  13461. namespace Catch {
  13462. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13463. : StreamingReporterBase( _config ),
  13464. m_xml(_config.stream())
  13465. {
  13466. m_reporterPrefs.shouldRedirectStdOut = true;
  13467. m_reporterPrefs.shouldReportAllAssertions = true;
  13468. }
  13469. XmlReporter::~XmlReporter() = default;
  13470. std::string XmlReporter::getDescription() {
  13471. return "Reports test results as an XML document";
  13472. }
  13473. std::string XmlReporter::getStylesheetRef() const {
  13474. return std::string();
  13475. }
  13476. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13477. m_xml
  13478. .writeAttribute( "filename", sourceInfo.file )
  13479. .writeAttribute( "line", sourceInfo.line );
  13480. }
  13481. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13482. StreamingReporterBase::noMatchingTestCases( s );
  13483. }
  13484. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13485. StreamingReporterBase::testRunStarting( testInfo );
  13486. std::string stylesheetRef = getStylesheetRef();
  13487. if( !stylesheetRef.empty() )
  13488. m_xml.writeStylesheetRef( stylesheetRef );
  13489. m_xml.startElement( "Catch" );
  13490. if( !m_config->name().empty() )
  13491. m_xml.writeAttribute( "name", m_config->name() );
  13492. if (m_config->testSpec().hasFilters())
  13493. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13494. if( m_config->rngSeed() != 0 )
  13495. m_xml.scopedElement( "Randomness" )
  13496. .writeAttribute( "seed", m_config->rngSeed() );
  13497. }
  13498. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13499. StreamingReporterBase::testGroupStarting( groupInfo );
  13500. m_xml.startElement( "Group" )
  13501. .writeAttribute( "name", groupInfo.name );
  13502. }
  13503. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13504. StreamingReporterBase::testCaseStarting(testInfo);
  13505. m_xml.startElement( "TestCase" )
  13506. .writeAttribute( "name", trim( testInfo.name ) )
  13507. .writeAttribute( "description", testInfo.description )
  13508. .writeAttribute( "tags", testInfo.tagsAsString() );
  13509. writeSourceInfo( testInfo.lineInfo );
  13510. if ( m_config->showDurations() == ShowDurations::Always )
  13511. m_testCaseTimer.start();
  13512. m_xml.ensureTagClosed();
  13513. }
  13514. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13515. StreamingReporterBase::sectionStarting( sectionInfo );
  13516. if( m_sectionDepth++ > 0 ) {
  13517. m_xml.startElement( "Section" )
  13518. .writeAttribute( "name", trim( sectionInfo.name ) );
  13519. writeSourceInfo( sectionInfo.lineInfo );
  13520. m_xml.ensureTagClosed();
  13521. }
  13522. }
  13523. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13524. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13525. AssertionResult const& result = assertionStats.assertionResult;
  13526. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13527. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13528. // Print any info messages in <Info> tags.
  13529. for( auto const& msg : assertionStats.infoMessages ) {
  13530. if( msg.type == ResultWas::Info && includeResults ) {
  13531. m_xml.scopedElement( "Info" )
  13532. .writeText( msg.message );
  13533. } else if ( msg.type == ResultWas::Warning ) {
  13534. m_xml.scopedElement( "Warning" )
  13535. .writeText( msg.message );
  13536. }
  13537. }
  13538. }
  13539. // Drop out if result was successful but we're not printing them.
  13540. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13541. return true;
  13542. // Print the expression if there is one.
  13543. if( result.hasExpression() ) {
  13544. m_xml.startElement( "Expression" )
  13545. .writeAttribute( "success", result.succeeded() )
  13546. .writeAttribute( "type", result.getTestMacroName() );
  13547. writeSourceInfo( result.getSourceInfo() );
  13548. m_xml.scopedElement( "Original" )
  13549. .writeText( result.getExpression() );
  13550. m_xml.scopedElement( "Expanded" )
  13551. .writeText( result.getExpandedExpression() );
  13552. }
  13553. // And... Print a result applicable to each result type.
  13554. switch( result.getResultType() ) {
  13555. case ResultWas::ThrewException:
  13556. m_xml.startElement( "Exception" );
  13557. writeSourceInfo( result.getSourceInfo() );
  13558. m_xml.writeText( result.getMessage() );
  13559. m_xml.endElement();
  13560. break;
  13561. case ResultWas::FatalErrorCondition:
  13562. m_xml.startElement( "FatalErrorCondition" );
  13563. writeSourceInfo( result.getSourceInfo() );
  13564. m_xml.writeText( result.getMessage() );
  13565. m_xml.endElement();
  13566. break;
  13567. case ResultWas::Info:
  13568. m_xml.scopedElement( "Info" )
  13569. .writeText( result.getMessage() );
  13570. break;
  13571. case ResultWas::Warning:
  13572. // Warning will already have been written
  13573. break;
  13574. case ResultWas::ExplicitFailure:
  13575. m_xml.startElement( "Failure" );
  13576. writeSourceInfo( result.getSourceInfo() );
  13577. m_xml.writeText( result.getMessage() );
  13578. m_xml.endElement();
  13579. break;
  13580. default:
  13581. break;
  13582. }
  13583. if( result.hasExpression() )
  13584. m_xml.endElement();
  13585. return true;
  13586. }
  13587. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  13588. StreamingReporterBase::sectionEnded( sectionStats );
  13589. if( --m_sectionDepth > 0 ) {
  13590. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  13591. e.writeAttribute( "successes", sectionStats.assertions.passed );
  13592. e.writeAttribute( "failures", sectionStats.assertions.failed );
  13593. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  13594. if ( m_config->showDurations() == ShowDurations::Always )
  13595. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  13596. m_xml.endElement();
  13597. }
  13598. }
  13599. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13600. StreamingReporterBase::testCaseEnded( testCaseStats );
  13601. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  13602. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  13603. if ( m_config->showDurations() == ShowDurations::Always )
  13604. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  13605. if( !testCaseStats.stdOut.empty() )
  13606. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  13607. if( !testCaseStats.stdErr.empty() )
  13608. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  13609. m_xml.endElement();
  13610. }
  13611. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13612. StreamingReporterBase::testGroupEnded( testGroupStats );
  13613. // TODO: Check testGroupStats.aborting and act accordingly.
  13614. m_xml.scopedElement( "OverallResults" )
  13615. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  13616. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  13617. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  13618. m_xml.endElement();
  13619. }
  13620. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13621. StreamingReporterBase::testRunEnded( testRunStats );
  13622. m_xml.scopedElement( "OverallResults" )
  13623. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  13624. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  13625. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  13626. m_xml.endElement();
  13627. }
  13628. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13629. void XmlReporter::benchmarkPreparing(std::string const& name) {
  13630. m_xml.startElement("BenchmarkResults")
  13631. .writeAttribute("name", name);
  13632. }
  13633. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  13634. m_xml.writeAttribute("samples", info.samples)
  13635. .writeAttribute("resamples", info.resamples)
  13636. .writeAttribute("iterations", info.iterations)
  13637. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  13638. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  13639. .writeComment("All values in nano seconds");
  13640. }
  13641. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  13642. m_xml.startElement("mean")
  13643. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  13644. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  13645. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  13646. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  13647. m_xml.endElement();
  13648. m_xml.startElement("standardDeviation")
  13649. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  13650. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  13651. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  13652. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  13653. m_xml.endElement();
  13654. m_xml.startElement("outliers")
  13655. .writeAttribute("variance", benchmarkStats.outlierVariance)
  13656. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  13657. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  13658. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  13659. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  13660. m_xml.endElement();
  13661. m_xml.endElement();
  13662. }
  13663. void XmlReporter::benchmarkFailed(std::string const &error) {
  13664. m_xml.scopedElement("failed").
  13665. writeAttribute("message", error);
  13666. m_xml.endElement();
  13667. }
  13668. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13669. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  13670. } // end namespace Catch
  13671. #if defined(_MSC_VER)
  13672. #pragma warning(pop)
  13673. #endif
  13674. // end catch_reporter_xml.cpp
  13675. namespace Catch {
  13676. LeakDetector leakDetector;
  13677. }
  13678. #ifdef __clang__
  13679. #pragma clang diagnostic pop
  13680. #endif
  13681. // end catch_impl.hpp
  13682. #endif
  13683. #ifdef CATCH_CONFIG_MAIN
  13684. // start catch_default_main.hpp
  13685. #ifndef __OBJC__
  13686. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  13687. // Standard C/C++ Win32 Unicode wmain entry point
  13688. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  13689. #else
  13690. // Standard C/C++ main entry point
  13691. int main (int argc, char * argv[]) {
  13692. #endif
  13693. return Catch::Session().run( argc, argv );
  13694. }
  13695. #else // __OBJC__
  13696. // Objective-C entry point
  13697. int main (int argc, char * const argv[]) {
  13698. #if !CATCH_ARC_ENABLED
  13699. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  13700. #endif
  13701. Catch::registerTestMethods();
  13702. int result = Catch::Session().run( argc, (char**)argv );
  13703. #if !CATCH_ARC_ENABLED
  13704. [pool drain];
  13705. #endif
  13706. return result;
  13707. }
  13708. #endif // __OBJC__
  13709. // end catch_default_main.hpp
  13710. #endif
  13711. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  13712. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  13713. # undef CLARA_CONFIG_MAIN
  13714. #endif
  13715. #if !defined(CATCH_CONFIG_DISABLE)
  13716. //////
  13717. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13718. #ifdef CATCH_CONFIG_PREFIX_ALL
  13719. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13720. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13721. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13722. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13723. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13724. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13725. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13726. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13727. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13728. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13729. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13730. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13731. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13732. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13733. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13734. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13735. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13736. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13737. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13738. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13739. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13740. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13741. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13742. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13743. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13744. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  13745. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  13746. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13747. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  13748. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13749. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13750. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13751. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13752. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13753. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13754. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13755. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13756. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13757. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13758. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13759. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13760. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13761. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13762. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13763. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13764. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13765. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13766. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13767. #else
  13768. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13769. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13770. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13771. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13772. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13773. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13774. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13775. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13776. #endif
  13777. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13778. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  13779. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  13780. #else
  13781. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  13782. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  13783. #endif
  13784. // "BDD-style" convenience wrappers
  13785. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  13786. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13787. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13788. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13789. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13790. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13791. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13792. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13793. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13794. #define CATCH_BENCHMARK(...) \
  13795. 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__,,))
  13796. #define CATCH_BENCHMARK_ADVANCED(name) \
  13797. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13798. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13799. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13800. #else
  13801. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13802. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13803. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13804. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13805. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13806. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13807. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13808. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13809. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13810. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13811. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13812. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13813. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13814. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13815. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13816. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13817. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13818. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13819. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13820. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13821. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13822. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13823. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13824. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13825. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13826. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  13827. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  13828. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13829. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  13830. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13831. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13832. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13833. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13834. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13835. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13836. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13837. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13838. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13839. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13840. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13841. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13842. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13843. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13844. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13845. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13846. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13847. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13848. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13849. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  13850. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13851. #else
  13852. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13853. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13854. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13855. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13856. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13857. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13858. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13859. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13860. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  13861. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13862. #endif
  13863. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13864. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  13865. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  13866. #else
  13867. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  13868. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  13869. #endif
  13870. #endif
  13871. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  13872. // "BDD-style" convenience wrappers
  13873. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  13874. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13875. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13876. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13877. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13878. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13879. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13880. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13881. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13882. #define BENCHMARK(...) \
  13883. 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__,,))
  13884. #define BENCHMARK_ADVANCED(name) \
  13885. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13886. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13887. using Catch::Detail::Approx;
  13888. #else // CATCH_CONFIG_DISABLE
  13889. //////
  13890. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13891. #ifdef CATCH_CONFIG_PREFIX_ALL
  13892. #define CATCH_REQUIRE( ... ) (void)(0)
  13893. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  13894. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  13895. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13896. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13897. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13898. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13899. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13900. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  13901. #define CATCH_CHECK( ... ) (void)(0)
  13902. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  13903. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  13904. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13905. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  13906. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  13907. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13908. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13909. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13910. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13911. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13912. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  13913. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13914. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  13915. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  13916. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13917. #define CATCH_INFO( msg ) (void)(0)
  13918. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  13919. #define CATCH_WARN( msg ) (void)(0)
  13920. #define CATCH_CAPTURE( msg ) (void)(0)
  13921. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13922. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13923. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  13924. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13925. #define CATCH_SECTION( ... )
  13926. #define CATCH_DYNAMIC_SECTION( ... )
  13927. #define CATCH_FAIL( ... ) (void)(0)
  13928. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  13929. #define CATCH_SUCCEED( ... ) (void)(0)
  13930. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13931. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13932. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13933. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13934. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13935. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13936. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13937. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13938. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13939. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13940. #else
  13941. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13942. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13943. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13944. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13945. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13946. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13947. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13948. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13949. #endif
  13950. // "BDD-style" convenience wrappers
  13951. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13952. #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 )
  13953. #define CATCH_GIVEN( desc )
  13954. #define CATCH_AND_GIVEN( desc )
  13955. #define CATCH_WHEN( desc )
  13956. #define CATCH_AND_WHEN( desc )
  13957. #define CATCH_THEN( desc )
  13958. #define CATCH_AND_THEN( desc )
  13959. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  13960. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13961. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13962. #else
  13963. #define REQUIRE( ... ) (void)(0)
  13964. #define REQUIRE_FALSE( ... ) (void)(0)
  13965. #define REQUIRE_THROWS( ... ) (void)(0)
  13966. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13967. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13968. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13969. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13970. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13971. #define REQUIRE_NOTHROW( ... ) (void)(0)
  13972. #define CHECK( ... ) (void)(0)
  13973. #define CHECK_FALSE( ... ) (void)(0)
  13974. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  13975. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13976. #define CHECK_NOFAIL( ... ) (void)(0)
  13977. #define CHECK_THROWS( ... ) (void)(0)
  13978. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13979. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13980. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13981. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13982. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13983. #define CHECK_NOTHROW( ... ) (void)(0)
  13984. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13985. #define CHECK_THAT( arg, matcher ) (void)(0)
  13986. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  13987. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13988. #define INFO( msg ) (void)(0)
  13989. #define UNSCOPED_INFO( msg ) (void)(0)
  13990. #define WARN( msg ) (void)(0)
  13991. #define CAPTURE( msg ) (void)(0)
  13992. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13993. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13994. #define METHOD_AS_TEST_CASE( method, ... )
  13995. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13996. #define SECTION( ... )
  13997. #define DYNAMIC_SECTION( ... )
  13998. #define FAIL( ... ) (void)(0)
  13999. #define FAIL_CHECK( ... ) (void)(0)
  14000. #define SUCCEED( ... ) (void)(0)
  14001. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  14002. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14003. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14004. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14005. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14006. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14007. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14008. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14009. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14010. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14011. #else
  14012. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14013. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14014. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14015. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14016. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14017. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14018. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14019. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14020. #endif
  14021. #define STATIC_REQUIRE( ... ) (void)(0)
  14022. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14023. #endif
  14024. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14025. // "BDD-style" convenience wrappers
  14026. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  14027. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  14028. #define GIVEN( desc )
  14029. #define AND_GIVEN( desc )
  14030. #define WHEN( desc )
  14031. #define AND_WHEN( desc )
  14032. #define THEN( desc )
  14033. #define AND_THEN( desc )
  14034. using Catch::Detail::Approx;
  14035. #endif
  14036. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14037. // start catch_reenable_warnings.h
  14038. #ifdef __clang__
  14039. # ifdef __ICC // icpc defines the __clang__ macro
  14040. # pragma warning(pop)
  14041. # else
  14042. # pragma clang diagnostic pop
  14043. # endif
  14044. #elif defined __GNUC__
  14045. # pragma GCC diagnostic pop
  14046. #endif
  14047. // end catch_reenable_warnings.h
  14048. // end catch.hpp
  14049. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED