La simu multi-agents qui repeint une image, mais en c++ Boilerplate pompé ici : https://github.com/andrew-r-king/sfml-vscode-boilerplate
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865
  1. /*
  2. * Catch v2.9.1
  3. * Generated: 2019-06-17 11:59:24.363643
  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 1
  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. // Check if string_view is available and usable
  228. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  229. #if defined(__has_include)
  230. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  231. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  232. #endif
  233. #endif
  234. ////////////////////////////////////////////////////////////////////////////////
  235. // Check if optional is available and usable
  236. #if defined(__has_include)
  237. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  238. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  239. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  240. #endif // __has_include
  241. ////////////////////////////////////////////////////////////////////////////////
  242. // Check if variant is available and usable
  243. #if defined(__has_include)
  244. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  245. # if defined(__clang__) && (__clang_major__ < 8)
  246. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  247. // fix should be in clang 8, workaround in libstdc++ 8.2
  248. # include <ciso646>
  249. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  250. # define CATCH_CONFIG_NO_CPP17_VARIANT
  251. # else
  252. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  253. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  254. # else
  255. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  256. # endif // defined(__clang__) && (__clang_major__ < 8)
  257. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  258. #endif // __has_include
  259. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  260. # define CATCH_CONFIG_COUNTER
  261. #endif
  262. #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)
  263. # define CATCH_CONFIG_WINDOWS_SEH
  264. #endif
  265. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  266. #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)
  267. # define CATCH_CONFIG_POSIX_SIGNALS
  268. #endif
  269. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  270. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  271. # define CATCH_CONFIG_WCHAR
  272. #endif
  273. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  274. # define CATCH_CONFIG_CPP11_TO_STRING
  275. #endif
  276. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  277. # define CATCH_CONFIG_CPP17_OPTIONAL
  278. #endif
  279. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  280. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  281. #endif
  282. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  283. # define CATCH_CONFIG_CPP17_STRING_VIEW
  284. #endif
  285. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  286. # define CATCH_CONFIG_CPP17_VARIANT
  287. #endif
  288. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  289. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  290. #endif
  291. #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)
  292. # define CATCH_CONFIG_NEW_CAPTURE
  293. #endif
  294. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  295. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  296. #endif
  297. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  298. # define CATCH_CONFIG_POLYFILL_ISNAN
  299. #endif
  300. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  301. # define CATCH_CONFIG_USE_ASYNC
  302. #endif
  303. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  304. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  305. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  306. #endif
  307. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  308. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  309. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  310. #endif
  311. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  312. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  313. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  314. #endif
  315. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  316. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  317. # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
  318. #endif
  319. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  320. #define CATCH_TRY if ((true))
  321. #define CATCH_CATCH_ALL if ((false))
  322. #define CATCH_CATCH_ANON(type) if ((false))
  323. #else
  324. #define CATCH_TRY try
  325. #define CATCH_CATCH_ALL catch (...)
  326. #define CATCH_CATCH_ANON(type) catch (type)
  327. #endif
  328. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  329. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  330. #endif
  331. // end catch_compiler_capabilities.h
  332. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  333. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  334. #ifdef CATCH_CONFIG_COUNTER
  335. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  336. #else
  337. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  338. #endif
  339. #include <iosfwd>
  340. #include <string>
  341. #include <cstdint>
  342. // We need a dummy global operator<< so we can bring it into Catch namespace later
  343. struct Catch_global_namespace_dummy {};
  344. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  345. namespace Catch {
  346. struct CaseSensitive { enum Choice {
  347. Yes,
  348. No
  349. }; };
  350. class NonCopyable {
  351. NonCopyable( NonCopyable const& ) = delete;
  352. NonCopyable( NonCopyable && ) = delete;
  353. NonCopyable& operator = ( NonCopyable const& ) = delete;
  354. NonCopyable& operator = ( NonCopyable && ) = delete;
  355. protected:
  356. NonCopyable();
  357. virtual ~NonCopyable();
  358. };
  359. struct SourceLineInfo {
  360. SourceLineInfo() = delete;
  361. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  362. : file( _file ),
  363. line( _line )
  364. {}
  365. SourceLineInfo( SourceLineInfo const& other ) = default;
  366. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  367. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  368. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  369. bool empty() const noexcept;
  370. bool operator == ( SourceLineInfo const& other ) const noexcept;
  371. bool operator < ( SourceLineInfo const& other ) const noexcept;
  372. char const* file;
  373. std::size_t line;
  374. };
  375. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  376. // Bring in operator<< from global namespace into Catch namespace
  377. // This is necessary because the overload of operator<< above makes
  378. // lookup stop at namespace Catch
  379. using ::operator<<;
  380. // Use this in variadic streaming macros to allow
  381. // >> +StreamEndStop
  382. // as well as
  383. // >> stuff +StreamEndStop
  384. struct StreamEndStop {
  385. std::string operator+() const;
  386. };
  387. template<typename T>
  388. T const& operator + ( T const& value, StreamEndStop ) {
  389. return value;
  390. }
  391. }
  392. #define CATCH_INTERNAL_LINEINFO \
  393. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  394. // end catch_common.h
  395. namespace Catch {
  396. struct RegistrarForTagAliases {
  397. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  398. };
  399. } // end namespace Catch
  400. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  401. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  402. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  403. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  404. // end catch_tag_alias_autoregistrar.h
  405. // start catch_test_registry.h
  406. // start catch_interfaces_testcase.h
  407. #include <vector>
  408. namespace Catch {
  409. class TestSpec;
  410. struct ITestInvoker {
  411. virtual void invoke () const = 0;
  412. virtual ~ITestInvoker();
  413. };
  414. class TestCase;
  415. struct IConfig;
  416. struct ITestCaseRegistry {
  417. virtual ~ITestCaseRegistry();
  418. virtual std::vector<TestCase> const& getAllTests() const = 0;
  419. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  420. };
  421. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  422. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  423. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  424. }
  425. // end catch_interfaces_testcase.h
  426. // start catch_stringref.h
  427. #include <cstddef>
  428. #include <string>
  429. #include <iosfwd>
  430. namespace Catch {
  431. /// A non-owning string class (similar to the forthcoming std::string_view)
  432. /// Note that, because a StringRef may be a substring of another string,
  433. /// it may not be null terminated. c_str() must return a null terminated
  434. /// string, however, and so the StringRef will internally take ownership
  435. /// (taking a copy), if necessary. In theory this ownership is not externally
  436. /// visible - but it does mean (substring) StringRefs should not be shared between
  437. /// threads.
  438. class StringRef {
  439. public:
  440. using size_type = std::size_t;
  441. private:
  442. friend struct StringRefTestAccess;
  443. char const* m_start;
  444. size_type m_size;
  445. char* m_data = nullptr;
  446. void takeOwnership();
  447. static constexpr char const* const s_empty = "";
  448. public: // construction/ assignment
  449. StringRef() noexcept
  450. : StringRef( s_empty, 0 )
  451. {}
  452. StringRef( StringRef const& other ) noexcept
  453. : m_start( other.m_start ),
  454. m_size( other.m_size )
  455. {}
  456. StringRef( StringRef&& other ) noexcept
  457. : m_start( other.m_start ),
  458. m_size( other.m_size ),
  459. m_data( other.m_data )
  460. {
  461. other.m_data = nullptr;
  462. }
  463. StringRef( char const* rawChars ) noexcept;
  464. StringRef( char const* rawChars, size_type size ) noexcept
  465. : m_start( rawChars ),
  466. m_size( size )
  467. {}
  468. StringRef( std::string const& stdString ) noexcept
  469. : m_start( stdString.c_str() ),
  470. m_size( stdString.size() )
  471. {}
  472. ~StringRef() noexcept {
  473. delete[] m_data;
  474. }
  475. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  476. delete[] m_data;
  477. m_data = nullptr;
  478. m_start = other.m_start;
  479. m_size = other.m_size;
  480. return *this;
  481. }
  482. operator std::string() const;
  483. void swap( StringRef& other ) noexcept;
  484. public: // operators
  485. auto operator == ( StringRef const& other ) const noexcept -> bool;
  486. auto operator != ( StringRef const& other ) const noexcept -> bool;
  487. auto operator[] ( size_type index ) const noexcept -> char;
  488. public: // named queries
  489. auto empty() const noexcept -> bool {
  490. return m_size == 0;
  491. }
  492. auto size() const noexcept -> size_type {
  493. return m_size;
  494. }
  495. auto numberOfCharacters() const noexcept -> size_type;
  496. auto c_str() const -> char const*;
  497. public: // substrings and searches
  498. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  499. // Returns the current start pointer.
  500. // Note that the pointer can change when if the StringRef is a substring
  501. auto currentData() const noexcept -> char const*;
  502. private: // ownership queries - may not be consistent between calls
  503. auto isOwned() const noexcept -> bool;
  504. auto isSubstring() const noexcept -> bool;
  505. };
  506. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  507. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  508. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  509. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  510. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  511. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  512. return StringRef( rawChars, size );
  513. }
  514. } // namespace Catch
  515. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  516. return Catch::StringRef( rawChars, size );
  517. }
  518. // end catch_stringref.h
  519. // start catch_type_traits.hpp
  520. #include <type_traits>
  521. namespace Catch{
  522. #ifdef CATCH_CPP17_OR_GREATER
  523. template <typename...>
  524. inline constexpr auto is_unique = std::true_type{};
  525. template <typename T, typename... Rest>
  526. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  527. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  528. >{};
  529. #else
  530. template <typename...>
  531. struct is_unique : std::true_type{};
  532. template <typename T0, typename T1, typename... Rest>
  533. struct is_unique<T0, T1, Rest...> : std::integral_constant
  534. <bool,
  535. !std::is_same<T0, T1>::value
  536. && is_unique<T0, Rest...>::value
  537. && is_unique<T1, Rest...>::value
  538. >{};
  539. #endif
  540. }
  541. // end catch_type_traits.hpp
  542. // start catch_preprocessor.hpp
  543. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  544. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  545. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  546. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  547. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  548. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  549. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  550. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  551. // MSVC needs more evaluations
  552. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  553. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  554. #else
  555. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  556. #endif
  557. #define CATCH_REC_END(...)
  558. #define CATCH_REC_OUT
  559. #define CATCH_EMPTY()
  560. #define CATCH_DEFER(id) id CATCH_EMPTY()
  561. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  562. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  563. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  564. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  565. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  566. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  567. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  568. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  569. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  570. #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__ )
  571. #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__ )
  572. #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__ )
  573. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  574. // and passes userdata as the first parameter to each invocation,
  575. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  576. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  577. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  578. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  579. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  580. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  581. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  582. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  583. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  584. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  585. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  586. #else
  587. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  588. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  589. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  590. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  591. #endif
  592. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  593. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  594. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  595. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  596. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  597. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  598. #else
  599. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  600. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  601. #endif
  602. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  603. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  604. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  605. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  606. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  607. #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)
  608. #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)
  609. #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)
  610. #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)
  611. #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)
  612. #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)
  613. #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)
  614. #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)
  615. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  616. #define INTERNAL_CATCH_TYPE_GEN\
  617. template<typename...> struct TypeList {};\
  618. template<typename...Ts>\
  619. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  620. \
  621. template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
  622. constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
  623. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  624. constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
  625. template< template<typename...> class L1, typename...E1, typename...Rest>\
  626. constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
  627. \
  628. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  629. constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
  630. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  631. constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
  632. \
  633. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  634. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
  635. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  636. constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
  637. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  638. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  639. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  640. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  641. \
  642. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  643. constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
  644. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  645. constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
  646. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  647. constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
  648. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  649. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  650. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  651. static void TestName()
  652. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  653. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  654. static void TestName()
  655. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  656. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  657. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  658. static void TestName()
  659. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  660. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  661. static void TestName()
  662. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  663. template<typename Type>\
  664. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  665. {\
  666. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  667. }
  668. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  669. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  670. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  671. {\
  672. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  673. }
  674. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  675. template<typename Type>\
  676. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  677. {\
  678. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  679. }
  680. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  681. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  682. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  683. {\
  684. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  685. }
  686. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  687. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  688. template<typename TestType> \
  689. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  690. void test();\
  691. }
  692. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  693. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  694. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  695. void test();\
  696. }
  697. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  698. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  699. template<typename TestType> \
  700. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  701. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  702. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  703. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  704. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  705. #define INTERNAL_CATCH_NTTP_0
  706. #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)
  707. #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__)
  708. #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__)
  709. #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__)
  710. #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__)
  711. #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__)
  712. #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__)
  713. #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__)
  714. #else
  715. #define INTERNAL_CATCH_NTTP_0(signature)
  716. #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__))
  717. #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__))
  718. #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__))
  719. #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__))
  720. #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__))
  721. #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__))
  722. #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__))
  723. #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__))
  724. #endif
  725. // end catch_preprocessor.hpp
  726. // start catch_meta.hpp
  727. #include <type_traits>
  728. namespace Catch {
  729. template<typename T>
  730. struct always_false : std::false_type {};
  731. template <typename> struct true_given : std::true_type {};
  732. struct is_callable_tester {
  733. template <typename Fun, typename... Args>
  734. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  735. template <typename...>
  736. std::false_type static test(...);
  737. };
  738. template <typename T>
  739. struct is_callable;
  740. template <typename Fun, typename... Args>
  741. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  742. } // namespace Catch
  743. namespace mpl_{
  744. struct na;
  745. }
  746. // end catch_meta.hpp
  747. namespace Catch {
  748. template<typename C>
  749. class TestInvokerAsMethod : public ITestInvoker {
  750. void (C::*m_testAsMethod)();
  751. public:
  752. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  753. void invoke() const override {
  754. C obj;
  755. (obj.*m_testAsMethod)();
  756. }
  757. };
  758. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  759. template<typename C>
  760. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  761. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  762. }
  763. struct NameAndTags {
  764. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  765. StringRef name;
  766. StringRef tags;
  767. };
  768. struct AutoReg : NonCopyable {
  769. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  770. ~AutoReg();
  771. };
  772. } // end namespace Catch
  773. #if defined(CATCH_CONFIG_DISABLE)
  774. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  775. static void TestName()
  776. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  777. namespace{ \
  778. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  779. void test(); \
  780. }; \
  781. } \
  782. void TestName::test()
  783. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  784. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  785. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  786. namespace{ \
  787. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  788. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  789. } \
  790. } \
  791. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  792. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  793. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  794. 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__ )
  795. #else
  796. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  797. 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__ ) )
  798. #endif
  799. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  800. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  801. 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__ )
  802. #else
  803. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  804. 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__ ) )
  805. #endif
  806. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  807. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  808. 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__ )
  809. #else
  810. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  811. 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__ ) )
  812. #endif
  813. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  814. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  815. 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__ )
  816. #else
  817. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  818. 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__ ) )
  819. #endif
  820. #endif
  821. ///////////////////////////////////////////////////////////////////////////////
  822. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  823. static void TestName(); \
  824. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  825. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  826. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  827. static void TestName()
  828. #define INTERNAL_CATCH_TESTCASE( ... ) \
  829. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  830. ///////////////////////////////////////////////////////////////////////////////
  831. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  832. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  833. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  834. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  835. ///////////////////////////////////////////////////////////////////////////////
  836. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  837. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  838. namespace{ \
  839. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  840. void test(); \
  841. }; \
  842. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  843. } \
  844. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  845. void TestName::test()
  846. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  847. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  848. ///////////////////////////////////////////////////////////////////////////////
  849. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  850. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  851. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  852. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  853. ///////////////////////////////////////////////////////////////////////////////
  854. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  855. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  856. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  857. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  858. namespace {\
  859. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  860. INTERNAL_CATCH_TYPE_GEN\
  861. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  862. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  863. template<typename...Types> \
  864. struct TestName{\
  865. TestName(){\
  866. int index = 0; \
  867. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  868. using expander = int[];\
  869. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  870. }\
  871. };\
  872. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  873. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  874. return 0;\
  875. }();\
  876. }\
  877. }\
  878. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  879. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  880. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  881. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  882. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  883. 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__ )
  884. #else
  885. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  886. 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__ ) )
  887. #endif
  888. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  889. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  890. 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__ )
  891. #else
  892. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  893. 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__ ) )
  894. #endif
  895. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  896. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  897. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  898. template<typename TestType> static void TestFuncName(); \
  899. namespace {\
  900. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  901. INTERNAL_CATCH_TYPE_GEN \
  902. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  903. template<typename... Types> \
  904. struct TestName { \
  905. void reg_tests() { \
  906. int index = 0; \
  907. using expander = int[]; \
  908. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  909. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  910. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  911. (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 */\
  912. } \
  913. }; \
  914. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  915. using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
  916. TestInit t; \
  917. t.reg_tests(); \
  918. return 0; \
  919. }(); \
  920. } \
  921. } \
  922. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  923. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  924. template<typename TestType> \
  925. static void TestFuncName()
  926. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  927. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  928. 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__)
  929. #else
  930. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  931. 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__ ) )
  932. #endif
  933. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  934. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  935. 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__)
  936. #else
  937. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  938. 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__ ) )
  939. #endif
  940. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  941. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  942. template<typename TestType> static void TestFunc(); \
  943. namespace {\
  944. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  945. INTERNAL_CATCH_TYPE_GEN\
  946. template<typename... Types> \
  947. struct TestName { \
  948. void reg_tests() { \
  949. int index = 0; \
  950. using expander = int[]; \
  951. (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 */\
  952. } \
  953. };\
  954. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  955. using TestInit = decltype(convert<TestName>(TmplList {})); \
  956. TestInit t; \
  957. t.reg_tests(); \
  958. return 0; \
  959. }(); \
  960. }}\
  961. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  962. template<typename TestType> \
  963. static void TestFunc()
  964. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  965. 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 )
  966. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  967. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  968. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  969. namespace {\
  970. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  971. INTERNAL_CATCH_TYPE_GEN\
  972. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  973. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  974. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  975. template<typename...Types> \
  976. struct TestNameClass{\
  977. TestNameClass(){\
  978. int index = 0; \
  979. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  980. using expander = int[];\
  981. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
  982. }\
  983. };\
  984. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  985. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  986. return 0;\
  987. }();\
  988. }\
  989. }\
  990. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  991. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
  992. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  993. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  994. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  995. 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__ )
  996. #else
  997. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  998. 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__ ) )
  999. #endif
  1000. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1001. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1002. 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__ )
  1003. #else
  1004. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1005. 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__ ) )
  1006. #endif
  1007. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1008. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1009. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1010. template<typename TestType> \
  1011. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1012. void test();\
  1013. };\
  1014. namespace {\
  1015. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1016. INTERNAL_CATCH_TYPE_GEN \
  1017. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1018. template<typename...Types>\
  1019. struct TestNameClass{\
  1020. void reg_tests(){\
  1021. int index = 0;\
  1022. using expander = int[];\
  1023. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1024. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1025. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1026. (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 */ \
  1027. }\
  1028. };\
  1029. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1030. using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
  1031. TestInit t;\
  1032. t.reg_tests();\
  1033. return 0;\
  1034. }(); \
  1035. }\
  1036. }\
  1037. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1038. CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
  1039. template<typename TestType> \
  1040. void TestName<TestType>::test()
  1041. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1042. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1043. 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__ )
  1044. #else
  1045. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1046. 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__ ) )
  1047. #endif
  1048. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1049. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1050. 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__ )
  1051. #else
  1052. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1053. 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__ ) )
  1054. #endif
  1055. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1056. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1057. template<typename TestType> \
  1058. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1059. void test();\
  1060. };\
  1061. namespace {\
  1062. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1063. INTERNAL_CATCH_TYPE_GEN\
  1064. template<typename...Types>\
  1065. struct TestNameClass{\
  1066. void reg_tests(){\
  1067. int index = 0;\
  1068. using expander = int[];\
  1069. (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 */ \
  1070. }\
  1071. };\
  1072. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1073. using TestInit = decltype(convert<TestNameClass>(TmplList {}));\
  1074. TestInit t;\
  1075. t.reg_tests();\
  1076. return 0;\
  1077. }(); \
  1078. }}\
  1079. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1080. template<typename TestType> \
  1081. void TestName<TestType>::test()
  1082. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1083. 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 )
  1084. // end catch_test_registry.h
  1085. // start catch_capture.hpp
  1086. // start catch_assertionhandler.h
  1087. // start catch_assertioninfo.h
  1088. // start catch_result_type.h
  1089. namespace Catch {
  1090. // ResultWas::OfType enum
  1091. struct ResultWas { enum OfType {
  1092. Unknown = -1,
  1093. Ok = 0,
  1094. Info = 1,
  1095. Warning = 2,
  1096. FailureBit = 0x10,
  1097. ExpressionFailed = FailureBit | 1,
  1098. ExplicitFailure = FailureBit | 2,
  1099. Exception = 0x100 | FailureBit,
  1100. ThrewException = Exception | 1,
  1101. DidntThrowException = Exception | 2,
  1102. FatalErrorCondition = 0x200 | FailureBit
  1103. }; };
  1104. bool isOk( ResultWas::OfType resultType );
  1105. bool isJustInfo( int flags );
  1106. // ResultDisposition::Flags enum
  1107. struct ResultDisposition { enum Flags {
  1108. Normal = 0x01,
  1109. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1110. FalseTest = 0x04, // Prefix expression with !
  1111. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1112. }; };
  1113. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1114. bool shouldContinueOnFailure( int flags );
  1115. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1116. bool shouldSuppressFailure( int flags );
  1117. } // end namespace Catch
  1118. // end catch_result_type.h
  1119. namespace Catch {
  1120. struct AssertionInfo
  1121. {
  1122. StringRef macroName;
  1123. SourceLineInfo lineInfo;
  1124. StringRef capturedExpression;
  1125. ResultDisposition::Flags resultDisposition;
  1126. // We want to delete this constructor but a compiler bug in 4.8 means
  1127. // the struct is then treated as non-aggregate
  1128. //AssertionInfo() = delete;
  1129. };
  1130. } // end namespace Catch
  1131. // end catch_assertioninfo.h
  1132. // start catch_decomposer.h
  1133. // start catch_tostring.h
  1134. #include <vector>
  1135. #include <cstddef>
  1136. #include <type_traits>
  1137. #include <string>
  1138. // start catch_stream.h
  1139. #include <iosfwd>
  1140. #include <cstddef>
  1141. #include <ostream>
  1142. namespace Catch {
  1143. std::ostream& cout();
  1144. std::ostream& cerr();
  1145. std::ostream& clog();
  1146. class StringRef;
  1147. struct IStream {
  1148. virtual ~IStream();
  1149. virtual std::ostream& stream() const = 0;
  1150. };
  1151. auto makeStream( StringRef const &filename ) -> IStream const*;
  1152. class ReusableStringStream {
  1153. std::size_t m_index;
  1154. std::ostream* m_oss;
  1155. public:
  1156. ReusableStringStream();
  1157. ~ReusableStringStream();
  1158. auto str() const -> std::string;
  1159. template<typename T>
  1160. auto operator << ( T const& value ) -> ReusableStringStream& {
  1161. *m_oss << value;
  1162. return *this;
  1163. }
  1164. auto get() -> std::ostream& { return *m_oss; }
  1165. };
  1166. }
  1167. // end catch_stream.h
  1168. // start catch_interfaces_enum_values_registry.h
  1169. #include <vector>
  1170. namespace Catch {
  1171. namespace Detail {
  1172. struct EnumInfo {
  1173. StringRef m_name;
  1174. std::vector<std::pair<int, std::string>> m_values;
  1175. ~EnumInfo();
  1176. StringRef lookup( int value ) const;
  1177. };
  1178. } // namespace Detail
  1179. struct IMutableEnumValuesRegistry {
  1180. virtual ~IMutableEnumValuesRegistry();
  1181. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1182. template<typename E>
  1183. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1184. std::vector<int> intValues;
  1185. intValues.reserve( values.size() );
  1186. for( auto enumValue : values )
  1187. intValues.push_back( static_cast<int>( enumValue ) );
  1188. return registerEnum( enumName, allEnums, intValues );
  1189. }
  1190. };
  1191. } // Catch
  1192. // end catch_interfaces_enum_values_registry.h
  1193. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1194. #include <string_view>
  1195. #endif
  1196. #ifdef __OBJC__
  1197. // start catch_objc_arc.hpp
  1198. #import <Foundation/Foundation.h>
  1199. #ifdef __has_feature
  1200. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1201. #else
  1202. #define CATCH_ARC_ENABLED 0
  1203. #endif
  1204. void arcSafeRelease( NSObject* obj );
  1205. id performOptionalSelector( id obj, SEL sel );
  1206. #if !CATCH_ARC_ENABLED
  1207. inline void arcSafeRelease( NSObject* obj ) {
  1208. [obj release];
  1209. }
  1210. inline id performOptionalSelector( id obj, SEL sel ) {
  1211. if( [obj respondsToSelector: sel] )
  1212. return [obj performSelector: sel];
  1213. return nil;
  1214. }
  1215. #define CATCH_UNSAFE_UNRETAINED
  1216. #define CATCH_ARC_STRONG
  1217. #else
  1218. inline void arcSafeRelease( NSObject* ){}
  1219. inline id performOptionalSelector( id obj, SEL sel ) {
  1220. #ifdef __clang__
  1221. #pragma clang diagnostic push
  1222. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1223. #endif
  1224. if( [obj respondsToSelector: sel] )
  1225. return [obj performSelector: sel];
  1226. #ifdef __clang__
  1227. #pragma clang diagnostic pop
  1228. #endif
  1229. return nil;
  1230. }
  1231. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1232. #define CATCH_ARC_STRONG __strong
  1233. #endif
  1234. // end catch_objc_arc.hpp
  1235. #endif
  1236. #ifdef _MSC_VER
  1237. #pragma warning(push)
  1238. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1239. #endif
  1240. namespace Catch {
  1241. namespace Detail {
  1242. extern const std::string unprintableString;
  1243. std::string rawMemoryToString( const void *object, std::size_t size );
  1244. template<typename T>
  1245. std::string rawMemoryToString( const T& object ) {
  1246. return rawMemoryToString( &object, sizeof(object) );
  1247. }
  1248. template<typename T>
  1249. class IsStreamInsertable {
  1250. template<typename SS, typename TT>
  1251. static auto test(int)
  1252. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  1253. template<typename, typename>
  1254. static auto test(...)->std::false_type;
  1255. public:
  1256. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1257. };
  1258. template<typename E>
  1259. std::string convertUnknownEnumToString( E e );
  1260. template<typename T>
  1261. typename std::enable_if<
  1262. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1263. std::string>::type convertUnstreamable( T const& ) {
  1264. return Detail::unprintableString;
  1265. }
  1266. template<typename T>
  1267. typename std::enable_if<
  1268. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1269. std::string>::type convertUnstreamable(T const& ex) {
  1270. return ex.what();
  1271. }
  1272. template<typename T>
  1273. typename std::enable_if<
  1274. std::is_enum<T>::value
  1275. , std::string>::type convertUnstreamable( T const& value ) {
  1276. return convertUnknownEnumToString( value );
  1277. }
  1278. #if defined(_MANAGED)
  1279. //! Convert a CLR string to a utf8 std::string
  1280. template<typename T>
  1281. std::string clrReferenceToString( T^ ref ) {
  1282. if (ref == nullptr)
  1283. return std::string("null");
  1284. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1285. cli::pin_ptr<System::Byte> p = &bytes[0];
  1286. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1287. }
  1288. #endif
  1289. } // namespace Detail
  1290. // If we decide for C++14, change these to enable_if_ts
  1291. template <typename T, typename = void>
  1292. struct StringMaker {
  1293. template <typename Fake = T>
  1294. static
  1295. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1296. convert(const Fake& value) {
  1297. ReusableStringStream rss;
  1298. // NB: call using the function-like syntax to avoid ambiguity with
  1299. // user-defined templated operator<< under clang.
  1300. rss.operator<<(value);
  1301. return rss.str();
  1302. }
  1303. template <typename Fake = T>
  1304. static
  1305. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1306. convert( const Fake& value ) {
  1307. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1308. return Detail::convertUnstreamable(value);
  1309. #else
  1310. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1311. #endif
  1312. }
  1313. };
  1314. namespace Detail {
  1315. // This function dispatches all stringification requests inside of Catch.
  1316. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1317. template <typename T>
  1318. std::string stringify(const T& e) {
  1319. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1320. }
  1321. template<typename E>
  1322. std::string convertUnknownEnumToString( E e ) {
  1323. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1324. }
  1325. #if defined(_MANAGED)
  1326. template <typename T>
  1327. std::string stringify( T^ e ) {
  1328. return ::Catch::StringMaker<T^>::convert(e);
  1329. }
  1330. #endif
  1331. } // namespace Detail
  1332. // Some predefined specializations
  1333. template<>
  1334. struct StringMaker<std::string> {
  1335. static std::string convert(const std::string& str);
  1336. };
  1337. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1338. template<>
  1339. struct StringMaker<std::string_view> {
  1340. static std::string convert(std::string_view str);
  1341. };
  1342. #endif
  1343. template<>
  1344. struct StringMaker<char const *> {
  1345. static std::string convert(char const * str);
  1346. };
  1347. template<>
  1348. struct StringMaker<char *> {
  1349. static std::string convert(char * str);
  1350. };
  1351. #ifdef CATCH_CONFIG_WCHAR
  1352. template<>
  1353. struct StringMaker<std::wstring> {
  1354. static std::string convert(const std::wstring& wstr);
  1355. };
  1356. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1357. template<>
  1358. struct StringMaker<std::wstring_view> {
  1359. static std::string convert(std::wstring_view str);
  1360. };
  1361. # endif
  1362. template<>
  1363. struct StringMaker<wchar_t const *> {
  1364. static std::string convert(wchar_t const * str);
  1365. };
  1366. template<>
  1367. struct StringMaker<wchar_t *> {
  1368. static std::string convert(wchar_t * str);
  1369. };
  1370. #endif
  1371. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1372. // while keeping string semantics?
  1373. template<int SZ>
  1374. struct StringMaker<char[SZ]> {
  1375. static std::string convert(char const* str) {
  1376. return ::Catch::Detail::stringify(std::string{ str });
  1377. }
  1378. };
  1379. template<int SZ>
  1380. struct StringMaker<signed char[SZ]> {
  1381. static std::string convert(signed char const* str) {
  1382. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1383. }
  1384. };
  1385. template<int SZ>
  1386. struct StringMaker<unsigned char[SZ]> {
  1387. static std::string convert(unsigned char const* str) {
  1388. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1389. }
  1390. };
  1391. template<>
  1392. struct StringMaker<int> {
  1393. static std::string convert(int value);
  1394. };
  1395. template<>
  1396. struct StringMaker<long> {
  1397. static std::string convert(long value);
  1398. };
  1399. template<>
  1400. struct StringMaker<long long> {
  1401. static std::string convert(long long value);
  1402. };
  1403. template<>
  1404. struct StringMaker<unsigned int> {
  1405. static std::string convert(unsigned int value);
  1406. };
  1407. template<>
  1408. struct StringMaker<unsigned long> {
  1409. static std::string convert(unsigned long value);
  1410. };
  1411. template<>
  1412. struct StringMaker<unsigned long long> {
  1413. static std::string convert(unsigned long long value);
  1414. };
  1415. template<>
  1416. struct StringMaker<bool> {
  1417. static std::string convert(bool b);
  1418. };
  1419. template<>
  1420. struct StringMaker<char> {
  1421. static std::string convert(char c);
  1422. };
  1423. template<>
  1424. struct StringMaker<signed char> {
  1425. static std::string convert(signed char c);
  1426. };
  1427. template<>
  1428. struct StringMaker<unsigned char> {
  1429. static std::string convert(unsigned char c);
  1430. };
  1431. template<>
  1432. struct StringMaker<std::nullptr_t> {
  1433. static std::string convert(std::nullptr_t);
  1434. };
  1435. template<>
  1436. struct StringMaker<float> {
  1437. static std::string convert(float value);
  1438. static int precision;
  1439. };
  1440. template<>
  1441. struct StringMaker<double> {
  1442. static std::string convert(double value);
  1443. static int precision;
  1444. };
  1445. template <typename T>
  1446. struct StringMaker<T*> {
  1447. template <typename U>
  1448. static std::string convert(U* p) {
  1449. if (p) {
  1450. return ::Catch::Detail::rawMemoryToString(p);
  1451. } else {
  1452. return "nullptr";
  1453. }
  1454. }
  1455. };
  1456. template <typename R, typename C>
  1457. struct StringMaker<R C::*> {
  1458. static std::string convert(R C::* p) {
  1459. if (p) {
  1460. return ::Catch::Detail::rawMemoryToString(p);
  1461. } else {
  1462. return "nullptr";
  1463. }
  1464. }
  1465. };
  1466. #if defined(_MANAGED)
  1467. template <typename T>
  1468. struct StringMaker<T^> {
  1469. static std::string convert( T^ ref ) {
  1470. return ::Catch::Detail::clrReferenceToString(ref);
  1471. }
  1472. };
  1473. #endif
  1474. namespace Detail {
  1475. template<typename InputIterator>
  1476. std::string rangeToString(InputIterator first, InputIterator last) {
  1477. ReusableStringStream rss;
  1478. rss << "{ ";
  1479. if (first != last) {
  1480. rss << ::Catch::Detail::stringify(*first);
  1481. for (++first; first != last; ++first)
  1482. rss << ", " << ::Catch::Detail::stringify(*first);
  1483. }
  1484. rss << " }";
  1485. return rss.str();
  1486. }
  1487. }
  1488. #ifdef __OBJC__
  1489. template<>
  1490. struct StringMaker<NSString*> {
  1491. static std::string convert(NSString * nsstring) {
  1492. if (!nsstring)
  1493. return "nil";
  1494. return std::string("@") + [nsstring UTF8String];
  1495. }
  1496. };
  1497. template<>
  1498. struct StringMaker<NSObject*> {
  1499. static std::string convert(NSObject* nsObject) {
  1500. return ::Catch::Detail::stringify([nsObject description]);
  1501. }
  1502. };
  1503. namespace Detail {
  1504. inline std::string stringify( NSString* nsstring ) {
  1505. return StringMaker<NSString*>::convert( nsstring );
  1506. }
  1507. } // namespace Detail
  1508. #endif // __OBJC__
  1509. } // namespace Catch
  1510. //////////////////////////////////////////////////////
  1511. // Separate std-lib types stringification, so it can be selectively enabled
  1512. // This means that we do not bring in
  1513. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1514. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1515. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1516. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1517. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1518. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1519. #endif
  1520. // Separate std::pair specialization
  1521. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1522. #include <utility>
  1523. namespace Catch {
  1524. template<typename T1, typename T2>
  1525. struct StringMaker<std::pair<T1, T2> > {
  1526. static std::string convert(const std::pair<T1, T2>& pair) {
  1527. ReusableStringStream rss;
  1528. rss << "{ "
  1529. << ::Catch::Detail::stringify(pair.first)
  1530. << ", "
  1531. << ::Catch::Detail::stringify(pair.second)
  1532. << " }";
  1533. return rss.str();
  1534. }
  1535. };
  1536. }
  1537. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1538. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1539. #include <optional>
  1540. namespace Catch {
  1541. template<typename T>
  1542. struct StringMaker<std::optional<T> > {
  1543. static std::string convert(const std::optional<T>& optional) {
  1544. ReusableStringStream rss;
  1545. if (optional.has_value()) {
  1546. rss << ::Catch::Detail::stringify(*optional);
  1547. } else {
  1548. rss << "{ }";
  1549. }
  1550. return rss.str();
  1551. }
  1552. };
  1553. }
  1554. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1555. // Separate std::tuple specialization
  1556. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1557. #include <tuple>
  1558. namespace Catch {
  1559. namespace Detail {
  1560. template<
  1561. typename Tuple,
  1562. std::size_t N = 0,
  1563. bool = (N < std::tuple_size<Tuple>::value)
  1564. >
  1565. struct TupleElementPrinter {
  1566. static void print(const Tuple& tuple, std::ostream& os) {
  1567. os << (N ? ", " : " ")
  1568. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1569. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1570. }
  1571. };
  1572. template<
  1573. typename Tuple,
  1574. std::size_t N
  1575. >
  1576. struct TupleElementPrinter<Tuple, N, false> {
  1577. static void print(const Tuple&, std::ostream&) {}
  1578. };
  1579. }
  1580. template<typename ...Types>
  1581. struct StringMaker<std::tuple<Types...>> {
  1582. static std::string convert(const std::tuple<Types...>& tuple) {
  1583. ReusableStringStream rss;
  1584. rss << '{';
  1585. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1586. rss << " }";
  1587. return rss.str();
  1588. }
  1589. };
  1590. }
  1591. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1592. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1593. #include <variant>
  1594. namespace Catch {
  1595. template<>
  1596. struct StringMaker<std::monostate> {
  1597. static std::string convert(const std::monostate&) {
  1598. return "{ }";
  1599. }
  1600. };
  1601. template<typename... Elements>
  1602. struct StringMaker<std::variant<Elements...>> {
  1603. static std::string convert(const std::variant<Elements...>& variant) {
  1604. if (variant.valueless_by_exception()) {
  1605. return "{valueless variant}";
  1606. } else {
  1607. return std::visit(
  1608. [](const auto& value) {
  1609. return ::Catch::Detail::stringify(value);
  1610. },
  1611. variant
  1612. );
  1613. }
  1614. }
  1615. };
  1616. }
  1617. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1618. namespace Catch {
  1619. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1620. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1621. using std::begin;
  1622. using std::end;
  1623. not_this_one begin( ... );
  1624. not_this_one end( ... );
  1625. template <typename T>
  1626. struct is_range {
  1627. static const bool value =
  1628. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1629. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1630. };
  1631. #if defined(_MANAGED) // Managed types are never ranges
  1632. template <typename T>
  1633. struct is_range<T^> {
  1634. static const bool value = false;
  1635. };
  1636. #endif
  1637. template<typename Range>
  1638. std::string rangeToString( Range const& range ) {
  1639. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1640. }
  1641. // Handle vector<bool> specially
  1642. template<typename Allocator>
  1643. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1644. ReusableStringStream rss;
  1645. rss << "{ ";
  1646. bool first = true;
  1647. for( bool b : v ) {
  1648. if( first )
  1649. first = false;
  1650. else
  1651. rss << ", ";
  1652. rss << ::Catch::Detail::stringify( b );
  1653. }
  1654. rss << " }";
  1655. return rss.str();
  1656. }
  1657. template<typename R>
  1658. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1659. static std::string convert( R const& range ) {
  1660. return rangeToString( range );
  1661. }
  1662. };
  1663. template <typename T, int SZ>
  1664. struct StringMaker<T[SZ]> {
  1665. static std::string convert(T const(&arr)[SZ]) {
  1666. return rangeToString(arr);
  1667. }
  1668. };
  1669. } // namespace Catch
  1670. // Separate std::chrono::duration specialization
  1671. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1672. #include <ctime>
  1673. #include <ratio>
  1674. #include <chrono>
  1675. namespace Catch {
  1676. template <class Ratio>
  1677. struct ratio_string {
  1678. static std::string symbol();
  1679. };
  1680. template <class Ratio>
  1681. std::string ratio_string<Ratio>::symbol() {
  1682. Catch::ReusableStringStream rss;
  1683. rss << '[' << Ratio::num << '/'
  1684. << Ratio::den << ']';
  1685. return rss.str();
  1686. }
  1687. template <>
  1688. struct ratio_string<std::atto> {
  1689. static std::string symbol();
  1690. };
  1691. template <>
  1692. struct ratio_string<std::femto> {
  1693. static std::string symbol();
  1694. };
  1695. template <>
  1696. struct ratio_string<std::pico> {
  1697. static std::string symbol();
  1698. };
  1699. template <>
  1700. struct ratio_string<std::nano> {
  1701. static std::string symbol();
  1702. };
  1703. template <>
  1704. struct ratio_string<std::micro> {
  1705. static std::string symbol();
  1706. };
  1707. template <>
  1708. struct ratio_string<std::milli> {
  1709. static std::string symbol();
  1710. };
  1711. ////////////
  1712. // std::chrono::duration specializations
  1713. template<typename Value, typename Ratio>
  1714. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1715. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1716. ReusableStringStream rss;
  1717. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1718. return rss.str();
  1719. }
  1720. };
  1721. template<typename Value>
  1722. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1723. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1724. ReusableStringStream rss;
  1725. rss << duration.count() << " s";
  1726. return rss.str();
  1727. }
  1728. };
  1729. template<typename Value>
  1730. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1731. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1732. ReusableStringStream rss;
  1733. rss << duration.count() << " m";
  1734. return rss.str();
  1735. }
  1736. };
  1737. template<typename Value>
  1738. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1739. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1740. ReusableStringStream rss;
  1741. rss << duration.count() << " h";
  1742. return rss.str();
  1743. }
  1744. };
  1745. ////////////
  1746. // std::chrono::time_point specialization
  1747. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1748. template<typename Clock, typename Duration>
  1749. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1750. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1751. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1752. }
  1753. };
  1754. // std::chrono::time_point<system_clock> specialization
  1755. template<typename Duration>
  1756. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1757. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1758. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1759. #ifdef _MSC_VER
  1760. std::tm timeInfo = {};
  1761. gmtime_s(&timeInfo, &converted);
  1762. #else
  1763. std::tm* timeInfo = std::gmtime(&converted);
  1764. #endif
  1765. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1766. char timeStamp[timeStampSize];
  1767. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1768. #ifdef _MSC_VER
  1769. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1770. #else
  1771. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1772. #endif
  1773. return std::string(timeStamp);
  1774. }
  1775. };
  1776. }
  1777. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1778. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1779. namespace Catch { \
  1780. template<> struct StringMaker<enumName> { \
  1781. static std::string convert( enumName value ) { \
  1782. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1783. return enumInfo.lookup( static_cast<int>( value ) ); \
  1784. } \
  1785. }; \
  1786. }
  1787. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1788. #ifdef _MSC_VER
  1789. #pragma warning(pop)
  1790. #endif
  1791. // end catch_tostring.h
  1792. #include <iosfwd>
  1793. #ifdef _MSC_VER
  1794. #pragma warning(push)
  1795. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1796. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1797. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1798. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1799. #pragma warning(disable:4800) // Forcing result to true or false
  1800. #endif
  1801. namespace Catch {
  1802. struct ITransientExpression {
  1803. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1804. auto getResult() const -> bool { return m_result; }
  1805. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1806. ITransientExpression( bool isBinaryExpression, bool result )
  1807. : m_isBinaryExpression( isBinaryExpression ),
  1808. m_result( result )
  1809. {}
  1810. // We don't actually need a virtual destructor, but many static analysers
  1811. // complain if it's not here :-(
  1812. virtual ~ITransientExpression();
  1813. bool m_isBinaryExpression;
  1814. bool m_result;
  1815. };
  1816. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1817. template<typename LhsT, typename RhsT>
  1818. class BinaryExpr : public ITransientExpression {
  1819. LhsT m_lhs;
  1820. StringRef m_op;
  1821. RhsT m_rhs;
  1822. void streamReconstructedExpression( std::ostream &os ) const override {
  1823. formatReconstructedExpression
  1824. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1825. }
  1826. public:
  1827. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1828. : ITransientExpression{ true, comparisonResult },
  1829. m_lhs( lhs ),
  1830. m_op( op ),
  1831. m_rhs( rhs )
  1832. {}
  1833. template<typename T>
  1834. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1835. static_assert(always_false<T>::value,
  1836. "chained comparisons are not supported inside assertions, "
  1837. "wrap the expression inside parentheses, or decompose it");
  1838. }
  1839. template<typename T>
  1840. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1841. static_assert(always_false<T>::value,
  1842. "chained comparisons are not supported inside assertions, "
  1843. "wrap the expression inside parentheses, or decompose it");
  1844. }
  1845. template<typename T>
  1846. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1847. static_assert(always_false<T>::value,
  1848. "chained comparisons are not supported inside assertions, "
  1849. "wrap the expression inside parentheses, or decompose it");
  1850. }
  1851. template<typename T>
  1852. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1853. static_assert(always_false<T>::value,
  1854. "chained comparisons are not supported inside assertions, "
  1855. "wrap the expression inside parentheses, or decompose it");
  1856. }
  1857. template<typename T>
  1858. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1859. static_assert(always_false<T>::value,
  1860. "chained comparisons are not supported inside assertions, "
  1861. "wrap the expression inside parentheses, or decompose it");
  1862. }
  1863. template<typename T>
  1864. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1865. static_assert(always_false<T>::value,
  1866. "chained comparisons are not supported inside assertions, "
  1867. "wrap the expression inside parentheses, or decompose it");
  1868. }
  1869. template<typename T>
  1870. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1871. static_assert(always_false<T>::value,
  1872. "chained comparisons are not supported inside assertions, "
  1873. "wrap the expression inside parentheses, or decompose it");
  1874. }
  1875. template<typename T>
  1876. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1877. static_assert(always_false<T>::value,
  1878. "chained comparisons are not supported inside assertions, "
  1879. "wrap the expression inside parentheses, or decompose it");
  1880. }
  1881. };
  1882. template<typename LhsT>
  1883. class UnaryExpr : public ITransientExpression {
  1884. LhsT m_lhs;
  1885. void streamReconstructedExpression( std::ostream &os ) const override {
  1886. os << Catch::Detail::stringify( m_lhs );
  1887. }
  1888. public:
  1889. explicit UnaryExpr( LhsT lhs )
  1890. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1891. m_lhs( lhs )
  1892. {}
  1893. };
  1894. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1895. template<typename LhsT, typename RhsT>
  1896. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1897. template<typename T>
  1898. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1899. template<typename T>
  1900. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1901. template<typename T>
  1902. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1903. template<typename T>
  1904. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1905. template<typename LhsT, typename RhsT>
  1906. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1907. template<typename T>
  1908. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1909. template<typename T>
  1910. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1911. template<typename T>
  1912. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1913. template<typename T>
  1914. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1915. template<typename LhsT>
  1916. class ExprLhs {
  1917. LhsT m_lhs;
  1918. public:
  1919. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1920. template<typename RhsT>
  1921. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1922. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1923. }
  1924. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1925. return { m_lhs == rhs, m_lhs, "==", rhs };
  1926. }
  1927. template<typename RhsT>
  1928. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1929. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1930. }
  1931. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1932. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1933. }
  1934. template<typename RhsT>
  1935. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1936. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1937. }
  1938. template<typename RhsT>
  1939. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1940. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1941. }
  1942. template<typename RhsT>
  1943. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1944. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1945. }
  1946. template<typename RhsT>
  1947. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1948. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1949. }
  1950. template<typename RhsT>
  1951. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1952. static_assert(always_false<RhsT>::value,
  1953. "operator&& is not supported inside assertions, "
  1954. "wrap the expression inside parentheses, or decompose it");
  1955. }
  1956. template<typename RhsT>
  1957. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1958. static_assert(always_false<RhsT>::value,
  1959. "operator|| is not supported inside assertions, "
  1960. "wrap the expression inside parentheses, or decompose it");
  1961. }
  1962. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1963. return UnaryExpr<LhsT>{ m_lhs };
  1964. }
  1965. };
  1966. void handleExpression( ITransientExpression const& expr );
  1967. template<typename T>
  1968. void handleExpression( ExprLhs<T> const& expr ) {
  1969. handleExpression( expr.makeUnaryExpr() );
  1970. }
  1971. struct Decomposer {
  1972. template<typename T>
  1973. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1974. return ExprLhs<T const&>{ lhs };
  1975. }
  1976. auto operator <=( bool value ) -> ExprLhs<bool> {
  1977. return ExprLhs<bool>{ value };
  1978. }
  1979. };
  1980. } // end namespace Catch
  1981. #ifdef _MSC_VER
  1982. #pragma warning(pop)
  1983. #endif
  1984. // end catch_decomposer.h
  1985. // start catch_interfaces_capture.h
  1986. #include <string>
  1987. #include <chrono>
  1988. namespace Catch {
  1989. class AssertionResult;
  1990. struct AssertionInfo;
  1991. struct SectionInfo;
  1992. struct SectionEndInfo;
  1993. struct MessageInfo;
  1994. struct MessageBuilder;
  1995. struct Counts;
  1996. struct AssertionReaction;
  1997. struct SourceLineInfo;
  1998. struct ITransientExpression;
  1999. struct IGeneratorTracker;
  2000. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2001. struct BenchmarkInfo;
  2002. template <typename Duration = std::chrono::duration<double, std::nano>>
  2003. struct BenchmarkStats;
  2004. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2005. struct IResultCapture {
  2006. virtual ~IResultCapture();
  2007. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2008. Counts& assertions ) = 0;
  2009. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2010. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2011. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2012. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2013. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2014. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2015. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2016. virtual void benchmarkFailed( std::string const& error ) = 0;
  2017. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2018. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2019. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2020. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2021. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2022. virtual void handleExpr
  2023. ( AssertionInfo const& info,
  2024. ITransientExpression const& expr,
  2025. AssertionReaction& reaction ) = 0;
  2026. virtual void handleMessage
  2027. ( AssertionInfo const& info,
  2028. ResultWas::OfType resultType,
  2029. StringRef const& message,
  2030. AssertionReaction& reaction ) = 0;
  2031. virtual void handleUnexpectedExceptionNotThrown
  2032. ( AssertionInfo const& info,
  2033. AssertionReaction& reaction ) = 0;
  2034. virtual void handleUnexpectedInflightException
  2035. ( AssertionInfo const& info,
  2036. std::string const& message,
  2037. AssertionReaction& reaction ) = 0;
  2038. virtual void handleIncomplete
  2039. ( AssertionInfo const& info ) = 0;
  2040. virtual void handleNonExpr
  2041. ( AssertionInfo const &info,
  2042. ResultWas::OfType resultType,
  2043. AssertionReaction &reaction ) = 0;
  2044. virtual bool lastAssertionPassed() = 0;
  2045. virtual void assertionPassed() = 0;
  2046. // Deprecated, do not use:
  2047. virtual std::string getCurrentTestName() const = 0;
  2048. virtual const AssertionResult* getLastResult() const = 0;
  2049. virtual void exceptionEarlyReported() = 0;
  2050. };
  2051. IResultCapture& getResultCapture();
  2052. }
  2053. // end catch_interfaces_capture.h
  2054. namespace Catch {
  2055. struct TestFailureException{};
  2056. struct AssertionResultData;
  2057. struct IResultCapture;
  2058. class RunContext;
  2059. class LazyExpression {
  2060. friend class AssertionHandler;
  2061. friend struct AssertionStats;
  2062. friend class RunContext;
  2063. ITransientExpression const* m_transientExpression = nullptr;
  2064. bool m_isNegated;
  2065. public:
  2066. LazyExpression( bool isNegated );
  2067. LazyExpression( LazyExpression const& other );
  2068. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2069. explicit operator bool() const;
  2070. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2071. };
  2072. struct AssertionReaction {
  2073. bool shouldDebugBreak = false;
  2074. bool shouldThrow = false;
  2075. };
  2076. class AssertionHandler {
  2077. AssertionInfo m_assertionInfo;
  2078. AssertionReaction m_reaction;
  2079. bool m_completed = false;
  2080. IResultCapture& m_resultCapture;
  2081. public:
  2082. AssertionHandler
  2083. ( StringRef const& macroName,
  2084. SourceLineInfo const& lineInfo,
  2085. StringRef capturedExpression,
  2086. ResultDisposition::Flags resultDisposition );
  2087. ~AssertionHandler() {
  2088. if ( !m_completed ) {
  2089. m_resultCapture.handleIncomplete( m_assertionInfo );
  2090. }
  2091. }
  2092. template<typename T>
  2093. void handleExpr( ExprLhs<T> const& expr ) {
  2094. handleExpr( expr.makeUnaryExpr() );
  2095. }
  2096. void handleExpr( ITransientExpression const& expr );
  2097. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2098. void handleExceptionThrownAsExpected();
  2099. void handleUnexpectedExceptionNotThrown();
  2100. void handleExceptionNotThrownAsExpected();
  2101. void handleThrowingCallSkipped();
  2102. void handleUnexpectedInflightException();
  2103. void complete();
  2104. void setCompleted();
  2105. // query
  2106. auto allowThrows() const -> bool;
  2107. };
  2108. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2109. } // namespace Catch
  2110. // end catch_assertionhandler.h
  2111. // start catch_message.h
  2112. #include <string>
  2113. #include <vector>
  2114. namespace Catch {
  2115. struct MessageInfo {
  2116. MessageInfo( StringRef const& _macroName,
  2117. SourceLineInfo const& _lineInfo,
  2118. ResultWas::OfType _type );
  2119. StringRef macroName;
  2120. std::string message;
  2121. SourceLineInfo lineInfo;
  2122. ResultWas::OfType type;
  2123. unsigned int sequence;
  2124. bool operator == ( MessageInfo const& other ) const;
  2125. bool operator < ( MessageInfo const& other ) const;
  2126. private:
  2127. static unsigned int globalCount;
  2128. };
  2129. struct MessageStream {
  2130. template<typename T>
  2131. MessageStream& operator << ( T const& value ) {
  2132. m_stream << value;
  2133. return *this;
  2134. }
  2135. ReusableStringStream m_stream;
  2136. };
  2137. struct MessageBuilder : MessageStream {
  2138. MessageBuilder( StringRef const& macroName,
  2139. SourceLineInfo const& lineInfo,
  2140. ResultWas::OfType type );
  2141. template<typename T>
  2142. MessageBuilder& operator << ( T const& value ) {
  2143. m_stream << value;
  2144. return *this;
  2145. }
  2146. MessageInfo m_info;
  2147. };
  2148. class ScopedMessage {
  2149. public:
  2150. explicit ScopedMessage( MessageBuilder const& builder );
  2151. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2152. ScopedMessage( ScopedMessage&& old );
  2153. ~ScopedMessage();
  2154. MessageInfo m_info;
  2155. bool m_moved;
  2156. };
  2157. class Capturer {
  2158. std::vector<MessageInfo> m_messages;
  2159. IResultCapture& m_resultCapture = getResultCapture();
  2160. size_t m_captured = 0;
  2161. public:
  2162. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2163. ~Capturer();
  2164. void captureValue( size_t index, std::string const& value );
  2165. template<typename T>
  2166. void captureValues( size_t index, T const& value ) {
  2167. captureValue( index, Catch::Detail::stringify( value ) );
  2168. }
  2169. template<typename T, typename... Ts>
  2170. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2171. captureValue( index, Catch::Detail::stringify(value) );
  2172. captureValues( index+1, values... );
  2173. }
  2174. };
  2175. } // end namespace Catch
  2176. // end catch_message.h
  2177. #if !defined(CATCH_CONFIG_DISABLE)
  2178. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2179. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2180. #else
  2181. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2182. #endif
  2183. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2184. ///////////////////////////////////////////////////////////////////////////////
  2185. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2186. // macros.
  2187. #define INTERNAL_CATCH_TRY
  2188. #define INTERNAL_CATCH_CATCH( capturer )
  2189. #else // CATCH_CONFIG_FAST_COMPILE
  2190. #define INTERNAL_CATCH_TRY try
  2191. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2192. #endif
  2193. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2194. ///////////////////////////////////////////////////////////////////////////////
  2195. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2196. do { \
  2197. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2198. INTERNAL_CATCH_TRY { \
  2199. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2200. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2201. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  2202. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2203. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2204. } 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
  2205. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  2206. ///////////////////////////////////////////////////////////////////////////////
  2207. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2208. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2209. if( Catch::getResultCapture().lastAssertionPassed() )
  2210. ///////////////////////////////////////////////////////////////////////////////
  2211. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2212. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2213. if( !Catch::getResultCapture().lastAssertionPassed() )
  2214. ///////////////////////////////////////////////////////////////////////////////
  2215. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2216. do { \
  2217. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2218. try { \
  2219. static_cast<void>(__VA_ARGS__); \
  2220. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2221. } \
  2222. catch( ... ) { \
  2223. catchAssertionHandler.handleUnexpectedInflightException(); \
  2224. } \
  2225. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2226. } while( false )
  2227. ///////////////////////////////////////////////////////////////////////////////
  2228. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2229. do { \
  2230. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2231. if( catchAssertionHandler.allowThrows() ) \
  2232. try { \
  2233. static_cast<void>(__VA_ARGS__); \
  2234. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2235. } \
  2236. catch( ... ) { \
  2237. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2238. } \
  2239. else \
  2240. catchAssertionHandler.handleThrowingCallSkipped(); \
  2241. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2242. } while( false )
  2243. ///////////////////////////////////////////////////////////////////////////////
  2244. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2245. do { \
  2246. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2247. if( catchAssertionHandler.allowThrows() ) \
  2248. try { \
  2249. static_cast<void>(expr); \
  2250. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2251. } \
  2252. catch( exceptionType const& ) { \
  2253. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2254. } \
  2255. catch( ... ) { \
  2256. catchAssertionHandler.handleUnexpectedInflightException(); \
  2257. } \
  2258. else \
  2259. catchAssertionHandler.handleThrowingCallSkipped(); \
  2260. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2261. } while( false )
  2262. ///////////////////////////////////////////////////////////////////////////////
  2263. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2264. do { \
  2265. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2266. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2267. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2268. } while( false )
  2269. ///////////////////////////////////////////////////////////////////////////////
  2270. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2271. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2272. varName.captureValues( 0, __VA_ARGS__ )
  2273. ///////////////////////////////////////////////////////////////////////////////
  2274. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2275. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2276. ///////////////////////////////////////////////////////////////////////////////
  2277. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2278. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2279. ///////////////////////////////////////////////////////////////////////////////
  2280. // Although this is matcher-based, it can be used with just a string
  2281. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2282. do { \
  2283. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2284. if( catchAssertionHandler.allowThrows() ) \
  2285. try { \
  2286. static_cast<void>(__VA_ARGS__); \
  2287. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2288. } \
  2289. catch( ... ) { \
  2290. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2291. } \
  2292. else \
  2293. catchAssertionHandler.handleThrowingCallSkipped(); \
  2294. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2295. } while( false )
  2296. #endif // CATCH_CONFIG_DISABLE
  2297. // end catch_capture.hpp
  2298. // start catch_section.h
  2299. // start catch_section_info.h
  2300. // start catch_totals.h
  2301. #include <cstddef>
  2302. namespace Catch {
  2303. struct Counts {
  2304. Counts operator - ( Counts const& other ) const;
  2305. Counts& operator += ( Counts const& other );
  2306. std::size_t total() const;
  2307. bool allPassed() const;
  2308. bool allOk() const;
  2309. std::size_t passed = 0;
  2310. std::size_t failed = 0;
  2311. std::size_t failedButOk = 0;
  2312. };
  2313. struct Totals {
  2314. Totals operator - ( Totals const& other ) const;
  2315. Totals& operator += ( Totals const& other );
  2316. Totals delta( Totals const& prevTotals ) const;
  2317. int error = 0;
  2318. Counts assertions;
  2319. Counts testCases;
  2320. };
  2321. }
  2322. // end catch_totals.h
  2323. #include <string>
  2324. namespace Catch {
  2325. struct SectionInfo {
  2326. SectionInfo
  2327. ( SourceLineInfo const& _lineInfo,
  2328. std::string const& _name );
  2329. // Deprecated
  2330. SectionInfo
  2331. ( SourceLineInfo const& _lineInfo,
  2332. std::string const& _name,
  2333. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2334. std::string name;
  2335. std::string description; // !Deprecated: this will always be empty
  2336. SourceLineInfo lineInfo;
  2337. };
  2338. struct SectionEndInfo {
  2339. SectionInfo sectionInfo;
  2340. Counts prevAssertions;
  2341. double durationInSeconds;
  2342. };
  2343. } // end namespace Catch
  2344. // end catch_section_info.h
  2345. // start catch_timer.h
  2346. #include <cstdint>
  2347. namespace Catch {
  2348. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2349. auto getEstimatedClockResolution() -> uint64_t;
  2350. class Timer {
  2351. uint64_t m_nanoseconds = 0;
  2352. public:
  2353. void start();
  2354. auto getElapsedNanoseconds() const -> uint64_t;
  2355. auto getElapsedMicroseconds() const -> uint64_t;
  2356. auto getElapsedMilliseconds() const -> unsigned int;
  2357. auto getElapsedSeconds() const -> double;
  2358. };
  2359. } // namespace Catch
  2360. // end catch_timer.h
  2361. #include <string>
  2362. namespace Catch {
  2363. class Section : NonCopyable {
  2364. public:
  2365. Section( SectionInfo const& info );
  2366. ~Section();
  2367. // This indicates whether the section should be executed or not
  2368. explicit operator bool() const;
  2369. private:
  2370. SectionInfo m_info;
  2371. std::string m_name;
  2372. Counts m_assertions;
  2373. bool m_sectionIncluded;
  2374. Timer m_timer;
  2375. };
  2376. } // end namespace Catch
  2377. #define INTERNAL_CATCH_SECTION( ... ) \
  2378. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2379. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2380. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2381. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2382. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2383. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2384. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2385. // end catch_section.h
  2386. // start catch_interfaces_exception.h
  2387. // start catch_interfaces_registry_hub.h
  2388. #include <string>
  2389. #include <memory>
  2390. namespace Catch {
  2391. class TestCase;
  2392. struct ITestCaseRegistry;
  2393. struct IExceptionTranslatorRegistry;
  2394. struct IExceptionTranslator;
  2395. struct IReporterRegistry;
  2396. struct IReporterFactory;
  2397. struct ITagAliasRegistry;
  2398. struct IMutableEnumValuesRegistry;
  2399. class StartupExceptionRegistry;
  2400. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2401. struct IRegistryHub {
  2402. virtual ~IRegistryHub();
  2403. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2404. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2405. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2406. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2407. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2408. };
  2409. struct IMutableRegistryHub {
  2410. virtual ~IMutableRegistryHub();
  2411. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2412. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2413. virtual void registerTest( TestCase const& testInfo ) = 0;
  2414. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2415. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2416. virtual void registerStartupException() noexcept = 0;
  2417. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2418. };
  2419. IRegistryHub const& getRegistryHub();
  2420. IMutableRegistryHub& getMutableRegistryHub();
  2421. void cleanUp();
  2422. std::string translateActiveException();
  2423. }
  2424. // end catch_interfaces_registry_hub.h
  2425. #if defined(CATCH_CONFIG_DISABLE)
  2426. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2427. static std::string translatorName( signature )
  2428. #endif
  2429. #include <exception>
  2430. #include <string>
  2431. #include <vector>
  2432. namespace Catch {
  2433. using exceptionTranslateFunction = std::string(*)();
  2434. struct IExceptionTranslator;
  2435. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2436. struct IExceptionTranslator {
  2437. virtual ~IExceptionTranslator();
  2438. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2439. };
  2440. struct IExceptionTranslatorRegistry {
  2441. virtual ~IExceptionTranslatorRegistry();
  2442. virtual std::string translateActiveException() const = 0;
  2443. };
  2444. class ExceptionTranslatorRegistrar {
  2445. template<typename T>
  2446. class ExceptionTranslator : public IExceptionTranslator {
  2447. public:
  2448. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2449. : m_translateFunction( translateFunction )
  2450. {}
  2451. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2452. try {
  2453. if( it == itEnd )
  2454. std::rethrow_exception(std::current_exception());
  2455. else
  2456. return (*it)->translate( it+1, itEnd );
  2457. }
  2458. catch( T& ex ) {
  2459. return m_translateFunction( ex );
  2460. }
  2461. }
  2462. protected:
  2463. std::string(*m_translateFunction)( T& );
  2464. };
  2465. public:
  2466. template<typename T>
  2467. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2468. getMutableRegistryHub().registerTranslator
  2469. ( new ExceptionTranslator<T>( translateFunction ) );
  2470. }
  2471. };
  2472. }
  2473. ///////////////////////////////////////////////////////////////////////////////
  2474. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2475. static std::string translatorName( signature ); \
  2476. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2477. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2478. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2479. static std::string translatorName( signature )
  2480. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2481. // end catch_interfaces_exception.h
  2482. // start catch_approx.h
  2483. #include <type_traits>
  2484. namespace Catch {
  2485. namespace Detail {
  2486. class Approx {
  2487. private:
  2488. bool equalityComparisonImpl(double other) const;
  2489. // Validates the new margin (margin >= 0)
  2490. // out-of-line to avoid including stdexcept in the header
  2491. void setMargin(double margin);
  2492. // Validates the new epsilon (0 < epsilon < 1)
  2493. // out-of-line to avoid including stdexcept in the header
  2494. void setEpsilon(double epsilon);
  2495. public:
  2496. explicit Approx ( double value );
  2497. static Approx custom();
  2498. Approx operator-() const;
  2499. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2500. Approx operator()( T const& value ) {
  2501. Approx approx( static_cast<double>(value) );
  2502. approx.m_epsilon = m_epsilon;
  2503. approx.m_margin = m_margin;
  2504. approx.m_scale = m_scale;
  2505. return approx;
  2506. }
  2507. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2508. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2509. {}
  2510. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2511. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2512. auto lhs_v = static_cast<double>(lhs);
  2513. return rhs.equalityComparisonImpl(lhs_v);
  2514. }
  2515. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2516. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2517. return operator==( rhs, lhs );
  2518. }
  2519. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2520. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2521. return !operator==( lhs, rhs );
  2522. }
  2523. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2524. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2525. return !operator==( rhs, lhs );
  2526. }
  2527. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2528. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2529. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2530. }
  2531. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2532. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2533. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2534. }
  2535. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2536. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2537. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2538. }
  2539. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2540. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2541. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2542. }
  2543. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2544. Approx& epsilon( T const& newEpsilon ) {
  2545. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2546. setEpsilon(epsilonAsDouble);
  2547. return *this;
  2548. }
  2549. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2550. Approx& margin( T const& newMargin ) {
  2551. double marginAsDouble = static_cast<double>(newMargin);
  2552. setMargin(marginAsDouble);
  2553. return *this;
  2554. }
  2555. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2556. Approx& scale( T const& newScale ) {
  2557. m_scale = static_cast<double>(newScale);
  2558. return *this;
  2559. }
  2560. std::string toString() const;
  2561. private:
  2562. double m_epsilon;
  2563. double m_margin;
  2564. double m_scale;
  2565. double m_value;
  2566. };
  2567. } // end namespace Detail
  2568. namespace literals {
  2569. Detail::Approx operator "" _a(long double val);
  2570. Detail::Approx operator "" _a(unsigned long long val);
  2571. } // end namespace literals
  2572. template<>
  2573. struct StringMaker<Catch::Detail::Approx> {
  2574. static std::string convert(Catch::Detail::Approx const& value);
  2575. };
  2576. } // end namespace Catch
  2577. // end catch_approx.h
  2578. // start catch_string_manip.h
  2579. #include <string>
  2580. #include <iosfwd>
  2581. #include <vector>
  2582. namespace Catch {
  2583. bool startsWith( std::string const& s, std::string const& prefix );
  2584. bool startsWith( std::string const& s, char prefix );
  2585. bool endsWith( std::string const& s, std::string const& suffix );
  2586. bool endsWith( std::string const& s, char suffix );
  2587. bool contains( std::string const& s, std::string const& infix );
  2588. void toLowerInPlace( std::string& s );
  2589. std::string toLower( std::string const& s );
  2590. std::string trim( std::string const& str );
  2591. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2592. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2593. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2594. struct pluralise {
  2595. pluralise( std::size_t count, std::string const& label );
  2596. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2597. std::size_t m_count;
  2598. std::string m_label;
  2599. };
  2600. }
  2601. // end catch_string_manip.h
  2602. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2603. // start catch_capture_matchers.h
  2604. // start catch_matchers.h
  2605. #include <string>
  2606. #include <vector>
  2607. namespace Catch {
  2608. namespace Matchers {
  2609. namespace Impl {
  2610. template<typename ArgT> struct MatchAllOf;
  2611. template<typename ArgT> struct MatchAnyOf;
  2612. template<typename ArgT> struct MatchNotOf;
  2613. class MatcherUntypedBase {
  2614. public:
  2615. MatcherUntypedBase() = default;
  2616. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2617. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2618. std::string toString() const;
  2619. protected:
  2620. virtual ~MatcherUntypedBase();
  2621. virtual std::string describe() const = 0;
  2622. mutable std::string m_cachedToString;
  2623. };
  2624. #ifdef __clang__
  2625. # pragma clang diagnostic push
  2626. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2627. #endif
  2628. template<typename ObjectT>
  2629. struct MatcherMethod {
  2630. virtual bool match( ObjectT const& arg ) const = 0;
  2631. };
  2632. #ifdef __clang__
  2633. # pragma clang diagnostic pop
  2634. #endif
  2635. template<typename T>
  2636. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2637. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2638. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2639. MatchNotOf<T> operator ! () const;
  2640. };
  2641. template<typename ArgT>
  2642. struct MatchAllOf : MatcherBase<ArgT> {
  2643. bool match( ArgT const& arg ) const override {
  2644. for( auto matcher : m_matchers ) {
  2645. if (!matcher->match(arg))
  2646. return false;
  2647. }
  2648. return true;
  2649. }
  2650. std::string describe() const override {
  2651. std::string description;
  2652. description.reserve( 4 + m_matchers.size()*32 );
  2653. description += "( ";
  2654. bool first = true;
  2655. for( auto matcher : m_matchers ) {
  2656. if( first )
  2657. first = false;
  2658. else
  2659. description += " and ";
  2660. description += matcher->toString();
  2661. }
  2662. description += " )";
  2663. return description;
  2664. }
  2665. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2666. m_matchers.push_back( &other );
  2667. return *this;
  2668. }
  2669. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2670. };
  2671. template<typename ArgT>
  2672. struct MatchAnyOf : MatcherBase<ArgT> {
  2673. bool match( ArgT const& arg ) const override {
  2674. for( auto matcher : m_matchers ) {
  2675. if (matcher->match(arg))
  2676. return true;
  2677. }
  2678. return false;
  2679. }
  2680. std::string describe() const override {
  2681. std::string description;
  2682. description.reserve( 4 + m_matchers.size()*32 );
  2683. description += "( ";
  2684. bool first = true;
  2685. for( auto matcher : m_matchers ) {
  2686. if( first )
  2687. first = false;
  2688. else
  2689. description += " or ";
  2690. description += matcher->toString();
  2691. }
  2692. description += " )";
  2693. return description;
  2694. }
  2695. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2696. m_matchers.push_back( &other );
  2697. return *this;
  2698. }
  2699. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2700. };
  2701. template<typename ArgT>
  2702. struct MatchNotOf : MatcherBase<ArgT> {
  2703. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2704. bool match( ArgT const& arg ) const override {
  2705. return !m_underlyingMatcher.match( arg );
  2706. }
  2707. std::string describe() const override {
  2708. return "not " + m_underlyingMatcher.toString();
  2709. }
  2710. MatcherBase<ArgT> const& m_underlyingMatcher;
  2711. };
  2712. template<typename T>
  2713. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2714. return MatchAllOf<T>() && *this && other;
  2715. }
  2716. template<typename T>
  2717. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2718. return MatchAnyOf<T>() || *this || other;
  2719. }
  2720. template<typename T>
  2721. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2722. return MatchNotOf<T>( *this );
  2723. }
  2724. } // namespace Impl
  2725. } // namespace Matchers
  2726. using namespace Matchers;
  2727. using Matchers::Impl::MatcherBase;
  2728. } // namespace Catch
  2729. // end catch_matchers.h
  2730. // start catch_matchers_floating.h
  2731. #include <type_traits>
  2732. #include <cmath>
  2733. namespace Catch {
  2734. namespace Matchers {
  2735. namespace Floating {
  2736. enum class FloatingPointKind : uint8_t;
  2737. struct WithinAbsMatcher : MatcherBase<double> {
  2738. WithinAbsMatcher(double target, double margin);
  2739. bool match(double const& matchee) const override;
  2740. std::string describe() const override;
  2741. private:
  2742. double m_target;
  2743. double m_margin;
  2744. };
  2745. struct WithinUlpsMatcher : MatcherBase<double> {
  2746. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2747. bool match(double const& matchee) const override;
  2748. std::string describe() const override;
  2749. private:
  2750. double m_target;
  2751. int m_ulps;
  2752. FloatingPointKind m_type;
  2753. };
  2754. } // namespace Floating
  2755. // The following functions create the actual matcher objects.
  2756. // This allows the types to be inferred
  2757. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2758. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2759. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2760. } // namespace Matchers
  2761. } // namespace Catch
  2762. // end catch_matchers_floating.h
  2763. // start catch_matchers_generic.hpp
  2764. #include <functional>
  2765. #include <string>
  2766. namespace Catch {
  2767. namespace Matchers {
  2768. namespace Generic {
  2769. namespace Detail {
  2770. std::string finalizeDescription(const std::string& desc);
  2771. }
  2772. template <typename T>
  2773. class PredicateMatcher : public MatcherBase<T> {
  2774. std::function<bool(T const&)> m_predicate;
  2775. std::string m_description;
  2776. public:
  2777. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2778. :m_predicate(std::move(elem)),
  2779. m_description(Detail::finalizeDescription(descr))
  2780. {}
  2781. bool match( T const& item ) const override {
  2782. return m_predicate(item);
  2783. }
  2784. std::string describe() const override {
  2785. return m_description;
  2786. }
  2787. };
  2788. } // namespace Generic
  2789. // The following functions create the actual matcher objects.
  2790. // The user has to explicitly specify type to the function, because
  2791. // inferring std::function<bool(T const&)> is hard (but possible) and
  2792. // requires a lot of TMP.
  2793. template<typename T>
  2794. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2795. return Generic::PredicateMatcher<T>(predicate, description);
  2796. }
  2797. } // namespace Matchers
  2798. } // namespace Catch
  2799. // end catch_matchers_generic.hpp
  2800. // start catch_matchers_string.h
  2801. #include <string>
  2802. namespace Catch {
  2803. namespace Matchers {
  2804. namespace StdString {
  2805. struct CasedString
  2806. {
  2807. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2808. std::string adjustString( std::string const& str ) const;
  2809. std::string caseSensitivitySuffix() const;
  2810. CaseSensitive::Choice m_caseSensitivity;
  2811. std::string m_str;
  2812. };
  2813. struct StringMatcherBase : MatcherBase<std::string> {
  2814. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2815. std::string describe() const override;
  2816. CasedString m_comparator;
  2817. std::string m_operation;
  2818. };
  2819. struct EqualsMatcher : StringMatcherBase {
  2820. EqualsMatcher( CasedString const& comparator );
  2821. bool match( std::string const& source ) const override;
  2822. };
  2823. struct ContainsMatcher : StringMatcherBase {
  2824. ContainsMatcher( CasedString const& comparator );
  2825. bool match( std::string const& source ) const override;
  2826. };
  2827. struct StartsWithMatcher : StringMatcherBase {
  2828. StartsWithMatcher( CasedString const& comparator );
  2829. bool match( std::string const& source ) const override;
  2830. };
  2831. struct EndsWithMatcher : StringMatcherBase {
  2832. EndsWithMatcher( CasedString const& comparator );
  2833. bool match( std::string const& source ) const override;
  2834. };
  2835. struct RegexMatcher : MatcherBase<std::string> {
  2836. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2837. bool match( std::string const& matchee ) const override;
  2838. std::string describe() const override;
  2839. private:
  2840. std::string m_regex;
  2841. CaseSensitive::Choice m_caseSensitivity;
  2842. };
  2843. } // namespace StdString
  2844. // The following functions create the actual matcher objects.
  2845. // This allows the types to be inferred
  2846. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2847. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2848. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2849. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2850. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2851. } // namespace Matchers
  2852. } // namespace Catch
  2853. // end catch_matchers_string.h
  2854. // start catch_matchers_vector.h
  2855. #include <algorithm>
  2856. namespace Catch {
  2857. namespace Matchers {
  2858. namespace Vector {
  2859. template<typename T>
  2860. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2861. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2862. bool match(std::vector<T> const &v) const override {
  2863. for (auto const& el : v) {
  2864. if (el == m_comparator) {
  2865. return true;
  2866. }
  2867. }
  2868. return false;
  2869. }
  2870. std::string describe() const override {
  2871. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2872. }
  2873. T const& m_comparator;
  2874. };
  2875. template<typename T>
  2876. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2877. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2878. bool match(std::vector<T> const &v) const override {
  2879. // !TBD: see note in EqualsMatcher
  2880. if (m_comparator.size() > v.size())
  2881. return false;
  2882. for (auto const& comparator : m_comparator) {
  2883. auto present = false;
  2884. for (const auto& el : v) {
  2885. if (el == comparator) {
  2886. present = true;
  2887. break;
  2888. }
  2889. }
  2890. if (!present) {
  2891. return false;
  2892. }
  2893. }
  2894. return true;
  2895. }
  2896. std::string describe() const override {
  2897. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2898. }
  2899. std::vector<T> const& m_comparator;
  2900. };
  2901. template<typename T>
  2902. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2903. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2904. bool match(std::vector<T> const &v) const override {
  2905. // !TBD: This currently works if all elements can be compared using !=
  2906. // - a more general approach would be via a compare template that defaults
  2907. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2908. // - then just call that directly
  2909. if (m_comparator.size() != v.size())
  2910. return false;
  2911. for (std::size_t i = 0; i < v.size(); ++i)
  2912. if (m_comparator[i] != v[i])
  2913. return false;
  2914. return true;
  2915. }
  2916. std::string describe() const override {
  2917. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2918. }
  2919. std::vector<T> const& m_comparator;
  2920. };
  2921. template<typename T>
  2922. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  2923. ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
  2924. bool match(std::vector<T> const &v) const override {
  2925. if (m_comparator.size() != v.size())
  2926. return false;
  2927. for (std::size_t i = 0; i < v.size(); ++i)
  2928. if (m_comparator[i] != approx(v[i]))
  2929. return false;
  2930. return true;
  2931. }
  2932. std::string describe() const override {
  2933. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  2934. }
  2935. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2936. ApproxMatcher& epsilon( T const& newEpsilon ) {
  2937. approx.epsilon(newEpsilon);
  2938. return *this;
  2939. }
  2940. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2941. ApproxMatcher& margin( T const& newMargin ) {
  2942. approx.margin(newMargin);
  2943. return *this;
  2944. }
  2945. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2946. ApproxMatcher& scale( T const& newScale ) {
  2947. approx.scale(newScale);
  2948. return *this;
  2949. }
  2950. std::vector<T> const& m_comparator;
  2951. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  2952. };
  2953. template<typename T>
  2954. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2955. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2956. bool match(std::vector<T> const& vec) const override {
  2957. // Note: This is a reimplementation of std::is_permutation,
  2958. // because I don't want to include <algorithm> inside the common path
  2959. if (m_target.size() != vec.size()) {
  2960. return false;
  2961. }
  2962. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  2963. }
  2964. std::string describe() const override {
  2965. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2966. }
  2967. private:
  2968. std::vector<T> const& m_target;
  2969. };
  2970. } // namespace Vector
  2971. // The following functions create the actual matcher objects.
  2972. // This allows the types to be inferred
  2973. template<typename T>
  2974. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2975. return Vector::ContainsMatcher<T>( comparator );
  2976. }
  2977. template<typename T>
  2978. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2979. return Vector::ContainsElementMatcher<T>( comparator );
  2980. }
  2981. template<typename T>
  2982. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2983. return Vector::EqualsMatcher<T>( comparator );
  2984. }
  2985. template<typename T>
  2986. Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
  2987. return Vector::ApproxMatcher<T>( comparator );
  2988. }
  2989. template<typename T>
  2990. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2991. return Vector::UnorderedEqualsMatcher<T>(target);
  2992. }
  2993. } // namespace Matchers
  2994. } // namespace Catch
  2995. // end catch_matchers_vector.h
  2996. namespace Catch {
  2997. template<typename ArgT, typename MatcherT>
  2998. class MatchExpr : public ITransientExpression {
  2999. ArgT const& m_arg;
  3000. MatcherT m_matcher;
  3001. StringRef m_matcherString;
  3002. public:
  3003. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3004. : ITransientExpression{ true, matcher.match( arg ) },
  3005. m_arg( arg ),
  3006. m_matcher( matcher ),
  3007. m_matcherString( matcherString )
  3008. {}
  3009. void streamReconstructedExpression( std::ostream &os ) const override {
  3010. auto matcherAsString = m_matcher.toString();
  3011. os << Catch::Detail::stringify( m_arg ) << ' ';
  3012. if( matcherAsString == Detail::unprintableString )
  3013. os << m_matcherString;
  3014. else
  3015. os << matcherAsString;
  3016. }
  3017. };
  3018. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3019. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3020. template<typename ArgT, typename MatcherT>
  3021. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3022. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3023. }
  3024. } // namespace Catch
  3025. ///////////////////////////////////////////////////////////////////////////////
  3026. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3027. do { \
  3028. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3029. INTERNAL_CATCH_TRY { \
  3030. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3031. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3032. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3033. } while( false )
  3034. ///////////////////////////////////////////////////////////////////////////////
  3035. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3036. do { \
  3037. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3038. if( catchAssertionHandler.allowThrows() ) \
  3039. try { \
  3040. static_cast<void>(__VA_ARGS__ ); \
  3041. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3042. } \
  3043. catch( exceptionType const& ex ) { \
  3044. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3045. } \
  3046. catch( ... ) { \
  3047. catchAssertionHandler.handleUnexpectedInflightException(); \
  3048. } \
  3049. else \
  3050. catchAssertionHandler.handleThrowingCallSkipped(); \
  3051. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3052. } while( false )
  3053. // end catch_capture_matchers.h
  3054. #endif
  3055. // start catch_generators.hpp
  3056. // start catch_interfaces_generatortracker.h
  3057. #include <memory>
  3058. namespace Catch {
  3059. namespace Generators {
  3060. class GeneratorUntypedBase {
  3061. public:
  3062. GeneratorUntypedBase() = default;
  3063. virtual ~GeneratorUntypedBase();
  3064. // Attempts to move the generator to the next element
  3065. //
  3066. // Returns true iff the move succeeded (and a valid element
  3067. // can be retrieved).
  3068. virtual bool next() = 0;
  3069. };
  3070. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3071. } // namespace Generators
  3072. struct IGeneratorTracker {
  3073. virtual ~IGeneratorTracker();
  3074. virtual auto hasGenerator() const -> bool = 0;
  3075. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3076. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3077. };
  3078. } // namespace Catch
  3079. // end catch_interfaces_generatortracker.h
  3080. // start catch_enforce.h
  3081. #include <exception>
  3082. namespace Catch {
  3083. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3084. template <typename Ex>
  3085. [[noreturn]]
  3086. void throw_exception(Ex const& e) {
  3087. throw e;
  3088. }
  3089. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3090. [[noreturn]]
  3091. void throw_exception(std::exception const& e);
  3092. #endif
  3093. [[noreturn]]
  3094. void throw_logic_error(std::string const& msg);
  3095. [[noreturn]]
  3096. void throw_domain_error(std::string const& msg);
  3097. [[noreturn]]
  3098. void throw_runtime_error(std::string const& msg);
  3099. } // namespace Catch;
  3100. #define CATCH_MAKE_MSG(...) \
  3101. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3102. #define CATCH_INTERNAL_ERROR(...) \
  3103. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
  3104. #define CATCH_ERROR(...) \
  3105. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3106. #define CATCH_RUNTIME_ERROR(...) \
  3107. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
  3108. #define CATCH_ENFORCE( condition, ... ) \
  3109. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3110. // end catch_enforce.h
  3111. #include <memory>
  3112. #include <vector>
  3113. #include <cassert>
  3114. #include <utility>
  3115. #include <exception>
  3116. namespace Catch {
  3117. class GeneratorException : public std::exception {
  3118. const char* const m_msg = "";
  3119. public:
  3120. GeneratorException(const char* msg):
  3121. m_msg(msg)
  3122. {}
  3123. const char* what() const noexcept override final;
  3124. };
  3125. namespace Generators {
  3126. // !TBD move this into its own location?
  3127. namespace pf{
  3128. template<typename T, typename... Args>
  3129. std::unique_ptr<T> make_unique( Args&&... args ) {
  3130. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3131. }
  3132. }
  3133. template<typename T>
  3134. struct IGenerator : GeneratorUntypedBase {
  3135. virtual ~IGenerator() = default;
  3136. // Returns the current element of the generator
  3137. //
  3138. // \Precondition The generator is either freshly constructed,
  3139. // or the last call to `next()` returned true
  3140. virtual T const& get() const = 0;
  3141. using type = T;
  3142. };
  3143. template<typename T>
  3144. class SingleValueGenerator final : public IGenerator<T> {
  3145. T m_value;
  3146. public:
  3147. SingleValueGenerator(T const& value) : m_value( value ) {}
  3148. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3149. T const& get() const override {
  3150. return m_value;
  3151. }
  3152. bool next() override {
  3153. return false;
  3154. }
  3155. };
  3156. template<typename T>
  3157. class FixedValuesGenerator final : public IGenerator<T> {
  3158. std::vector<T> m_values;
  3159. size_t m_idx = 0;
  3160. public:
  3161. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3162. T const& get() const override {
  3163. return m_values[m_idx];
  3164. }
  3165. bool next() override {
  3166. ++m_idx;
  3167. return m_idx < m_values.size();
  3168. }
  3169. };
  3170. template <typename T>
  3171. class GeneratorWrapper final {
  3172. std::unique_ptr<IGenerator<T>> m_generator;
  3173. public:
  3174. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3175. m_generator(std::move(generator))
  3176. {}
  3177. T const& get() const {
  3178. return m_generator->get();
  3179. }
  3180. bool next() {
  3181. return m_generator->next();
  3182. }
  3183. };
  3184. template <typename T>
  3185. GeneratorWrapper<T> value(T&& value) {
  3186. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3187. }
  3188. template <typename T>
  3189. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3190. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3191. }
  3192. template<typename T>
  3193. class Generators : public IGenerator<T> {
  3194. std::vector<GeneratorWrapper<T>> m_generators;
  3195. size_t m_current = 0;
  3196. void populate(GeneratorWrapper<T>&& generator) {
  3197. m_generators.emplace_back(std::move(generator));
  3198. }
  3199. void populate(T&& val) {
  3200. m_generators.emplace_back(value(std::move(val)));
  3201. }
  3202. template<typename U>
  3203. void populate(U&& val) {
  3204. populate(T(std::move(val)));
  3205. }
  3206. template<typename U, typename... Gs>
  3207. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  3208. populate(std::forward<U>(valueOrGenerator));
  3209. populate(std::forward<Gs>(moreGenerators)...);
  3210. }
  3211. public:
  3212. template <typename... Gs>
  3213. Generators(Gs... moreGenerators) {
  3214. m_generators.reserve(sizeof...(Gs));
  3215. populate(std::forward<Gs>(moreGenerators)...);
  3216. }
  3217. T const& get() const override {
  3218. return m_generators[m_current].get();
  3219. }
  3220. bool next() override {
  3221. if (m_current >= m_generators.size()) {
  3222. return false;
  3223. }
  3224. const bool current_status = m_generators[m_current].next();
  3225. if (!current_status) {
  3226. ++m_current;
  3227. }
  3228. return m_current < m_generators.size();
  3229. }
  3230. };
  3231. template<typename... Ts>
  3232. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3233. return values<std::tuple<Ts...>>( tuples );
  3234. }
  3235. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3236. template <typename T>
  3237. struct as {};
  3238. template<typename T, typename... Gs>
  3239. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  3240. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3241. }
  3242. template<typename T>
  3243. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3244. return Generators<T>(std::move(generator));
  3245. }
  3246. template<typename T, typename... Gs>
  3247. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3248. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3249. }
  3250. template<typename T, typename U, typename... Gs>
  3251. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3252. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3253. }
  3254. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3255. template<typename L>
  3256. // Note: The type after -> is weird, because VS2015 cannot parse
  3257. // the expression used in the typedef inside, when it is in
  3258. // return type. Yeah.
  3259. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3260. using UnderlyingType = typename decltype(generatorExpression())::type;
  3261. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3262. if (!tracker.hasGenerator()) {
  3263. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3264. }
  3265. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3266. return generator.get();
  3267. }
  3268. } // namespace Generators
  3269. } // namespace Catch
  3270. #define GENERATE( ... ) \
  3271. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3272. #define GENERATE_COPY( ... ) \
  3273. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3274. #define GENERATE_REF( ... ) \
  3275. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3276. // end catch_generators.hpp
  3277. // start catch_generators_generic.hpp
  3278. namespace Catch {
  3279. namespace Generators {
  3280. template <typename T>
  3281. class TakeGenerator : public IGenerator<T> {
  3282. GeneratorWrapper<T> m_generator;
  3283. size_t m_returned = 0;
  3284. size_t m_target;
  3285. public:
  3286. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3287. m_generator(std::move(generator)),
  3288. m_target(target)
  3289. {
  3290. assert(target != 0 && "Empty generators are not allowed");
  3291. }
  3292. T const& get() const override {
  3293. return m_generator.get();
  3294. }
  3295. bool next() override {
  3296. ++m_returned;
  3297. if (m_returned >= m_target) {
  3298. return false;
  3299. }
  3300. const auto success = m_generator.next();
  3301. // If the underlying generator does not contain enough values
  3302. // then we cut short as well
  3303. if (!success) {
  3304. m_returned = m_target;
  3305. }
  3306. return success;
  3307. }
  3308. };
  3309. template <typename T>
  3310. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3311. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3312. }
  3313. template <typename T, typename Predicate>
  3314. class FilterGenerator : public IGenerator<T> {
  3315. GeneratorWrapper<T> m_generator;
  3316. Predicate m_predicate;
  3317. public:
  3318. template <typename P = Predicate>
  3319. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3320. m_generator(std::move(generator)),
  3321. m_predicate(std::forward<P>(pred))
  3322. {
  3323. if (!m_predicate(m_generator.get())) {
  3324. // It might happen that there are no values that pass the
  3325. // filter. In that case we throw an exception.
  3326. auto has_initial_value = next();
  3327. if (!has_initial_value) {
  3328. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3329. }
  3330. }
  3331. }
  3332. T const& get() const override {
  3333. return m_generator.get();
  3334. }
  3335. bool next() override {
  3336. bool success = m_generator.next();
  3337. if (!success) {
  3338. return false;
  3339. }
  3340. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3341. return success;
  3342. }
  3343. };
  3344. template <typename T, typename Predicate>
  3345. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3346. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3347. }
  3348. template <typename T>
  3349. class RepeatGenerator : public IGenerator<T> {
  3350. GeneratorWrapper<T> m_generator;
  3351. mutable std::vector<T> m_returned;
  3352. size_t m_target_repeats;
  3353. size_t m_current_repeat = 0;
  3354. size_t m_repeat_index = 0;
  3355. public:
  3356. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3357. m_generator(std::move(generator)),
  3358. m_target_repeats(repeats)
  3359. {
  3360. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3361. }
  3362. T const& get() const override {
  3363. if (m_current_repeat == 0) {
  3364. m_returned.push_back(m_generator.get());
  3365. return m_returned.back();
  3366. }
  3367. return m_returned[m_repeat_index];
  3368. }
  3369. bool next() override {
  3370. // There are 2 basic cases:
  3371. // 1) We are still reading the generator
  3372. // 2) We are reading our own cache
  3373. // In the first case, we need to poke the underlying generator.
  3374. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3375. if (m_current_repeat == 0) {
  3376. const auto success = m_generator.next();
  3377. if (!success) {
  3378. ++m_current_repeat;
  3379. }
  3380. return m_current_repeat < m_target_repeats;
  3381. }
  3382. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3383. ++m_repeat_index;
  3384. if (m_repeat_index == m_returned.size()) {
  3385. m_repeat_index = 0;
  3386. ++m_current_repeat;
  3387. }
  3388. return m_current_repeat < m_target_repeats;
  3389. }
  3390. };
  3391. template <typename T>
  3392. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3393. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3394. }
  3395. template <typename T, typename U, typename Func>
  3396. class MapGenerator : public IGenerator<T> {
  3397. // TBD: provide static assert for mapping function, for friendly error message
  3398. GeneratorWrapper<U> m_generator;
  3399. Func m_function;
  3400. // To avoid returning dangling reference, we have to save the values
  3401. T m_cache;
  3402. public:
  3403. template <typename F2 = Func>
  3404. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3405. m_generator(std::move(generator)),
  3406. m_function(std::forward<F2>(function)),
  3407. m_cache(m_function(m_generator.get()))
  3408. {}
  3409. T const& get() const override {
  3410. return m_cache;
  3411. }
  3412. bool next() override {
  3413. const auto success = m_generator.next();
  3414. if (success) {
  3415. m_cache = m_function(m_generator.get());
  3416. }
  3417. return success;
  3418. }
  3419. };
  3420. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3421. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3422. // replaced with std::invoke_result here. Also *_t format is preferred over
  3423. // typename *::type format.
  3424. template <typename Func, typename U>
  3425. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3426. #else
  3427. template <typename Func, typename U>
  3428. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3429. #endif
  3430. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3431. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3432. return GeneratorWrapper<T>(
  3433. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3434. );
  3435. }
  3436. template <typename T, typename U, typename Func>
  3437. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3438. return GeneratorWrapper<T>(
  3439. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3440. );
  3441. }
  3442. template <typename T>
  3443. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3444. std::vector<T> m_chunk;
  3445. size_t m_chunk_size;
  3446. GeneratorWrapper<T> m_generator;
  3447. bool m_used_up = false;
  3448. public:
  3449. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3450. m_chunk_size(size), m_generator(std::move(generator))
  3451. {
  3452. m_chunk.reserve(m_chunk_size);
  3453. m_chunk.push_back(m_generator.get());
  3454. for (size_t i = 1; i < m_chunk_size; ++i) {
  3455. if (!m_generator.next()) {
  3456. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3457. }
  3458. m_chunk.push_back(m_generator.get());
  3459. }
  3460. }
  3461. std::vector<T> const& get() const override {
  3462. return m_chunk;
  3463. }
  3464. bool next() override {
  3465. m_chunk.clear();
  3466. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3467. if (!m_generator.next()) {
  3468. return false;
  3469. }
  3470. m_chunk.push_back(m_generator.get());
  3471. }
  3472. return true;
  3473. }
  3474. };
  3475. template <typename T>
  3476. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3477. return GeneratorWrapper<std::vector<T>>(
  3478. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3479. );
  3480. }
  3481. } // namespace Generators
  3482. } // namespace Catch
  3483. // end catch_generators_generic.hpp
  3484. // start catch_generators_specific.hpp
  3485. // start catch_context.h
  3486. #include <memory>
  3487. namespace Catch {
  3488. struct IResultCapture;
  3489. struct IRunner;
  3490. struct IConfig;
  3491. struct IMutableContext;
  3492. using IConfigPtr = std::shared_ptr<IConfig const>;
  3493. struct IContext
  3494. {
  3495. virtual ~IContext();
  3496. virtual IResultCapture* getResultCapture() = 0;
  3497. virtual IRunner* getRunner() = 0;
  3498. virtual IConfigPtr const& getConfig() const = 0;
  3499. };
  3500. struct IMutableContext : IContext
  3501. {
  3502. virtual ~IMutableContext();
  3503. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3504. virtual void setRunner( IRunner* runner ) = 0;
  3505. virtual void setConfig( IConfigPtr const& config ) = 0;
  3506. private:
  3507. static IMutableContext *currentContext;
  3508. friend IMutableContext& getCurrentMutableContext();
  3509. friend void cleanUpContext();
  3510. static void createContext();
  3511. };
  3512. inline IMutableContext& getCurrentMutableContext()
  3513. {
  3514. if( !IMutableContext::currentContext )
  3515. IMutableContext::createContext();
  3516. return *IMutableContext::currentContext;
  3517. }
  3518. inline IContext& getCurrentContext()
  3519. {
  3520. return getCurrentMutableContext();
  3521. }
  3522. void cleanUpContext();
  3523. }
  3524. // end catch_context.h
  3525. // start catch_interfaces_config.h
  3526. // start catch_option.hpp
  3527. namespace Catch {
  3528. // An optional type
  3529. template<typename T>
  3530. class Option {
  3531. public:
  3532. Option() : nullableValue( nullptr ) {}
  3533. Option( T const& _value )
  3534. : nullableValue( new( storage ) T( _value ) )
  3535. {}
  3536. Option( Option const& _other )
  3537. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3538. {}
  3539. ~Option() {
  3540. reset();
  3541. }
  3542. Option& operator= ( Option const& _other ) {
  3543. if( &_other != this ) {
  3544. reset();
  3545. if( _other )
  3546. nullableValue = new( storage ) T( *_other );
  3547. }
  3548. return *this;
  3549. }
  3550. Option& operator = ( T const& _value ) {
  3551. reset();
  3552. nullableValue = new( storage ) T( _value );
  3553. return *this;
  3554. }
  3555. void reset() {
  3556. if( nullableValue )
  3557. nullableValue->~T();
  3558. nullableValue = nullptr;
  3559. }
  3560. T& operator*() { return *nullableValue; }
  3561. T const& operator*() const { return *nullableValue; }
  3562. T* operator->() { return nullableValue; }
  3563. const T* operator->() const { return nullableValue; }
  3564. T valueOr( T const& defaultValue ) const {
  3565. return nullableValue ? *nullableValue : defaultValue;
  3566. }
  3567. bool some() const { return nullableValue != nullptr; }
  3568. bool none() const { return nullableValue == nullptr; }
  3569. bool operator !() const { return nullableValue == nullptr; }
  3570. explicit operator bool() const {
  3571. return some();
  3572. }
  3573. private:
  3574. T *nullableValue;
  3575. alignas(alignof(T)) char storage[sizeof(T)];
  3576. };
  3577. } // end namespace Catch
  3578. // end catch_option.hpp
  3579. #include <iosfwd>
  3580. #include <string>
  3581. #include <vector>
  3582. #include <memory>
  3583. namespace Catch {
  3584. enum class Verbosity {
  3585. Quiet = 0,
  3586. Normal,
  3587. High
  3588. };
  3589. struct WarnAbout { enum What {
  3590. Nothing = 0x00,
  3591. NoAssertions = 0x01,
  3592. NoTests = 0x02
  3593. }; };
  3594. struct ShowDurations { enum OrNot {
  3595. DefaultForReporter,
  3596. Always,
  3597. Never
  3598. }; };
  3599. struct RunTests { enum InWhatOrder {
  3600. InDeclarationOrder,
  3601. InLexicographicalOrder,
  3602. InRandomOrder
  3603. }; };
  3604. struct UseColour { enum YesOrNo {
  3605. Auto,
  3606. Yes,
  3607. No
  3608. }; };
  3609. struct WaitForKeypress { enum When {
  3610. Never,
  3611. BeforeStart = 1,
  3612. BeforeExit = 2,
  3613. BeforeStartAndExit = BeforeStart | BeforeExit
  3614. }; };
  3615. class TestSpec;
  3616. struct IConfig : NonCopyable {
  3617. virtual ~IConfig();
  3618. virtual bool allowThrows() const = 0;
  3619. virtual std::ostream& stream() const = 0;
  3620. virtual std::string name() const = 0;
  3621. virtual bool includeSuccessfulResults() const = 0;
  3622. virtual bool shouldDebugBreak() const = 0;
  3623. virtual bool warnAboutMissingAssertions() const = 0;
  3624. virtual bool warnAboutNoTests() const = 0;
  3625. virtual int abortAfter() const = 0;
  3626. virtual bool showInvisibles() const = 0;
  3627. virtual ShowDurations::OrNot showDurations() const = 0;
  3628. virtual TestSpec const& testSpec() const = 0;
  3629. virtual bool hasTestFilters() const = 0;
  3630. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3631. virtual RunTests::InWhatOrder runOrder() const = 0;
  3632. virtual unsigned int rngSeed() const = 0;
  3633. virtual UseColour::YesOrNo useColour() const = 0;
  3634. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3635. virtual Verbosity verbosity() const = 0;
  3636. virtual bool benchmarkNoAnalysis() const = 0;
  3637. virtual int benchmarkSamples() const = 0;
  3638. virtual double benchmarkConfidenceInterval() const = 0;
  3639. virtual unsigned int benchmarkResamples() const = 0;
  3640. };
  3641. using IConfigPtr = std::shared_ptr<IConfig const>;
  3642. }
  3643. // end catch_interfaces_config.h
  3644. #include <random>
  3645. namespace Catch {
  3646. namespace Generators {
  3647. template <typename Float>
  3648. class RandomFloatingGenerator final : public IGenerator<Float> {
  3649. // FIXME: What is the right seed?
  3650. std::minstd_rand m_rand;
  3651. std::uniform_real_distribution<Float> m_dist;
  3652. Float m_current_number;
  3653. public:
  3654. RandomFloatingGenerator(Float a, Float b):
  3655. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3656. m_dist(a, b) {
  3657. static_cast<void>(next());
  3658. }
  3659. Float const& get() const override {
  3660. return m_current_number;
  3661. }
  3662. bool next() override {
  3663. m_current_number = m_dist(m_rand);
  3664. return true;
  3665. }
  3666. };
  3667. template <typename Integer>
  3668. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3669. std::minstd_rand m_rand;
  3670. std::uniform_int_distribution<Integer> m_dist;
  3671. Integer m_current_number;
  3672. public:
  3673. RandomIntegerGenerator(Integer a, Integer b):
  3674. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3675. m_dist(a, b) {
  3676. static_cast<void>(next());
  3677. }
  3678. Integer const& get() const override {
  3679. return m_current_number;
  3680. }
  3681. bool next() override {
  3682. m_current_number = m_dist(m_rand);
  3683. return true;
  3684. }
  3685. };
  3686. // TODO: Ideally this would be also constrained against the various char types,
  3687. // but I don't expect users to run into that in practice.
  3688. template <typename T>
  3689. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3690. GeneratorWrapper<T>>::type
  3691. random(T a, T b) {
  3692. return GeneratorWrapper<T>(
  3693. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3694. );
  3695. }
  3696. template <typename T>
  3697. typename std::enable_if<std::is_floating_point<T>::value,
  3698. GeneratorWrapper<T>>::type
  3699. random(T a, T b) {
  3700. return GeneratorWrapper<T>(
  3701. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3702. );
  3703. }
  3704. template <typename T>
  3705. class RangeGenerator final : public IGenerator<T> {
  3706. T m_current;
  3707. T m_end;
  3708. T m_step;
  3709. bool m_positive;
  3710. public:
  3711. RangeGenerator(T const& start, T const& end, T const& step):
  3712. m_current(start),
  3713. m_end(end),
  3714. m_step(step),
  3715. m_positive(m_step > T(0))
  3716. {
  3717. assert(m_current != m_end && "Range start and end cannot be equal");
  3718. assert(m_step != T(0) && "Step size cannot be zero");
  3719. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3720. }
  3721. RangeGenerator(T const& start, T const& end):
  3722. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3723. {}
  3724. T const& get() const override {
  3725. return m_current;
  3726. }
  3727. bool next() override {
  3728. m_current += m_step;
  3729. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3730. }
  3731. };
  3732. template <typename T>
  3733. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3734. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3735. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3736. }
  3737. template <typename T>
  3738. GeneratorWrapper<T> range(T const& start, T const& end) {
  3739. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3740. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3741. }
  3742. } // namespace Generators
  3743. } // namespace Catch
  3744. // end catch_generators_specific.hpp
  3745. // These files are included here so the single_include script doesn't put them
  3746. // in the conditionally compiled sections
  3747. // start catch_test_case_info.h
  3748. #include <string>
  3749. #include <vector>
  3750. #include <memory>
  3751. #ifdef __clang__
  3752. #pragma clang diagnostic push
  3753. #pragma clang diagnostic ignored "-Wpadded"
  3754. #endif
  3755. namespace Catch {
  3756. struct ITestInvoker;
  3757. struct TestCaseInfo {
  3758. enum SpecialProperties{
  3759. None = 0,
  3760. IsHidden = 1 << 1,
  3761. ShouldFail = 1 << 2,
  3762. MayFail = 1 << 3,
  3763. Throws = 1 << 4,
  3764. NonPortable = 1 << 5,
  3765. Benchmark = 1 << 6
  3766. };
  3767. TestCaseInfo( std::string const& _name,
  3768. std::string const& _className,
  3769. std::string const& _description,
  3770. std::vector<std::string> const& _tags,
  3771. SourceLineInfo const& _lineInfo );
  3772. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3773. bool isHidden() const;
  3774. bool throws() const;
  3775. bool okToFail() const;
  3776. bool expectedToFail() const;
  3777. std::string tagsAsString() const;
  3778. std::string name;
  3779. std::string className;
  3780. std::string description;
  3781. std::vector<std::string> tags;
  3782. std::vector<std::string> lcaseTags;
  3783. SourceLineInfo lineInfo;
  3784. SpecialProperties properties;
  3785. };
  3786. class TestCase : public TestCaseInfo {
  3787. public:
  3788. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3789. TestCase withName( std::string const& _newName ) const;
  3790. void invoke() const;
  3791. TestCaseInfo const& getTestCaseInfo() const;
  3792. bool operator == ( TestCase const& other ) const;
  3793. bool operator < ( TestCase const& other ) const;
  3794. private:
  3795. std::shared_ptr<ITestInvoker> test;
  3796. };
  3797. TestCase makeTestCase( ITestInvoker* testCase,
  3798. std::string const& className,
  3799. NameAndTags const& nameAndTags,
  3800. SourceLineInfo const& lineInfo );
  3801. }
  3802. #ifdef __clang__
  3803. #pragma clang diagnostic pop
  3804. #endif
  3805. // end catch_test_case_info.h
  3806. // start catch_interfaces_runner.h
  3807. namespace Catch {
  3808. struct IRunner {
  3809. virtual ~IRunner();
  3810. virtual bool aborting() const = 0;
  3811. };
  3812. }
  3813. // end catch_interfaces_runner.h
  3814. #ifdef __OBJC__
  3815. // start catch_objc.hpp
  3816. #import <objc/runtime.h>
  3817. #include <string>
  3818. // NB. Any general catch headers included here must be included
  3819. // in catch.hpp first to make sure they are included by the single
  3820. // header for non obj-usage
  3821. ///////////////////////////////////////////////////////////////////////////////
  3822. // This protocol is really only here for (self) documenting purposes, since
  3823. // all its methods are optional.
  3824. @protocol OcFixture
  3825. @optional
  3826. -(void) setUp;
  3827. -(void) tearDown;
  3828. @end
  3829. namespace Catch {
  3830. class OcMethod : public ITestInvoker {
  3831. public:
  3832. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3833. virtual void invoke() const {
  3834. id obj = [[m_cls alloc] init];
  3835. performOptionalSelector( obj, @selector(setUp) );
  3836. performOptionalSelector( obj, m_sel );
  3837. performOptionalSelector( obj, @selector(tearDown) );
  3838. arcSafeRelease( obj );
  3839. }
  3840. private:
  3841. virtual ~OcMethod() {}
  3842. Class m_cls;
  3843. SEL m_sel;
  3844. };
  3845. namespace Detail{
  3846. inline std::string getAnnotation( Class cls,
  3847. std::string const& annotationName,
  3848. std::string const& testCaseName ) {
  3849. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3850. SEL sel = NSSelectorFromString( selStr );
  3851. arcSafeRelease( selStr );
  3852. id value = performOptionalSelector( cls, sel );
  3853. if( value )
  3854. return [(NSString*)value UTF8String];
  3855. return "";
  3856. }
  3857. }
  3858. inline std::size_t registerTestMethods() {
  3859. std::size_t noTestMethods = 0;
  3860. int noClasses = objc_getClassList( nullptr, 0 );
  3861. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3862. objc_getClassList( classes, noClasses );
  3863. for( int c = 0; c < noClasses; c++ ) {
  3864. Class cls = classes[c];
  3865. {
  3866. u_int count;
  3867. Method* methods = class_copyMethodList( cls, &count );
  3868. for( u_int m = 0; m < count ; m++ ) {
  3869. SEL selector = method_getName(methods[m]);
  3870. std::string methodName = sel_getName(selector);
  3871. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3872. std::string testCaseName = methodName.substr( 15 );
  3873. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3874. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3875. const char* className = class_getName( cls );
  3876. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3877. noTestMethods++;
  3878. }
  3879. }
  3880. free(methods);
  3881. }
  3882. }
  3883. return noTestMethods;
  3884. }
  3885. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3886. namespace Matchers {
  3887. namespace Impl {
  3888. namespace NSStringMatchers {
  3889. struct StringHolder : MatcherBase<NSString*>{
  3890. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3891. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3892. StringHolder() {
  3893. arcSafeRelease( m_substr );
  3894. }
  3895. bool match( NSString* const& str ) const override {
  3896. return false;
  3897. }
  3898. NSString* CATCH_ARC_STRONG m_substr;
  3899. };
  3900. struct Equals : StringHolder {
  3901. Equals( NSString* substr ) : StringHolder( substr ){}
  3902. bool match( NSString* const& str ) const override {
  3903. return (str != nil || m_substr == nil ) &&
  3904. [str isEqualToString:m_substr];
  3905. }
  3906. std::string describe() const override {
  3907. return "equals string: " + Catch::Detail::stringify( m_substr );
  3908. }
  3909. };
  3910. struct Contains : StringHolder {
  3911. Contains( NSString* substr ) : StringHolder( substr ){}
  3912. bool match( NSString* const& str ) const override {
  3913. return (str != nil || m_substr == nil ) &&
  3914. [str rangeOfString:m_substr].location != NSNotFound;
  3915. }
  3916. std::string describe() const override {
  3917. return "contains string: " + Catch::Detail::stringify( m_substr );
  3918. }
  3919. };
  3920. struct StartsWith : StringHolder {
  3921. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3922. bool match( NSString* const& str ) const override {
  3923. return (str != nil || m_substr == nil ) &&
  3924. [str rangeOfString:m_substr].location == 0;
  3925. }
  3926. std::string describe() const override {
  3927. return "starts with: " + Catch::Detail::stringify( m_substr );
  3928. }
  3929. };
  3930. struct EndsWith : StringHolder {
  3931. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3932. bool match( NSString* const& str ) const override {
  3933. return (str != nil || m_substr == nil ) &&
  3934. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3935. }
  3936. std::string describe() const override {
  3937. return "ends with: " + Catch::Detail::stringify( m_substr );
  3938. }
  3939. };
  3940. } // namespace NSStringMatchers
  3941. } // namespace Impl
  3942. inline Impl::NSStringMatchers::Equals
  3943. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3944. inline Impl::NSStringMatchers::Contains
  3945. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3946. inline Impl::NSStringMatchers::StartsWith
  3947. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3948. inline Impl::NSStringMatchers::EndsWith
  3949. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3950. } // namespace Matchers
  3951. using namespace Matchers;
  3952. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3953. } // namespace Catch
  3954. ///////////////////////////////////////////////////////////////////////////////
  3955. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3956. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3957. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3958. { \
  3959. return @ name; \
  3960. } \
  3961. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3962. { \
  3963. return @ desc; \
  3964. } \
  3965. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3966. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3967. // end catch_objc.hpp
  3968. #endif
  3969. // Benchmarking needs the externally-facing parts of reporters to work
  3970. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  3971. // start catch_external_interfaces.h
  3972. // start catch_reporter_bases.hpp
  3973. // start catch_interfaces_reporter.h
  3974. // start catch_config.hpp
  3975. // start catch_test_spec_parser.h
  3976. #ifdef __clang__
  3977. #pragma clang diagnostic push
  3978. #pragma clang diagnostic ignored "-Wpadded"
  3979. #endif
  3980. // start catch_test_spec.h
  3981. #ifdef __clang__
  3982. #pragma clang diagnostic push
  3983. #pragma clang diagnostic ignored "-Wpadded"
  3984. #endif
  3985. // start catch_wildcard_pattern.h
  3986. namespace Catch
  3987. {
  3988. class WildcardPattern {
  3989. enum WildcardPosition {
  3990. NoWildcard = 0,
  3991. WildcardAtStart = 1,
  3992. WildcardAtEnd = 2,
  3993. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3994. };
  3995. public:
  3996. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3997. virtual ~WildcardPattern() = default;
  3998. virtual bool matches( std::string const& str ) const;
  3999. private:
  4000. std::string adjustCase( std::string const& str ) const;
  4001. CaseSensitive::Choice m_caseSensitivity;
  4002. WildcardPosition m_wildcard = NoWildcard;
  4003. std::string m_pattern;
  4004. };
  4005. }
  4006. // end catch_wildcard_pattern.h
  4007. #include <string>
  4008. #include <vector>
  4009. #include <memory>
  4010. namespace Catch {
  4011. class TestSpec {
  4012. struct Pattern {
  4013. virtual ~Pattern();
  4014. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4015. };
  4016. using PatternPtr = std::shared_ptr<Pattern>;
  4017. class NamePattern : public Pattern {
  4018. public:
  4019. NamePattern( std::string const& name );
  4020. virtual ~NamePattern();
  4021. bool matches( TestCaseInfo const& testCase ) const override;
  4022. private:
  4023. WildcardPattern m_wildcardPattern;
  4024. };
  4025. class TagPattern : public Pattern {
  4026. public:
  4027. TagPattern( std::string const& tag );
  4028. virtual ~TagPattern();
  4029. bool matches( TestCaseInfo const& testCase ) const override;
  4030. private:
  4031. std::string m_tag;
  4032. };
  4033. class ExcludedPattern : public Pattern {
  4034. public:
  4035. ExcludedPattern( PatternPtr const& underlyingPattern );
  4036. virtual ~ExcludedPattern();
  4037. bool matches( TestCaseInfo const& testCase ) const override;
  4038. private:
  4039. PatternPtr m_underlyingPattern;
  4040. };
  4041. struct Filter {
  4042. std::vector<PatternPtr> m_patterns;
  4043. bool matches( TestCaseInfo const& testCase ) const;
  4044. };
  4045. public:
  4046. bool hasFilters() const;
  4047. bool matches( TestCaseInfo const& testCase ) const;
  4048. private:
  4049. std::vector<Filter> m_filters;
  4050. friend class TestSpecParser;
  4051. };
  4052. }
  4053. #ifdef __clang__
  4054. #pragma clang diagnostic pop
  4055. #endif
  4056. // end catch_test_spec.h
  4057. // start catch_interfaces_tag_alias_registry.h
  4058. #include <string>
  4059. namespace Catch {
  4060. struct TagAlias;
  4061. struct ITagAliasRegistry {
  4062. virtual ~ITagAliasRegistry();
  4063. // Nullptr if not present
  4064. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4065. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4066. static ITagAliasRegistry const& get();
  4067. };
  4068. } // end namespace Catch
  4069. // end catch_interfaces_tag_alias_registry.h
  4070. namespace Catch {
  4071. class TestSpecParser {
  4072. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4073. Mode m_mode = None;
  4074. bool m_exclusion = false;
  4075. std::size_t m_start = std::string::npos, m_pos = 0;
  4076. std::string m_arg;
  4077. std::vector<std::size_t> m_escapeChars;
  4078. TestSpec::Filter m_currentFilter;
  4079. TestSpec m_testSpec;
  4080. ITagAliasRegistry const* m_tagAliases = nullptr;
  4081. public:
  4082. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4083. TestSpecParser& parse( std::string const& arg );
  4084. TestSpec testSpec();
  4085. private:
  4086. void visitChar( char c );
  4087. void startNewMode( Mode mode, std::size_t start );
  4088. void escape();
  4089. std::string subString() const;
  4090. template<typename T>
  4091. void addPattern() {
  4092. std::string token = subString();
  4093. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  4094. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  4095. m_escapeChars.clear();
  4096. if( startsWith( token, "exclude:" ) ) {
  4097. m_exclusion = true;
  4098. token = token.substr( 8 );
  4099. }
  4100. if( !token.empty() ) {
  4101. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  4102. if( m_exclusion )
  4103. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  4104. m_currentFilter.m_patterns.push_back( pattern );
  4105. }
  4106. m_exclusion = false;
  4107. m_mode = None;
  4108. }
  4109. void addFilter();
  4110. };
  4111. TestSpec parseTestSpec( std::string const& arg );
  4112. } // namespace Catch
  4113. #ifdef __clang__
  4114. #pragma clang diagnostic pop
  4115. #endif
  4116. // end catch_test_spec_parser.h
  4117. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4118. #include <memory>
  4119. #include <vector>
  4120. #include <string>
  4121. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4122. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4123. #endif
  4124. namespace Catch {
  4125. struct IStream;
  4126. struct ConfigData {
  4127. bool listTests = false;
  4128. bool listTags = false;
  4129. bool listReporters = false;
  4130. bool listTestNamesOnly = false;
  4131. bool showSuccessfulTests = false;
  4132. bool shouldDebugBreak = false;
  4133. bool noThrow = false;
  4134. bool showHelp = false;
  4135. bool showInvisibles = false;
  4136. bool filenamesAsTags = false;
  4137. bool libIdentify = false;
  4138. int abortAfter = -1;
  4139. unsigned int rngSeed = 0;
  4140. bool benchmarkNoAnalysis = false;
  4141. unsigned int benchmarkSamples = 100;
  4142. double benchmarkConfidenceInterval = 0.95;
  4143. unsigned int benchmarkResamples = 100000;
  4144. Verbosity verbosity = Verbosity::Normal;
  4145. WarnAbout::What warnings = WarnAbout::Nothing;
  4146. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4147. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4148. UseColour::YesOrNo useColour = UseColour::Auto;
  4149. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4150. std::string outputFilename;
  4151. std::string name;
  4152. std::string processName;
  4153. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4154. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4155. #endif
  4156. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4157. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4158. std::vector<std::string> testsOrTags;
  4159. std::vector<std::string> sectionsToRun;
  4160. };
  4161. class Config : public IConfig {
  4162. public:
  4163. Config() = default;
  4164. Config( ConfigData const& data );
  4165. virtual ~Config() = default;
  4166. std::string const& getFilename() const;
  4167. bool listTests() const;
  4168. bool listTestNamesOnly() const;
  4169. bool listTags() const;
  4170. bool listReporters() const;
  4171. std::string getProcessName() const;
  4172. std::string const& getReporterName() const;
  4173. std::vector<std::string> const& getTestsOrTags() const override;
  4174. std::vector<std::string> const& getSectionsToRun() const override;
  4175. TestSpec const& testSpec() const override;
  4176. bool hasTestFilters() const override;
  4177. bool showHelp() const;
  4178. // IConfig interface
  4179. bool allowThrows() const override;
  4180. std::ostream& stream() const override;
  4181. std::string name() const override;
  4182. bool includeSuccessfulResults() const override;
  4183. bool warnAboutMissingAssertions() const override;
  4184. bool warnAboutNoTests() const override;
  4185. ShowDurations::OrNot showDurations() const override;
  4186. RunTests::InWhatOrder runOrder() const override;
  4187. unsigned int rngSeed() const override;
  4188. UseColour::YesOrNo useColour() const override;
  4189. bool shouldDebugBreak() const override;
  4190. int abortAfter() const override;
  4191. bool showInvisibles() const override;
  4192. Verbosity verbosity() const override;
  4193. bool benchmarkNoAnalysis() const override;
  4194. int benchmarkSamples() const override;
  4195. double benchmarkConfidenceInterval() const override;
  4196. unsigned int benchmarkResamples() const override;
  4197. private:
  4198. IStream const* openStream();
  4199. ConfigData m_data;
  4200. std::unique_ptr<IStream const> m_stream;
  4201. TestSpec m_testSpec;
  4202. bool m_hasTestFilters = false;
  4203. };
  4204. } // end namespace Catch
  4205. // end catch_config.hpp
  4206. // start catch_assertionresult.h
  4207. #include <string>
  4208. namespace Catch {
  4209. struct AssertionResultData
  4210. {
  4211. AssertionResultData() = delete;
  4212. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4213. std::string message;
  4214. mutable std::string reconstructedExpression;
  4215. LazyExpression lazyExpression;
  4216. ResultWas::OfType resultType;
  4217. std::string reconstructExpression() const;
  4218. };
  4219. class AssertionResult {
  4220. public:
  4221. AssertionResult() = delete;
  4222. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4223. bool isOk() const;
  4224. bool succeeded() const;
  4225. ResultWas::OfType getResultType() const;
  4226. bool hasExpression() const;
  4227. bool hasMessage() const;
  4228. std::string getExpression() const;
  4229. std::string getExpressionInMacro() const;
  4230. bool hasExpandedExpression() const;
  4231. std::string getExpandedExpression() const;
  4232. std::string getMessage() const;
  4233. SourceLineInfo getSourceInfo() const;
  4234. StringRef getTestMacroName() const;
  4235. //protected:
  4236. AssertionInfo m_info;
  4237. AssertionResultData m_resultData;
  4238. };
  4239. } // end namespace Catch
  4240. // end catch_assertionresult.h
  4241. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4242. // start catch_estimate.hpp
  4243. // Statistics estimates
  4244. namespace Catch {
  4245. namespace Benchmark {
  4246. template <typename Duration>
  4247. struct Estimate {
  4248. Duration point;
  4249. Duration lower_bound;
  4250. Duration upper_bound;
  4251. double confidence_interval;
  4252. template <typename Duration2>
  4253. operator Estimate<Duration2>() const {
  4254. return { point, lower_bound, upper_bound, confidence_interval };
  4255. }
  4256. };
  4257. } // namespace Benchmark
  4258. } // namespace Catch
  4259. // end catch_estimate.hpp
  4260. // start catch_outlier_classification.hpp
  4261. // Outlier information
  4262. namespace Catch {
  4263. namespace Benchmark {
  4264. struct OutlierClassification {
  4265. int samples_seen = 0;
  4266. int low_severe = 0; // more than 3 times IQR below Q1
  4267. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4268. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4269. int high_severe = 0; // more than 3 times IQR above Q3
  4270. int total() const {
  4271. return low_severe + low_mild + high_mild + high_severe;
  4272. }
  4273. };
  4274. } // namespace Benchmark
  4275. } // namespace Catch
  4276. // end catch_outlier_classification.hpp
  4277. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4278. #include <string>
  4279. #include <iosfwd>
  4280. #include <map>
  4281. #include <set>
  4282. #include <memory>
  4283. #include <algorithm>
  4284. namespace Catch {
  4285. struct ReporterConfig {
  4286. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4287. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4288. std::ostream& stream() const;
  4289. IConfigPtr fullConfig() const;
  4290. private:
  4291. std::ostream* m_stream;
  4292. IConfigPtr m_fullConfig;
  4293. };
  4294. struct ReporterPreferences {
  4295. bool shouldRedirectStdOut = false;
  4296. bool shouldReportAllAssertions = false;
  4297. };
  4298. template<typename T>
  4299. struct LazyStat : Option<T> {
  4300. LazyStat& operator=( T const& _value ) {
  4301. Option<T>::operator=( _value );
  4302. used = false;
  4303. return *this;
  4304. }
  4305. void reset() {
  4306. Option<T>::reset();
  4307. used = false;
  4308. }
  4309. bool used = false;
  4310. };
  4311. struct TestRunInfo {
  4312. TestRunInfo( std::string const& _name );
  4313. std::string name;
  4314. };
  4315. struct GroupInfo {
  4316. GroupInfo( std::string const& _name,
  4317. std::size_t _groupIndex,
  4318. std::size_t _groupsCount );
  4319. std::string name;
  4320. std::size_t groupIndex;
  4321. std::size_t groupsCounts;
  4322. };
  4323. struct AssertionStats {
  4324. AssertionStats( AssertionResult const& _assertionResult,
  4325. std::vector<MessageInfo> const& _infoMessages,
  4326. Totals const& _totals );
  4327. AssertionStats( AssertionStats const& ) = default;
  4328. AssertionStats( AssertionStats && ) = default;
  4329. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4330. AssertionStats& operator = ( AssertionStats && ) = delete;
  4331. virtual ~AssertionStats();
  4332. AssertionResult assertionResult;
  4333. std::vector<MessageInfo> infoMessages;
  4334. Totals totals;
  4335. };
  4336. struct SectionStats {
  4337. SectionStats( SectionInfo const& _sectionInfo,
  4338. Counts const& _assertions,
  4339. double _durationInSeconds,
  4340. bool _missingAssertions );
  4341. SectionStats( SectionStats const& ) = default;
  4342. SectionStats( SectionStats && ) = default;
  4343. SectionStats& operator = ( SectionStats const& ) = default;
  4344. SectionStats& operator = ( SectionStats && ) = default;
  4345. virtual ~SectionStats();
  4346. SectionInfo sectionInfo;
  4347. Counts assertions;
  4348. double durationInSeconds;
  4349. bool missingAssertions;
  4350. };
  4351. struct TestCaseStats {
  4352. TestCaseStats( TestCaseInfo const& _testInfo,
  4353. Totals const& _totals,
  4354. std::string const& _stdOut,
  4355. std::string const& _stdErr,
  4356. bool _aborting );
  4357. TestCaseStats( TestCaseStats const& ) = default;
  4358. TestCaseStats( TestCaseStats && ) = default;
  4359. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4360. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4361. virtual ~TestCaseStats();
  4362. TestCaseInfo testInfo;
  4363. Totals totals;
  4364. std::string stdOut;
  4365. std::string stdErr;
  4366. bool aborting;
  4367. };
  4368. struct TestGroupStats {
  4369. TestGroupStats( GroupInfo const& _groupInfo,
  4370. Totals const& _totals,
  4371. bool _aborting );
  4372. TestGroupStats( GroupInfo const& _groupInfo );
  4373. TestGroupStats( TestGroupStats const& ) = default;
  4374. TestGroupStats( TestGroupStats && ) = default;
  4375. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4376. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4377. virtual ~TestGroupStats();
  4378. GroupInfo groupInfo;
  4379. Totals totals;
  4380. bool aborting;
  4381. };
  4382. struct TestRunStats {
  4383. TestRunStats( TestRunInfo const& _runInfo,
  4384. Totals const& _totals,
  4385. bool _aborting );
  4386. TestRunStats( TestRunStats const& ) = default;
  4387. TestRunStats( TestRunStats && ) = default;
  4388. TestRunStats& operator = ( TestRunStats const& ) = default;
  4389. TestRunStats& operator = ( TestRunStats && ) = default;
  4390. virtual ~TestRunStats();
  4391. TestRunInfo runInfo;
  4392. Totals totals;
  4393. bool aborting;
  4394. };
  4395. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4396. struct BenchmarkInfo {
  4397. std::string name;
  4398. double estimatedDuration;
  4399. int iterations;
  4400. int samples;
  4401. unsigned int resamples;
  4402. double clockResolution;
  4403. double clockCost;
  4404. };
  4405. template <class Duration>
  4406. struct BenchmarkStats {
  4407. BenchmarkInfo info;
  4408. std::vector<Duration> samples;
  4409. Benchmark::Estimate<Duration> mean;
  4410. Benchmark::Estimate<Duration> standardDeviation;
  4411. Benchmark::OutlierClassification outliers;
  4412. double outlierVariance;
  4413. template <typename Duration2>
  4414. operator BenchmarkStats<Duration2>() const {
  4415. std::vector<Duration2> samples2;
  4416. samples2.reserve(samples.size());
  4417. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4418. return {
  4419. info,
  4420. std::move(samples2),
  4421. mean,
  4422. standardDeviation,
  4423. outliers,
  4424. outlierVariance,
  4425. };
  4426. }
  4427. };
  4428. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4429. struct IStreamingReporter {
  4430. virtual ~IStreamingReporter() = default;
  4431. // Implementing class must also provide the following static methods:
  4432. // static std::string getDescription();
  4433. // static std::set<Verbosity> getSupportedVerbosities()
  4434. virtual ReporterPreferences getPreferences() const = 0;
  4435. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4436. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4437. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4438. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4439. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4440. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4441. virtual void benchmarkPreparing( std::string const& ) {}
  4442. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4443. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4444. virtual void benchmarkFailed( std::string const& ) {}
  4445. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4446. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4447. // The return value indicates if the messages buffer should be cleared:
  4448. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4449. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4450. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4451. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4452. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4453. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4454. // Default empty implementation provided
  4455. virtual void fatalErrorEncountered( StringRef name );
  4456. virtual bool isMulti() const;
  4457. };
  4458. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4459. struct IReporterFactory {
  4460. virtual ~IReporterFactory();
  4461. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4462. virtual std::string getDescription() const = 0;
  4463. };
  4464. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4465. struct IReporterRegistry {
  4466. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4467. using Listeners = std::vector<IReporterFactoryPtr>;
  4468. virtual ~IReporterRegistry();
  4469. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4470. virtual FactoryMap const& getFactories() const = 0;
  4471. virtual Listeners const& getListeners() const = 0;
  4472. };
  4473. } // end namespace Catch
  4474. // end catch_interfaces_reporter.h
  4475. #include <algorithm>
  4476. #include <cstring>
  4477. #include <cfloat>
  4478. #include <cstdio>
  4479. #include <cassert>
  4480. #include <memory>
  4481. #include <ostream>
  4482. namespace Catch {
  4483. void prepareExpandedExpression(AssertionResult& result);
  4484. // Returns double formatted as %.3f (format expected on output)
  4485. std::string getFormattedDuration( double duration );
  4486. std::string serializeFilters( std::vector<std::string> const& container );
  4487. template<typename DerivedT>
  4488. struct StreamingReporterBase : IStreamingReporter {
  4489. StreamingReporterBase( ReporterConfig const& _config )
  4490. : m_config( _config.fullConfig() ),
  4491. stream( _config.stream() )
  4492. {
  4493. m_reporterPrefs.shouldRedirectStdOut = false;
  4494. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4495. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4496. }
  4497. ReporterPreferences getPreferences() const override {
  4498. return m_reporterPrefs;
  4499. }
  4500. static std::set<Verbosity> getSupportedVerbosities() {
  4501. return { Verbosity::Normal };
  4502. }
  4503. ~StreamingReporterBase() override = default;
  4504. void noMatchingTestCases(std::string const&) override {}
  4505. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4506. currentTestRunInfo = _testRunInfo;
  4507. }
  4508. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4509. currentGroupInfo = _groupInfo;
  4510. }
  4511. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4512. currentTestCaseInfo = _testInfo;
  4513. }
  4514. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4515. m_sectionStack.push_back(_sectionInfo);
  4516. }
  4517. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4518. m_sectionStack.pop_back();
  4519. }
  4520. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4521. currentTestCaseInfo.reset();
  4522. }
  4523. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4524. currentGroupInfo.reset();
  4525. }
  4526. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4527. currentTestCaseInfo.reset();
  4528. currentGroupInfo.reset();
  4529. currentTestRunInfo.reset();
  4530. }
  4531. void skipTest(TestCaseInfo const&) override {
  4532. // Don't do anything with this by default.
  4533. // It can optionally be overridden in the derived class.
  4534. }
  4535. IConfigPtr m_config;
  4536. std::ostream& stream;
  4537. LazyStat<TestRunInfo> currentTestRunInfo;
  4538. LazyStat<GroupInfo> currentGroupInfo;
  4539. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4540. std::vector<SectionInfo> m_sectionStack;
  4541. ReporterPreferences m_reporterPrefs;
  4542. };
  4543. template<typename DerivedT>
  4544. struct CumulativeReporterBase : IStreamingReporter {
  4545. template<typename T, typename ChildNodeT>
  4546. struct Node {
  4547. explicit Node( T const& _value ) : value( _value ) {}
  4548. virtual ~Node() {}
  4549. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4550. T value;
  4551. ChildNodes children;
  4552. };
  4553. struct SectionNode {
  4554. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4555. virtual ~SectionNode() = default;
  4556. bool operator == (SectionNode const& other) const {
  4557. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4558. }
  4559. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4560. return operator==(*other);
  4561. }
  4562. SectionStats stats;
  4563. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4564. using Assertions = std::vector<AssertionStats>;
  4565. ChildSections childSections;
  4566. Assertions assertions;
  4567. std::string stdOut;
  4568. std::string stdErr;
  4569. };
  4570. struct BySectionInfo {
  4571. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4572. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4573. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4574. return ((node->stats.sectionInfo.name == m_other.name) &&
  4575. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4576. }
  4577. void operator=(BySectionInfo const&) = delete;
  4578. private:
  4579. SectionInfo const& m_other;
  4580. };
  4581. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4582. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4583. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4584. CumulativeReporterBase( ReporterConfig const& _config )
  4585. : m_config( _config.fullConfig() ),
  4586. stream( _config.stream() )
  4587. {
  4588. m_reporterPrefs.shouldRedirectStdOut = false;
  4589. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4590. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4591. }
  4592. ~CumulativeReporterBase() override = default;
  4593. ReporterPreferences getPreferences() const override {
  4594. return m_reporterPrefs;
  4595. }
  4596. static std::set<Verbosity> getSupportedVerbosities() {
  4597. return { Verbosity::Normal };
  4598. }
  4599. void testRunStarting( TestRunInfo const& ) override {}
  4600. void testGroupStarting( GroupInfo const& ) override {}
  4601. void testCaseStarting( TestCaseInfo const& ) override {}
  4602. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4603. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4604. std::shared_ptr<SectionNode> node;
  4605. if( m_sectionStack.empty() ) {
  4606. if( !m_rootSection )
  4607. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4608. node = m_rootSection;
  4609. }
  4610. else {
  4611. SectionNode& parentNode = *m_sectionStack.back();
  4612. auto it =
  4613. std::find_if( parentNode.childSections.begin(),
  4614. parentNode.childSections.end(),
  4615. BySectionInfo( sectionInfo ) );
  4616. if( it == parentNode.childSections.end() ) {
  4617. node = std::make_shared<SectionNode>( incompleteStats );
  4618. parentNode.childSections.push_back( node );
  4619. }
  4620. else
  4621. node = *it;
  4622. }
  4623. m_sectionStack.push_back( node );
  4624. m_deepestSection = std::move(node);
  4625. }
  4626. void assertionStarting(AssertionInfo const&) override {}
  4627. bool assertionEnded(AssertionStats const& assertionStats) override {
  4628. assert(!m_sectionStack.empty());
  4629. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4630. // which getExpandedExpression() calls to build the expression string.
  4631. // Our section stack copy of the assertionResult will likely outlive the
  4632. // temporary, so it must be expanded or discarded now to avoid calling
  4633. // a destroyed object later.
  4634. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4635. SectionNode& sectionNode = *m_sectionStack.back();
  4636. sectionNode.assertions.push_back(assertionStats);
  4637. return true;
  4638. }
  4639. void sectionEnded(SectionStats const& sectionStats) override {
  4640. assert(!m_sectionStack.empty());
  4641. SectionNode& node = *m_sectionStack.back();
  4642. node.stats = sectionStats;
  4643. m_sectionStack.pop_back();
  4644. }
  4645. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4646. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4647. assert(m_sectionStack.size() == 0);
  4648. node->children.push_back(m_rootSection);
  4649. m_testCases.push_back(node);
  4650. m_rootSection.reset();
  4651. assert(m_deepestSection);
  4652. m_deepestSection->stdOut = testCaseStats.stdOut;
  4653. m_deepestSection->stdErr = testCaseStats.stdErr;
  4654. }
  4655. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4656. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4657. node->children.swap(m_testCases);
  4658. m_testGroups.push_back(node);
  4659. }
  4660. void testRunEnded(TestRunStats const& testRunStats) override {
  4661. auto node = std::make_shared<TestRunNode>(testRunStats);
  4662. node->children.swap(m_testGroups);
  4663. m_testRuns.push_back(node);
  4664. testRunEndedCumulative();
  4665. }
  4666. virtual void testRunEndedCumulative() = 0;
  4667. void skipTest(TestCaseInfo const&) override {}
  4668. IConfigPtr m_config;
  4669. std::ostream& stream;
  4670. std::vector<AssertionStats> m_assertions;
  4671. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4672. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4673. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4674. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4675. std::shared_ptr<SectionNode> m_rootSection;
  4676. std::shared_ptr<SectionNode> m_deepestSection;
  4677. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4678. ReporterPreferences m_reporterPrefs;
  4679. };
  4680. template<char C>
  4681. char const* getLineOfChars() {
  4682. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4683. if( !*line ) {
  4684. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4685. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4686. }
  4687. return line;
  4688. }
  4689. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4690. TestEventListenerBase( ReporterConfig const& _config );
  4691. static std::set<Verbosity> getSupportedVerbosities();
  4692. void assertionStarting(AssertionInfo const&) override;
  4693. bool assertionEnded(AssertionStats const&) override;
  4694. };
  4695. } // end namespace Catch
  4696. // end catch_reporter_bases.hpp
  4697. // start catch_console_colour.h
  4698. namespace Catch {
  4699. struct Colour {
  4700. enum Code {
  4701. None = 0,
  4702. White,
  4703. Red,
  4704. Green,
  4705. Blue,
  4706. Cyan,
  4707. Yellow,
  4708. Grey,
  4709. Bright = 0x10,
  4710. BrightRed = Bright | Red,
  4711. BrightGreen = Bright | Green,
  4712. LightGrey = Bright | Grey,
  4713. BrightWhite = Bright | White,
  4714. BrightYellow = Bright | Yellow,
  4715. // By intention
  4716. FileName = LightGrey,
  4717. Warning = BrightYellow,
  4718. ResultError = BrightRed,
  4719. ResultSuccess = BrightGreen,
  4720. ResultExpectedFailure = Warning,
  4721. Error = BrightRed,
  4722. Success = Green,
  4723. OriginalExpression = Cyan,
  4724. ReconstructedExpression = BrightYellow,
  4725. SecondaryText = LightGrey,
  4726. Headers = White
  4727. };
  4728. // Use constructed object for RAII guard
  4729. Colour( Code _colourCode );
  4730. Colour( Colour&& other ) noexcept;
  4731. Colour& operator=( Colour&& other ) noexcept;
  4732. ~Colour();
  4733. // Use static method for one-shot changes
  4734. static void use( Code _colourCode );
  4735. private:
  4736. bool m_moved = false;
  4737. };
  4738. std::ostream& operator << ( std::ostream& os, Colour const& );
  4739. } // end namespace Catch
  4740. // end catch_console_colour.h
  4741. // start catch_reporter_registrars.hpp
  4742. namespace Catch {
  4743. template<typename T>
  4744. class ReporterRegistrar {
  4745. class ReporterFactory : public IReporterFactory {
  4746. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4747. return std::unique_ptr<T>( new T( config ) );
  4748. }
  4749. std::string getDescription() const override {
  4750. return T::getDescription();
  4751. }
  4752. };
  4753. public:
  4754. explicit ReporterRegistrar( std::string const& name ) {
  4755. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4756. }
  4757. };
  4758. template<typename T>
  4759. class ListenerRegistrar {
  4760. class ListenerFactory : public IReporterFactory {
  4761. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4762. return std::unique_ptr<T>( new T( config ) );
  4763. }
  4764. std::string getDescription() const override {
  4765. return std::string();
  4766. }
  4767. };
  4768. public:
  4769. ListenerRegistrar() {
  4770. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4771. }
  4772. };
  4773. }
  4774. #if !defined(CATCH_CONFIG_DISABLE)
  4775. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4776. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4777. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4778. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4779. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4780. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4781. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4782. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4783. #else // CATCH_CONFIG_DISABLE
  4784. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4785. #define CATCH_REGISTER_LISTENER(listenerType)
  4786. #endif // CATCH_CONFIG_DISABLE
  4787. // end catch_reporter_registrars.hpp
  4788. // Allow users to base their work off existing reporters
  4789. // start catch_reporter_compact.h
  4790. namespace Catch {
  4791. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4792. using StreamingReporterBase::StreamingReporterBase;
  4793. ~CompactReporter() override;
  4794. static std::string getDescription();
  4795. ReporterPreferences getPreferences() const override;
  4796. void noMatchingTestCases(std::string const& spec) override;
  4797. void assertionStarting(AssertionInfo const&) override;
  4798. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4799. void sectionEnded(SectionStats const& _sectionStats) override;
  4800. void testRunEnded(TestRunStats const& _testRunStats) override;
  4801. };
  4802. } // end namespace Catch
  4803. // end catch_reporter_compact.h
  4804. // start catch_reporter_console.h
  4805. #if defined(_MSC_VER)
  4806. #pragma warning(push)
  4807. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4808. // Note that 4062 (not all labels are handled
  4809. // and default is missing) is enabled
  4810. #endif
  4811. namespace Catch {
  4812. // Fwd decls
  4813. struct SummaryColumn;
  4814. class TablePrinter;
  4815. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4816. std::unique_ptr<TablePrinter> m_tablePrinter;
  4817. ConsoleReporter(ReporterConfig const& config);
  4818. ~ConsoleReporter() override;
  4819. static std::string getDescription();
  4820. void noMatchingTestCases(std::string const& spec) override;
  4821. void assertionStarting(AssertionInfo const&) override;
  4822. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4823. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4824. void sectionEnded(SectionStats const& _sectionStats) override;
  4825. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4826. void benchmarkPreparing(std::string const& name) override;
  4827. void benchmarkStarting(BenchmarkInfo const& info) override;
  4828. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  4829. void benchmarkFailed(std::string const& error) override;
  4830. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4831. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4832. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4833. void testRunEnded(TestRunStats const& _testRunStats) override;
  4834. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4835. private:
  4836. void lazyPrint();
  4837. void lazyPrintWithoutClosingBenchmarkTable();
  4838. void lazyPrintRunInfo();
  4839. void lazyPrintGroupInfo();
  4840. void printTestCaseAndSectionHeader();
  4841. void printClosedHeader(std::string const& _name);
  4842. void printOpenHeader(std::string const& _name);
  4843. // if string has a : in first line will set indent to follow it on
  4844. // subsequent lines
  4845. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4846. void printTotals(Totals const& totals);
  4847. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4848. void printTotalsDivider(Totals const& totals);
  4849. void printSummaryDivider();
  4850. void printTestFilters();
  4851. private:
  4852. bool m_headerPrinted = false;
  4853. };
  4854. } // end namespace Catch
  4855. #if defined(_MSC_VER)
  4856. #pragma warning(pop)
  4857. #endif
  4858. // end catch_reporter_console.h
  4859. // start catch_reporter_junit.h
  4860. // start catch_xmlwriter.h
  4861. #include <vector>
  4862. namespace Catch {
  4863. class XmlEncode {
  4864. public:
  4865. enum ForWhat { ForTextNodes, ForAttributes };
  4866. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4867. void encodeTo( std::ostream& os ) const;
  4868. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4869. private:
  4870. std::string m_str;
  4871. ForWhat m_forWhat;
  4872. };
  4873. class XmlWriter {
  4874. public:
  4875. class ScopedElement {
  4876. public:
  4877. ScopedElement( XmlWriter* writer );
  4878. ScopedElement( ScopedElement&& other ) noexcept;
  4879. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4880. ~ScopedElement();
  4881. ScopedElement& writeText( std::string const& text, bool indent = true );
  4882. template<typename T>
  4883. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4884. m_writer->writeAttribute( name, attribute );
  4885. return *this;
  4886. }
  4887. private:
  4888. mutable XmlWriter* m_writer = nullptr;
  4889. };
  4890. XmlWriter( std::ostream& os = Catch::cout() );
  4891. ~XmlWriter();
  4892. XmlWriter( XmlWriter const& ) = delete;
  4893. XmlWriter& operator=( XmlWriter const& ) = delete;
  4894. XmlWriter& startElement( std::string const& name );
  4895. ScopedElement scopedElement( std::string const& name );
  4896. XmlWriter& endElement();
  4897. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4898. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4899. template<typename T>
  4900. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4901. ReusableStringStream rss;
  4902. rss << attribute;
  4903. return writeAttribute( name, rss.str() );
  4904. }
  4905. XmlWriter& writeText( std::string const& text, bool indent = true );
  4906. XmlWriter& writeComment( std::string const& text );
  4907. void writeStylesheetRef( std::string const& url );
  4908. XmlWriter& writeBlankLine();
  4909. void ensureTagClosed();
  4910. private:
  4911. void writeDeclaration();
  4912. void newlineIfNecessary();
  4913. bool m_tagIsOpen = false;
  4914. bool m_needsNewline = false;
  4915. std::vector<std::string> m_tags;
  4916. std::string m_indent;
  4917. std::ostream& m_os;
  4918. };
  4919. }
  4920. // end catch_xmlwriter.h
  4921. namespace Catch {
  4922. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4923. public:
  4924. JunitReporter(ReporterConfig const& _config);
  4925. ~JunitReporter() override;
  4926. static std::string getDescription();
  4927. void noMatchingTestCases(std::string const& /*spec*/) override;
  4928. void testRunStarting(TestRunInfo const& runInfo) override;
  4929. void testGroupStarting(GroupInfo const& groupInfo) override;
  4930. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4931. bool assertionEnded(AssertionStats const& assertionStats) override;
  4932. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4933. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4934. void testRunEndedCumulative() override;
  4935. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4936. void writeTestCase(TestCaseNode const& testCaseNode);
  4937. void writeSection(std::string const& className,
  4938. std::string const& rootName,
  4939. SectionNode const& sectionNode);
  4940. void writeAssertions(SectionNode const& sectionNode);
  4941. void writeAssertion(AssertionStats const& stats);
  4942. XmlWriter xml;
  4943. Timer suiteTimer;
  4944. std::string stdOutForSuite;
  4945. std::string stdErrForSuite;
  4946. unsigned int unexpectedExceptions = 0;
  4947. bool m_okToFail = false;
  4948. };
  4949. } // end namespace Catch
  4950. // end catch_reporter_junit.h
  4951. // start catch_reporter_xml.h
  4952. namespace Catch {
  4953. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4954. public:
  4955. XmlReporter(ReporterConfig const& _config);
  4956. ~XmlReporter() override;
  4957. static std::string getDescription();
  4958. virtual std::string getStylesheetRef() const;
  4959. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4960. public: // StreamingReporterBase
  4961. void noMatchingTestCases(std::string const& s) override;
  4962. void testRunStarting(TestRunInfo const& testInfo) override;
  4963. void testGroupStarting(GroupInfo const& groupInfo) override;
  4964. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4965. void sectionStarting(SectionInfo const& sectionInfo) override;
  4966. void assertionStarting(AssertionInfo const&) override;
  4967. bool assertionEnded(AssertionStats const& assertionStats) override;
  4968. void sectionEnded(SectionStats const& sectionStats) override;
  4969. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4970. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4971. void testRunEnded(TestRunStats const& testRunStats) override;
  4972. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4973. void benchmarkStarting(BenchmarkInfo const&) override;
  4974. void benchmarkEnded(BenchmarkStats<> const&) override;
  4975. void benchmarkFailed(std::string const&) override;
  4976. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4977. private:
  4978. Timer m_testCaseTimer;
  4979. XmlWriter m_xml;
  4980. int m_sectionDepth = 0;
  4981. };
  4982. } // end namespace Catch
  4983. // end catch_reporter_xml.h
  4984. // end catch_external_interfaces.h
  4985. #endif
  4986. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4987. // start catch_benchmark.hpp
  4988. // Benchmark
  4989. // start catch_chronometer.hpp
  4990. // User-facing chronometer
  4991. // start catch_clock.hpp
  4992. // Clocks
  4993. #include <chrono>
  4994. #include <ratio>
  4995. namespace Catch {
  4996. namespace Benchmark {
  4997. template <typename Clock>
  4998. using ClockDuration = typename Clock::duration;
  4999. template <typename Clock>
  5000. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5001. template <typename Clock>
  5002. using TimePoint = typename Clock::time_point;
  5003. using default_clock = std::chrono::steady_clock;
  5004. template <typename Clock>
  5005. struct now {
  5006. TimePoint<Clock> operator()() const {
  5007. return Clock::now();
  5008. }
  5009. };
  5010. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5011. } // namespace Benchmark
  5012. } // namespace Catch
  5013. // end catch_clock.hpp
  5014. // start catch_optimizer.hpp
  5015. // Hinting the optimizer
  5016. #if defined(_MSC_VER)
  5017. # include <atomic> // atomic_thread_fence
  5018. #endif
  5019. namespace Catch {
  5020. namespace Benchmark {
  5021. #if defined(__GNUC__) || defined(__clang__)
  5022. template <typename T>
  5023. inline void keep_memory(T* p) {
  5024. asm volatile("" : : "g"(p) : "memory");
  5025. }
  5026. inline void keep_memory() {
  5027. asm volatile("" : : : "memory");
  5028. }
  5029. namespace Detail {
  5030. inline void optimizer_barrier() { keep_memory(); }
  5031. } // namespace Detail
  5032. #elif defined(_MSC_VER)
  5033. #pragma optimize("", off)
  5034. template <typename T>
  5035. inline void keep_memory(T* p) {
  5036. // thanks @milleniumbug
  5037. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5038. }
  5039. // TODO equivalent keep_memory()
  5040. #pragma optimize("", on)
  5041. namespace Detail {
  5042. inline void optimizer_barrier() {
  5043. std::atomic_thread_fence(std::memory_order_seq_cst);
  5044. }
  5045. } // namespace Detail
  5046. #endif
  5047. template <typename T>
  5048. inline void deoptimize_value(T&& x) {
  5049. keep_memory(&x);
  5050. }
  5051. template <typename Fn, typename... Args>
  5052. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5053. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5054. }
  5055. template <typename Fn, typename... Args>
  5056. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5057. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5058. }
  5059. } // namespace Benchmark
  5060. } // namespace Catch
  5061. // end catch_optimizer.hpp
  5062. // start catch_complete_invoke.hpp
  5063. // Invoke with a special case for void
  5064. #include <type_traits>
  5065. #include <utility>
  5066. namespace Catch {
  5067. namespace Benchmark {
  5068. namespace Detail {
  5069. template <typename T>
  5070. struct CompleteType { using type = T; };
  5071. template <>
  5072. struct CompleteType<void> { struct type {}; };
  5073. template <typename T>
  5074. using CompleteType_t = typename CompleteType<T>::type;
  5075. template <typename Result>
  5076. struct CompleteInvoker {
  5077. template <typename Fun, typename... Args>
  5078. static Result invoke(Fun&& fun, Args&&... args) {
  5079. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5080. }
  5081. };
  5082. template <>
  5083. struct CompleteInvoker<void> {
  5084. template <typename Fun, typename... Args>
  5085. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5086. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5087. return {};
  5088. }
  5089. };
  5090. template <typename Sig>
  5091. using ResultOf_t = typename std::result_of<Sig>::type;
  5092. // invoke and not return void :(
  5093. template <typename Fun, typename... Args>
  5094. CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
  5095. return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5096. }
  5097. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5098. } // namespace Detail
  5099. template <typename Fun>
  5100. Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
  5101. CATCH_TRY{
  5102. return Detail::complete_invoke(std::forward<Fun>(fun));
  5103. } CATCH_CATCH_ALL{
  5104. getResultCapture().benchmarkFailed(translateActiveException());
  5105. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5106. }
  5107. }
  5108. } // namespace Benchmark
  5109. } // namespace Catch
  5110. // end catch_complete_invoke.hpp
  5111. namespace Catch {
  5112. namespace Benchmark {
  5113. namespace Detail {
  5114. struct ChronometerConcept {
  5115. virtual void start() = 0;
  5116. virtual void finish() = 0;
  5117. virtual ~ChronometerConcept() = default;
  5118. };
  5119. template <typename Clock>
  5120. struct ChronometerModel final : public ChronometerConcept {
  5121. void start() override { started = Clock::now(); }
  5122. void finish() override { finished = Clock::now(); }
  5123. ClockDuration<Clock> elapsed() const { return finished - started; }
  5124. TimePoint<Clock> started;
  5125. TimePoint<Clock> finished;
  5126. };
  5127. } // namespace Detail
  5128. struct Chronometer {
  5129. public:
  5130. template <typename Fun>
  5131. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5132. int runs() const { return k; }
  5133. Chronometer(Detail::ChronometerConcept& meter, int k)
  5134. : impl(&meter)
  5135. , k(k) {}
  5136. private:
  5137. template <typename Fun>
  5138. void measure(Fun&& fun, std::false_type) {
  5139. measure([&fun](int) { return fun(); }, std::true_type());
  5140. }
  5141. template <typename Fun>
  5142. void measure(Fun&& fun, std::true_type) {
  5143. Detail::optimizer_barrier();
  5144. impl->start();
  5145. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5146. impl->finish();
  5147. Detail::optimizer_barrier();
  5148. }
  5149. Detail::ChronometerConcept* impl;
  5150. int k;
  5151. };
  5152. } // namespace Benchmark
  5153. } // namespace Catch
  5154. // end catch_chronometer.hpp
  5155. // start catch_environment.hpp
  5156. // Environment information
  5157. namespace Catch {
  5158. namespace Benchmark {
  5159. template <typename Duration>
  5160. struct EnvironmentEstimate {
  5161. Duration mean;
  5162. OutlierClassification outliers;
  5163. template <typename Duration2>
  5164. operator EnvironmentEstimate<Duration2>() const {
  5165. return { mean, outliers };
  5166. }
  5167. };
  5168. template <typename Clock>
  5169. struct Environment {
  5170. using clock_type = Clock;
  5171. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5172. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5173. };
  5174. } // namespace Benchmark
  5175. } // namespace Catch
  5176. // end catch_environment.hpp
  5177. // start catch_execution_plan.hpp
  5178. // Execution plan
  5179. // start catch_benchmark_function.hpp
  5180. // Dumb std::function implementation for consistent call overhead
  5181. #include <cassert>
  5182. #include <type_traits>
  5183. #include <utility>
  5184. #include <memory>
  5185. namespace Catch {
  5186. namespace Benchmark {
  5187. namespace Detail {
  5188. template <typename T>
  5189. using Decay = typename std::decay<T>::type;
  5190. template <typename T, typename U>
  5191. struct is_related
  5192. : std::is_same<Decay<T>, Decay<U>> {};
  5193. /// We need to reinvent std::function because every piece of code that might add overhead
  5194. /// in a measurement context needs to have consistent performance characteristics so that we
  5195. /// can account for it in the measurement.
  5196. /// Implementations of std::function with optimizations that aren't always applicable, like
  5197. /// small buffer optimizations, are not uncommon.
  5198. /// This is effectively an implementation of std::function without any such optimizations;
  5199. /// it may be slow, but it is consistently slow.
  5200. struct BenchmarkFunction {
  5201. private:
  5202. struct callable {
  5203. virtual void call(Chronometer meter) const = 0;
  5204. virtual callable* clone() const = 0;
  5205. virtual ~callable() = default;
  5206. };
  5207. template <typename Fun>
  5208. struct model : public callable {
  5209. model(Fun&& fun) : fun(std::move(fun)) {}
  5210. model(Fun const& fun) : fun(fun) {}
  5211. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5212. void call(Chronometer meter) const override {
  5213. call(meter, is_callable<Fun(Chronometer)>());
  5214. }
  5215. void call(Chronometer meter, std::true_type) const {
  5216. fun(meter);
  5217. }
  5218. void call(Chronometer meter, std::false_type) const {
  5219. meter.measure(fun);
  5220. }
  5221. Fun fun;
  5222. };
  5223. struct do_nothing { void operator()() const {} };
  5224. template <typename T>
  5225. BenchmarkFunction(model<T>* c) : f(c) {}
  5226. public:
  5227. BenchmarkFunction()
  5228. : f(new model<do_nothing>{ {} }) {}
  5229. template <typename Fun,
  5230. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5231. BenchmarkFunction(Fun&& fun)
  5232. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5233. BenchmarkFunction(BenchmarkFunction&& that)
  5234. : f(std::move(that.f)) {}
  5235. BenchmarkFunction(BenchmarkFunction const& that)
  5236. : f(that.f->clone()) {}
  5237. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5238. f = std::move(that.f);
  5239. return *this;
  5240. }
  5241. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5242. f.reset(that.f->clone());
  5243. return *this;
  5244. }
  5245. void operator()(Chronometer meter) const { f->call(meter); }
  5246. private:
  5247. std::unique_ptr<callable> f;
  5248. };
  5249. } // namespace Detail
  5250. } // namespace Benchmark
  5251. } // namespace Catch
  5252. // end catch_benchmark_function.hpp
  5253. // start catch_repeat.hpp
  5254. // repeat algorithm
  5255. #include <type_traits>
  5256. #include <utility>
  5257. namespace Catch {
  5258. namespace Benchmark {
  5259. namespace Detail {
  5260. template <typename Fun>
  5261. struct repeater {
  5262. void operator()(int k) const {
  5263. for (int i = 0; i < k; ++i) {
  5264. fun();
  5265. }
  5266. }
  5267. Fun fun;
  5268. };
  5269. template <typename Fun>
  5270. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5271. return { std::forward<Fun>(fun) };
  5272. }
  5273. } // namespace Detail
  5274. } // namespace Benchmark
  5275. } // namespace Catch
  5276. // end catch_repeat.hpp
  5277. // start catch_run_for_at_least.hpp
  5278. // Run a function for a minimum amount of time
  5279. // start catch_measure.hpp
  5280. // Measure
  5281. // start catch_timing.hpp
  5282. // Timing
  5283. #include <tuple>
  5284. #include <type_traits>
  5285. namespace Catch {
  5286. namespace Benchmark {
  5287. template <typename Duration, typename Result>
  5288. struct Timing {
  5289. Duration elapsed;
  5290. Result result;
  5291. int iterations;
  5292. };
  5293. template <typename Clock, typename Sig>
  5294. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
  5295. } // namespace Benchmark
  5296. } // namespace Catch
  5297. // end catch_timing.hpp
  5298. #include <utility>
  5299. namespace Catch {
  5300. namespace Benchmark {
  5301. namespace Detail {
  5302. template <typename Clock, typename Fun, typename... Args>
  5303. TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
  5304. auto start = Clock::now();
  5305. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5306. auto end = Clock::now();
  5307. auto delta = end - start;
  5308. return { delta, std::forward<decltype(r)>(r), 1 };
  5309. }
  5310. } // namespace Detail
  5311. } // namespace Benchmark
  5312. } // namespace Catch
  5313. // end catch_measure.hpp
  5314. #include <utility>
  5315. #include <type_traits>
  5316. namespace Catch {
  5317. namespace Benchmark {
  5318. namespace Detail {
  5319. template <typename Clock, typename Fun>
  5320. TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
  5321. return Detail::measure<Clock>(fun, iters);
  5322. }
  5323. template <typename Clock, typename Fun>
  5324. TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
  5325. Detail::ChronometerModel<Clock> meter;
  5326. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5327. return { meter.elapsed(), std::move(result), iters };
  5328. }
  5329. template <typename Clock, typename Fun>
  5330. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5331. struct optimized_away_error : std::exception {
  5332. const char* what() const noexcept override {
  5333. return "could not measure benchmark, maybe it was optimized away";
  5334. }
  5335. };
  5336. template <typename Clock, typename Fun>
  5337. TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5338. auto iters = seed;
  5339. while (iters < (1 << 30)) {
  5340. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5341. if (Timing.elapsed >= how_long) {
  5342. return { Timing.elapsed, std::move(Timing.result), iters };
  5343. }
  5344. iters *= 2;
  5345. }
  5346. throw optimized_away_error{};
  5347. }
  5348. } // namespace Detail
  5349. } // namespace Benchmark
  5350. } // namespace Catch
  5351. // end catch_run_for_at_least.hpp
  5352. #include <algorithm>
  5353. namespace Catch {
  5354. namespace Benchmark {
  5355. template <typename Duration>
  5356. struct ExecutionPlan {
  5357. int iterations_per_sample;
  5358. Duration estimated_duration;
  5359. Detail::BenchmarkFunction benchmark;
  5360. Duration warmup_time;
  5361. int warmup_iterations;
  5362. template <typename Duration2>
  5363. operator ExecutionPlan<Duration2>() const {
  5364. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5365. }
  5366. template <typename Clock>
  5367. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5368. // warmup a bit
  5369. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5370. std::vector<FloatDuration<Clock>> times;
  5371. times.reserve(cfg.benchmarkSamples());
  5372. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5373. Detail::ChronometerModel<Clock> model;
  5374. this->benchmark(Chronometer(model, iterations_per_sample));
  5375. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5376. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5377. return sample_time / iterations_per_sample;
  5378. });
  5379. return times;
  5380. }
  5381. };
  5382. } // namespace Benchmark
  5383. } // namespace Catch
  5384. // end catch_execution_plan.hpp
  5385. // start catch_estimate_clock.hpp
  5386. // Environment measurement
  5387. // start catch_stats.hpp
  5388. // Statistical analysis tools
  5389. #include <algorithm>
  5390. #include <functional>
  5391. #include <vector>
  5392. #include <numeric>
  5393. #include <tuple>
  5394. #include <cmath>
  5395. #include <utility>
  5396. #include <cstddef>
  5397. namespace Catch {
  5398. namespace Benchmark {
  5399. namespace Detail {
  5400. using sample = std::vector<double>;
  5401. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5402. template <typename Iterator>
  5403. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5404. std::vector<double> copy(first, last);
  5405. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5406. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5407. auto iqr = q3 - q1;
  5408. auto los = q1 - (iqr * 3.);
  5409. auto lom = q1 - (iqr * 1.5);
  5410. auto him = q3 + (iqr * 1.5);
  5411. auto his = q3 + (iqr * 3.);
  5412. OutlierClassification o;
  5413. for (; first != last; ++first) {
  5414. auto&& t = *first;
  5415. if (t < los) ++o.low_severe;
  5416. else if (t < lom) ++o.low_mild;
  5417. else if (t > his) ++o.high_severe;
  5418. else if (t > him) ++o.high_mild;
  5419. ++o.samples_seen;
  5420. }
  5421. return o;
  5422. }
  5423. template <typename Iterator>
  5424. double mean(Iterator first, Iterator last) {
  5425. auto count = last - first;
  5426. double sum = std::accumulate(first, last, 0.);
  5427. return sum / count;
  5428. }
  5429. template <typename URng, typename Iterator, typename Estimator>
  5430. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5431. auto n = last - first;
  5432. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5433. sample out;
  5434. out.reserve(resamples);
  5435. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5436. std::vector<double> resampled;
  5437. resampled.reserve(n);
  5438. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5439. return estimator(resampled.begin(), resampled.end());
  5440. });
  5441. std::sort(out.begin(), out.end());
  5442. return out;
  5443. }
  5444. template <typename Estimator, typename Iterator>
  5445. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5446. auto n = last - first;
  5447. auto second = std::next(first);
  5448. sample results;
  5449. results.reserve(n);
  5450. for (auto it = first; it != last; ++it) {
  5451. std::iter_swap(it, first);
  5452. results.push_back(estimator(second, last));
  5453. }
  5454. return results;
  5455. }
  5456. inline double normal_cdf(double x) {
  5457. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5458. }
  5459. double erfc_inv(double x);
  5460. double normal_quantile(double p);
  5461. template <typename Iterator, typename Estimator>
  5462. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5463. auto n_samples = last - first;
  5464. double point = estimator(first, last);
  5465. // Degenerate case with a single sample
  5466. if (n_samples == 1) return { point, point, point, confidence_level };
  5467. sample jack = jackknife(estimator, first, last);
  5468. double jack_mean = mean(jack.begin(), jack.end());
  5469. double sum_squares, sum_cubes;
  5470. 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> {
  5471. auto d = jack_mean - x;
  5472. auto d2 = d * d;
  5473. auto d3 = d2 * d;
  5474. return { sqcb.first + d2, sqcb.second + d3 };
  5475. });
  5476. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5477. int n = static_cast<int>(resample.size());
  5478. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5479. // degenerate case with uniform samples
  5480. if (prob_n == 0) return { point, point, point, confidence_level };
  5481. double bias = normal_quantile(prob_n);
  5482. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5483. auto cumn = [n](double x) -> int {
  5484. return std::lround(normal_cdf(x) * n); };
  5485. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5486. double b1 = bias + z1;
  5487. double b2 = bias - z1;
  5488. double a1 = a(b1);
  5489. double a2 = a(b2);
  5490. auto lo = std::max(cumn(a1), 0);
  5491. auto hi = std::min(cumn(a2), n - 1);
  5492. return { point, resample[lo], resample[hi], confidence_level };
  5493. }
  5494. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5495. struct bootstrap_analysis {
  5496. Estimate<double> mean;
  5497. Estimate<double> standard_deviation;
  5498. double outlier_variance;
  5499. };
  5500. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5501. } // namespace Detail
  5502. } // namespace Benchmark
  5503. } // namespace Catch
  5504. // end catch_stats.hpp
  5505. #include <algorithm>
  5506. #include <iterator>
  5507. #include <tuple>
  5508. #include <vector>
  5509. #include <cmath>
  5510. namespace Catch {
  5511. namespace Benchmark {
  5512. namespace Detail {
  5513. template <typename Clock>
  5514. std::vector<double> resolution(int k) {
  5515. std::vector<TimePoint<Clock>> times;
  5516. times.reserve(k + 1);
  5517. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5518. std::vector<double> deltas;
  5519. deltas.reserve(k);
  5520. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5521. std::back_inserter(deltas),
  5522. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5523. return deltas;
  5524. }
  5525. const auto warmup_iterations = 10000;
  5526. const auto warmup_time = std::chrono::milliseconds(100);
  5527. const auto minimum_ticks = 1000;
  5528. const auto warmup_seed = 10000;
  5529. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5530. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5531. const auto clock_cost_estimation_tick_limit = 100000;
  5532. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5533. const auto clock_cost_estimation_iterations = 10000;
  5534. template <typename Clock>
  5535. int warmup() {
  5536. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5537. .iterations;
  5538. }
  5539. template <typename Clock>
  5540. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5541. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5542. .result;
  5543. return {
  5544. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5545. classify_outliers(r.begin(), r.end()),
  5546. };
  5547. }
  5548. template <typename Clock>
  5549. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5550. auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5551. auto time_clock = [](int k) {
  5552. return Detail::measure<Clock>([k] {
  5553. for (int i = 0; i < k; ++i) {
  5554. volatile auto ignored = Clock::now();
  5555. (void)ignored;
  5556. }
  5557. }).elapsed;
  5558. };
  5559. time_clock(1);
  5560. int iters = clock_cost_estimation_iterations;
  5561. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5562. std::vector<double> times;
  5563. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5564. times.reserve(nsamples);
  5565. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5566. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5567. });
  5568. return {
  5569. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5570. classify_outliers(times.begin(), times.end()),
  5571. };
  5572. }
  5573. template <typename Clock>
  5574. Environment<FloatDuration<Clock>> measure_environment() {
  5575. static Environment<FloatDuration<Clock>>* env = nullptr;
  5576. if (env) {
  5577. return *env;
  5578. }
  5579. auto iters = Detail::warmup<Clock>();
  5580. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5581. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5582. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5583. return *env;
  5584. }
  5585. } // namespace Detail
  5586. } // namespace Benchmark
  5587. } // namespace Catch
  5588. // end catch_estimate_clock.hpp
  5589. // start catch_analyse.hpp
  5590. // Run and analyse one benchmark
  5591. // start catch_sample_analysis.hpp
  5592. // Benchmark results
  5593. #include <algorithm>
  5594. #include <vector>
  5595. #include <string>
  5596. #include <iterator>
  5597. namespace Catch {
  5598. namespace Benchmark {
  5599. template <typename Duration>
  5600. struct SampleAnalysis {
  5601. std::vector<Duration> samples;
  5602. Estimate<Duration> mean;
  5603. Estimate<Duration> standard_deviation;
  5604. OutlierClassification outliers;
  5605. double outlier_variance;
  5606. template <typename Duration2>
  5607. operator SampleAnalysis<Duration2>() const {
  5608. std::vector<Duration2> samples2;
  5609. samples2.reserve(samples.size());
  5610. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5611. return {
  5612. std::move(samples2),
  5613. mean,
  5614. standard_deviation,
  5615. outliers,
  5616. outlier_variance,
  5617. };
  5618. }
  5619. };
  5620. } // namespace Benchmark
  5621. } // namespace Catch
  5622. // end catch_sample_analysis.hpp
  5623. #include <algorithm>
  5624. #include <iterator>
  5625. #include <vector>
  5626. namespace Catch {
  5627. namespace Benchmark {
  5628. namespace Detail {
  5629. template <typename Duration, typename Iterator>
  5630. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5631. if (!cfg.benchmarkNoAnalysis()) {
  5632. std::vector<double> samples;
  5633. samples.reserve(last - first);
  5634. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5635. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5636. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5637. auto wrap_estimate = [](Estimate<double> e) {
  5638. return Estimate<Duration> {
  5639. Duration(e.point),
  5640. Duration(e.lower_bound),
  5641. Duration(e.upper_bound),
  5642. e.confidence_interval,
  5643. };
  5644. };
  5645. std::vector<Duration> samples2;
  5646. samples2.reserve(samples.size());
  5647. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5648. return {
  5649. std::move(samples2),
  5650. wrap_estimate(analysis.mean),
  5651. wrap_estimate(analysis.standard_deviation),
  5652. outliers,
  5653. analysis.outlier_variance,
  5654. };
  5655. } else {
  5656. std::vector<Duration> samples;
  5657. samples.reserve(last - first);
  5658. Duration mean = Duration(0);
  5659. int i = 0;
  5660. for (auto it = first; it < last; ++it, ++i) {
  5661. samples.push_back(Duration(*it));
  5662. mean += Duration(*it);
  5663. }
  5664. mean /= i;
  5665. return {
  5666. std::move(samples),
  5667. Estimate<Duration>{mean, mean, mean, 0.0},
  5668. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5669. OutlierClassification{},
  5670. 0.0
  5671. };
  5672. }
  5673. }
  5674. } // namespace Detail
  5675. } // namespace Benchmark
  5676. } // namespace Catch
  5677. // end catch_analyse.hpp
  5678. #include <algorithm>
  5679. #include <functional>
  5680. #include <string>
  5681. #include <vector>
  5682. #include <cmath>
  5683. namespace Catch {
  5684. namespace Benchmark {
  5685. struct Benchmark {
  5686. Benchmark(std::string &&name)
  5687. : name(std::move(name)) {}
  5688. template <class FUN>
  5689. Benchmark(std::string &&name, FUN &&func)
  5690. : fun(std::move(func)), name(std::move(name)) {}
  5691. template <typename Clock>
  5692. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5693. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5694. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
  5695. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5696. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5697. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
  5698. }
  5699. template <typename Clock = default_clock>
  5700. void run() {
  5701. IConfigPtr cfg = getCurrentContext().getConfig();
  5702. auto env = Detail::measure_environment<Clock>();
  5703. getResultCapture().benchmarkPreparing(name);
  5704. CATCH_TRY{
  5705. auto plan = user_code([&] {
  5706. return prepare<Clock>(*cfg, env);
  5707. });
  5708. BenchmarkInfo info {
  5709. name,
  5710. plan.estimated_duration.count(),
  5711. plan.iterations_per_sample,
  5712. cfg->benchmarkSamples(),
  5713. cfg->benchmarkResamples(),
  5714. env.clock_resolution.mean.count(),
  5715. env.clock_cost.mean.count()
  5716. };
  5717. getResultCapture().benchmarkStarting(info);
  5718. auto samples = user_code([&] {
  5719. return plan.template run<Clock>(*cfg, env);
  5720. });
  5721. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5722. BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5723. getResultCapture().benchmarkEnded(stats);
  5724. } CATCH_CATCH_ALL{
  5725. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5726. std::rethrow_exception(std::current_exception());
  5727. }
  5728. }
  5729. // sets lambda to be used in fun *and* executes benchmark!
  5730. template <typename Fun,
  5731. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5732. Benchmark & operator=(Fun func) {
  5733. fun = Detail::BenchmarkFunction(func);
  5734. run();
  5735. return *this;
  5736. }
  5737. explicit operator bool() {
  5738. return true;
  5739. }
  5740. private:
  5741. Detail::BenchmarkFunction fun;
  5742. std::string name;
  5743. };
  5744. }
  5745. } // namespace Catch
  5746. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  5747. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  5748. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  5749. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5750. BenchmarkName = [&](int benchmarkIndex)
  5751. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  5752. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  5753. BenchmarkName = [&]
  5754. // end catch_benchmark.hpp
  5755. #endif
  5756. #endif // ! CATCH_CONFIG_IMPL_ONLY
  5757. #ifdef CATCH_IMPL
  5758. // start catch_impl.hpp
  5759. #ifdef __clang__
  5760. #pragma clang diagnostic push
  5761. #pragma clang diagnostic ignored "-Wweak-vtables"
  5762. #endif
  5763. // Keep these here for external reporters
  5764. // start catch_test_case_tracker.h
  5765. #include <string>
  5766. #include <vector>
  5767. #include <memory>
  5768. namespace Catch {
  5769. namespace TestCaseTracking {
  5770. struct NameAndLocation {
  5771. std::string name;
  5772. SourceLineInfo location;
  5773. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  5774. };
  5775. struct ITracker;
  5776. using ITrackerPtr = std::shared_ptr<ITracker>;
  5777. struct ITracker {
  5778. virtual ~ITracker();
  5779. // static queries
  5780. virtual NameAndLocation const& nameAndLocation() const = 0;
  5781. // dynamic queries
  5782. virtual bool isComplete() const = 0; // Successfully completed or failed
  5783. virtual bool isSuccessfullyCompleted() const = 0;
  5784. virtual bool isOpen() const = 0; // Started but not complete
  5785. virtual bool hasChildren() const = 0;
  5786. virtual ITracker& parent() = 0;
  5787. // actions
  5788. virtual void close() = 0; // Successfully complete
  5789. virtual void fail() = 0;
  5790. virtual void markAsNeedingAnotherRun() = 0;
  5791. virtual void addChild( ITrackerPtr const& child ) = 0;
  5792. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  5793. virtual void openChild() = 0;
  5794. // Debug/ checking
  5795. virtual bool isSectionTracker() const = 0;
  5796. virtual bool isGeneratorTracker() const = 0;
  5797. };
  5798. class TrackerContext {
  5799. enum RunState {
  5800. NotStarted,
  5801. Executing,
  5802. CompletedCycle
  5803. };
  5804. ITrackerPtr m_rootTracker;
  5805. ITracker* m_currentTracker = nullptr;
  5806. RunState m_runState = NotStarted;
  5807. public:
  5808. ITracker& startRun();
  5809. void endRun();
  5810. void startCycle();
  5811. void completeCycle();
  5812. bool completedCycle() const;
  5813. ITracker& currentTracker();
  5814. void setCurrentTracker( ITracker* tracker );
  5815. };
  5816. class TrackerBase : public ITracker {
  5817. protected:
  5818. enum CycleState {
  5819. NotStarted,
  5820. Executing,
  5821. ExecutingChildren,
  5822. NeedsAnotherRun,
  5823. CompletedSuccessfully,
  5824. Failed
  5825. };
  5826. using Children = std::vector<ITrackerPtr>;
  5827. NameAndLocation m_nameAndLocation;
  5828. TrackerContext& m_ctx;
  5829. ITracker* m_parent;
  5830. Children m_children;
  5831. CycleState m_runState = NotStarted;
  5832. public:
  5833. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5834. NameAndLocation const& nameAndLocation() const override;
  5835. bool isComplete() const override;
  5836. bool isSuccessfullyCompleted() const override;
  5837. bool isOpen() const override;
  5838. bool hasChildren() const override;
  5839. void addChild( ITrackerPtr const& child ) override;
  5840. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  5841. ITracker& parent() override;
  5842. void openChild() override;
  5843. bool isSectionTracker() const override;
  5844. bool isGeneratorTracker() const override;
  5845. void open();
  5846. void close() override;
  5847. void fail() override;
  5848. void markAsNeedingAnotherRun() override;
  5849. private:
  5850. void moveToParent();
  5851. void moveToThis();
  5852. };
  5853. class SectionTracker : public TrackerBase {
  5854. std::vector<std::string> m_filters;
  5855. public:
  5856. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  5857. bool isSectionTracker() const override;
  5858. bool isComplete() const override;
  5859. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  5860. void tryOpen();
  5861. void addInitialFilters( std::vector<std::string> const& filters );
  5862. void addNextFilters( std::vector<std::string> const& filters );
  5863. };
  5864. } // namespace TestCaseTracking
  5865. using TestCaseTracking::ITracker;
  5866. using TestCaseTracking::TrackerContext;
  5867. using TestCaseTracking::SectionTracker;
  5868. } // namespace Catch
  5869. // end catch_test_case_tracker.h
  5870. // start catch_leak_detector.h
  5871. namespace Catch {
  5872. struct LeakDetector {
  5873. LeakDetector();
  5874. ~LeakDetector();
  5875. };
  5876. }
  5877. // end catch_leak_detector.h
  5878. // Cpp files will be included in the single-header file here
  5879. // start catch_stats.cpp
  5880. // Statistical analysis tools
  5881. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5882. #include <cassert>
  5883. #include <random>
  5884. #if defined(CATCH_CONFIG_USE_ASYNC)
  5885. #include <future>
  5886. #endif
  5887. namespace {
  5888. double erf_inv(double x) {
  5889. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  5890. double w, p;
  5891. w = -log((1.0 - x) * (1.0 + x));
  5892. if (w < 6.250000) {
  5893. w = w - 3.125000;
  5894. p = -3.6444120640178196996e-21;
  5895. p = -1.685059138182016589e-19 + p * w;
  5896. p = 1.2858480715256400167e-18 + p * w;
  5897. p = 1.115787767802518096e-17 + p * w;
  5898. p = -1.333171662854620906e-16 + p * w;
  5899. p = 2.0972767875968561637e-17 + p * w;
  5900. p = 6.6376381343583238325e-15 + p * w;
  5901. p = -4.0545662729752068639e-14 + p * w;
  5902. p = -8.1519341976054721522e-14 + p * w;
  5903. p = 2.6335093153082322977e-12 + p * w;
  5904. p = -1.2975133253453532498e-11 + p * w;
  5905. p = -5.4154120542946279317e-11 + p * w;
  5906. p = 1.051212273321532285e-09 + p * w;
  5907. p = -4.1126339803469836976e-09 + p * w;
  5908. p = -2.9070369957882005086e-08 + p * w;
  5909. p = 4.2347877827932403518e-07 + p * w;
  5910. p = -1.3654692000834678645e-06 + p * w;
  5911. p = -1.3882523362786468719e-05 + p * w;
  5912. p = 0.0001867342080340571352 + p * w;
  5913. p = -0.00074070253416626697512 + p * w;
  5914. p = -0.0060336708714301490533 + p * w;
  5915. p = 0.24015818242558961693 + p * w;
  5916. p = 1.6536545626831027356 + p * w;
  5917. } else if (w < 16.000000) {
  5918. w = sqrt(w) - 3.250000;
  5919. p = 2.2137376921775787049e-09;
  5920. p = 9.0756561938885390979e-08 + p * w;
  5921. p = -2.7517406297064545428e-07 + p * w;
  5922. p = 1.8239629214389227755e-08 + p * w;
  5923. p = 1.5027403968909827627e-06 + p * w;
  5924. p = -4.013867526981545969e-06 + p * w;
  5925. p = 2.9234449089955446044e-06 + p * w;
  5926. p = 1.2475304481671778723e-05 + p * w;
  5927. p = -4.7318229009055733981e-05 + p * w;
  5928. p = 6.8284851459573175448e-05 + p * w;
  5929. p = 2.4031110387097893999e-05 + p * w;
  5930. p = -0.0003550375203628474796 + p * w;
  5931. p = 0.00095328937973738049703 + p * w;
  5932. p = -0.0016882755560235047313 + p * w;
  5933. p = 0.0024914420961078508066 + p * w;
  5934. p = -0.0037512085075692412107 + p * w;
  5935. p = 0.005370914553590063617 + p * w;
  5936. p = 1.0052589676941592334 + p * w;
  5937. p = 3.0838856104922207635 + p * w;
  5938. } else {
  5939. w = sqrt(w) - 5.000000;
  5940. p = -2.7109920616438573243e-11;
  5941. p = -2.5556418169965252055e-10 + p * w;
  5942. p = 1.5076572693500548083e-09 + p * w;
  5943. p = -3.7894654401267369937e-09 + p * w;
  5944. p = 7.6157012080783393804e-09 + p * w;
  5945. p = -1.4960026627149240478e-08 + p * w;
  5946. p = 2.9147953450901080826e-08 + p * w;
  5947. p = -6.7711997758452339498e-08 + p * w;
  5948. p = 2.2900482228026654717e-07 + p * w;
  5949. p = -9.9298272942317002539e-07 + p * w;
  5950. p = 4.5260625972231537039e-06 + p * w;
  5951. p = -1.9681778105531670567e-05 + p * w;
  5952. p = 7.5995277030017761139e-05 + p * w;
  5953. p = -0.00021503011930044477347 + p * w;
  5954. p = -0.00013871931833623122026 + p * w;
  5955. p = 1.0103004648645343977 + p * w;
  5956. p = 4.8499064014085844221 + p * w;
  5957. }
  5958. return p * x;
  5959. }
  5960. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  5961. auto m = Catch::Benchmark::Detail::mean(first, last);
  5962. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  5963. double diff = b - m;
  5964. return a + diff * diff;
  5965. }) / (last - first);
  5966. return std::sqrt(variance);
  5967. }
  5968. }
  5969. namespace Catch {
  5970. namespace Benchmark {
  5971. namespace Detail {
  5972. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  5973. auto count = last - first;
  5974. double idx = (count - 1) * k / static_cast<double>(q);
  5975. int j = static_cast<int>(idx);
  5976. double g = idx - j;
  5977. std::nth_element(first, first + j, last);
  5978. auto xj = first[j];
  5979. if (g == 0) return xj;
  5980. auto xj1 = *std::min_element(first + (j + 1), last);
  5981. return xj + g * (xj1 - xj);
  5982. }
  5983. double erfc_inv(double x) {
  5984. return erf_inv(1.0 - x);
  5985. }
  5986. double normal_quantile(double p) {
  5987. static const double ROOT_TWO = std::sqrt(2.0);
  5988. double result = 0.0;
  5989. assert(p >= 0 && p <= 1);
  5990. if (p < 0 || p > 1) {
  5991. return result;
  5992. }
  5993. result = -erfc_inv(2.0 * p);
  5994. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  5995. result *= /*sd * */ ROOT_TWO;
  5996. // result += normal disttribution mean (0)
  5997. return result;
  5998. }
  5999. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6000. double sb = stddev.point;
  6001. double mn = mean.point / n;
  6002. double mg_min = mn / 2.;
  6003. double sg = std::min(mg_min / 4., sb / std::sqrt(n));
  6004. double sg2 = sg * sg;
  6005. double sb2 = sb * sb;
  6006. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6007. double k = mn - x;
  6008. double d = k * k;
  6009. double nd = n * d;
  6010. double k0 = -n * nd;
  6011. double k1 = sb2 - n * sg2 + nd;
  6012. double det = k1 * k1 - 4 * sg2 * k0;
  6013. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6014. };
  6015. auto var_out = [n, sb2, sg2](double c) {
  6016. double nc = n - c;
  6017. return (nc / n) * (sb2 - nc * sg2);
  6018. };
  6019. return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
  6020. }
  6021. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6022. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6023. static std::random_device entropy;
  6024. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  6025. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6026. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6027. auto stddev = &standard_deviation;
  6028. #if defined(CATCH_CONFIG_USE_ASYNC)
  6029. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6030. auto seed = entropy();
  6031. return std::async(std::launch::async, [=] {
  6032. std::mt19937 rng(seed);
  6033. auto resampled = resample(rng, n_resamples, first, last, f);
  6034. return bootstrap(confidence_level, first, last, resampled, f);
  6035. });
  6036. };
  6037. auto mean_future = Estimate(mean);
  6038. auto stddev_future = Estimate(stddev);
  6039. auto mean_estimate = mean_future.get();
  6040. auto stddev_estimate = stddev_future.get();
  6041. #else
  6042. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6043. auto seed = entropy();
  6044. std::mt19937 rng(seed);
  6045. auto resampled = resample(rng, n_resamples, first, last, f);
  6046. return bootstrap(confidence_level, first, last, resampled, f);
  6047. };
  6048. auto mean_estimate = Estimate(mean);
  6049. auto stddev_estimate = Estimate(stddev);
  6050. #endif // CATCH_USE_ASYNC
  6051. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6052. return { mean_estimate, stddev_estimate, outlier_variance };
  6053. }
  6054. } // namespace Detail
  6055. } // namespace Benchmark
  6056. } // namespace Catch
  6057. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6058. // end catch_stats.cpp
  6059. // start catch_approx.cpp
  6060. #include <cmath>
  6061. #include <limits>
  6062. namespace {
  6063. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6064. // But without the subtraction to allow for INFINITY in comparison
  6065. bool marginComparison(double lhs, double rhs, double margin) {
  6066. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6067. }
  6068. }
  6069. namespace Catch {
  6070. namespace Detail {
  6071. Approx::Approx ( double value )
  6072. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6073. m_margin( 0.0 ),
  6074. m_scale( 0.0 ),
  6075. m_value( value )
  6076. {}
  6077. Approx Approx::custom() {
  6078. return Approx( 0 );
  6079. }
  6080. Approx Approx::operator-() const {
  6081. auto temp(*this);
  6082. temp.m_value = -temp.m_value;
  6083. return temp;
  6084. }
  6085. std::string Approx::toString() const {
  6086. ReusableStringStream rss;
  6087. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6088. return rss.str();
  6089. }
  6090. bool Approx::equalityComparisonImpl(const double other) const {
  6091. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6092. // Thanks to Richard Harris for his help refining the scaled margin value
  6093. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  6094. }
  6095. void Approx::setMargin(double newMargin) {
  6096. CATCH_ENFORCE(newMargin >= 0,
  6097. "Invalid Approx::margin: " << newMargin << '.'
  6098. << " Approx::Margin has to be non-negative.");
  6099. m_margin = newMargin;
  6100. }
  6101. void Approx::setEpsilon(double newEpsilon) {
  6102. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6103. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6104. << " Approx::epsilon has to be in [0, 1]");
  6105. m_epsilon = newEpsilon;
  6106. }
  6107. } // end namespace Detail
  6108. namespace literals {
  6109. Detail::Approx operator "" _a(long double val) {
  6110. return Detail::Approx(val);
  6111. }
  6112. Detail::Approx operator "" _a(unsigned long long val) {
  6113. return Detail::Approx(val);
  6114. }
  6115. } // end namespace literals
  6116. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6117. return value.toString();
  6118. }
  6119. } // end namespace Catch
  6120. // end catch_approx.cpp
  6121. // start catch_assertionhandler.cpp
  6122. // start catch_debugger.h
  6123. namespace Catch {
  6124. bool isDebuggerActive();
  6125. }
  6126. #ifdef CATCH_PLATFORM_MAC
  6127. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6128. #elif defined(CATCH_PLATFORM_LINUX)
  6129. // If we can use inline assembler, do it because this allows us to break
  6130. // directly at the location of the failing check instead of breaking inside
  6131. // raise() called from it, i.e. one stack frame below.
  6132. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6133. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6134. #else // Fall back to the generic way.
  6135. #include <signal.h>
  6136. #define CATCH_TRAP() raise(SIGTRAP)
  6137. #endif
  6138. #elif defined(_MSC_VER)
  6139. #define CATCH_TRAP() __debugbreak()
  6140. #elif defined(__MINGW32__)
  6141. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6142. #define CATCH_TRAP() DebugBreak()
  6143. #endif
  6144. #ifdef CATCH_TRAP
  6145. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6146. #else
  6147. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6148. #endif
  6149. // end catch_debugger.h
  6150. // start catch_run_context.h
  6151. // start catch_fatal_condition.h
  6152. // start catch_windows_h_proxy.h
  6153. #if defined(CATCH_PLATFORM_WINDOWS)
  6154. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  6155. # define CATCH_DEFINED_NOMINMAX
  6156. # define NOMINMAX
  6157. #endif
  6158. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  6159. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6160. # define WIN32_LEAN_AND_MEAN
  6161. #endif
  6162. #ifdef __AFXDLL
  6163. #include <AfxWin.h>
  6164. #else
  6165. #include <windows.h>
  6166. #endif
  6167. #ifdef CATCH_DEFINED_NOMINMAX
  6168. # undef NOMINMAX
  6169. #endif
  6170. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  6171. # undef WIN32_LEAN_AND_MEAN
  6172. #endif
  6173. #endif // defined(CATCH_PLATFORM_WINDOWS)
  6174. // end catch_windows_h_proxy.h
  6175. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6176. namespace Catch {
  6177. struct FatalConditionHandler {
  6178. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  6179. FatalConditionHandler();
  6180. static void reset();
  6181. ~FatalConditionHandler();
  6182. private:
  6183. static bool isSet;
  6184. static ULONG guaranteeSize;
  6185. static PVOID exceptionHandlerHandle;
  6186. };
  6187. } // namespace Catch
  6188. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  6189. #include <signal.h>
  6190. namespace Catch {
  6191. struct FatalConditionHandler {
  6192. static bool isSet;
  6193. static struct sigaction oldSigActions[];
  6194. static stack_t oldSigStack;
  6195. static char altStackMem[];
  6196. static void handleSignal( int sig );
  6197. FatalConditionHandler();
  6198. ~FatalConditionHandler();
  6199. static void reset();
  6200. };
  6201. } // namespace Catch
  6202. #else
  6203. namespace Catch {
  6204. struct FatalConditionHandler {
  6205. void reset();
  6206. };
  6207. }
  6208. #endif
  6209. // end catch_fatal_condition.h
  6210. #include <string>
  6211. namespace Catch {
  6212. struct IMutableContext;
  6213. ///////////////////////////////////////////////////////////////////////////
  6214. class RunContext : public IResultCapture, public IRunner {
  6215. public:
  6216. RunContext( RunContext const& ) = delete;
  6217. RunContext& operator =( RunContext const& ) = delete;
  6218. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6219. ~RunContext() override;
  6220. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6221. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6222. Totals runTest(TestCase const& testCase);
  6223. IConfigPtr config() const;
  6224. IStreamingReporter& reporter() const;
  6225. public: // IResultCapture
  6226. // Assertion handlers
  6227. void handleExpr
  6228. ( AssertionInfo const& info,
  6229. ITransientExpression const& expr,
  6230. AssertionReaction& reaction ) override;
  6231. void handleMessage
  6232. ( AssertionInfo const& info,
  6233. ResultWas::OfType resultType,
  6234. StringRef const& message,
  6235. AssertionReaction& reaction ) override;
  6236. void handleUnexpectedExceptionNotThrown
  6237. ( AssertionInfo const& info,
  6238. AssertionReaction& reaction ) override;
  6239. void handleUnexpectedInflightException
  6240. ( AssertionInfo const& info,
  6241. std::string const& message,
  6242. AssertionReaction& reaction ) override;
  6243. void handleIncomplete
  6244. ( AssertionInfo const& info ) override;
  6245. void handleNonExpr
  6246. ( AssertionInfo const &info,
  6247. ResultWas::OfType resultType,
  6248. AssertionReaction &reaction ) override;
  6249. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6250. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6251. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6252. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6253. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6254. void benchmarkPreparing( std::string const& name ) override;
  6255. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6256. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6257. void benchmarkFailed( std::string const& error ) override;
  6258. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6259. void pushScopedMessage( MessageInfo const& message ) override;
  6260. void popScopedMessage( MessageInfo const& message ) override;
  6261. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6262. std::string getCurrentTestName() const override;
  6263. const AssertionResult* getLastResult() const override;
  6264. void exceptionEarlyReported() override;
  6265. void handleFatalErrorCondition( StringRef message ) override;
  6266. bool lastAssertionPassed() override;
  6267. void assertionPassed() override;
  6268. public:
  6269. // !TBD We need to do this another way!
  6270. bool aborting() const final;
  6271. private:
  6272. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6273. void invokeActiveTestCase();
  6274. void resetAssertionInfo();
  6275. bool testForMissingAssertions( Counts& assertions );
  6276. void assertionEnded( AssertionResult const& result );
  6277. void reportExpr
  6278. ( AssertionInfo const &info,
  6279. ResultWas::OfType resultType,
  6280. ITransientExpression const *expr,
  6281. bool negated );
  6282. void populateReaction( AssertionReaction& reaction );
  6283. private:
  6284. void handleUnfinishedSections();
  6285. TestRunInfo m_runInfo;
  6286. IMutableContext& m_context;
  6287. TestCase const* m_activeTestCase = nullptr;
  6288. ITracker* m_testCaseTracker = nullptr;
  6289. Option<AssertionResult> m_lastResult;
  6290. IConfigPtr m_config;
  6291. Totals m_totals;
  6292. IStreamingReporterPtr m_reporter;
  6293. std::vector<MessageInfo> m_messages;
  6294. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6295. AssertionInfo m_lastAssertionInfo;
  6296. std::vector<SectionEndInfo> m_unfinishedSections;
  6297. std::vector<ITracker*> m_activeSections;
  6298. TrackerContext m_trackerContext;
  6299. bool m_lastAssertionPassed = false;
  6300. bool m_shouldReportUnexpected = true;
  6301. bool m_includeSuccessfulResults;
  6302. };
  6303. } // end namespace Catch
  6304. // end catch_run_context.h
  6305. namespace Catch {
  6306. namespace {
  6307. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6308. expr.streamReconstructedExpression( os );
  6309. return os;
  6310. }
  6311. }
  6312. LazyExpression::LazyExpression( bool isNegated )
  6313. : m_isNegated( isNegated )
  6314. {}
  6315. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6316. LazyExpression::operator bool() const {
  6317. return m_transientExpression != nullptr;
  6318. }
  6319. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6320. if( lazyExpr.m_isNegated )
  6321. os << "!";
  6322. if( lazyExpr ) {
  6323. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6324. os << "(" << *lazyExpr.m_transientExpression << ")";
  6325. else
  6326. os << *lazyExpr.m_transientExpression;
  6327. }
  6328. else {
  6329. os << "{** error - unchecked empty expression requested **}";
  6330. }
  6331. return os;
  6332. }
  6333. AssertionHandler::AssertionHandler
  6334. ( StringRef const& macroName,
  6335. SourceLineInfo const& lineInfo,
  6336. StringRef capturedExpression,
  6337. ResultDisposition::Flags resultDisposition )
  6338. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6339. m_resultCapture( getResultCapture() )
  6340. {}
  6341. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6342. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6343. }
  6344. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6345. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6346. }
  6347. auto AssertionHandler::allowThrows() const -> bool {
  6348. return getCurrentContext().getConfig()->allowThrows();
  6349. }
  6350. void AssertionHandler::complete() {
  6351. setCompleted();
  6352. if( m_reaction.shouldDebugBreak ) {
  6353. // If you find your debugger stopping you here then go one level up on the
  6354. // call-stack for the code that caused it (typically a failed assertion)
  6355. // (To go back to the test and change execution, jump over the throw, next)
  6356. CATCH_BREAK_INTO_DEBUGGER();
  6357. }
  6358. if (m_reaction.shouldThrow) {
  6359. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6360. throw Catch::TestFailureException();
  6361. #else
  6362. CATCH_ERROR( "Test failure requires aborting test!" );
  6363. #endif
  6364. }
  6365. }
  6366. void AssertionHandler::setCompleted() {
  6367. m_completed = true;
  6368. }
  6369. void AssertionHandler::handleUnexpectedInflightException() {
  6370. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6371. }
  6372. void AssertionHandler::handleExceptionThrownAsExpected() {
  6373. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6374. }
  6375. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6376. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6377. }
  6378. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6379. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6380. }
  6381. void AssertionHandler::handleThrowingCallSkipped() {
  6382. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6383. }
  6384. // This is the overload that takes a string and infers the Equals matcher from it
  6385. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6386. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6387. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6388. }
  6389. } // namespace Catch
  6390. // end catch_assertionhandler.cpp
  6391. // start catch_assertionresult.cpp
  6392. namespace Catch {
  6393. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6394. lazyExpression(_lazyExpression),
  6395. resultType(_resultType) {}
  6396. std::string AssertionResultData::reconstructExpression() const {
  6397. if( reconstructedExpression.empty() ) {
  6398. if( lazyExpression ) {
  6399. ReusableStringStream rss;
  6400. rss << lazyExpression;
  6401. reconstructedExpression = rss.str();
  6402. }
  6403. }
  6404. return reconstructedExpression;
  6405. }
  6406. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6407. : m_info( info ),
  6408. m_resultData( data )
  6409. {}
  6410. // Result was a success
  6411. bool AssertionResult::succeeded() const {
  6412. return Catch::isOk( m_resultData.resultType );
  6413. }
  6414. // Result was a success, or failure is suppressed
  6415. bool AssertionResult::isOk() const {
  6416. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6417. }
  6418. ResultWas::OfType AssertionResult::getResultType() const {
  6419. return m_resultData.resultType;
  6420. }
  6421. bool AssertionResult::hasExpression() const {
  6422. return m_info.capturedExpression[0] != 0;
  6423. }
  6424. bool AssertionResult::hasMessage() const {
  6425. return !m_resultData.message.empty();
  6426. }
  6427. std::string AssertionResult::getExpression() const {
  6428. if( isFalseTest( m_info.resultDisposition ) )
  6429. return "!(" + m_info.capturedExpression + ")";
  6430. else
  6431. return m_info.capturedExpression;
  6432. }
  6433. std::string AssertionResult::getExpressionInMacro() const {
  6434. std::string expr;
  6435. if( m_info.macroName[0] == 0 )
  6436. expr = m_info.capturedExpression;
  6437. else {
  6438. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6439. expr += m_info.macroName;
  6440. expr += "( ";
  6441. expr += m_info.capturedExpression;
  6442. expr += " )";
  6443. }
  6444. return expr;
  6445. }
  6446. bool AssertionResult::hasExpandedExpression() const {
  6447. return hasExpression() && getExpandedExpression() != getExpression();
  6448. }
  6449. std::string AssertionResult::getExpandedExpression() const {
  6450. std::string expr = m_resultData.reconstructExpression();
  6451. return expr.empty()
  6452. ? getExpression()
  6453. : expr;
  6454. }
  6455. std::string AssertionResult::getMessage() const {
  6456. return m_resultData.message;
  6457. }
  6458. SourceLineInfo AssertionResult::getSourceInfo() const {
  6459. return m_info.lineInfo;
  6460. }
  6461. StringRef AssertionResult::getTestMacroName() const {
  6462. return m_info.macroName;
  6463. }
  6464. } // end namespace Catch
  6465. // end catch_assertionresult.cpp
  6466. // start catch_capture_matchers.cpp
  6467. namespace Catch {
  6468. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6469. // This is the general overload that takes a any string matcher
  6470. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6471. // the Equals matcher (so the header does not mention matchers)
  6472. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6473. std::string exceptionMessage = Catch::translateActiveException();
  6474. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6475. handler.handleExpr( expr );
  6476. }
  6477. } // namespace Catch
  6478. // end catch_capture_matchers.cpp
  6479. // start catch_commandline.cpp
  6480. // start catch_commandline.h
  6481. // start catch_clara.h
  6482. // Use Catch's value for console width (store Clara's off to the side, if present)
  6483. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6484. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6485. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6486. #endif
  6487. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6488. #ifdef __clang__
  6489. #pragma clang diagnostic push
  6490. #pragma clang diagnostic ignored "-Wweak-vtables"
  6491. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6492. #pragma clang diagnostic ignored "-Wshadow"
  6493. #endif
  6494. // start clara.hpp
  6495. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6496. //
  6497. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6498. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6499. //
  6500. // See https://github.com/philsquared/Clara for more details
  6501. // Clara v1.1.5
  6502. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6503. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6504. #endif
  6505. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6506. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6507. #endif
  6508. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6509. #ifdef __has_include
  6510. #if __has_include(<optional>) && __cplusplus >= 201703L
  6511. #include <optional>
  6512. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6513. #endif
  6514. #endif
  6515. #endif
  6516. // ----------- #included from clara_textflow.hpp -----------
  6517. // TextFlowCpp
  6518. //
  6519. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6520. //
  6521. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6522. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6523. //
  6524. // This project is hosted at https://github.com/philsquared/textflowcpp
  6525. #include <cassert>
  6526. #include <ostream>
  6527. #include <sstream>
  6528. #include <vector>
  6529. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6530. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6531. #endif
  6532. namespace Catch {
  6533. namespace clara {
  6534. namespace TextFlow {
  6535. inline auto isWhitespace(char c) -> bool {
  6536. static std::string chars = " \t\n\r";
  6537. return chars.find(c) != std::string::npos;
  6538. }
  6539. inline auto isBreakableBefore(char c) -> bool {
  6540. static std::string chars = "[({<|";
  6541. return chars.find(c) != std::string::npos;
  6542. }
  6543. inline auto isBreakableAfter(char c) -> bool {
  6544. static std::string chars = "])}>.,:;*+-=&/\\";
  6545. return chars.find(c) != std::string::npos;
  6546. }
  6547. class Columns;
  6548. class Column {
  6549. std::vector<std::string> m_strings;
  6550. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6551. size_t m_indent = 0;
  6552. size_t m_initialIndent = std::string::npos;
  6553. public:
  6554. class iterator {
  6555. friend Column;
  6556. Column const& m_column;
  6557. size_t m_stringIndex = 0;
  6558. size_t m_pos = 0;
  6559. size_t m_len = 0;
  6560. size_t m_end = 0;
  6561. bool m_suffix = false;
  6562. iterator(Column const& column, size_t stringIndex)
  6563. : m_column(column),
  6564. m_stringIndex(stringIndex) {}
  6565. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6566. auto isBoundary(size_t at) const -> bool {
  6567. assert(at > 0);
  6568. assert(at <= line().size());
  6569. return at == line().size() ||
  6570. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6571. isBreakableBefore(line()[at]) ||
  6572. isBreakableAfter(line()[at - 1]);
  6573. }
  6574. void calcLength() {
  6575. assert(m_stringIndex < m_column.m_strings.size());
  6576. m_suffix = false;
  6577. auto width = m_column.m_width - indent();
  6578. m_end = m_pos;
  6579. if (line()[m_pos] == '\n') {
  6580. ++m_end;
  6581. }
  6582. while (m_end < line().size() && line()[m_end] != '\n')
  6583. ++m_end;
  6584. if (m_end < m_pos + width) {
  6585. m_len = m_end - m_pos;
  6586. } else {
  6587. size_t len = width;
  6588. while (len > 0 && !isBoundary(m_pos + len))
  6589. --len;
  6590. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6591. --len;
  6592. if (len > 0) {
  6593. m_len = len;
  6594. } else {
  6595. m_suffix = true;
  6596. m_len = width - 1;
  6597. }
  6598. }
  6599. }
  6600. auto indent() const -> size_t {
  6601. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6602. return initial == std::string::npos ? m_column.m_indent : initial;
  6603. }
  6604. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6605. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6606. }
  6607. public:
  6608. using difference_type = std::ptrdiff_t;
  6609. using value_type = std::string;
  6610. using pointer = value_type * ;
  6611. using reference = value_type & ;
  6612. using iterator_category = std::forward_iterator_tag;
  6613. explicit iterator(Column const& column) : m_column(column) {
  6614. assert(m_column.m_width > m_column.m_indent);
  6615. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6616. calcLength();
  6617. if (m_len == 0)
  6618. m_stringIndex++; // Empty string
  6619. }
  6620. auto operator *() const -> std::string {
  6621. assert(m_stringIndex < m_column.m_strings.size());
  6622. assert(m_pos <= m_end);
  6623. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6624. }
  6625. auto operator ++() -> iterator& {
  6626. m_pos += m_len;
  6627. if (m_pos < line().size() && line()[m_pos] == '\n')
  6628. m_pos += 1;
  6629. else
  6630. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6631. ++m_pos;
  6632. if (m_pos == line().size()) {
  6633. m_pos = 0;
  6634. ++m_stringIndex;
  6635. }
  6636. if (m_stringIndex < m_column.m_strings.size())
  6637. calcLength();
  6638. return *this;
  6639. }
  6640. auto operator ++(int) -> iterator {
  6641. iterator prev(*this);
  6642. operator++();
  6643. return prev;
  6644. }
  6645. auto operator ==(iterator const& other) const -> bool {
  6646. return
  6647. m_pos == other.m_pos &&
  6648. m_stringIndex == other.m_stringIndex &&
  6649. &m_column == &other.m_column;
  6650. }
  6651. auto operator !=(iterator const& other) const -> bool {
  6652. return !operator==(other);
  6653. }
  6654. };
  6655. using const_iterator = iterator;
  6656. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6657. auto width(size_t newWidth) -> Column& {
  6658. assert(newWidth > 0);
  6659. m_width = newWidth;
  6660. return *this;
  6661. }
  6662. auto indent(size_t newIndent) -> Column& {
  6663. m_indent = newIndent;
  6664. return *this;
  6665. }
  6666. auto initialIndent(size_t newIndent) -> Column& {
  6667. m_initialIndent = newIndent;
  6668. return *this;
  6669. }
  6670. auto width() const -> size_t { return m_width; }
  6671. auto begin() const -> iterator { return iterator(*this); }
  6672. auto end() const -> iterator { return { *this, m_strings.size() }; }
  6673. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  6674. bool first = true;
  6675. for (auto line : col) {
  6676. if (first)
  6677. first = false;
  6678. else
  6679. os << "\n";
  6680. os << line;
  6681. }
  6682. return os;
  6683. }
  6684. auto operator + (Column const& other)->Columns;
  6685. auto toString() const -> std::string {
  6686. std::ostringstream oss;
  6687. oss << *this;
  6688. return oss.str();
  6689. }
  6690. };
  6691. class Spacer : public Column {
  6692. public:
  6693. explicit Spacer(size_t spaceWidth) : Column("") {
  6694. width(spaceWidth);
  6695. }
  6696. };
  6697. class Columns {
  6698. std::vector<Column> m_columns;
  6699. public:
  6700. class iterator {
  6701. friend Columns;
  6702. struct EndTag {};
  6703. std::vector<Column> const& m_columns;
  6704. std::vector<Column::iterator> m_iterators;
  6705. size_t m_activeIterators;
  6706. iterator(Columns const& columns, EndTag)
  6707. : m_columns(columns.m_columns),
  6708. m_activeIterators(0) {
  6709. m_iterators.reserve(m_columns.size());
  6710. for (auto const& col : m_columns)
  6711. m_iterators.push_back(col.end());
  6712. }
  6713. public:
  6714. using difference_type = std::ptrdiff_t;
  6715. using value_type = std::string;
  6716. using pointer = value_type * ;
  6717. using reference = value_type & ;
  6718. using iterator_category = std::forward_iterator_tag;
  6719. explicit iterator(Columns const& columns)
  6720. : m_columns(columns.m_columns),
  6721. m_activeIterators(m_columns.size()) {
  6722. m_iterators.reserve(m_columns.size());
  6723. for (auto const& col : m_columns)
  6724. m_iterators.push_back(col.begin());
  6725. }
  6726. auto operator ==(iterator const& other) const -> bool {
  6727. return m_iterators == other.m_iterators;
  6728. }
  6729. auto operator !=(iterator const& other) const -> bool {
  6730. return m_iterators != other.m_iterators;
  6731. }
  6732. auto operator *() const -> std::string {
  6733. std::string row, padding;
  6734. for (size_t i = 0; i < m_columns.size(); ++i) {
  6735. auto width = m_columns[i].width();
  6736. if (m_iterators[i] != m_columns[i].end()) {
  6737. std::string col = *m_iterators[i];
  6738. row += padding + col;
  6739. if (col.size() < width)
  6740. padding = std::string(width - col.size(), ' ');
  6741. else
  6742. padding = "";
  6743. } else {
  6744. padding += std::string(width, ' ');
  6745. }
  6746. }
  6747. return row;
  6748. }
  6749. auto operator ++() -> iterator& {
  6750. for (size_t i = 0; i < m_columns.size(); ++i) {
  6751. if (m_iterators[i] != m_columns[i].end())
  6752. ++m_iterators[i];
  6753. }
  6754. return *this;
  6755. }
  6756. auto operator ++(int) -> iterator {
  6757. iterator prev(*this);
  6758. operator++();
  6759. return prev;
  6760. }
  6761. };
  6762. using const_iterator = iterator;
  6763. auto begin() const -> iterator { return iterator(*this); }
  6764. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  6765. auto operator += (Column const& col) -> Columns& {
  6766. m_columns.push_back(col);
  6767. return *this;
  6768. }
  6769. auto operator + (Column const& col) -> Columns {
  6770. Columns combined = *this;
  6771. combined += col;
  6772. return combined;
  6773. }
  6774. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  6775. bool first = true;
  6776. for (auto line : cols) {
  6777. if (first)
  6778. first = false;
  6779. else
  6780. os << "\n";
  6781. os << line;
  6782. }
  6783. return os;
  6784. }
  6785. auto toString() const -> std::string {
  6786. std::ostringstream oss;
  6787. oss << *this;
  6788. return oss.str();
  6789. }
  6790. };
  6791. inline auto Column::operator + (Column const& other) -> Columns {
  6792. Columns cols;
  6793. cols += *this;
  6794. cols += other;
  6795. return cols;
  6796. }
  6797. }
  6798. }
  6799. }
  6800. // ----------- end of #include from clara_textflow.hpp -----------
  6801. // ........... back in clara.hpp
  6802. #include <cctype>
  6803. #include <string>
  6804. #include <memory>
  6805. #include <set>
  6806. #include <algorithm>
  6807. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  6808. #define CATCH_PLATFORM_WINDOWS
  6809. #endif
  6810. namespace Catch { namespace clara {
  6811. namespace detail {
  6812. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  6813. template<typename L>
  6814. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  6815. template<typename ClassT, typename ReturnT, typename... Args>
  6816. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  6817. static const bool isValid = false;
  6818. };
  6819. template<typename ClassT, typename ReturnT, typename ArgT>
  6820. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  6821. static const bool isValid = true;
  6822. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  6823. using ReturnType = ReturnT;
  6824. };
  6825. class TokenStream;
  6826. // Transport for raw args (copied from main args, or supplied via init list for testing)
  6827. class Args {
  6828. friend TokenStream;
  6829. std::string m_exeName;
  6830. std::vector<std::string> m_args;
  6831. public:
  6832. Args( int argc, char const* const* argv )
  6833. : m_exeName(argv[0]),
  6834. m_args(argv + 1, argv + argc) {}
  6835. Args( std::initializer_list<std::string> args )
  6836. : m_exeName( *args.begin() ),
  6837. m_args( args.begin()+1, args.end() )
  6838. {}
  6839. auto exeName() const -> std::string {
  6840. return m_exeName;
  6841. }
  6842. };
  6843. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  6844. // may encode an option + its argument if the : or = form is used
  6845. enum class TokenType {
  6846. Option, Argument
  6847. };
  6848. struct Token {
  6849. TokenType type;
  6850. std::string token;
  6851. };
  6852. inline auto isOptPrefix( char c ) -> bool {
  6853. return c == '-'
  6854. #ifdef CATCH_PLATFORM_WINDOWS
  6855. || c == '/'
  6856. #endif
  6857. ;
  6858. }
  6859. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  6860. class TokenStream {
  6861. using Iterator = std::vector<std::string>::const_iterator;
  6862. Iterator it;
  6863. Iterator itEnd;
  6864. std::vector<Token> m_tokenBuffer;
  6865. void loadBuffer() {
  6866. m_tokenBuffer.resize( 0 );
  6867. // Skip any empty strings
  6868. while( it != itEnd && it->empty() )
  6869. ++it;
  6870. if( it != itEnd ) {
  6871. auto const &next = *it;
  6872. if( isOptPrefix( next[0] ) ) {
  6873. auto delimiterPos = next.find_first_of( " :=" );
  6874. if( delimiterPos != std::string::npos ) {
  6875. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  6876. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  6877. } else {
  6878. if( next[1] != '-' && next.size() > 2 ) {
  6879. std::string opt = "- ";
  6880. for( size_t i = 1; i < next.size(); ++i ) {
  6881. opt[1] = next[i];
  6882. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  6883. }
  6884. } else {
  6885. m_tokenBuffer.push_back( { TokenType::Option, next } );
  6886. }
  6887. }
  6888. } else {
  6889. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  6890. }
  6891. }
  6892. }
  6893. public:
  6894. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  6895. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  6896. loadBuffer();
  6897. }
  6898. explicit operator bool() const {
  6899. return !m_tokenBuffer.empty() || it != itEnd;
  6900. }
  6901. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  6902. auto operator*() const -> Token {
  6903. assert( !m_tokenBuffer.empty() );
  6904. return m_tokenBuffer.front();
  6905. }
  6906. auto operator->() const -> Token const * {
  6907. assert( !m_tokenBuffer.empty() );
  6908. return &m_tokenBuffer.front();
  6909. }
  6910. auto operator++() -> TokenStream & {
  6911. if( m_tokenBuffer.size() >= 2 ) {
  6912. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  6913. } else {
  6914. if( it != itEnd )
  6915. ++it;
  6916. loadBuffer();
  6917. }
  6918. return *this;
  6919. }
  6920. };
  6921. class ResultBase {
  6922. public:
  6923. enum Type {
  6924. Ok, LogicError, RuntimeError
  6925. };
  6926. protected:
  6927. ResultBase( Type type ) : m_type( type ) {}
  6928. virtual ~ResultBase() = default;
  6929. virtual void enforceOk() const = 0;
  6930. Type m_type;
  6931. };
  6932. template<typename T>
  6933. class ResultValueBase : public ResultBase {
  6934. public:
  6935. auto value() const -> T const & {
  6936. enforceOk();
  6937. return m_value;
  6938. }
  6939. protected:
  6940. ResultValueBase( Type type ) : ResultBase( type ) {}
  6941. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  6942. if( m_type == ResultBase::Ok )
  6943. new( &m_value ) T( other.m_value );
  6944. }
  6945. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  6946. new( &m_value ) T( value );
  6947. }
  6948. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  6949. if( m_type == ResultBase::Ok )
  6950. m_value.~T();
  6951. ResultBase::operator=(other);
  6952. if( m_type == ResultBase::Ok )
  6953. new( &m_value ) T( other.m_value );
  6954. return *this;
  6955. }
  6956. ~ResultValueBase() override {
  6957. if( m_type == Ok )
  6958. m_value.~T();
  6959. }
  6960. union {
  6961. T m_value;
  6962. };
  6963. };
  6964. template<>
  6965. class ResultValueBase<void> : public ResultBase {
  6966. protected:
  6967. using ResultBase::ResultBase;
  6968. };
  6969. template<typename T = void>
  6970. class BasicResult : public ResultValueBase<T> {
  6971. public:
  6972. template<typename U>
  6973. explicit BasicResult( BasicResult<U> const &other )
  6974. : ResultValueBase<T>( other.type() ),
  6975. m_errorMessage( other.errorMessage() )
  6976. {
  6977. assert( type() != ResultBase::Ok );
  6978. }
  6979. template<typename U>
  6980. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  6981. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  6982. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  6983. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  6984. explicit operator bool() const { return m_type == ResultBase::Ok; }
  6985. auto type() const -> ResultBase::Type { return m_type; }
  6986. auto errorMessage() const -> std::string { return m_errorMessage; }
  6987. protected:
  6988. void enforceOk() const override {
  6989. // Errors shouldn't reach this point, but if they do
  6990. // the actual error message will be in m_errorMessage
  6991. assert( m_type != ResultBase::LogicError );
  6992. assert( m_type != ResultBase::RuntimeError );
  6993. if( m_type != ResultBase::Ok )
  6994. std::abort();
  6995. }
  6996. std::string m_errorMessage; // Only populated if resultType is an error
  6997. BasicResult( ResultBase::Type type, std::string const &message )
  6998. : ResultValueBase<T>(type),
  6999. m_errorMessage(message)
  7000. {
  7001. assert( m_type != ResultBase::Ok );
  7002. }
  7003. using ResultValueBase<T>::ResultValueBase;
  7004. using ResultBase::m_type;
  7005. };
  7006. enum class ParseResultType {
  7007. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7008. };
  7009. class ParseState {
  7010. public:
  7011. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7012. : m_type(type),
  7013. m_remainingTokens( remainingTokens )
  7014. {}
  7015. auto type() const -> ParseResultType { return m_type; }
  7016. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7017. private:
  7018. ParseResultType m_type;
  7019. TokenStream m_remainingTokens;
  7020. };
  7021. using Result = BasicResult<void>;
  7022. using ParserResult = BasicResult<ParseResultType>;
  7023. using InternalParseResult = BasicResult<ParseState>;
  7024. struct HelpColumns {
  7025. std::string left;
  7026. std::string right;
  7027. };
  7028. template<typename T>
  7029. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7030. std::stringstream ss;
  7031. ss << source;
  7032. ss >> target;
  7033. if( ss.fail() )
  7034. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7035. else
  7036. return ParserResult::ok( ParseResultType::Matched );
  7037. }
  7038. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7039. target = source;
  7040. return ParserResult::ok( ParseResultType::Matched );
  7041. }
  7042. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7043. std::string srcLC = source;
  7044. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  7045. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7046. target = true;
  7047. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7048. target = false;
  7049. else
  7050. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7051. return ParserResult::ok( ParseResultType::Matched );
  7052. }
  7053. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7054. template<typename T>
  7055. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7056. T temp;
  7057. auto result = convertInto( source, temp );
  7058. if( result )
  7059. target = std::move(temp);
  7060. return result;
  7061. }
  7062. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7063. struct NonCopyable {
  7064. NonCopyable() = default;
  7065. NonCopyable( NonCopyable const & ) = delete;
  7066. NonCopyable( NonCopyable && ) = delete;
  7067. NonCopyable &operator=( NonCopyable const & ) = delete;
  7068. NonCopyable &operator=( NonCopyable && ) = delete;
  7069. };
  7070. struct BoundRef : NonCopyable {
  7071. virtual ~BoundRef() = default;
  7072. virtual auto isContainer() const -> bool { return false; }
  7073. virtual auto isFlag() const -> bool { return false; }
  7074. };
  7075. struct BoundValueRefBase : BoundRef {
  7076. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7077. };
  7078. struct BoundFlagRefBase : BoundRef {
  7079. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7080. virtual auto isFlag() const -> bool { return true; }
  7081. };
  7082. template<typename T>
  7083. struct BoundValueRef : BoundValueRefBase {
  7084. T &m_ref;
  7085. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7086. auto setValue( std::string const &arg ) -> ParserResult override {
  7087. return convertInto( arg, m_ref );
  7088. }
  7089. };
  7090. template<typename T>
  7091. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7092. std::vector<T> &m_ref;
  7093. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7094. auto isContainer() const -> bool override { return true; }
  7095. auto setValue( std::string const &arg ) -> ParserResult override {
  7096. T temp;
  7097. auto result = convertInto( arg, temp );
  7098. if( result )
  7099. m_ref.push_back( temp );
  7100. return result;
  7101. }
  7102. };
  7103. struct BoundFlagRef : BoundFlagRefBase {
  7104. bool &m_ref;
  7105. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7106. auto setFlag( bool flag ) -> ParserResult override {
  7107. m_ref = flag;
  7108. return ParserResult::ok( ParseResultType::Matched );
  7109. }
  7110. };
  7111. template<typename ReturnType>
  7112. struct LambdaInvoker {
  7113. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7114. template<typename L, typename ArgType>
  7115. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7116. return lambda( arg );
  7117. }
  7118. };
  7119. template<>
  7120. struct LambdaInvoker<void> {
  7121. template<typename L, typename ArgType>
  7122. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7123. lambda( arg );
  7124. return ParserResult::ok( ParseResultType::Matched );
  7125. }
  7126. };
  7127. template<typename ArgType, typename L>
  7128. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7129. ArgType temp{};
  7130. auto result = convertInto( arg, temp );
  7131. return !result
  7132. ? result
  7133. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7134. }
  7135. template<typename L>
  7136. struct BoundLambda : BoundValueRefBase {
  7137. L m_lambda;
  7138. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7139. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7140. auto setValue( std::string const &arg ) -> ParserResult override {
  7141. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7142. }
  7143. };
  7144. template<typename L>
  7145. struct BoundFlagLambda : BoundFlagRefBase {
  7146. L m_lambda;
  7147. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7148. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7149. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7150. auto setFlag( bool flag ) -> ParserResult override {
  7151. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7152. }
  7153. };
  7154. enum class Optionality { Optional, Required };
  7155. struct Parser;
  7156. class ParserBase {
  7157. public:
  7158. virtual ~ParserBase() = default;
  7159. virtual auto validate() const -> Result { return Result::ok(); }
  7160. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7161. virtual auto cardinality() const -> size_t { return 1; }
  7162. auto parse( Args const &args ) const -> InternalParseResult {
  7163. return parse( args.exeName(), TokenStream( args ) );
  7164. }
  7165. };
  7166. template<typename DerivedT>
  7167. class ComposableParserImpl : public ParserBase {
  7168. public:
  7169. template<typename T>
  7170. auto operator|( T const &other ) const -> Parser;
  7171. template<typename T>
  7172. auto operator+( T const &other ) const -> Parser;
  7173. };
  7174. // Common code and state for Args and Opts
  7175. template<typename DerivedT>
  7176. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7177. protected:
  7178. Optionality m_optionality = Optionality::Optional;
  7179. std::shared_ptr<BoundRef> m_ref;
  7180. std::string m_hint;
  7181. std::string m_description;
  7182. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7183. public:
  7184. template<typename T>
  7185. ParserRefImpl( T &ref, std::string const &hint )
  7186. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7187. m_hint( hint )
  7188. {}
  7189. template<typename LambdaT>
  7190. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7191. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7192. m_hint(hint)
  7193. {}
  7194. auto operator()( std::string const &description ) -> DerivedT & {
  7195. m_description = description;
  7196. return static_cast<DerivedT &>( *this );
  7197. }
  7198. auto optional() -> DerivedT & {
  7199. m_optionality = Optionality::Optional;
  7200. return static_cast<DerivedT &>( *this );
  7201. };
  7202. auto required() -> DerivedT & {
  7203. m_optionality = Optionality::Required;
  7204. return static_cast<DerivedT &>( *this );
  7205. };
  7206. auto isOptional() const -> bool {
  7207. return m_optionality == Optionality::Optional;
  7208. }
  7209. auto cardinality() const -> size_t override {
  7210. if( m_ref->isContainer() )
  7211. return 0;
  7212. else
  7213. return 1;
  7214. }
  7215. auto hint() const -> std::string { return m_hint; }
  7216. };
  7217. class ExeName : public ComposableParserImpl<ExeName> {
  7218. std::shared_ptr<std::string> m_name;
  7219. std::shared_ptr<BoundValueRefBase> m_ref;
  7220. template<typename LambdaT>
  7221. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7222. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7223. }
  7224. public:
  7225. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7226. explicit ExeName( std::string &ref ) : ExeName() {
  7227. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7228. }
  7229. template<typename LambdaT>
  7230. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7231. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7232. }
  7233. // The exe name is not parsed out of the normal tokens, but is handled specially
  7234. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7235. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7236. }
  7237. auto name() const -> std::string { return *m_name; }
  7238. auto set( std::string const& newName ) -> ParserResult {
  7239. auto lastSlash = newName.find_last_of( "\\/" );
  7240. auto filename = ( lastSlash == std::string::npos )
  7241. ? newName
  7242. : newName.substr( lastSlash+1 );
  7243. *m_name = filename;
  7244. if( m_ref )
  7245. return m_ref->setValue( filename );
  7246. else
  7247. return ParserResult::ok( ParseResultType::Matched );
  7248. }
  7249. };
  7250. class Arg : public ParserRefImpl<Arg> {
  7251. public:
  7252. using ParserRefImpl::ParserRefImpl;
  7253. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7254. auto validationResult = validate();
  7255. if( !validationResult )
  7256. return InternalParseResult( validationResult );
  7257. auto remainingTokens = tokens;
  7258. auto const &token = *remainingTokens;
  7259. if( token.type != TokenType::Argument )
  7260. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7261. assert( !m_ref->isFlag() );
  7262. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7263. auto result = valueRef->setValue( remainingTokens->token );
  7264. if( !result )
  7265. return InternalParseResult( result );
  7266. else
  7267. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7268. }
  7269. };
  7270. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7271. #ifdef CATCH_PLATFORM_WINDOWS
  7272. if( optName[0] == '/' )
  7273. return "-" + optName.substr( 1 );
  7274. else
  7275. #endif
  7276. return optName;
  7277. }
  7278. class Opt : public ParserRefImpl<Opt> {
  7279. protected:
  7280. std::vector<std::string> m_optNames;
  7281. public:
  7282. template<typename LambdaT>
  7283. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7284. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7285. template<typename LambdaT>
  7286. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7287. template<typename T>
  7288. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7289. auto operator[]( std::string const &optName ) -> Opt & {
  7290. m_optNames.push_back( optName );
  7291. return *this;
  7292. }
  7293. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7294. std::ostringstream oss;
  7295. bool first = true;
  7296. for( auto const &opt : m_optNames ) {
  7297. if (first)
  7298. first = false;
  7299. else
  7300. oss << ", ";
  7301. oss << opt;
  7302. }
  7303. if( !m_hint.empty() )
  7304. oss << " <" << m_hint << ">";
  7305. return { { oss.str(), m_description } };
  7306. }
  7307. auto isMatch( std::string const &optToken ) const -> bool {
  7308. auto normalisedToken = normaliseOpt( optToken );
  7309. for( auto const &name : m_optNames ) {
  7310. if( normaliseOpt( name ) == normalisedToken )
  7311. return true;
  7312. }
  7313. return false;
  7314. }
  7315. using ParserBase::parse;
  7316. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7317. auto validationResult = validate();
  7318. if( !validationResult )
  7319. return InternalParseResult( validationResult );
  7320. auto remainingTokens = tokens;
  7321. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7322. auto const &token = *remainingTokens;
  7323. if( isMatch(token.token ) ) {
  7324. if( m_ref->isFlag() ) {
  7325. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7326. auto result = flagRef->setFlag( true );
  7327. if( !result )
  7328. return InternalParseResult( result );
  7329. if( result.value() == ParseResultType::ShortCircuitAll )
  7330. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7331. } else {
  7332. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7333. ++remainingTokens;
  7334. if( !remainingTokens )
  7335. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7336. auto const &argToken = *remainingTokens;
  7337. if( argToken.type != TokenType::Argument )
  7338. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7339. auto result = valueRef->setValue( argToken.token );
  7340. if( !result )
  7341. return InternalParseResult( result );
  7342. if( result.value() == ParseResultType::ShortCircuitAll )
  7343. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7344. }
  7345. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7346. }
  7347. }
  7348. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7349. }
  7350. auto validate() const -> Result override {
  7351. if( m_optNames.empty() )
  7352. return Result::logicError( "No options supplied to Opt" );
  7353. for( auto const &name : m_optNames ) {
  7354. if( name.empty() )
  7355. return Result::logicError( "Option name cannot be empty" );
  7356. #ifdef CATCH_PLATFORM_WINDOWS
  7357. if( name[0] != '-' && name[0] != '/' )
  7358. return Result::logicError( "Option name must begin with '-' or '/'" );
  7359. #else
  7360. if( name[0] != '-' )
  7361. return Result::logicError( "Option name must begin with '-'" );
  7362. #endif
  7363. }
  7364. return ParserRefImpl::validate();
  7365. }
  7366. };
  7367. struct Help : Opt {
  7368. Help( bool &showHelpFlag )
  7369. : Opt([&]( bool flag ) {
  7370. showHelpFlag = flag;
  7371. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7372. })
  7373. {
  7374. static_cast<Opt &>( *this )
  7375. ("display usage information")
  7376. ["-?"]["-h"]["--help"]
  7377. .optional();
  7378. }
  7379. };
  7380. struct Parser : ParserBase {
  7381. mutable ExeName m_exeName;
  7382. std::vector<Opt> m_options;
  7383. std::vector<Arg> m_args;
  7384. auto operator|=( ExeName const &exeName ) -> Parser & {
  7385. m_exeName = exeName;
  7386. return *this;
  7387. }
  7388. auto operator|=( Arg const &arg ) -> Parser & {
  7389. m_args.push_back(arg);
  7390. return *this;
  7391. }
  7392. auto operator|=( Opt const &opt ) -> Parser & {
  7393. m_options.push_back(opt);
  7394. return *this;
  7395. }
  7396. auto operator|=( Parser const &other ) -> Parser & {
  7397. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7398. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7399. return *this;
  7400. }
  7401. template<typename T>
  7402. auto operator|( T const &other ) const -> Parser {
  7403. return Parser( *this ) |= other;
  7404. }
  7405. // Forward deprecated interface with '+' instead of '|'
  7406. template<typename T>
  7407. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7408. template<typename T>
  7409. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7410. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7411. std::vector<HelpColumns> cols;
  7412. for (auto const &o : m_options) {
  7413. auto childCols = o.getHelpColumns();
  7414. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7415. }
  7416. return cols;
  7417. }
  7418. void writeToStream( std::ostream &os ) const {
  7419. if (!m_exeName.name().empty()) {
  7420. os << "usage:\n" << " " << m_exeName.name() << " ";
  7421. bool required = true, first = true;
  7422. for( auto const &arg : m_args ) {
  7423. if (first)
  7424. first = false;
  7425. else
  7426. os << " ";
  7427. if( arg.isOptional() && required ) {
  7428. os << "[";
  7429. required = false;
  7430. }
  7431. os << "<" << arg.hint() << ">";
  7432. if( arg.cardinality() == 0 )
  7433. os << " ... ";
  7434. }
  7435. if( !required )
  7436. os << "]";
  7437. if( !m_options.empty() )
  7438. os << " options";
  7439. os << "\n\nwhere options are:" << std::endl;
  7440. }
  7441. auto rows = getHelpColumns();
  7442. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7443. size_t optWidth = 0;
  7444. for( auto const &cols : rows )
  7445. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7446. optWidth = (std::min)(optWidth, consoleWidth/2);
  7447. for( auto const &cols : rows ) {
  7448. auto row =
  7449. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7450. TextFlow::Spacer(4) +
  7451. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7452. os << row << std::endl;
  7453. }
  7454. }
  7455. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7456. parser.writeToStream( os );
  7457. return os;
  7458. }
  7459. auto validate() const -> Result override {
  7460. for( auto const &opt : m_options ) {
  7461. auto result = opt.validate();
  7462. if( !result )
  7463. return result;
  7464. }
  7465. for( auto const &arg : m_args ) {
  7466. auto result = arg.validate();
  7467. if( !result )
  7468. return result;
  7469. }
  7470. return Result::ok();
  7471. }
  7472. using ParserBase::parse;
  7473. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7474. struct ParserInfo {
  7475. ParserBase const* parser = nullptr;
  7476. size_t count = 0;
  7477. };
  7478. const size_t totalParsers = m_options.size() + m_args.size();
  7479. assert( totalParsers < 512 );
  7480. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7481. ParserInfo parseInfos[512];
  7482. {
  7483. size_t i = 0;
  7484. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7485. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7486. }
  7487. m_exeName.set( exeName );
  7488. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7489. while( result.value().remainingTokens() ) {
  7490. bool tokenParsed = false;
  7491. for( size_t i = 0; i < totalParsers; ++i ) {
  7492. auto& parseInfo = parseInfos[i];
  7493. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7494. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7495. if (!result)
  7496. return result;
  7497. if (result.value().type() != ParseResultType::NoMatch) {
  7498. tokenParsed = true;
  7499. ++parseInfo.count;
  7500. break;
  7501. }
  7502. }
  7503. }
  7504. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7505. return result;
  7506. if( !tokenParsed )
  7507. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7508. }
  7509. // !TBD Check missing required options
  7510. return result;
  7511. }
  7512. };
  7513. template<typename DerivedT>
  7514. template<typename T>
  7515. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7516. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7517. }
  7518. } // namespace detail
  7519. // A Combined parser
  7520. using detail::Parser;
  7521. // A parser for options
  7522. using detail::Opt;
  7523. // A parser for arguments
  7524. using detail::Arg;
  7525. // Wrapper for argc, argv from main()
  7526. using detail::Args;
  7527. // Specifies the name of the executable
  7528. using detail::ExeName;
  7529. // Convenience wrapper for option parser that specifies the help option
  7530. using detail::Help;
  7531. // enum of result types from a parse
  7532. using detail::ParseResultType;
  7533. // Result type for parser operation
  7534. using detail::ParserResult;
  7535. }} // namespace Catch::clara
  7536. // end clara.hpp
  7537. #ifdef __clang__
  7538. #pragma clang diagnostic pop
  7539. #endif
  7540. // Restore Clara's value for console width, if present
  7541. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7542. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7543. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7544. #endif
  7545. // end catch_clara.h
  7546. namespace Catch {
  7547. clara::Parser makeCommandLineParser( ConfigData& config );
  7548. } // end namespace Catch
  7549. // end catch_commandline.h
  7550. #include <fstream>
  7551. #include <ctime>
  7552. namespace Catch {
  7553. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7554. using namespace clara;
  7555. auto const setWarning = [&]( std::string const& warning ) {
  7556. auto warningSet = [&]() {
  7557. if( warning == "NoAssertions" )
  7558. return WarnAbout::NoAssertions;
  7559. if ( warning == "NoTests" )
  7560. return WarnAbout::NoTests;
  7561. return WarnAbout::Nothing;
  7562. }();
  7563. if (warningSet == WarnAbout::Nothing)
  7564. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7565. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7566. return ParserResult::ok( ParseResultType::Matched );
  7567. };
  7568. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7569. std::ifstream f( filename.c_str() );
  7570. if( !f.is_open() )
  7571. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7572. std::string line;
  7573. while( std::getline( f, line ) ) {
  7574. line = trim(line);
  7575. if( !line.empty() && !startsWith( line, '#' ) ) {
  7576. if( !startsWith( line, '"' ) )
  7577. line = '"' + line + '"';
  7578. config.testsOrTags.push_back( line + ',' );
  7579. }
  7580. }
  7581. return ParserResult::ok( ParseResultType::Matched );
  7582. };
  7583. auto const setTestOrder = [&]( std::string const& order ) {
  7584. if( startsWith( "declared", order ) )
  7585. config.runOrder = RunTests::InDeclarationOrder;
  7586. else if( startsWith( "lexical", order ) )
  7587. config.runOrder = RunTests::InLexicographicalOrder;
  7588. else if( startsWith( "random", order ) )
  7589. config.runOrder = RunTests::InRandomOrder;
  7590. else
  7591. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7592. return ParserResult::ok( ParseResultType::Matched );
  7593. };
  7594. auto const setRngSeed = [&]( std::string const& seed ) {
  7595. if( seed != "time" )
  7596. return clara::detail::convertInto( seed, config.rngSeed );
  7597. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7598. return ParserResult::ok( ParseResultType::Matched );
  7599. };
  7600. auto const setColourUsage = [&]( std::string const& useColour ) {
  7601. auto mode = toLower( useColour );
  7602. if( mode == "yes" )
  7603. config.useColour = UseColour::Yes;
  7604. else if( mode == "no" )
  7605. config.useColour = UseColour::No;
  7606. else if( mode == "auto" )
  7607. config.useColour = UseColour::Auto;
  7608. else
  7609. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7610. return ParserResult::ok( ParseResultType::Matched );
  7611. };
  7612. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7613. auto keypressLc = toLower( keypress );
  7614. if( keypressLc == "start" )
  7615. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7616. else if( keypressLc == "exit" )
  7617. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7618. else if( keypressLc == "both" )
  7619. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7620. else
  7621. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  7622. return ParserResult::ok( ParseResultType::Matched );
  7623. };
  7624. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7625. auto lcVerbosity = toLower( verbosity );
  7626. if( lcVerbosity == "quiet" )
  7627. config.verbosity = Verbosity::Quiet;
  7628. else if( lcVerbosity == "normal" )
  7629. config.verbosity = Verbosity::Normal;
  7630. else if( lcVerbosity == "high" )
  7631. config.verbosity = Verbosity::High;
  7632. else
  7633. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7634. return ParserResult::ok( ParseResultType::Matched );
  7635. };
  7636. auto const setReporter = [&]( std::string const& reporter ) {
  7637. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7638. auto lcReporter = toLower( reporter );
  7639. auto result = factories.find( lcReporter );
  7640. if( factories.end() != result )
  7641. config.reporterName = lcReporter;
  7642. else
  7643. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7644. return ParserResult::ok( ParseResultType::Matched );
  7645. };
  7646. auto cli
  7647. = ExeName( config.processName )
  7648. | Help( config.showHelp )
  7649. | Opt( config.listTests )
  7650. ["-l"]["--list-tests"]
  7651. ( "list all/matching test cases" )
  7652. | Opt( config.listTags )
  7653. ["-t"]["--list-tags"]
  7654. ( "list all/matching tags" )
  7655. | Opt( config.showSuccessfulTests )
  7656. ["-s"]["--success"]
  7657. ( "include successful tests in output" )
  7658. | Opt( config.shouldDebugBreak )
  7659. ["-b"]["--break"]
  7660. ( "break into debugger on failure" )
  7661. | Opt( config.noThrow )
  7662. ["-e"]["--nothrow"]
  7663. ( "skip exception tests" )
  7664. | Opt( config.showInvisibles )
  7665. ["-i"]["--invisibles"]
  7666. ( "show invisibles (tabs, newlines)" )
  7667. | Opt( config.outputFilename, "filename" )
  7668. ["-o"]["--out"]
  7669. ( "output filename" )
  7670. | Opt( setReporter, "name" )
  7671. ["-r"]["--reporter"]
  7672. ( "reporter to use (defaults to console)" )
  7673. | Opt( config.name, "name" )
  7674. ["-n"]["--name"]
  7675. ( "suite name" )
  7676. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  7677. ["-a"]["--abort"]
  7678. ( "abort at first failure" )
  7679. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  7680. ["-x"]["--abortx"]
  7681. ( "abort after x failures" )
  7682. | Opt( setWarning, "warning name" )
  7683. ["-w"]["--warn"]
  7684. ( "enable warnings" )
  7685. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  7686. ["-d"]["--durations"]
  7687. ( "show test durations" )
  7688. | Opt( loadTestNamesFromFile, "filename" )
  7689. ["-f"]["--input-file"]
  7690. ( "load test names to run from a file" )
  7691. | Opt( config.filenamesAsTags )
  7692. ["-#"]["--filenames-as-tags"]
  7693. ( "adds a tag for the filename" )
  7694. | Opt( config.sectionsToRun, "section name" )
  7695. ["-c"]["--section"]
  7696. ( "specify section to run" )
  7697. | Opt( setVerbosity, "quiet|normal|high" )
  7698. ["-v"]["--verbosity"]
  7699. ( "set output verbosity" )
  7700. | Opt( config.listTestNamesOnly )
  7701. ["--list-test-names-only"]
  7702. ( "list all/matching test cases names only" )
  7703. | Opt( config.listReporters )
  7704. ["--list-reporters"]
  7705. ( "list all reporters" )
  7706. | Opt( setTestOrder, "decl|lex|rand" )
  7707. ["--order"]
  7708. ( "test case order (defaults to decl)" )
  7709. | Opt( setRngSeed, "'time'|number" )
  7710. ["--rng-seed"]
  7711. ( "set a specific seed for random numbers" )
  7712. | Opt( setColourUsage, "yes|no" )
  7713. ["--use-colour"]
  7714. ( "should output be colourised" )
  7715. | Opt( config.libIdentify )
  7716. ["--libidentify"]
  7717. ( "report name and version according to libidentify standard" )
  7718. | Opt( setWaitForKeypress, "start|exit|both" )
  7719. ["--wait-for-keypress"]
  7720. ( "waits for a keypress before exiting" )
  7721. | Opt( config.benchmarkSamples, "samples" )
  7722. ["--benchmark-samples"]
  7723. ( "number of samples to collect (default: 100)" )
  7724. | Opt( config.benchmarkResamples, "resamples" )
  7725. ["--benchmark-resamples"]
  7726. ( "number of resamples for the bootstrap (default: 100000)" )
  7727. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  7728. ["--benchmark-confidence-interval"]
  7729. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  7730. | Opt( config.benchmarkNoAnalysis )
  7731. ["--benchmark-no-analysis"]
  7732. ( "perform only measurements; do not perform any analysis" )
  7733. | Arg( config.testsOrTags, "test name|pattern|tags" )
  7734. ( "which test or tests to use" );
  7735. return cli;
  7736. }
  7737. } // end namespace Catch
  7738. // end catch_commandline.cpp
  7739. // start catch_common.cpp
  7740. #include <cstring>
  7741. #include <ostream>
  7742. namespace Catch {
  7743. bool SourceLineInfo::empty() const noexcept {
  7744. return file[0] == '\0';
  7745. }
  7746. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  7747. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  7748. }
  7749. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  7750. // We can assume that the same file will usually have the same pointer.
  7751. // Thus, if the pointers are the same, there is no point in calling the strcmp
  7752. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  7753. }
  7754. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  7755. #ifndef __GNUG__
  7756. os << info.file << '(' << info.line << ')';
  7757. #else
  7758. os << info.file << ':' << info.line;
  7759. #endif
  7760. return os;
  7761. }
  7762. std::string StreamEndStop::operator+() const {
  7763. return std::string();
  7764. }
  7765. NonCopyable::NonCopyable() = default;
  7766. NonCopyable::~NonCopyable() = default;
  7767. }
  7768. // end catch_common.cpp
  7769. // start catch_config.cpp
  7770. namespace Catch {
  7771. Config::Config( ConfigData const& data )
  7772. : m_data( data ),
  7773. m_stream( openStream() )
  7774. {
  7775. TestSpecParser parser(ITagAliasRegistry::get());
  7776. if (!data.testsOrTags.empty()) {
  7777. m_hasTestFilters = true;
  7778. for( auto const& testOrTags : data.testsOrTags )
  7779. parser.parse( testOrTags );
  7780. }
  7781. m_testSpec = parser.testSpec();
  7782. }
  7783. std::string const& Config::getFilename() const {
  7784. return m_data.outputFilename ;
  7785. }
  7786. bool Config::listTests() const { return m_data.listTests; }
  7787. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  7788. bool Config::listTags() const { return m_data.listTags; }
  7789. bool Config::listReporters() const { return m_data.listReporters; }
  7790. std::string Config::getProcessName() const { return m_data.processName; }
  7791. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  7792. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  7793. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  7794. TestSpec const& Config::testSpec() const { return m_testSpec; }
  7795. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  7796. bool Config::showHelp() const { return m_data.showHelp; }
  7797. // IConfig interface
  7798. bool Config::allowThrows() const { return !m_data.noThrow; }
  7799. std::ostream& Config::stream() const { return m_stream->stream(); }
  7800. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  7801. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  7802. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  7803. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  7804. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  7805. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  7806. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  7807. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  7808. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  7809. int Config::abortAfter() const { return m_data.abortAfter; }
  7810. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  7811. Verbosity Config::verbosity() const { return m_data.verbosity; }
  7812. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  7813. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  7814. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  7815. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  7816. IStream const* Config::openStream() {
  7817. return Catch::makeStream(m_data.outputFilename);
  7818. }
  7819. } // end namespace Catch
  7820. // end catch_config.cpp
  7821. // start catch_console_colour.cpp
  7822. #if defined(__clang__)
  7823. # pragma clang diagnostic push
  7824. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7825. #endif
  7826. // start catch_errno_guard.h
  7827. namespace Catch {
  7828. class ErrnoGuard {
  7829. public:
  7830. ErrnoGuard();
  7831. ~ErrnoGuard();
  7832. private:
  7833. int m_oldErrno;
  7834. };
  7835. }
  7836. // end catch_errno_guard.h
  7837. #include <sstream>
  7838. namespace Catch {
  7839. namespace {
  7840. struct IColourImpl {
  7841. virtual ~IColourImpl() = default;
  7842. virtual void use( Colour::Code _colourCode ) = 0;
  7843. };
  7844. struct NoColourImpl : IColourImpl {
  7845. void use( Colour::Code ) {}
  7846. static IColourImpl* instance() {
  7847. static NoColourImpl s_instance;
  7848. return &s_instance;
  7849. }
  7850. };
  7851. } // anon namespace
  7852. } // namespace Catch
  7853. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  7854. # ifdef CATCH_PLATFORM_WINDOWS
  7855. # define CATCH_CONFIG_COLOUR_WINDOWS
  7856. # else
  7857. # define CATCH_CONFIG_COLOUR_ANSI
  7858. # endif
  7859. #endif
  7860. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  7861. namespace Catch {
  7862. namespace {
  7863. class Win32ColourImpl : public IColourImpl {
  7864. public:
  7865. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  7866. {
  7867. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  7868. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  7869. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  7870. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  7871. }
  7872. void use( Colour::Code _colourCode ) override {
  7873. switch( _colourCode ) {
  7874. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  7875. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7876. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  7877. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  7878. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  7879. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  7880. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  7881. case Colour::Grey: return setTextAttribute( 0 );
  7882. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  7883. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  7884. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  7885. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  7886. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  7887. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7888. default:
  7889. CATCH_ERROR( "Unknown colour requested" );
  7890. }
  7891. }
  7892. private:
  7893. void setTextAttribute( WORD _textAttribute ) {
  7894. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  7895. }
  7896. HANDLE stdoutHandle;
  7897. WORD originalForegroundAttributes;
  7898. WORD originalBackgroundAttributes;
  7899. };
  7900. IColourImpl* platformColourInstance() {
  7901. static Win32ColourImpl s_instance;
  7902. IConfigPtr config = getCurrentContext().getConfig();
  7903. UseColour::YesOrNo colourMode = config
  7904. ? config->useColour()
  7905. : UseColour::Auto;
  7906. if( colourMode == UseColour::Auto )
  7907. colourMode = UseColour::Yes;
  7908. return colourMode == UseColour::Yes
  7909. ? &s_instance
  7910. : NoColourImpl::instance();
  7911. }
  7912. } // end anon namespace
  7913. } // end namespace Catch
  7914. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  7915. #include <unistd.h>
  7916. namespace Catch {
  7917. namespace {
  7918. // use POSIX/ ANSI console terminal codes
  7919. // Thanks to Adam Strzelecki for original contribution
  7920. // (http://github.com/nanoant)
  7921. // https://github.com/philsquared/Catch/pull/131
  7922. class PosixColourImpl : public IColourImpl {
  7923. public:
  7924. void use( Colour::Code _colourCode ) override {
  7925. switch( _colourCode ) {
  7926. case Colour::None:
  7927. case Colour::White: return setColour( "[0m" );
  7928. case Colour::Red: return setColour( "[0;31m" );
  7929. case Colour::Green: return setColour( "[0;32m" );
  7930. case Colour::Blue: return setColour( "[0;34m" );
  7931. case Colour::Cyan: return setColour( "[0;36m" );
  7932. case Colour::Yellow: return setColour( "[0;33m" );
  7933. case Colour::Grey: return setColour( "[1;30m" );
  7934. case Colour::LightGrey: return setColour( "[0;37m" );
  7935. case Colour::BrightRed: return setColour( "[1;31m" );
  7936. case Colour::BrightGreen: return setColour( "[1;32m" );
  7937. case Colour::BrightWhite: return setColour( "[1;37m" );
  7938. case Colour::BrightYellow: return setColour( "[1;33m" );
  7939. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  7940. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  7941. }
  7942. }
  7943. static IColourImpl* instance() {
  7944. static PosixColourImpl s_instance;
  7945. return &s_instance;
  7946. }
  7947. private:
  7948. void setColour( const char* _escapeCode ) {
  7949. getCurrentContext().getConfig()->stream()
  7950. << '\033' << _escapeCode;
  7951. }
  7952. };
  7953. bool useColourOnPlatform() {
  7954. return
  7955. #ifdef CATCH_PLATFORM_MAC
  7956. !isDebuggerActive() &&
  7957. #endif
  7958. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  7959. isatty(STDOUT_FILENO)
  7960. #else
  7961. false
  7962. #endif
  7963. ;
  7964. }
  7965. IColourImpl* platformColourInstance() {
  7966. ErrnoGuard guard;
  7967. IConfigPtr config = getCurrentContext().getConfig();
  7968. UseColour::YesOrNo colourMode = config
  7969. ? config->useColour()
  7970. : UseColour::Auto;
  7971. if( colourMode == UseColour::Auto )
  7972. colourMode = useColourOnPlatform()
  7973. ? UseColour::Yes
  7974. : UseColour::No;
  7975. return colourMode == UseColour::Yes
  7976. ? PosixColourImpl::instance()
  7977. : NoColourImpl::instance();
  7978. }
  7979. } // end anon namespace
  7980. } // end namespace Catch
  7981. #else // not Windows or ANSI ///////////////////////////////////////////////
  7982. namespace Catch {
  7983. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  7984. } // end namespace Catch
  7985. #endif // Windows/ ANSI/ None
  7986. namespace Catch {
  7987. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  7988. Colour::Colour( Colour&& rhs ) noexcept {
  7989. m_moved = rhs.m_moved;
  7990. rhs.m_moved = true;
  7991. }
  7992. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  7993. m_moved = rhs.m_moved;
  7994. rhs.m_moved = true;
  7995. return *this;
  7996. }
  7997. Colour::~Colour(){ if( !m_moved ) use( None ); }
  7998. void Colour::use( Code _colourCode ) {
  7999. static IColourImpl* impl = platformColourInstance();
  8000. // Strictly speaking, this cannot possibly happen.
  8001. // However, under some conditions it does happen (see #1626),
  8002. // and this change is small enough that we can let practicality
  8003. // triumph over purity in this case.
  8004. if (impl != NULL) {
  8005. impl->use( _colourCode );
  8006. }
  8007. }
  8008. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8009. return os;
  8010. }
  8011. } // end namespace Catch
  8012. #if defined(__clang__)
  8013. # pragma clang diagnostic pop
  8014. #endif
  8015. // end catch_console_colour.cpp
  8016. // start catch_context.cpp
  8017. namespace Catch {
  8018. class Context : public IMutableContext, NonCopyable {
  8019. public: // IContext
  8020. IResultCapture* getResultCapture() override {
  8021. return m_resultCapture;
  8022. }
  8023. IRunner* getRunner() override {
  8024. return m_runner;
  8025. }
  8026. IConfigPtr const& getConfig() const override {
  8027. return m_config;
  8028. }
  8029. ~Context() override;
  8030. public: // IMutableContext
  8031. void setResultCapture( IResultCapture* resultCapture ) override {
  8032. m_resultCapture = resultCapture;
  8033. }
  8034. void setRunner( IRunner* runner ) override {
  8035. m_runner = runner;
  8036. }
  8037. void setConfig( IConfigPtr const& config ) override {
  8038. m_config = config;
  8039. }
  8040. friend IMutableContext& getCurrentMutableContext();
  8041. private:
  8042. IConfigPtr m_config;
  8043. IRunner* m_runner = nullptr;
  8044. IResultCapture* m_resultCapture = nullptr;
  8045. };
  8046. IMutableContext *IMutableContext::currentContext = nullptr;
  8047. void IMutableContext::createContext()
  8048. {
  8049. currentContext = new Context();
  8050. }
  8051. void cleanUpContext() {
  8052. delete IMutableContext::currentContext;
  8053. IMutableContext::currentContext = nullptr;
  8054. }
  8055. IContext::~IContext() = default;
  8056. IMutableContext::~IMutableContext() = default;
  8057. Context::~Context() = default;
  8058. }
  8059. // end catch_context.cpp
  8060. // start catch_debug_console.cpp
  8061. // start catch_debug_console.h
  8062. #include <string>
  8063. namespace Catch {
  8064. void writeToDebugConsole( std::string const& text );
  8065. }
  8066. // end catch_debug_console.h
  8067. #ifdef CATCH_PLATFORM_WINDOWS
  8068. namespace Catch {
  8069. void writeToDebugConsole( std::string const& text ) {
  8070. ::OutputDebugStringA( text.c_str() );
  8071. }
  8072. }
  8073. #else
  8074. namespace Catch {
  8075. void writeToDebugConsole( std::string const& text ) {
  8076. // !TBD: Need a version for Mac/ XCode and other IDEs
  8077. Catch::cout() << text;
  8078. }
  8079. }
  8080. #endif // Platform
  8081. // end catch_debug_console.cpp
  8082. // start catch_debugger.cpp
  8083. #ifdef CATCH_PLATFORM_MAC
  8084. # include <assert.h>
  8085. # include <stdbool.h>
  8086. # include <sys/types.h>
  8087. # include <unistd.h>
  8088. # include <cstddef>
  8089. # include <ostream>
  8090. #ifdef __apple_build_version__
  8091. // These headers will only compile with AppleClang (XCode)
  8092. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8093. # include <sys/sysctl.h>
  8094. #endif
  8095. namespace Catch {
  8096. #ifdef __apple_build_version__
  8097. // The following function is taken directly from the following technical note:
  8098. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8099. // Returns true if the current process is being debugged (either
  8100. // running under the debugger or has a debugger attached post facto).
  8101. bool isDebuggerActive(){
  8102. int mib[4];
  8103. struct kinfo_proc info;
  8104. std::size_t size;
  8105. // Initialize the flags so that, if sysctl fails for some bizarre
  8106. // reason, we get a predictable result.
  8107. info.kp_proc.p_flag = 0;
  8108. // Initialize mib, which tells sysctl the info we want, in this case
  8109. // we're looking for information about a specific process ID.
  8110. mib[0] = CTL_KERN;
  8111. mib[1] = KERN_PROC;
  8112. mib[2] = KERN_PROC_PID;
  8113. mib[3] = getpid();
  8114. // Call sysctl.
  8115. size = sizeof(info);
  8116. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8117. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8118. return false;
  8119. }
  8120. // We're being debugged if the P_TRACED flag is set.
  8121. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8122. }
  8123. #else
  8124. bool isDebuggerActive() {
  8125. // We need to find another way to determine this for non-appleclang compilers on macOS
  8126. return false;
  8127. }
  8128. #endif
  8129. } // namespace Catch
  8130. #elif defined(CATCH_PLATFORM_LINUX)
  8131. #include <fstream>
  8132. #include <string>
  8133. namespace Catch{
  8134. // The standard POSIX way of detecting a debugger is to attempt to
  8135. // ptrace() the process, but this needs to be done from a child and not
  8136. // this process itself to still allow attaching to this process later
  8137. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8138. // "debugger" (which doesn't need to be gdb, of course, it could also
  8139. // be strace, for example) in /proc/$PID/status, so just get it from
  8140. // there instead.
  8141. bool isDebuggerActive(){
  8142. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8143. // This way our users can properly assert over errno values
  8144. ErrnoGuard guard;
  8145. std::ifstream in("/proc/self/status");
  8146. for( std::string line; std::getline(in, line); ) {
  8147. static const int PREFIX_LEN = 11;
  8148. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8149. // We're traced if the PID is not 0 and no other PID starts
  8150. // with 0 digit, so it's enough to check for just a single
  8151. // character.
  8152. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8153. }
  8154. }
  8155. return false;
  8156. }
  8157. } // namespace Catch
  8158. #elif defined(_MSC_VER)
  8159. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8160. namespace Catch {
  8161. bool isDebuggerActive() {
  8162. return IsDebuggerPresent() != 0;
  8163. }
  8164. }
  8165. #elif defined(__MINGW32__)
  8166. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8167. namespace Catch {
  8168. bool isDebuggerActive() {
  8169. return IsDebuggerPresent() != 0;
  8170. }
  8171. }
  8172. #else
  8173. namespace Catch {
  8174. bool isDebuggerActive() { return false; }
  8175. }
  8176. #endif // Platform
  8177. // end catch_debugger.cpp
  8178. // start catch_decomposer.cpp
  8179. namespace Catch {
  8180. ITransientExpression::~ITransientExpression() = default;
  8181. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8182. if( lhs.size() + rhs.size() < 40 &&
  8183. lhs.find('\n') == std::string::npos &&
  8184. rhs.find('\n') == std::string::npos )
  8185. os << lhs << " " << op << " " << rhs;
  8186. else
  8187. os << lhs << "\n" << op << "\n" << rhs;
  8188. }
  8189. }
  8190. // end catch_decomposer.cpp
  8191. // start catch_enforce.cpp
  8192. #include <stdexcept>
  8193. namespace Catch {
  8194. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8195. [[noreturn]]
  8196. void throw_exception(std::exception const& e) {
  8197. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8198. << "The message was: " << e.what() << '\n';
  8199. std::terminate();
  8200. }
  8201. #endif
  8202. [[noreturn]]
  8203. void throw_logic_error(std::string const& msg) {
  8204. throw_exception(std::logic_error(msg));
  8205. }
  8206. [[noreturn]]
  8207. void throw_domain_error(std::string const& msg) {
  8208. throw_exception(std::domain_error(msg));
  8209. }
  8210. [[noreturn]]
  8211. void throw_runtime_error(std::string const& msg) {
  8212. throw_exception(std::runtime_error(msg));
  8213. }
  8214. } // namespace Catch;
  8215. // end catch_enforce.cpp
  8216. // start catch_enum_values_registry.cpp
  8217. // start catch_enum_values_registry.h
  8218. #include <vector>
  8219. #include <memory>
  8220. namespace Catch {
  8221. namespace Detail {
  8222. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8223. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8224. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8225. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8226. };
  8227. std::vector<std::string> parseEnums( StringRef enums );
  8228. } // Detail
  8229. } // Catch
  8230. // end catch_enum_values_registry.h
  8231. #include <map>
  8232. #include <cassert>
  8233. namespace Catch {
  8234. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8235. namespace Detail {
  8236. std::vector<std::string> parseEnums( StringRef enums ) {
  8237. auto enumValues = splitStringRef( enums, ',' );
  8238. std::vector<std::string> parsed;
  8239. parsed.reserve( enumValues.size() );
  8240. for( auto const& enumValue : enumValues ) {
  8241. auto identifiers = splitStringRef( enumValue, ':' );
  8242. parsed.push_back( Catch::trim( identifiers.back() ) );
  8243. }
  8244. return parsed;
  8245. }
  8246. EnumInfo::~EnumInfo() {}
  8247. StringRef EnumInfo::lookup( int value ) const {
  8248. for( auto const& valueToName : m_values ) {
  8249. if( valueToName.first == value )
  8250. return valueToName.second;
  8251. }
  8252. return "{** unexpected enum value **}";
  8253. }
  8254. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8255. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8256. enumInfo->m_name = enumName;
  8257. enumInfo->m_values.reserve( values.size() );
  8258. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8259. assert( valueNames.size() == values.size() );
  8260. std::size_t i = 0;
  8261. for( auto value : values )
  8262. enumInfo->m_values.push_back({ value, valueNames[i++] });
  8263. return enumInfo;
  8264. }
  8265. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8266. auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
  8267. EnumInfo* raw = enumInfo.get();
  8268. m_enumInfos.push_back( std::move( enumInfo ) );
  8269. return *raw;
  8270. }
  8271. } // Detail
  8272. } // Catch
  8273. // end catch_enum_values_registry.cpp
  8274. // start catch_errno_guard.cpp
  8275. #include <cerrno>
  8276. namespace Catch {
  8277. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8278. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8279. }
  8280. // end catch_errno_guard.cpp
  8281. // start catch_exception_translator_registry.cpp
  8282. // start catch_exception_translator_registry.h
  8283. #include <vector>
  8284. #include <string>
  8285. #include <memory>
  8286. namespace Catch {
  8287. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8288. public:
  8289. ~ExceptionTranslatorRegistry();
  8290. virtual void registerTranslator( const IExceptionTranslator* translator );
  8291. std::string translateActiveException() const override;
  8292. std::string tryTranslators() const;
  8293. private:
  8294. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8295. };
  8296. }
  8297. // end catch_exception_translator_registry.h
  8298. #ifdef __OBJC__
  8299. #import "Foundation/Foundation.h"
  8300. #endif
  8301. namespace Catch {
  8302. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8303. }
  8304. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8305. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8306. }
  8307. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8308. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8309. try {
  8310. #ifdef __OBJC__
  8311. // In Objective-C try objective-c exceptions first
  8312. @try {
  8313. return tryTranslators();
  8314. }
  8315. @catch (NSException *exception) {
  8316. return Catch::Detail::stringify( [exception description] );
  8317. }
  8318. #else
  8319. // Compiling a mixed mode project with MSVC means that CLR
  8320. // exceptions will be caught in (...) as well. However, these
  8321. // do not fill-in std::current_exception and thus lead to crash
  8322. // when attempting rethrow.
  8323. // /EHa switch also causes structured exceptions to be caught
  8324. // here, but they fill-in current_exception properly, so
  8325. // at worst the output should be a little weird, instead of
  8326. // causing a crash.
  8327. if (std::current_exception() == nullptr) {
  8328. return "Non C++ exception. Possibly a CLR exception.";
  8329. }
  8330. return tryTranslators();
  8331. #endif
  8332. }
  8333. catch( TestFailureException& ) {
  8334. std::rethrow_exception(std::current_exception());
  8335. }
  8336. catch( std::exception& ex ) {
  8337. return ex.what();
  8338. }
  8339. catch( std::string& msg ) {
  8340. return msg;
  8341. }
  8342. catch( const char* msg ) {
  8343. return msg;
  8344. }
  8345. catch(...) {
  8346. return "Unknown exception";
  8347. }
  8348. }
  8349. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8350. if (m_translators.empty()) {
  8351. std::rethrow_exception(std::current_exception());
  8352. } else {
  8353. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8354. }
  8355. }
  8356. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8357. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8358. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8359. }
  8360. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8361. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8362. }
  8363. #endif
  8364. }
  8365. // end catch_exception_translator_registry.cpp
  8366. // start catch_fatal_condition.cpp
  8367. #if defined(__GNUC__)
  8368. # pragma GCC diagnostic push
  8369. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8370. #endif
  8371. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8372. namespace {
  8373. // Report the error condition
  8374. void reportFatal( char const * const message ) {
  8375. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8376. }
  8377. }
  8378. #endif // signals/SEH handling
  8379. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8380. namespace Catch {
  8381. struct SignalDefs { DWORD id; const char* name; };
  8382. // There is no 1-1 mapping between signals and windows exceptions.
  8383. // Windows can easily distinguish between SO and SigSegV,
  8384. // but SigInt, SigTerm, etc are handled differently.
  8385. static SignalDefs signalDefs[] = {
  8386. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8387. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8388. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8389. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8390. };
  8391. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8392. for (auto const& def : signalDefs) {
  8393. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8394. reportFatal(def.name);
  8395. }
  8396. }
  8397. // If its not an exception we care about, pass it along.
  8398. // This stops us from eating debugger breaks etc.
  8399. return EXCEPTION_CONTINUE_SEARCH;
  8400. }
  8401. FatalConditionHandler::FatalConditionHandler() {
  8402. isSet = true;
  8403. // 32k seems enough for Catch to handle stack overflow,
  8404. // but the value was found experimentally, so there is no strong guarantee
  8405. guaranteeSize = 32 * 1024;
  8406. exceptionHandlerHandle = nullptr;
  8407. // Register as first handler in current chain
  8408. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8409. // Pass in guarantee size to be filled
  8410. SetThreadStackGuarantee(&guaranteeSize);
  8411. }
  8412. void FatalConditionHandler::reset() {
  8413. if (isSet) {
  8414. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  8415. SetThreadStackGuarantee(&guaranteeSize);
  8416. exceptionHandlerHandle = nullptr;
  8417. isSet = false;
  8418. }
  8419. }
  8420. FatalConditionHandler::~FatalConditionHandler() {
  8421. reset();
  8422. }
  8423. bool FatalConditionHandler::isSet = false;
  8424. ULONG FatalConditionHandler::guaranteeSize = 0;
  8425. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  8426. } // namespace Catch
  8427. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  8428. namespace Catch {
  8429. struct SignalDefs {
  8430. int id;
  8431. const char* name;
  8432. };
  8433. // 32kb for the alternate stack seems to be sufficient. However, this value
  8434. // is experimentally determined, so that's not guaranteed.
  8435. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  8436. static SignalDefs signalDefs[] = {
  8437. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8438. { SIGILL, "SIGILL - Illegal instruction signal" },
  8439. { SIGFPE, "SIGFPE - Floating point error signal" },
  8440. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8441. { SIGTERM, "SIGTERM - Termination request signal" },
  8442. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8443. };
  8444. void FatalConditionHandler::handleSignal( int sig ) {
  8445. char const * name = "<unknown signal>";
  8446. for (auto const& def : signalDefs) {
  8447. if (sig == def.id) {
  8448. name = def.name;
  8449. break;
  8450. }
  8451. }
  8452. reset();
  8453. reportFatal(name);
  8454. raise( sig );
  8455. }
  8456. FatalConditionHandler::FatalConditionHandler() {
  8457. isSet = true;
  8458. stack_t sigStack;
  8459. sigStack.ss_sp = altStackMem;
  8460. sigStack.ss_size = sigStackSize;
  8461. sigStack.ss_flags = 0;
  8462. sigaltstack(&sigStack, &oldSigStack);
  8463. struct sigaction sa = { };
  8464. sa.sa_handler = handleSignal;
  8465. sa.sa_flags = SA_ONSTACK;
  8466. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8467. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8468. }
  8469. }
  8470. FatalConditionHandler::~FatalConditionHandler() {
  8471. reset();
  8472. }
  8473. void FatalConditionHandler::reset() {
  8474. if( isSet ) {
  8475. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  8476. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  8477. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8478. }
  8479. // Return the old stack
  8480. sigaltstack(&oldSigStack, nullptr);
  8481. isSet = false;
  8482. }
  8483. }
  8484. bool FatalConditionHandler::isSet = false;
  8485. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  8486. stack_t FatalConditionHandler::oldSigStack = {};
  8487. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  8488. } // namespace Catch
  8489. #else
  8490. namespace Catch {
  8491. void FatalConditionHandler::reset() {}
  8492. }
  8493. #endif // signals/SEH handling
  8494. #if defined(__GNUC__)
  8495. # pragma GCC diagnostic pop
  8496. #endif
  8497. // end catch_fatal_condition.cpp
  8498. // start catch_generators.cpp
  8499. // start catch_random_number_generator.h
  8500. #include <algorithm>
  8501. #include <random>
  8502. namespace Catch {
  8503. struct IConfig;
  8504. std::mt19937& rng();
  8505. void seedRng( IConfig const& config );
  8506. unsigned int rngSeed();
  8507. }
  8508. // end catch_random_number_generator.h
  8509. #include <limits>
  8510. #include <set>
  8511. namespace Catch {
  8512. IGeneratorTracker::~IGeneratorTracker() {}
  8513. const char* GeneratorException::what() const noexcept {
  8514. return m_msg;
  8515. }
  8516. namespace Generators {
  8517. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8518. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8519. return getResultCapture().acquireGeneratorTracker( lineInfo );
  8520. }
  8521. } // namespace Generators
  8522. } // namespace Catch
  8523. // end catch_generators.cpp
  8524. // start catch_interfaces_capture.cpp
  8525. namespace Catch {
  8526. IResultCapture::~IResultCapture() = default;
  8527. }
  8528. // end catch_interfaces_capture.cpp
  8529. // start catch_interfaces_config.cpp
  8530. namespace Catch {
  8531. IConfig::~IConfig() = default;
  8532. }
  8533. // end catch_interfaces_config.cpp
  8534. // start catch_interfaces_exception.cpp
  8535. namespace Catch {
  8536. IExceptionTranslator::~IExceptionTranslator() = default;
  8537. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8538. }
  8539. // end catch_interfaces_exception.cpp
  8540. // start catch_interfaces_registry_hub.cpp
  8541. namespace Catch {
  8542. IRegistryHub::~IRegistryHub() = default;
  8543. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8544. }
  8545. // end catch_interfaces_registry_hub.cpp
  8546. // start catch_interfaces_reporter.cpp
  8547. // start catch_reporter_listening.h
  8548. namespace Catch {
  8549. class ListeningReporter : public IStreamingReporter {
  8550. using Reporters = std::vector<IStreamingReporterPtr>;
  8551. Reporters m_listeners;
  8552. IStreamingReporterPtr m_reporter = nullptr;
  8553. ReporterPreferences m_preferences;
  8554. public:
  8555. ListeningReporter();
  8556. void addListener( IStreamingReporterPtr&& listener );
  8557. void addReporter( IStreamingReporterPtr&& reporter );
  8558. public: // IStreamingReporter
  8559. ReporterPreferences getPreferences() const override;
  8560. void noMatchingTestCases( std::string const& spec ) override;
  8561. static std::set<Verbosity> getSupportedVerbosities();
  8562. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8563. void benchmarkPreparing(std::string const& name) override;
  8564. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8565. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  8566. void benchmarkFailed(std::string const&) override;
  8567. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  8568. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  8569. void testGroupStarting( GroupInfo const& groupInfo ) override;
  8570. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  8571. void sectionStarting( SectionInfo const& sectionInfo ) override;
  8572. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  8573. // The return value indicates if the messages buffer should be cleared:
  8574. bool assertionEnded( AssertionStats const& assertionStats ) override;
  8575. void sectionEnded( SectionStats const& sectionStats ) override;
  8576. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  8577. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  8578. void testRunEnded( TestRunStats const& testRunStats ) override;
  8579. void skipTest( TestCaseInfo const& testInfo ) override;
  8580. bool isMulti() const override;
  8581. };
  8582. } // end namespace Catch
  8583. // end catch_reporter_listening.h
  8584. namespace Catch {
  8585. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  8586. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  8587. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  8588. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  8589. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  8590. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  8591. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  8592. GroupInfo::GroupInfo( std::string const& _name,
  8593. std::size_t _groupIndex,
  8594. std::size_t _groupsCount )
  8595. : name( _name ),
  8596. groupIndex( _groupIndex ),
  8597. groupsCounts( _groupsCount )
  8598. {}
  8599. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  8600. std::vector<MessageInfo> const& _infoMessages,
  8601. Totals const& _totals )
  8602. : assertionResult( _assertionResult ),
  8603. infoMessages( _infoMessages ),
  8604. totals( _totals )
  8605. {
  8606. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  8607. if( assertionResult.hasMessage() ) {
  8608. // Copy message into messages list.
  8609. // !TBD This should have been done earlier, somewhere
  8610. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  8611. builder << assertionResult.getMessage();
  8612. builder.m_info.message = builder.m_stream.str();
  8613. infoMessages.push_back( builder.m_info );
  8614. }
  8615. }
  8616. AssertionStats::~AssertionStats() = default;
  8617. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  8618. Counts const& _assertions,
  8619. double _durationInSeconds,
  8620. bool _missingAssertions )
  8621. : sectionInfo( _sectionInfo ),
  8622. assertions( _assertions ),
  8623. durationInSeconds( _durationInSeconds ),
  8624. missingAssertions( _missingAssertions )
  8625. {}
  8626. SectionStats::~SectionStats() = default;
  8627. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  8628. Totals const& _totals,
  8629. std::string const& _stdOut,
  8630. std::string const& _stdErr,
  8631. bool _aborting )
  8632. : testInfo( _testInfo ),
  8633. totals( _totals ),
  8634. stdOut( _stdOut ),
  8635. stdErr( _stdErr ),
  8636. aborting( _aborting )
  8637. {}
  8638. TestCaseStats::~TestCaseStats() = default;
  8639. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  8640. Totals const& _totals,
  8641. bool _aborting )
  8642. : groupInfo( _groupInfo ),
  8643. totals( _totals ),
  8644. aborting( _aborting )
  8645. {}
  8646. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  8647. : groupInfo( _groupInfo ),
  8648. aborting( false )
  8649. {}
  8650. TestGroupStats::~TestGroupStats() = default;
  8651. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  8652. Totals const& _totals,
  8653. bool _aborting )
  8654. : runInfo( _runInfo ),
  8655. totals( _totals ),
  8656. aborting( _aborting )
  8657. {}
  8658. TestRunStats::~TestRunStats() = default;
  8659. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  8660. bool IStreamingReporter::isMulti() const { return false; }
  8661. IReporterFactory::~IReporterFactory() = default;
  8662. IReporterRegistry::~IReporterRegistry() = default;
  8663. } // end namespace Catch
  8664. // end catch_interfaces_reporter.cpp
  8665. // start catch_interfaces_runner.cpp
  8666. namespace Catch {
  8667. IRunner::~IRunner() = default;
  8668. }
  8669. // end catch_interfaces_runner.cpp
  8670. // start catch_interfaces_testcase.cpp
  8671. namespace Catch {
  8672. ITestInvoker::~ITestInvoker() = default;
  8673. ITestCaseRegistry::~ITestCaseRegistry() = default;
  8674. }
  8675. // end catch_interfaces_testcase.cpp
  8676. // start catch_leak_detector.cpp
  8677. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  8678. #include <crtdbg.h>
  8679. namespace Catch {
  8680. LeakDetector::LeakDetector() {
  8681. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8682. flag |= _CRTDBG_LEAK_CHECK_DF;
  8683. flag |= _CRTDBG_ALLOC_MEM_DF;
  8684. _CrtSetDbgFlag(flag);
  8685. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  8686. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  8687. // Change this to leaking allocation's number to break there
  8688. _CrtSetBreakAlloc(-1);
  8689. }
  8690. }
  8691. #else
  8692. Catch::LeakDetector::LeakDetector() {}
  8693. #endif
  8694. Catch::LeakDetector::~LeakDetector() {
  8695. Catch::cleanUp();
  8696. }
  8697. // end catch_leak_detector.cpp
  8698. // start catch_list.cpp
  8699. // start catch_list.h
  8700. #include <set>
  8701. namespace Catch {
  8702. std::size_t listTests( Config const& config );
  8703. std::size_t listTestsNamesOnly( Config const& config );
  8704. struct TagInfo {
  8705. void add( std::string const& spelling );
  8706. std::string all() const;
  8707. std::set<std::string> spellings;
  8708. std::size_t count = 0;
  8709. };
  8710. std::size_t listTags( Config const& config );
  8711. std::size_t listReporters();
  8712. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  8713. } // end namespace Catch
  8714. // end catch_list.h
  8715. // start catch_text.h
  8716. namespace Catch {
  8717. using namespace clara::TextFlow;
  8718. }
  8719. // end catch_text.h
  8720. #include <limits>
  8721. #include <algorithm>
  8722. #include <iomanip>
  8723. namespace Catch {
  8724. std::size_t listTests( Config const& config ) {
  8725. TestSpec testSpec = config.testSpec();
  8726. if( config.hasTestFilters() )
  8727. Catch::cout() << "Matching test cases:\n";
  8728. else {
  8729. Catch::cout() << "All available test cases:\n";
  8730. }
  8731. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8732. for( auto const& testCaseInfo : matchedTestCases ) {
  8733. Colour::Code colour = testCaseInfo.isHidden()
  8734. ? Colour::SecondaryText
  8735. : Colour::None;
  8736. Colour colourGuard( colour );
  8737. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  8738. if( config.verbosity() >= Verbosity::High ) {
  8739. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  8740. std::string description = testCaseInfo.description;
  8741. if( description.empty() )
  8742. description = "(NO DESCRIPTION)";
  8743. Catch::cout() << Column( description ).indent(4) << std::endl;
  8744. }
  8745. if( !testCaseInfo.tags.empty() )
  8746. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  8747. }
  8748. if( !config.hasTestFilters() )
  8749. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  8750. else
  8751. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  8752. return matchedTestCases.size();
  8753. }
  8754. std::size_t listTestsNamesOnly( Config const& config ) {
  8755. TestSpec testSpec = config.testSpec();
  8756. std::size_t matchedTests = 0;
  8757. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8758. for( auto const& testCaseInfo : matchedTestCases ) {
  8759. matchedTests++;
  8760. if( startsWith( testCaseInfo.name, '#' ) )
  8761. Catch::cout() << '"' << testCaseInfo.name << '"';
  8762. else
  8763. Catch::cout() << testCaseInfo.name;
  8764. if ( config.verbosity() >= Verbosity::High )
  8765. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  8766. Catch::cout() << std::endl;
  8767. }
  8768. return matchedTests;
  8769. }
  8770. void TagInfo::add( std::string const& spelling ) {
  8771. ++count;
  8772. spellings.insert( spelling );
  8773. }
  8774. std::string TagInfo::all() const {
  8775. std::string out;
  8776. for( auto const& spelling : spellings )
  8777. out += "[" + spelling + "]";
  8778. return out;
  8779. }
  8780. std::size_t listTags( Config const& config ) {
  8781. TestSpec testSpec = config.testSpec();
  8782. if( config.hasTestFilters() )
  8783. Catch::cout() << "Tags for matching test cases:\n";
  8784. else {
  8785. Catch::cout() << "All available tags:\n";
  8786. }
  8787. std::map<std::string, TagInfo> tagCounts;
  8788. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  8789. for( auto const& testCase : matchedTestCases ) {
  8790. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  8791. std::string lcaseTagName = toLower( tagName );
  8792. auto countIt = tagCounts.find( lcaseTagName );
  8793. if( countIt == tagCounts.end() )
  8794. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  8795. countIt->second.add( tagName );
  8796. }
  8797. }
  8798. for( auto const& tagCount : tagCounts ) {
  8799. ReusableStringStream rss;
  8800. rss << " " << std::setw(2) << tagCount.second.count << " ";
  8801. auto str = rss.str();
  8802. auto wrapper = Column( tagCount.second.all() )
  8803. .initialIndent( 0 )
  8804. .indent( str.size() )
  8805. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  8806. Catch::cout() << str << wrapper << '\n';
  8807. }
  8808. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  8809. return tagCounts.size();
  8810. }
  8811. std::size_t listReporters() {
  8812. Catch::cout() << "Available reporters:\n";
  8813. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  8814. std::size_t maxNameLen = 0;
  8815. for( auto const& factoryKvp : factories )
  8816. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  8817. for( auto const& factoryKvp : factories ) {
  8818. Catch::cout()
  8819. << Column( factoryKvp.first + ":" )
  8820. .indent(2)
  8821. .width( 5+maxNameLen )
  8822. + Column( factoryKvp.second->getDescription() )
  8823. .initialIndent(0)
  8824. .indent(2)
  8825. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  8826. << "\n";
  8827. }
  8828. Catch::cout() << std::endl;
  8829. return factories.size();
  8830. }
  8831. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  8832. Option<std::size_t> listedCount;
  8833. getCurrentMutableContext().setConfig( config );
  8834. if( config->listTests() )
  8835. listedCount = listedCount.valueOr(0) + listTests( *config );
  8836. if( config->listTestNamesOnly() )
  8837. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  8838. if( config->listTags() )
  8839. listedCount = listedCount.valueOr(0) + listTags( *config );
  8840. if( config->listReporters() )
  8841. listedCount = listedCount.valueOr(0) + listReporters();
  8842. return listedCount;
  8843. }
  8844. } // end namespace Catch
  8845. // end catch_list.cpp
  8846. // start catch_matchers.cpp
  8847. namespace Catch {
  8848. namespace Matchers {
  8849. namespace Impl {
  8850. std::string MatcherUntypedBase::toString() const {
  8851. if( m_cachedToString.empty() )
  8852. m_cachedToString = describe();
  8853. return m_cachedToString;
  8854. }
  8855. MatcherUntypedBase::~MatcherUntypedBase() = default;
  8856. } // namespace Impl
  8857. } // namespace Matchers
  8858. using namespace Matchers;
  8859. using Matchers::Impl::MatcherBase;
  8860. } // namespace Catch
  8861. // end catch_matchers.cpp
  8862. // start catch_matchers_floating.cpp
  8863. // start catch_polyfills.hpp
  8864. namespace Catch {
  8865. bool isnan(float f);
  8866. bool isnan(double d);
  8867. }
  8868. // end catch_polyfills.hpp
  8869. // start catch_to_string.hpp
  8870. #include <string>
  8871. namespace Catch {
  8872. template <typename T>
  8873. std::string to_string(T const& t) {
  8874. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  8875. return std::to_string(t);
  8876. #else
  8877. ReusableStringStream rss;
  8878. rss << t;
  8879. return rss.str();
  8880. #endif
  8881. }
  8882. } // end namespace Catch
  8883. // end catch_to_string.hpp
  8884. #include <cstdlib>
  8885. #include <cstdint>
  8886. #include <cstring>
  8887. #include <sstream>
  8888. #include <iomanip>
  8889. #include <limits>
  8890. namespace Catch {
  8891. namespace Matchers {
  8892. namespace Floating {
  8893. enum class FloatingPointKind : uint8_t {
  8894. Float,
  8895. Double
  8896. };
  8897. }
  8898. }
  8899. }
  8900. namespace {
  8901. template <typename T>
  8902. struct Converter;
  8903. template <>
  8904. struct Converter<float> {
  8905. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  8906. Converter(float f) {
  8907. std::memcpy(&i, &f, sizeof(f));
  8908. }
  8909. int32_t i;
  8910. };
  8911. template <>
  8912. struct Converter<double> {
  8913. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  8914. Converter(double d) {
  8915. std::memcpy(&i, &d, sizeof(d));
  8916. }
  8917. int64_t i;
  8918. };
  8919. template <typename T>
  8920. auto convert(T t) -> Converter<T> {
  8921. return Converter<T>(t);
  8922. }
  8923. template <typename FP>
  8924. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  8925. // Comparison with NaN should always be false.
  8926. // This way we can rule it out before getting into the ugly details
  8927. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  8928. return false;
  8929. }
  8930. auto lc = convert(lhs);
  8931. auto rc = convert(rhs);
  8932. if ((lc.i < 0) != (rc.i < 0)) {
  8933. // Potentially we can have +0 and -0
  8934. return lhs == rhs;
  8935. }
  8936. auto ulpDiff = std::abs(lc.i - rc.i);
  8937. return ulpDiff <= maxUlpDiff;
  8938. }
  8939. template <typename FP>
  8940. FP step(FP start, FP direction, int steps) {
  8941. for (int i = 0; i < steps; ++i) {
  8942. start = std::nextafter(start, direction);
  8943. }
  8944. return start;
  8945. }
  8946. } // end anonymous namespace
  8947. namespace Catch {
  8948. namespace Matchers {
  8949. namespace Floating {
  8950. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  8951. :m_target{ target }, m_margin{ margin } {
  8952. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  8953. << " Margin has to be non-negative.");
  8954. }
  8955. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  8956. // But without the subtraction to allow for INFINITY in comparison
  8957. bool WithinAbsMatcher::match(double const& matchee) const {
  8958. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  8959. }
  8960. std::string WithinAbsMatcher::describe() const {
  8961. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  8962. }
  8963. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  8964. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  8965. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  8966. << " ULPs have to be non-negative.");
  8967. }
  8968. #if defined(__clang__)
  8969. #pragma clang diagnostic push
  8970. // Clang <3.5 reports on the default branch in the switch below
  8971. #pragma clang diagnostic ignored "-Wunreachable-code"
  8972. #endif
  8973. bool WithinUlpsMatcher::match(double const& matchee) const {
  8974. switch (m_type) {
  8975. case FloatingPointKind::Float:
  8976. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  8977. case FloatingPointKind::Double:
  8978. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  8979. default:
  8980. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  8981. }
  8982. }
  8983. #if defined(__clang__)
  8984. #pragma clang diagnostic pop
  8985. #endif
  8986. std::string WithinUlpsMatcher::describe() const {
  8987. std::stringstream ret;
  8988. ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
  8989. if (m_type == FloatingPointKind::Float) {
  8990. ret << 'f';
  8991. }
  8992. ret << " ([";
  8993. ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
  8994. if (m_type == FloatingPointKind::Double) {
  8995. ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
  8996. << ", "
  8997. << step(m_target, static_cast<double>(INFINITY), m_ulps);
  8998. } else {
  8999. ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
  9000. << ", "
  9001. << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
  9002. }
  9003. ret << "])";
  9004. return ret.str();
  9005. //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  9006. }
  9007. }// namespace Floating
  9008. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  9009. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9010. }
  9011. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  9012. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9013. }
  9014. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9015. return Floating::WithinAbsMatcher(target, margin);
  9016. }
  9017. } // namespace Matchers
  9018. } // namespace Catch
  9019. // end catch_matchers_floating.cpp
  9020. // start catch_matchers_generic.cpp
  9021. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9022. if (desc.empty()) {
  9023. return "matches undescribed predicate";
  9024. } else {
  9025. return "matches predicate: \"" + desc + '"';
  9026. }
  9027. }
  9028. // end catch_matchers_generic.cpp
  9029. // start catch_matchers_string.cpp
  9030. #include <regex>
  9031. namespace Catch {
  9032. namespace Matchers {
  9033. namespace StdString {
  9034. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9035. : m_caseSensitivity( caseSensitivity ),
  9036. m_str( adjustString( str ) )
  9037. {}
  9038. std::string CasedString::adjustString( std::string const& str ) const {
  9039. return m_caseSensitivity == CaseSensitive::No
  9040. ? toLower( str )
  9041. : str;
  9042. }
  9043. std::string CasedString::caseSensitivitySuffix() const {
  9044. return m_caseSensitivity == CaseSensitive::No
  9045. ? " (case insensitive)"
  9046. : std::string();
  9047. }
  9048. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9049. : m_comparator( comparator ),
  9050. m_operation( operation ) {
  9051. }
  9052. std::string StringMatcherBase::describe() const {
  9053. std::string description;
  9054. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9055. m_comparator.caseSensitivitySuffix().size());
  9056. description += m_operation;
  9057. description += ": \"";
  9058. description += m_comparator.m_str;
  9059. description += "\"";
  9060. description += m_comparator.caseSensitivitySuffix();
  9061. return description;
  9062. }
  9063. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9064. bool EqualsMatcher::match( std::string const& source ) const {
  9065. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9066. }
  9067. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9068. bool ContainsMatcher::match( std::string const& source ) const {
  9069. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9070. }
  9071. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9072. bool StartsWithMatcher::match( std::string const& source ) const {
  9073. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9074. }
  9075. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9076. bool EndsWithMatcher::match( std::string const& source ) const {
  9077. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9078. }
  9079. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9080. bool RegexMatcher::match(std::string const& matchee) const {
  9081. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9082. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9083. flags |= std::regex::icase;
  9084. }
  9085. auto reg = std::regex(m_regex, flags);
  9086. return std::regex_match(matchee, reg);
  9087. }
  9088. std::string RegexMatcher::describe() const {
  9089. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9090. }
  9091. } // namespace StdString
  9092. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9093. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9094. }
  9095. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9096. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9097. }
  9098. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9099. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9100. }
  9101. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9102. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9103. }
  9104. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9105. return StdString::RegexMatcher(regex, caseSensitivity);
  9106. }
  9107. } // namespace Matchers
  9108. } // namespace Catch
  9109. // end catch_matchers_string.cpp
  9110. // start catch_message.cpp
  9111. // start catch_uncaught_exceptions.h
  9112. namespace Catch {
  9113. bool uncaught_exceptions();
  9114. } // end namespace Catch
  9115. // end catch_uncaught_exceptions.h
  9116. #include <cassert>
  9117. #include <stack>
  9118. namespace Catch {
  9119. MessageInfo::MessageInfo( StringRef const& _macroName,
  9120. SourceLineInfo const& _lineInfo,
  9121. ResultWas::OfType _type )
  9122. : macroName( _macroName ),
  9123. lineInfo( _lineInfo ),
  9124. type( _type ),
  9125. sequence( ++globalCount )
  9126. {}
  9127. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9128. return sequence == other.sequence;
  9129. }
  9130. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9131. return sequence < other.sequence;
  9132. }
  9133. // This may need protecting if threading support is added
  9134. unsigned int MessageInfo::globalCount = 0;
  9135. ////////////////////////////////////////////////////////////////////////////
  9136. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9137. SourceLineInfo const& lineInfo,
  9138. ResultWas::OfType type )
  9139. :m_info(macroName, lineInfo, type) {}
  9140. ////////////////////////////////////////////////////////////////////////////
  9141. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9142. : m_info( builder.m_info ), m_moved()
  9143. {
  9144. m_info.message = builder.m_stream.str();
  9145. getResultCapture().pushScopedMessage( m_info );
  9146. }
  9147. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9148. : m_info( old.m_info ), m_moved()
  9149. {
  9150. old.m_moved = true;
  9151. }
  9152. ScopedMessage::~ScopedMessage() {
  9153. if ( !uncaught_exceptions() && !m_moved ){
  9154. getResultCapture().popScopedMessage(m_info);
  9155. }
  9156. }
  9157. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9158. auto trimmed = [&] (size_t start, size_t end) {
  9159. while (names[start] == ',' || isspace(names[start])) {
  9160. ++start;
  9161. }
  9162. while (names[end] == ',' || isspace(names[end])) {
  9163. --end;
  9164. }
  9165. return names.substr(start, end - start + 1);
  9166. };
  9167. auto skipq = [&] (size_t start, char quote) {
  9168. for (auto i = start + 1; i < names.size() ; ++i) {
  9169. if (names[i] == quote)
  9170. return i;
  9171. if (names[i] == '\\')
  9172. ++i;
  9173. }
  9174. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9175. };
  9176. size_t start = 0;
  9177. std::stack<char> openings;
  9178. for (size_t pos = 0; pos < names.size(); ++pos) {
  9179. char c = names[pos];
  9180. switch (c) {
  9181. case '[':
  9182. case '{':
  9183. case '(':
  9184. // It is basically impossible to disambiguate between
  9185. // comparison and start of template args in this context
  9186. // case '<':
  9187. openings.push(c);
  9188. break;
  9189. case ']':
  9190. case '}':
  9191. case ')':
  9192. // case '>':
  9193. openings.pop();
  9194. break;
  9195. case '"':
  9196. case '\'':
  9197. pos = skipq(pos, c);
  9198. break;
  9199. case ',':
  9200. if (start != pos && openings.size() == 0) {
  9201. m_messages.emplace_back(macroName, lineInfo, resultType);
  9202. m_messages.back().message = trimmed(start, pos);
  9203. m_messages.back().message += " := ";
  9204. start = pos;
  9205. }
  9206. }
  9207. }
  9208. assert(openings.size() == 0 && "Mismatched openings");
  9209. m_messages.emplace_back(macroName, lineInfo, resultType);
  9210. m_messages.back().message = trimmed(start, names.size() - 1);
  9211. m_messages.back().message += " := ";
  9212. }
  9213. Capturer::~Capturer() {
  9214. if ( !uncaught_exceptions() ){
  9215. assert( m_captured == m_messages.size() );
  9216. for( size_t i = 0; i < m_captured; ++i )
  9217. m_resultCapture.popScopedMessage( m_messages[i] );
  9218. }
  9219. }
  9220. void Capturer::captureValue( size_t index, std::string const& value ) {
  9221. assert( index < m_messages.size() );
  9222. m_messages[index].message += value;
  9223. m_resultCapture.pushScopedMessage( m_messages[index] );
  9224. m_captured++;
  9225. }
  9226. } // end namespace Catch
  9227. // end catch_message.cpp
  9228. // start catch_output_redirect.cpp
  9229. // start catch_output_redirect.h
  9230. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9231. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9232. #include <cstdio>
  9233. #include <iosfwd>
  9234. #include <string>
  9235. namespace Catch {
  9236. class RedirectedStream {
  9237. std::ostream& m_originalStream;
  9238. std::ostream& m_redirectionStream;
  9239. std::streambuf* m_prevBuf;
  9240. public:
  9241. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9242. ~RedirectedStream();
  9243. };
  9244. class RedirectedStdOut {
  9245. ReusableStringStream m_rss;
  9246. RedirectedStream m_cout;
  9247. public:
  9248. RedirectedStdOut();
  9249. auto str() const -> std::string;
  9250. };
  9251. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9252. // This means that we need to redirect 2 streams into 1 to keep proper
  9253. // order of writes
  9254. class RedirectedStdErr {
  9255. ReusableStringStream m_rss;
  9256. RedirectedStream m_cerr;
  9257. RedirectedStream m_clog;
  9258. public:
  9259. RedirectedStdErr();
  9260. auto str() const -> std::string;
  9261. };
  9262. class RedirectedStreams {
  9263. public:
  9264. RedirectedStreams(RedirectedStreams const&) = delete;
  9265. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9266. RedirectedStreams(RedirectedStreams&&) = delete;
  9267. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9268. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9269. ~RedirectedStreams();
  9270. private:
  9271. std::string& m_redirectedCout;
  9272. std::string& m_redirectedCerr;
  9273. RedirectedStdOut m_redirectedStdOut;
  9274. RedirectedStdErr m_redirectedStdErr;
  9275. };
  9276. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9277. // Windows's implementation of std::tmpfile is terrible (it tries
  9278. // to create a file inside system folder, thus requiring elevated
  9279. // privileges for the binary), so we have to use tmpnam(_s) and
  9280. // create the file ourselves there.
  9281. class TempFile {
  9282. public:
  9283. TempFile(TempFile const&) = delete;
  9284. TempFile& operator=(TempFile const&) = delete;
  9285. TempFile(TempFile&&) = delete;
  9286. TempFile& operator=(TempFile&&) = delete;
  9287. TempFile();
  9288. ~TempFile();
  9289. std::FILE* getFile();
  9290. std::string getContents();
  9291. private:
  9292. std::FILE* m_file = nullptr;
  9293. #if defined(_MSC_VER)
  9294. char m_buffer[L_tmpnam] = { 0 };
  9295. #endif
  9296. };
  9297. class OutputRedirect {
  9298. public:
  9299. OutputRedirect(OutputRedirect const&) = delete;
  9300. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9301. OutputRedirect(OutputRedirect&&) = delete;
  9302. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9303. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9304. ~OutputRedirect();
  9305. private:
  9306. int m_originalStdout = -1;
  9307. int m_originalStderr = -1;
  9308. TempFile m_stdoutFile;
  9309. TempFile m_stderrFile;
  9310. std::string& m_stdoutDest;
  9311. std::string& m_stderrDest;
  9312. };
  9313. #endif
  9314. } // end namespace Catch
  9315. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9316. // end catch_output_redirect.h
  9317. #include <cstdio>
  9318. #include <cstring>
  9319. #include <fstream>
  9320. #include <sstream>
  9321. #include <stdexcept>
  9322. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9323. #if defined(_MSC_VER)
  9324. #include <io.h> //_dup and _dup2
  9325. #define dup _dup
  9326. #define dup2 _dup2
  9327. #define fileno _fileno
  9328. #else
  9329. #include <unistd.h> // dup and dup2
  9330. #endif
  9331. #endif
  9332. namespace Catch {
  9333. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9334. : m_originalStream( originalStream ),
  9335. m_redirectionStream( redirectionStream ),
  9336. m_prevBuf( m_originalStream.rdbuf() )
  9337. {
  9338. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9339. }
  9340. RedirectedStream::~RedirectedStream() {
  9341. m_originalStream.rdbuf( m_prevBuf );
  9342. }
  9343. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9344. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9345. RedirectedStdErr::RedirectedStdErr()
  9346. : m_cerr( Catch::cerr(), m_rss.get() ),
  9347. m_clog( Catch::clog(), m_rss.get() )
  9348. {}
  9349. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9350. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9351. : m_redirectedCout(redirectedCout),
  9352. m_redirectedCerr(redirectedCerr)
  9353. {}
  9354. RedirectedStreams::~RedirectedStreams() {
  9355. m_redirectedCout += m_redirectedStdOut.str();
  9356. m_redirectedCerr += m_redirectedStdErr.str();
  9357. }
  9358. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9359. #if defined(_MSC_VER)
  9360. TempFile::TempFile() {
  9361. if (tmpnam_s(m_buffer)) {
  9362. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9363. }
  9364. if (fopen_s(&m_file, m_buffer, "w")) {
  9365. char buffer[100];
  9366. if (strerror_s(buffer, errno)) {
  9367. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9368. }
  9369. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9370. }
  9371. }
  9372. #else
  9373. TempFile::TempFile() {
  9374. m_file = std::tmpfile();
  9375. if (!m_file) {
  9376. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9377. }
  9378. }
  9379. #endif
  9380. TempFile::~TempFile() {
  9381. // TBD: What to do about errors here?
  9382. std::fclose(m_file);
  9383. // We manually create the file on Windows only, on Linux
  9384. // it will be autodeleted
  9385. #if defined(_MSC_VER)
  9386. std::remove(m_buffer);
  9387. #endif
  9388. }
  9389. FILE* TempFile::getFile() {
  9390. return m_file;
  9391. }
  9392. std::string TempFile::getContents() {
  9393. std::stringstream sstr;
  9394. char buffer[100] = {};
  9395. std::rewind(m_file);
  9396. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9397. sstr << buffer;
  9398. }
  9399. return sstr.str();
  9400. }
  9401. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9402. m_originalStdout(dup(1)),
  9403. m_originalStderr(dup(2)),
  9404. m_stdoutDest(stdout_dest),
  9405. m_stderrDest(stderr_dest) {
  9406. dup2(fileno(m_stdoutFile.getFile()), 1);
  9407. dup2(fileno(m_stderrFile.getFile()), 2);
  9408. }
  9409. OutputRedirect::~OutputRedirect() {
  9410. Catch::cout() << std::flush;
  9411. fflush(stdout);
  9412. // Since we support overriding these streams, we flush cerr
  9413. // even though std::cerr is unbuffered
  9414. Catch::cerr() << std::flush;
  9415. Catch::clog() << std::flush;
  9416. fflush(stderr);
  9417. dup2(m_originalStdout, 1);
  9418. dup2(m_originalStderr, 2);
  9419. m_stdoutDest += m_stdoutFile.getContents();
  9420. m_stderrDest += m_stderrFile.getContents();
  9421. }
  9422. #endif // CATCH_CONFIG_NEW_CAPTURE
  9423. } // namespace Catch
  9424. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9425. #if defined(_MSC_VER)
  9426. #undef dup
  9427. #undef dup2
  9428. #undef fileno
  9429. #endif
  9430. #endif
  9431. // end catch_output_redirect.cpp
  9432. // start catch_polyfills.cpp
  9433. #include <cmath>
  9434. namespace Catch {
  9435. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9436. bool isnan(float f) {
  9437. return std::isnan(f);
  9438. }
  9439. bool isnan(double d) {
  9440. return std::isnan(d);
  9441. }
  9442. #else
  9443. // For now we only use this for embarcadero
  9444. bool isnan(float f) {
  9445. return std::_isnan(f);
  9446. }
  9447. bool isnan(double d) {
  9448. return std::_isnan(d);
  9449. }
  9450. #endif
  9451. } // end namespace Catch
  9452. // end catch_polyfills.cpp
  9453. // start catch_random_number_generator.cpp
  9454. namespace Catch {
  9455. std::mt19937& rng() {
  9456. static std::mt19937 s_rng;
  9457. return s_rng;
  9458. }
  9459. void seedRng( IConfig const& config ) {
  9460. if( config.rngSeed() != 0 ) {
  9461. std::srand( config.rngSeed() );
  9462. rng().seed( config.rngSeed() );
  9463. }
  9464. }
  9465. unsigned int rngSeed() {
  9466. return getCurrentContext().getConfig()->rngSeed();
  9467. }
  9468. }
  9469. // end catch_random_number_generator.cpp
  9470. // start catch_registry_hub.cpp
  9471. // start catch_test_case_registry_impl.h
  9472. #include <vector>
  9473. #include <set>
  9474. #include <algorithm>
  9475. #include <ios>
  9476. namespace Catch {
  9477. class TestCase;
  9478. struct IConfig;
  9479. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  9480. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  9481. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  9482. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  9483. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  9484. class TestRegistry : public ITestCaseRegistry {
  9485. public:
  9486. virtual ~TestRegistry() = default;
  9487. virtual void registerTest( TestCase const& testCase );
  9488. std::vector<TestCase> const& getAllTests() const override;
  9489. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  9490. private:
  9491. std::vector<TestCase> m_functions;
  9492. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  9493. mutable std::vector<TestCase> m_sortedFunctions;
  9494. std::size_t m_unnamedCount = 0;
  9495. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  9496. };
  9497. ///////////////////////////////////////////////////////////////////////////
  9498. class TestInvokerAsFunction : public ITestInvoker {
  9499. void(*m_testAsFunction)();
  9500. public:
  9501. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  9502. void invoke() const override;
  9503. };
  9504. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  9505. ///////////////////////////////////////////////////////////////////////////
  9506. } // end namespace Catch
  9507. // end catch_test_case_registry_impl.h
  9508. // start catch_reporter_registry.h
  9509. #include <map>
  9510. namespace Catch {
  9511. class ReporterRegistry : public IReporterRegistry {
  9512. public:
  9513. ~ReporterRegistry() override;
  9514. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  9515. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  9516. void registerListener( IReporterFactoryPtr const& factory );
  9517. FactoryMap const& getFactories() const override;
  9518. Listeners const& getListeners() const override;
  9519. private:
  9520. FactoryMap m_factories;
  9521. Listeners m_listeners;
  9522. };
  9523. }
  9524. // end catch_reporter_registry.h
  9525. // start catch_tag_alias_registry.h
  9526. // start catch_tag_alias.h
  9527. #include <string>
  9528. namespace Catch {
  9529. struct TagAlias {
  9530. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  9531. std::string tag;
  9532. SourceLineInfo lineInfo;
  9533. };
  9534. } // end namespace Catch
  9535. // end catch_tag_alias.h
  9536. #include <map>
  9537. namespace Catch {
  9538. class TagAliasRegistry : public ITagAliasRegistry {
  9539. public:
  9540. ~TagAliasRegistry() override;
  9541. TagAlias const* find( std::string const& alias ) const override;
  9542. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  9543. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  9544. private:
  9545. std::map<std::string, TagAlias> m_registry;
  9546. };
  9547. } // end namespace Catch
  9548. // end catch_tag_alias_registry.h
  9549. // start catch_startup_exception_registry.h
  9550. #include <vector>
  9551. #include <exception>
  9552. namespace Catch {
  9553. class StartupExceptionRegistry {
  9554. public:
  9555. void add(std::exception_ptr const& exception) noexcept;
  9556. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  9557. private:
  9558. std::vector<std::exception_ptr> m_exceptions;
  9559. };
  9560. } // end namespace Catch
  9561. // end catch_startup_exception_registry.h
  9562. // start catch_singletons.hpp
  9563. namespace Catch {
  9564. struct ISingleton {
  9565. virtual ~ISingleton();
  9566. };
  9567. void addSingleton( ISingleton* singleton );
  9568. void cleanupSingletons();
  9569. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  9570. class Singleton : SingletonImplT, public ISingleton {
  9571. static auto getInternal() -> Singleton* {
  9572. static Singleton* s_instance = nullptr;
  9573. if( !s_instance ) {
  9574. s_instance = new Singleton;
  9575. addSingleton( s_instance );
  9576. }
  9577. return s_instance;
  9578. }
  9579. public:
  9580. static auto get() -> InterfaceT const& {
  9581. return *getInternal();
  9582. }
  9583. static auto getMutable() -> MutableInterfaceT& {
  9584. return *getInternal();
  9585. }
  9586. };
  9587. } // namespace Catch
  9588. // end catch_singletons.hpp
  9589. namespace Catch {
  9590. namespace {
  9591. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  9592. private NonCopyable {
  9593. public: // IRegistryHub
  9594. RegistryHub() = default;
  9595. IReporterRegistry const& getReporterRegistry() const override {
  9596. return m_reporterRegistry;
  9597. }
  9598. ITestCaseRegistry const& getTestCaseRegistry() const override {
  9599. return m_testCaseRegistry;
  9600. }
  9601. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  9602. return m_exceptionTranslatorRegistry;
  9603. }
  9604. ITagAliasRegistry const& getTagAliasRegistry() const override {
  9605. return m_tagAliasRegistry;
  9606. }
  9607. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  9608. return m_exceptionRegistry;
  9609. }
  9610. public: // IMutableRegistryHub
  9611. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  9612. m_reporterRegistry.registerReporter( name, factory );
  9613. }
  9614. void registerListener( IReporterFactoryPtr const& factory ) override {
  9615. m_reporterRegistry.registerListener( factory );
  9616. }
  9617. void registerTest( TestCase const& testInfo ) override {
  9618. m_testCaseRegistry.registerTest( testInfo );
  9619. }
  9620. void registerTranslator( const IExceptionTranslator* translator ) override {
  9621. m_exceptionTranslatorRegistry.registerTranslator( translator );
  9622. }
  9623. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  9624. m_tagAliasRegistry.add( alias, tag, lineInfo );
  9625. }
  9626. void registerStartupException() noexcept override {
  9627. m_exceptionRegistry.add(std::current_exception());
  9628. }
  9629. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  9630. return m_enumValuesRegistry;
  9631. }
  9632. private:
  9633. TestRegistry m_testCaseRegistry;
  9634. ReporterRegistry m_reporterRegistry;
  9635. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  9636. TagAliasRegistry m_tagAliasRegistry;
  9637. StartupExceptionRegistry m_exceptionRegistry;
  9638. Detail::EnumValuesRegistry m_enumValuesRegistry;
  9639. };
  9640. }
  9641. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  9642. IRegistryHub const& getRegistryHub() {
  9643. return RegistryHubSingleton::get();
  9644. }
  9645. IMutableRegistryHub& getMutableRegistryHub() {
  9646. return RegistryHubSingleton::getMutable();
  9647. }
  9648. void cleanUp() {
  9649. cleanupSingletons();
  9650. cleanUpContext();
  9651. }
  9652. std::string translateActiveException() {
  9653. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  9654. }
  9655. } // end namespace Catch
  9656. // end catch_registry_hub.cpp
  9657. // start catch_reporter_registry.cpp
  9658. namespace Catch {
  9659. ReporterRegistry::~ReporterRegistry() = default;
  9660. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  9661. auto it = m_factories.find( name );
  9662. if( it == m_factories.end() )
  9663. return nullptr;
  9664. return it->second->create( ReporterConfig( config ) );
  9665. }
  9666. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  9667. m_factories.emplace(name, factory);
  9668. }
  9669. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  9670. m_listeners.push_back( factory );
  9671. }
  9672. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  9673. return m_factories;
  9674. }
  9675. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  9676. return m_listeners;
  9677. }
  9678. }
  9679. // end catch_reporter_registry.cpp
  9680. // start catch_result_type.cpp
  9681. namespace Catch {
  9682. bool isOk( ResultWas::OfType resultType ) {
  9683. return ( resultType & ResultWas::FailureBit ) == 0;
  9684. }
  9685. bool isJustInfo( int flags ) {
  9686. return flags == ResultWas::Info;
  9687. }
  9688. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  9689. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  9690. }
  9691. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  9692. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  9693. } // end namespace Catch
  9694. // end catch_result_type.cpp
  9695. // start catch_run_context.cpp
  9696. #include <cassert>
  9697. #include <algorithm>
  9698. #include <sstream>
  9699. namespace Catch {
  9700. namespace Generators {
  9701. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  9702. GeneratorBasePtr m_generator;
  9703. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9704. : TrackerBase( nameAndLocation, ctx, parent )
  9705. {}
  9706. ~GeneratorTracker();
  9707. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  9708. std::shared_ptr<GeneratorTracker> tracker;
  9709. ITracker& currentTracker = ctx.currentTracker();
  9710. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9711. assert( childTracker );
  9712. assert( childTracker->isGeneratorTracker() );
  9713. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  9714. }
  9715. else {
  9716. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  9717. currentTracker.addChild( tracker );
  9718. }
  9719. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9720. tracker->open();
  9721. }
  9722. return *tracker;
  9723. }
  9724. // TrackerBase interface
  9725. bool isGeneratorTracker() const override { return true; }
  9726. auto hasGenerator() const -> bool override {
  9727. return !!m_generator;
  9728. }
  9729. void close() override {
  9730. TrackerBase::close();
  9731. // Generator interface only finds out if it has another item on atual move
  9732. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  9733. m_children.clear();
  9734. m_runState = Executing;
  9735. }
  9736. }
  9737. // IGeneratorTracker interface
  9738. auto getGenerator() const -> GeneratorBasePtr const& override {
  9739. return m_generator;
  9740. }
  9741. void setGenerator( GeneratorBasePtr&& generator ) override {
  9742. m_generator = std::move( generator );
  9743. }
  9744. };
  9745. GeneratorTracker::~GeneratorTracker() {}
  9746. }
  9747. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  9748. : m_runInfo(_config->name()),
  9749. m_context(getCurrentMutableContext()),
  9750. m_config(_config),
  9751. m_reporter(std::move(reporter)),
  9752. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  9753. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  9754. {
  9755. m_context.setRunner(this);
  9756. m_context.setConfig(m_config);
  9757. m_context.setResultCapture(this);
  9758. m_reporter->testRunStarting(m_runInfo);
  9759. }
  9760. RunContext::~RunContext() {
  9761. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  9762. }
  9763. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  9764. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  9765. }
  9766. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  9767. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  9768. }
  9769. Totals RunContext::runTest(TestCase const& testCase) {
  9770. Totals prevTotals = m_totals;
  9771. std::string redirectedCout;
  9772. std::string redirectedCerr;
  9773. auto const& testInfo = testCase.getTestCaseInfo();
  9774. m_reporter->testCaseStarting(testInfo);
  9775. m_activeTestCase = &testCase;
  9776. ITracker& rootTracker = m_trackerContext.startRun();
  9777. assert(rootTracker.isSectionTracker());
  9778. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  9779. do {
  9780. m_trackerContext.startCycle();
  9781. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  9782. runCurrentTest(redirectedCout, redirectedCerr);
  9783. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  9784. Totals deltaTotals = m_totals.delta(prevTotals);
  9785. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  9786. deltaTotals.assertions.failed++;
  9787. deltaTotals.testCases.passed--;
  9788. deltaTotals.testCases.failed++;
  9789. }
  9790. m_totals.testCases += deltaTotals.testCases;
  9791. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9792. deltaTotals,
  9793. redirectedCout,
  9794. redirectedCerr,
  9795. aborting()));
  9796. m_activeTestCase = nullptr;
  9797. m_testCaseTracker = nullptr;
  9798. return deltaTotals;
  9799. }
  9800. IConfigPtr RunContext::config() const {
  9801. return m_config;
  9802. }
  9803. IStreamingReporter& RunContext::reporter() const {
  9804. return *m_reporter;
  9805. }
  9806. void RunContext::assertionEnded(AssertionResult const & result) {
  9807. if (result.getResultType() == ResultWas::Ok) {
  9808. m_totals.assertions.passed++;
  9809. m_lastAssertionPassed = true;
  9810. } else if (!result.isOk()) {
  9811. m_lastAssertionPassed = false;
  9812. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  9813. m_totals.assertions.failedButOk++;
  9814. else
  9815. m_totals.assertions.failed++;
  9816. }
  9817. else {
  9818. m_lastAssertionPassed = true;
  9819. }
  9820. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  9821. // and should be let to clear themselves out.
  9822. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  9823. if (result.getResultType() != ResultWas::Warning)
  9824. m_messageScopes.clear();
  9825. // Reset working state
  9826. resetAssertionInfo();
  9827. m_lastResult = result;
  9828. }
  9829. void RunContext::resetAssertionInfo() {
  9830. m_lastAssertionInfo.macroName = StringRef();
  9831. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  9832. }
  9833. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  9834. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  9835. if (!sectionTracker.isOpen())
  9836. return false;
  9837. m_activeSections.push_back(&sectionTracker);
  9838. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  9839. m_reporter->sectionStarting(sectionInfo);
  9840. assertions = m_totals.assertions;
  9841. return true;
  9842. }
  9843. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  9844. using namespace Generators;
  9845. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  9846. assert( tracker.isOpen() );
  9847. m_lastAssertionInfo.lineInfo = lineInfo;
  9848. return tracker;
  9849. }
  9850. bool RunContext::testForMissingAssertions(Counts& assertions) {
  9851. if (assertions.total() != 0)
  9852. return false;
  9853. if (!m_config->warnAboutMissingAssertions())
  9854. return false;
  9855. if (m_trackerContext.currentTracker().hasChildren())
  9856. return false;
  9857. m_totals.assertions.failed++;
  9858. assertions.failed++;
  9859. return true;
  9860. }
  9861. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  9862. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  9863. bool missingAssertions = testForMissingAssertions(assertions);
  9864. if (!m_activeSections.empty()) {
  9865. m_activeSections.back()->close();
  9866. m_activeSections.pop_back();
  9867. }
  9868. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  9869. m_messages.clear();
  9870. m_messageScopes.clear();
  9871. }
  9872. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  9873. if (m_unfinishedSections.empty())
  9874. m_activeSections.back()->fail();
  9875. else
  9876. m_activeSections.back()->close();
  9877. m_activeSections.pop_back();
  9878. m_unfinishedSections.push_back(endInfo);
  9879. }
  9880. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  9881. void RunContext::benchmarkPreparing(std::string const& name) {
  9882. m_reporter->benchmarkPreparing(name);
  9883. }
  9884. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  9885. m_reporter->benchmarkStarting( info );
  9886. }
  9887. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  9888. m_reporter->benchmarkEnded( stats );
  9889. }
  9890. void RunContext::benchmarkFailed(std::string const & error) {
  9891. m_reporter->benchmarkFailed(error);
  9892. }
  9893. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9894. void RunContext::pushScopedMessage(MessageInfo const & message) {
  9895. m_messages.push_back(message);
  9896. }
  9897. void RunContext::popScopedMessage(MessageInfo const & message) {
  9898. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  9899. }
  9900. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  9901. m_messageScopes.emplace_back( builder );
  9902. }
  9903. std::string RunContext::getCurrentTestName() const {
  9904. return m_activeTestCase
  9905. ? m_activeTestCase->getTestCaseInfo().name
  9906. : std::string();
  9907. }
  9908. const AssertionResult * RunContext::getLastResult() const {
  9909. return &(*m_lastResult);
  9910. }
  9911. void RunContext::exceptionEarlyReported() {
  9912. m_shouldReportUnexpected = false;
  9913. }
  9914. void RunContext::handleFatalErrorCondition( StringRef message ) {
  9915. // First notify reporter that bad things happened
  9916. m_reporter->fatalErrorEncountered(message);
  9917. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  9918. // Instead, fake a result data.
  9919. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  9920. tempResult.message = message;
  9921. AssertionResult result(m_lastAssertionInfo, tempResult);
  9922. assertionEnded(result);
  9923. handleUnfinishedSections();
  9924. // Recreate section for test case (as we will lose the one that was in scope)
  9925. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  9926. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  9927. Counts assertions;
  9928. assertions.failed = 1;
  9929. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  9930. m_reporter->sectionEnded(testCaseSectionStats);
  9931. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  9932. Totals deltaTotals;
  9933. deltaTotals.testCases.failed = 1;
  9934. deltaTotals.assertions.failed = 1;
  9935. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  9936. deltaTotals,
  9937. std::string(),
  9938. std::string(),
  9939. false));
  9940. m_totals.testCases.failed++;
  9941. testGroupEnded(std::string(), m_totals, 1, 1);
  9942. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  9943. }
  9944. bool RunContext::lastAssertionPassed() {
  9945. return m_lastAssertionPassed;
  9946. }
  9947. void RunContext::assertionPassed() {
  9948. m_lastAssertionPassed = true;
  9949. ++m_totals.assertions.passed;
  9950. resetAssertionInfo();
  9951. m_messageScopes.clear();
  9952. }
  9953. bool RunContext::aborting() const {
  9954. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  9955. }
  9956. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  9957. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  9958. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  9959. m_reporter->sectionStarting(testCaseSection);
  9960. Counts prevAssertions = m_totals.assertions;
  9961. double duration = 0;
  9962. m_shouldReportUnexpected = true;
  9963. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  9964. seedRng(*m_config);
  9965. Timer timer;
  9966. CATCH_TRY {
  9967. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  9968. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  9969. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  9970. timer.start();
  9971. invokeActiveTestCase();
  9972. #else
  9973. OutputRedirect r(redirectedCout, redirectedCerr);
  9974. timer.start();
  9975. invokeActiveTestCase();
  9976. #endif
  9977. } else {
  9978. timer.start();
  9979. invokeActiveTestCase();
  9980. }
  9981. duration = timer.getElapsedSeconds();
  9982. } CATCH_CATCH_ANON (TestFailureException&) {
  9983. // This just means the test was aborted due to failure
  9984. } CATCH_CATCH_ALL {
  9985. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  9986. // are reported without translation at the point of origin.
  9987. if( m_shouldReportUnexpected ) {
  9988. AssertionReaction dummyReaction;
  9989. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  9990. }
  9991. }
  9992. Counts assertions = m_totals.assertions - prevAssertions;
  9993. bool missingAssertions = testForMissingAssertions(assertions);
  9994. m_testCaseTracker->close();
  9995. handleUnfinishedSections();
  9996. m_messages.clear();
  9997. m_messageScopes.clear();
  9998. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  9999. m_reporter->sectionEnded(testCaseSectionStats);
  10000. }
  10001. void RunContext::invokeActiveTestCase() {
  10002. FatalConditionHandler fatalConditionHandler; // Handle signals
  10003. m_activeTestCase->invoke();
  10004. fatalConditionHandler.reset();
  10005. }
  10006. void RunContext::handleUnfinishedSections() {
  10007. // If sections ended prematurely due to an exception we stored their
  10008. // infos here so we can tear them down outside the unwind process.
  10009. for (auto it = m_unfinishedSections.rbegin(),
  10010. itEnd = m_unfinishedSections.rend();
  10011. it != itEnd;
  10012. ++it)
  10013. sectionEnded(*it);
  10014. m_unfinishedSections.clear();
  10015. }
  10016. void RunContext::handleExpr(
  10017. AssertionInfo const& info,
  10018. ITransientExpression const& expr,
  10019. AssertionReaction& reaction
  10020. ) {
  10021. m_reporter->assertionStarting( info );
  10022. bool negated = isFalseTest( info.resultDisposition );
  10023. bool result = expr.getResult() != negated;
  10024. if( result ) {
  10025. if (!m_includeSuccessfulResults) {
  10026. assertionPassed();
  10027. }
  10028. else {
  10029. reportExpr(info, ResultWas::Ok, &expr, negated);
  10030. }
  10031. }
  10032. else {
  10033. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10034. populateReaction( reaction );
  10035. }
  10036. }
  10037. void RunContext::reportExpr(
  10038. AssertionInfo const &info,
  10039. ResultWas::OfType resultType,
  10040. ITransientExpression const *expr,
  10041. bool negated ) {
  10042. m_lastAssertionInfo = info;
  10043. AssertionResultData data( resultType, LazyExpression( negated ) );
  10044. AssertionResult assertionResult{ info, data };
  10045. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10046. assertionEnded( assertionResult );
  10047. }
  10048. void RunContext::handleMessage(
  10049. AssertionInfo const& info,
  10050. ResultWas::OfType resultType,
  10051. StringRef const& message,
  10052. AssertionReaction& reaction
  10053. ) {
  10054. m_reporter->assertionStarting( info );
  10055. m_lastAssertionInfo = info;
  10056. AssertionResultData data( resultType, LazyExpression( false ) );
  10057. data.message = message;
  10058. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10059. assertionEnded( assertionResult );
  10060. if( !assertionResult.isOk() )
  10061. populateReaction( reaction );
  10062. }
  10063. void RunContext::handleUnexpectedExceptionNotThrown(
  10064. AssertionInfo const& info,
  10065. AssertionReaction& reaction
  10066. ) {
  10067. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10068. }
  10069. void RunContext::handleUnexpectedInflightException(
  10070. AssertionInfo const& info,
  10071. std::string const& message,
  10072. AssertionReaction& reaction
  10073. ) {
  10074. m_lastAssertionInfo = info;
  10075. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10076. data.message = message;
  10077. AssertionResult assertionResult{ info, data };
  10078. assertionEnded( assertionResult );
  10079. populateReaction( reaction );
  10080. }
  10081. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10082. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10083. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10084. }
  10085. void RunContext::handleIncomplete(
  10086. AssertionInfo const& info
  10087. ) {
  10088. m_lastAssertionInfo = info;
  10089. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10090. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10091. AssertionResult assertionResult{ info, data };
  10092. assertionEnded( assertionResult );
  10093. }
  10094. void RunContext::handleNonExpr(
  10095. AssertionInfo const &info,
  10096. ResultWas::OfType resultType,
  10097. AssertionReaction &reaction
  10098. ) {
  10099. m_lastAssertionInfo = info;
  10100. AssertionResultData data( resultType, LazyExpression( false ) );
  10101. AssertionResult assertionResult{ info, data };
  10102. assertionEnded( assertionResult );
  10103. if( !assertionResult.isOk() )
  10104. populateReaction( reaction );
  10105. }
  10106. IResultCapture& getResultCapture() {
  10107. if (auto* capture = getCurrentContext().getResultCapture())
  10108. return *capture;
  10109. else
  10110. CATCH_INTERNAL_ERROR("No result capture instance");
  10111. }
  10112. }
  10113. // end catch_run_context.cpp
  10114. // start catch_section.cpp
  10115. namespace Catch {
  10116. Section::Section( SectionInfo const& info )
  10117. : m_info( info ),
  10118. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10119. {
  10120. m_timer.start();
  10121. }
  10122. Section::~Section() {
  10123. if( m_sectionIncluded ) {
  10124. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10125. if( uncaught_exceptions() )
  10126. getResultCapture().sectionEndedEarly( endInfo );
  10127. else
  10128. getResultCapture().sectionEnded( endInfo );
  10129. }
  10130. }
  10131. // This indicates whether the section should be executed or not
  10132. Section::operator bool() const {
  10133. return m_sectionIncluded;
  10134. }
  10135. } // end namespace Catch
  10136. // end catch_section.cpp
  10137. // start catch_section_info.cpp
  10138. namespace Catch {
  10139. SectionInfo::SectionInfo
  10140. ( SourceLineInfo const& _lineInfo,
  10141. std::string const& _name )
  10142. : name( _name ),
  10143. lineInfo( _lineInfo )
  10144. {}
  10145. } // end namespace Catch
  10146. // end catch_section_info.cpp
  10147. // start catch_session.cpp
  10148. // start catch_session.h
  10149. #include <memory>
  10150. namespace Catch {
  10151. class Session : NonCopyable {
  10152. public:
  10153. Session();
  10154. ~Session() override;
  10155. void showHelp() const;
  10156. void libIdentify();
  10157. int applyCommandLine( int argc, char const * const * argv );
  10158. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  10159. int applyCommandLine( int argc, wchar_t const * const * argv );
  10160. #endif
  10161. void useConfigData( ConfigData const& configData );
  10162. template<typename CharT>
  10163. int run(int argc, CharT const * const argv[]) {
  10164. if (m_startupExceptions)
  10165. return 1;
  10166. int returnCode = applyCommandLine(argc, argv);
  10167. if (returnCode == 0)
  10168. returnCode = run();
  10169. return returnCode;
  10170. }
  10171. int run();
  10172. clara::Parser const& cli() const;
  10173. void cli( clara::Parser const& newParser );
  10174. ConfigData& configData();
  10175. Config& config();
  10176. private:
  10177. int runInternal();
  10178. clara::Parser m_cli;
  10179. ConfigData m_configData;
  10180. std::shared_ptr<Config> m_config;
  10181. bool m_startupExceptions = false;
  10182. };
  10183. } // end namespace Catch
  10184. // end catch_session.h
  10185. // start catch_version.h
  10186. #include <iosfwd>
  10187. namespace Catch {
  10188. // Versioning information
  10189. struct Version {
  10190. Version( Version const& ) = delete;
  10191. Version& operator=( Version const& ) = delete;
  10192. Version( unsigned int _majorVersion,
  10193. unsigned int _minorVersion,
  10194. unsigned int _patchNumber,
  10195. char const * const _branchName,
  10196. unsigned int _buildNumber );
  10197. unsigned int const majorVersion;
  10198. unsigned int const minorVersion;
  10199. unsigned int const patchNumber;
  10200. // buildNumber is only used if branchName is not null
  10201. char const * const branchName;
  10202. unsigned int const buildNumber;
  10203. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10204. };
  10205. Version const& libraryVersion();
  10206. }
  10207. // end catch_version.h
  10208. #include <cstdlib>
  10209. #include <iomanip>
  10210. namespace Catch {
  10211. namespace {
  10212. const int MaxExitCode = 255;
  10213. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10214. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10215. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10216. return reporter;
  10217. }
  10218. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10219. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10220. return createReporter(config->getReporterName(), config);
  10221. }
  10222. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10223. // when the return type is std::unique_ptr<IStreamingReporter>
  10224. // doesn't compile without a std::move call. However, this causes
  10225. // a warning on newer platforms. Thus, we have to work around
  10226. // it a bit and downcast the pointer manually.
  10227. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10228. auto& multi = static_cast<ListeningReporter&>(*ret);
  10229. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10230. for (auto const& listener : listeners) {
  10231. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10232. }
  10233. multi.addReporter(createReporter(config->getReporterName(), config));
  10234. return ret;
  10235. }
  10236. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  10237. auto reporter = makeReporter(config);
  10238. RunContext context(config, std::move(reporter));
  10239. Totals totals;
  10240. context.testGroupStarting(config->name(), 1, 1);
  10241. TestSpec testSpec = config->testSpec();
  10242. auto const& allTestCases = getAllTestCasesSorted(*config);
  10243. for (auto const& testCase : allTestCases) {
  10244. bool matching = (!testSpec.hasFilters() && !testCase.isHidden()) ||
  10245. (testSpec.hasFilters() && matchTest(testCase, testSpec, *config));
  10246. if (!context.aborting() && matching)
  10247. totals += context.runTest(testCase);
  10248. else
  10249. context.reporter().skipTest(testCase);
  10250. }
  10251. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  10252. ReusableStringStream testConfig;
  10253. bool first = true;
  10254. for (const auto& input : config->getTestsOrTags()) {
  10255. if (!first) { testConfig << ' '; }
  10256. first = false;
  10257. testConfig << input;
  10258. }
  10259. context.reporter().noMatchingTestCases(testConfig.str());
  10260. totals.error = -1;
  10261. }
  10262. context.testGroupEnded(config->name(), totals, 1, 1);
  10263. return totals;
  10264. }
  10265. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10266. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10267. for (auto& testCase : tests) {
  10268. auto tags = testCase.tags;
  10269. std::string filename = testCase.lineInfo.file;
  10270. auto lastSlash = filename.find_last_of("\\/");
  10271. if (lastSlash != std::string::npos) {
  10272. filename.erase(0, lastSlash);
  10273. filename[0] = '#';
  10274. }
  10275. auto lastDot = filename.find_last_of('.');
  10276. if (lastDot != std::string::npos) {
  10277. filename.erase(lastDot);
  10278. }
  10279. tags.push_back(std::move(filename));
  10280. setTags(testCase, tags);
  10281. }
  10282. }
  10283. } // anon namespace
  10284. Session::Session() {
  10285. static bool alreadyInstantiated = false;
  10286. if( alreadyInstantiated ) {
  10287. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10288. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10289. }
  10290. // There cannot be exceptions at startup in no-exception mode.
  10291. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10292. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10293. if ( !exceptions.empty() ) {
  10294. config();
  10295. getCurrentMutableContext().setConfig(m_config);
  10296. m_startupExceptions = true;
  10297. Colour colourGuard( Colour::Red );
  10298. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10299. // iterate over all exceptions and notify user
  10300. for ( const auto& ex_ptr : exceptions ) {
  10301. try {
  10302. std::rethrow_exception(ex_ptr);
  10303. } catch ( std::exception const& ex ) {
  10304. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10305. }
  10306. }
  10307. }
  10308. #endif
  10309. alreadyInstantiated = true;
  10310. m_cli = makeCommandLineParser( m_configData );
  10311. }
  10312. Session::~Session() {
  10313. Catch::cleanUp();
  10314. }
  10315. void Session::showHelp() const {
  10316. Catch::cout()
  10317. << "\nCatch v" << libraryVersion() << "\n"
  10318. << m_cli << std::endl
  10319. << "For more detailed usage please see the project docs\n" << std::endl;
  10320. }
  10321. void Session::libIdentify() {
  10322. Catch::cout()
  10323. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  10324. << std::left << std::setw(16) << "category: " << "testframework\n"
  10325. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10326. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10327. }
  10328. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10329. if( m_startupExceptions )
  10330. return 1;
  10331. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10332. if( !result ) {
  10333. config();
  10334. getCurrentMutableContext().setConfig(m_config);
  10335. Catch::cerr()
  10336. << Colour( Colour::Red )
  10337. << "\nError(s) in input:\n"
  10338. << Column( result.errorMessage() ).indent( 2 )
  10339. << "\n\n";
  10340. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10341. return MaxExitCode;
  10342. }
  10343. if( m_configData.showHelp )
  10344. showHelp();
  10345. if( m_configData.libIdentify )
  10346. libIdentify();
  10347. m_config.reset();
  10348. return 0;
  10349. }
  10350. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  10351. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10352. char **utf8Argv = new char *[ argc ];
  10353. for ( int i = 0; i < argc; ++i ) {
  10354. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  10355. utf8Argv[ i ] = new char[ bufSize ];
  10356. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  10357. }
  10358. int returnCode = applyCommandLine( argc, utf8Argv );
  10359. for ( int i = 0; i < argc; ++i )
  10360. delete [] utf8Argv[ i ];
  10361. delete [] utf8Argv;
  10362. return returnCode;
  10363. }
  10364. #endif
  10365. void Session::useConfigData( ConfigData const& configData ) {
  10366. m_configData = configData;
  10367. m_config.reset();
  10368. }
  10369. int Session::run() {
  10370. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  10371. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  10372. static_cast<void>(std::getchar());
  10373. }
  10374. int exitCode = runInternal();
  10375. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  10376. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  10377. static_cast<void>(std::getchar());
  10378. }
  10379. return exitCode;
  10380. }
  10381. clara::Parser const& Session::cli() const {
  10382. return m_cli;
  10383. }
  10384. void Session::cli( clara::Parser const& newParser ) {
  10385. m_cli = newParser;
  10386. }
  10387. ConfigData& Session::configData() {
  10388. return m_configData;
  10389. }
  10390. Config& Session::config() {
  10391. if( !m_config )
  10392. m_config = std::make_shared<Config>( m_configData );
  10393. return *m_config;
  10394. }
  10395. int Session::runInternal() {
  10396. if( m_startupExceptions )
  10397. return 1;
  10398. if (m_configData.showHelp || m_configData.libIdentify) {
  10399. return 0;
  10400. }
  10401. CATCH_TRY {
  10402. config(); // Force config to be constructed
  10403. seedRng( *m_config );
  10404. if( m_configData.filenamesAsTags )
  10405. applyFilenamesAsTags( *m_config );
  10406. // Handle list request
  10407. if( Option<std::size_t> listed = list( m_config ) )
  10408. return static_cast<int>( *listed );
  10409. auto totals = runTests( m_config );
  10410. // Note that on unices only the lower 8 bits are usually used, clamping
  10411. // the return value to 255 prevents false negative when some multiple
  10412. // of 256 tests has failed
  10413. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  10414. }
  10415. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10416. catch( std::exception& ex ) {
  10417. Catch::cerr() << ex.what() << std::endl;
  10418. return MaxExitCode;
  10419. }
  10420. #endif
  10421. }
  10422. } // end namespace Catch
  10423. // end catch_session.cpp
  10424. // start catch_singletons.cpp
  10425. #include <vector>
  10426. namespace Catch {
  10427. namespace {
  10428. static auto getSingletons() -> std::vector<ISingleton*>*& {
  10429. static std::vector<ISingleton*>* g_singletons = nullptr;
  10430. if( !g_singletons )
  10431. g_singletons = new std::vector<ISingleton*>();
  10432. return g_singletons;
  10433. }
  10434. }
  10435. ISingleton::~ISingleton() {}
  10436. void addSingleton(ISingleton* singleton ) {
  10437. getSingletons()->push_back( singleton );
  10438. }
  10439. void cleanupSingletons() {
  10440. auto& singletons = getSingletons();
  10441. for( auto singleton : *singletons )
  10442. delete singleton;
  10443. delete singletons;
  10444. singletons = nullptr;
  10445. }
  10446. } // namespace Catch
  10447. // end catch_singletons.cpp
  10448. // start catch_startup_exception_registry.cpp
  10449. namespace Catch {
  10450. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  10451. CATCH_TRY {
  10452. m_exceptions.push_back(exception);
  10453. } CATCH_CATCH_ALL {
  10454. // If we run out of memory during start-up there's really not a lot more we can do about it
  10455. std::terminate();
  10456. }
  10457. }
  10458. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  10459. return m_exceptions;
  10460. }
  10461. } // end namespace Catch
  10462. // end catch_startup_exception_registry.cpp
  10463. // start catch_stream.cpp
  10464. #include <cstdio>
  10465. #include <iostream>
  10466. #include <fstream>
  10467. #include <sstream>
  10468. #include <vector>
  10469. #include <memory>
  10470. namespace Catch {
  10471. Catch::IStream::~IStream() = default;
  10472. namespace Detail { namespace {
  10473. template<typename WriterF, std::size_t bufferSize=256>
  10474. class StreamBufImpl : public std::streambuf {
  10475. char data[bufferSize];
  10476. WriterF m_writer;
  10477. public:
  10478. StreamBufImpl() {
  10479. setp( data, data + sizeof(data) );
  10480. }
  10481. ~StreamBufImpl() noexcept {
  10482. StreamBufImpl::sync();
  10483. }
  10484. private:
  10485. int overflow( int c ) override {
  10486. sync();
  10487. if( c != EOF ) {
  10488. if( pbase() == epptr() )
  10489. m_writer( std::string( 1, static_cast<char>( c ) ) );
  10490. else
  10491. sputc( static_cast<char>( c ) );
  10492. }
  10493. return 0;
  10494. }
  10495. int sync() override {
  10496. if( pbase() != pptr() ) {
  10497. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  10498. setp( pbase(), epptr() );
  10499. }
  10500. return 0;
  10501. }
  10502. };
  10503. ///////////////////////////////////////////////////////////////////////////
  10504. struct OutputDebugWriter {
  10505. void operator()( std::string const&str ) {
  10506. writeToDebugConsole( str );
  10507. }
  10508. };
  10509. ///////////////////////////////////////////////////////////////////////////
  10510. class FileStream : public IStream {
  10511. mutable std::ofstream m_ofs;
  10512. public:
  10513. FileStream( StringRef filename ) {
  10514. m_ofs.open( filename.c_str() );
  10515. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  10516. }
  10517. ~FileStream() override = default;
  10518. public: // IStream
  10519. std::ostream& stream() const override {
  10520. return m_ofs;
  10521. }
  10522. };
  10523. ///////////////////////////////////////////////////////////////////////////
  10524. class CoutStream : public IStream {
  10525. mutable std::ostream m_os;
  10526. public:
  10527. // Store the streambuf from cout up-front because
  10528. // cout may get redirected when running tests
  10529. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  10530. ~CoutStream() override = default;
  10531. public: // IStream
  10532. std::ostream& stream() const override { return m_os; }
  10533. };
  10534. ///////////////////////////////////////////////////////////////////////////
  10535. class DebugOutStream : public IStream {
  10536. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  10537. mutable std::ostream m_os;
  10538. public:
  10539. DebugOutStream()
  10540. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  10541. m_os( m_streamBuf.get() )
  10542. {}
  10543. ~DebugOutStream() override = default;
  10544. public: // IStream
  10545. std::ostream& stream() const override { return m_os; }
  10546. };
  10547. }} // namespace anon::detail
  10548. ///////////////////////////////////////////////////////////////////////////
  10549. auto makeStream( StringRef const &filename ) -> IStream const* {
  10550. if( filename.empty() )
  10551. return new Detail::CoutStream();
  10552. else if( filename[0] == '%' ) {
  10553. if( filename == "%debug" )
  10554. return new Detail::DebugOutStream();
  10555. else
  10556. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  10557. }
  10558. else
  10559. return new Detail::FileStream( filename );
  10560. }
  10561. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  10562. struct StringStreams {
  10563. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  10564. std::vector<std::size_t> m_unused;
  10565. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  10566. auto add() -> std::size_t {
  10567. if( m_unused.empty() ) {
  10568. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  10569. return m_streams.size()-1;
  10570. }
  10571. else {
  10572. auto index = m_unused.back();
  10573. m_unused.pop_back();
  10574. return index;
  10575. }
  10576. }
  10577. void release( std::size_t index ) {
  10578. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  10579. m_unused.push_back(index);
  10580. }
  10581. };
  10582. ReusableStringStream::ReusableStringStream()
  10583. : m_index( Singleton<StringStreams>::getMutable().add() ),
  10584. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  10585. {}
  10586. ReusableStringStream::~ReusableStringStream() {
  10587. static_cast<std::ostringstream*>( m_oss )->str("");
  10588. m_oss->clear();
  10589. Singleton<StringStreams>::getMutable().release( m_index );
  10590. }
  10591. auto ReusableStringStream::str() const -> std::string {
  10592. return static_cast<std::ostringstream*>( m_oss )->str();
  10593. }
  10594. ///////////////////////////////////////////////////////////////////////////
  10595. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  10596. std::ostream& cout() { return std::cout; }
  10597. std::ostream& cerr() { return std::cerr; }
  10598. std::ostream& clog() { return std::clog; }
  10599. #endif
  10600. }
  10601. // end catch_stream.cpp
  10602. // start catch_string_manip.cpp
  10603. #include <algorithm>
  10604. #include <ostream>
  10605. #include <cstring>
  10606. #include <cctype>
  10607. #include <vector>
  10608. namespace Catch {
  10609. namespace {
  10610. char toLowerCh(char c) {
  10611. return static_cast<char>( std::tolower( c ) );
  10612. }
  10613. }
  10614. bool startsWith( std::string const& s, std::string const& prefix ) {
  10615. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  10616. }
  10617. bool startsWith( std::string const& s, char prefix ) {
  10618. return !s.empty() && s[0] == prefix;
  10619. }
  10620. bool endsWith( std::string const& s, std::string const& suffix ) {
  10621. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  10622. }
  10623. bool endsWith( std::string const& s, char suffix ) {
  10624. return !s.empty() && s[s.size()-1] == suffix;
  10625. }
  10626. bool contains( std::string const& s, std::string const& infix ) {
  10627. return s.find( infix ) != std::string::npos;
  10628. }
  10629. void toLowerInPlace( std::string& s ) {
  10630. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  10631. }
  10632. std::string toLower( std::string const& s ) {
  10633. std::string lc = s;
  10634. toLowerInPlace( lc );
  10635. return lc;
  10636. }
  10637. std::string trim( std::string const& str ) {
  10638. static char const* whitespaceChars = "\n\r\t ";
  10639. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  10640. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  10641. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  10642. }
  10643. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  10644. bool replaced = false;
  10645. std::size_t i = str.find( replaceThis );
  10646. while( i != std::string::npos ) {
  10647. replaced = true;
  10648. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  10649. if( i < str.size()-withThis.size() )
  10650. i = str.find( replaceThis, i+withThis.size() );
  10651. else
  10652. i = std::string::npos;
  10653. }
  10654. return replaced;
  10655. }
  10656. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  10657. std::vector<StringRef> subStrings;
  10658. std::size_t start = 0;
  10659. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  10660. if( str[pos] == delimiter ) {
  10661. if( pos - start > 1 )
  10662. subStrings.push_back( str.substr( start, pos-start ) );
  10663. start = pos+1;
  10664. }
  10665. }
  10666. if( start < str.size() )
  10667. subStrings.push_back( str.substr( start, str.size()-start ) );
  10668. return subStrings;
  10669. }
  10670. pluralise::pluralise( std::size_t count, std::string const& label )
  10671. : m_count( count ),
  10672. m_label( label )
  10673. {}
  10674. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  10675. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  10676. if( pluraliser.m_count != 1 )
  10677. os << 's';
  10678. return os;
  10679. }
  10680. }
  10681. // end catch_string_manip.cpp
  10682. // start catch_stringref.cpp
  10683. #if defined(__clang__)
  10684. # pragma clang diagnostic push
  10685. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10686. #endif
  10687. #include <ostream>
  10688. #include <cstring>
  10689. #include <cstdint>
  10690. namespace {
  10691. const uint32_t byte_2_lead = 0xC0;
  10692. const uint32_t byte_3_lead = 0xE0;
  10693. const uint32_t byte_4_lead = 0xF0;
  10694. }
  10695. namespace Catch {
  10696. StringRef::StringRef( char const* rawChars ) noexcept
  10697. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  10698. {}
  10699. StringRef::operator std::string() const {
  10700. return std::string( m_start, m_size );
  10701. }
  10702. void StringRef::swap( StringRef& other ) noexcept {
  10703. std::swap( m_start, other.m_start );
  10704. std::swap( m_size, other.m_size );
  10705. std::swap( m_data, other.m_data );
  10706. }
  10707. auto StringRef::c_str() const -> char const* {
  10708. if( !isSubstring() )
  10709. return m_start;
  10710. const_cast<StringRef *>( this )->takeOwnership();
  10711. return m_data;
  10712. }
  10713. auto StringRef::currentData() const noexcept -> char const* {
  10714. return m_start;
  10715. }
  10716. auto StringRef::isOwned() const noexcept -> bool {
  10717. return m_data != nullptr;
  10718. }
  10719. auto StringRef::isSubstring() const noexcept -> bool {
  10720. return m_start[m_size] != '\0';
  10721. }
  10722. void StringRef::takeOwnership() {
  10723. if( !isOwned() ) {
  10724. m_data = new char[m_size+1];
  10725. memcpy( m_data, m_start, m_size );
  10726. m_data[m_size] = '\0';
  10727. }
  10728. }
  10729. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  10730. if( start < m_size )
  10731. return StringRef( m_start+start, size );
  10732. else
  10733. return StringRef();
  10734. }
  10735. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  10736. return
  10737. size() == other.size() &&
  10738. (std::strncmp( m_start, other.m_start, size() ) == 0);
  10739. }
  10740. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  10741. return !operator==( other );
  10742. }
  10743. auto StringRef::operator[](size_type index) const noexcept -> char {
  10744. return m_start[index];
  10745. }
  10746. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  10747. size_type noChars = m_size;
  10748. // Make adjustments for uft encodings
  10749. for( size_type i=0; i < m_size; ++i ) {
  10750. char c = m_start[i];
  10751. if( ( c & byte_2_lead ) == byte_2_lead ) {
  10752. noChars--;
  10753. if (( c & byte_3_lead ) == byte_3_lead )
  10754. noChars--;
  10755. if( ( c & byte_4_lead ) == byte_4_lead )
  10756. noChars--;
  10757. }
  10758. }
  10759. return noChars;
  10760. }
  10761. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  10762. std::string str;
  10763. str.reserve( lhs.size() + rhs.size() );
  10764. str += lhs;
  10765. str += rhs;
  10766. return str;
  10767. }
  10768. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  10769. return std::string( lhs ) + std::string( rhs );
  10770. }
  10771. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  10772. return std::string( lhs ) + std::string( rhs );
  10773. }
  10774. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  10775. return os.write(str.currentData(), str.size());
  10776. }
  10777. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  10778. lhs.append(rhs.currentData(), rhs.size());
  10779. return lhs;
  10780. }
  10781. } // namespace Catch
  10782. #if defined(__clang__)
  10783. # pragma clang diagnostic pop
  10784. #endif
  10785. // end catch_stringref.cpp
  10786. // start catch_tag_alias.cpp
  10787. namespace Catch {
  10788. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  10789. }
  10790. // end catch_tag_alias.cpp
  10791. // start catch_tag_alias_autoregistrar.cpp
  10792. namespace Catch {
  10793. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  10794. CATCH_TRY {
  10795. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  10796. } CATCH_CATCH_ALL {
  10797. // Do not throw when constructing global objects, instead register the exception to be processed later
  10798. getMutableRegistryHub().registerStartupException();
  10799. }
  10800. }
  10801. }
  10802. // end catch_tag_alias_autoregistrar.cpp
  10803. // start catch_tag_alias_registry.cpp
  10804. #include <sstream>
  10805. namespace Catch {
  10806. TagAliasRegistry::~TagAliasRegistry() {}
  10807. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  10808. auto it = m_registry.find( alias );
  10809. if( it != m_registry.end() )
  10810. return &(it->second);
  10811. else
  10812. return nullptr;
  10813. }
  10814. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  10815. std::string expandedTestSpec = unexpandedTestSpec;
  10816. for( auto const& registryKvp : m_registry ) {
  10817. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  10818. if( pos != std::string::npos ) {
  10819. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  10820. registryKvp.second.tag +
  10821. expandedTestSpec.substr( pos + registryKvp.first.size() );
  10822. }
  10823. }
  10824. return expandedTestSpec;
  10825. }
  10826. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  10827. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  10828. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  10829. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  10830. "error: tag alias, '" << alias << "' already registered.\n"
  10831. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  10832. << "\tRedefined at: " << lineInfo );
  10833. }
  10834. ITagAliasRegistry::~ITagAliasRegistry() {}
  10835. ITagAliasRegistry const& ITagAliasRegistry::get() {
  10836. return getRegistryHub().getTagAliasRegistry();
  10837. }
  10838. } // end namespace Catch
  10839. // end catch_tag_alias_registry.cpp
  10840. // start catch_test_case_info.cpp
  10841. #include <cctype>
  10842. #include <exception>
  10843. #include <algorithm>
  10844. #include <sstream>
  10845. namespace Catch {
  10846. namespace {
  10847. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  10848. if( startsWith( tag, '.' ) ||
  10849. tag == "!hide" )
  10850. return TestCaseInfo::IsHidden;
  10851. else if( tag == "!throws" )
  10852. return TestCaseInfo::Throws;
  10853. else if( tag == "!shouldfail" )
  10854. return TestCaseInfo::ShouldFail;
  10855. else if( tag == "!mayfail" )
  10856. return TestCaseInfo::MayFail;
  10857. else if( tag == "!nonportable" )
  10858. return TestCaseInfo::NonPortable;
  10859. else if( tag == "!benchmark" )
  10860. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  10861. else
  10862. return TestCaseInfo::None;
  10863. }
  10864. bool isReservedTag( std::string const& tag ) {
  10865. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  10866. }
  10867. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  10868. CATCH_ENFORCE( !isReservedTag(tag),
  10869. "Tag name: [" << tag << "] is not allowed.\n"
  10870. << "Tag names starting with non alphanumeric characters are reserved\n"
  10871. << _lineInfo );
  10872. }
  10873. }
  10874. TestCase makeTestCase( ITestInvoker* _testCase,
  10875. std::string const& _className,
  10876. NameAndTags const& nameAndTags,
  10877. SourceLineInfo const& _lineInfo )
  10878. {
  10879. bool isHidden = false;
  10880. // Parse out tags
  10881. std::vector<std::string> tags;
  10882. std::string desc, tag;
  10883. bool inTag = false;
  10884. std::string _descOrTags = nameAndTags.tags;
  10885. for (char c : _descOrTags) {
  10886. if( !inTag ) {
  10887. if( c == '[' )
  10888. inTag = true;
  10889. else
  10890. desc += c;
  10891. }
  10892. else {
  10893. if( c == ']' ) {
  10894. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  10895. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  10896. isHidden = true;
  10897. else if( prop == TestCaseInfo::None )
  10898. enforceNotReservedTag( tag, _lineInfo );
  10899. // Merged hide tags like `[.approvals]` should be added as
  10900. // `[.][approvals]`. The `[.]` is added at later point, so
  10901. // we only strip the prefix
  10902. if (startsWith(tag, '.') && tag.size() > 1) {
  10903. tag.erase(0, 1);
  10904. }
  10905. tags.push_back( tag );
  10906. tag.clear();
  10907. inTag = false;
  10908. }
  10909. else
  10910. tag += c;
  10911. }
  10912. }
  10913. if( isHidden ) {
  10914. tags.push_back( "." );
  10915. }
  10916. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  10917. return TestCase( _testCase, std::move(info) );
  10918. }
  10919. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  10920. std::sort(begin(tags), end(tags));
  10921. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  10922. testCaseInfo.lcaseTags.clear();
  10923. for( auto const& tag : tags ) {
  10924. std::string lcaseTag = toLower( tag );
  10925. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  10926. testCaseInfo.lcaseTags.push_back( lcaseTag );
  10927. }
  10928. testCaseInfo.tags = std::move(tags);
  10929. }
  10930. TestCaseInfo::TestCaseInfo( std::string const& _name,
  10931. std::string const& _className,
  10932. std::string const& _description,
  10933. std::vector<std::string> const& _tags,
  10934. SourceLineInfo const& _lineInfo )
  10935. : name( _name ),
  10936. className( _className ),
  10937. description( _description ),
  10938. lineInfo( _lineInfo ),
  10939. properties( None )
  10940. {
  10941. setTags( *this, _tags );
  10942. }
  10943. bool TestCaseInfo::isHidden() const {
  10944. return ( properties & IsHidden ) != 0;
  10945. }
  10946. bool TestCaseInfo::throws() const {
  10947. return ( properties & Throws ) != 0;
  10948. }
  10949. bool TestCaseInfo::okToFail() const {
  10950. return ( properties & (ShouldFail | MayFail ) ) != 0;
  10951. }
  10952. bool TestCaseInfo::expectedToFail() const {
  10953. return ( properties & (ShouldFail ) ) != 0;
  10954. }
  10955. std::string TestCaseInfo::tagsAsString() const {
  10956. std::string ret;
  10957. // '[' and ']' per tag
  10958. std::size_t full_size = 2 * tags.size();
  10959. for (const auto& tag : tags) {
  10960. full_size += tag.size();
  10961. }
  10962. ret.reserve(full_size);
  10963. for (const auto& tag : tags) {
  10964. ret.push_back('[');
  10965. ret.append(tag);
  10966. ret.push_back(']');
  10967. }
  10968. return ret;
  10969. }
  10970. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  10971. TestCase TestCase::withName( std::string const& _newName ) const {
  10972. TestCase other( *this );
  10973. other.name = _newName;
  10974. return other;
  10975. }
  10976. void TestCase::invoke() const {
  10977. test->invoke();
  10978. }
  10979. bool TestCase::operator == ( TestCase const& other ) const {
  10980. return test.get() == other.test.get() &&
  10981. name == other.name &&
  10982. className == other.className;
  10983. }
  10984. bool TestCase::operator < ( TestCase const& other ) const {
  10985. return name < other.name;
  10986. }
  10987. TestCaseInfo const& TestCase::getTestCaseInfo() const
  10988. {
  10989. return *this;
  10990. }
  10991. } // end namespace Catch
  10992. // end catch_test_case_info.cpp
  10993. // start catch_test_case_registry_impl.cpp
  10994. #include <sstream>
  10995. namespace Catch {
  10996. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  10997. std::vector<TestCase> sorted = unsortedTestCases;
  10998. switch( config.runOrder() ) {
  10999. case RunTests::InLexicographicalOrder:
  11000. std::sort( sorted.begin(), sorted.end() );
  11001. break;
  11002. case RunTests::InRandomOrder:
  11003. seedRng( config );
  11004. std::shuffle( sorted.begin(), sorted.end(), rng() );
  11005. break;
  11006. case RunTests::InDeclarationOrder:
  11007. // already in declaration order
  11008. break;
  11009. }
  11010. return sorted;
  11011. }
  11012. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11013. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  11014. }
  11015. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11016. std::set<TestCase> seenFunctions;
  11017. for( auto const& function : functions ) {
  11018. auto prev = seenFunctions.insert( function );
  11019. CATCH_ENFORCE( prev.second,
  11020. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11021. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11022. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11023. }
  11024. }
  11025. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11026. std::vector<TestCase> filtered;
  11027. filtered.reserve( testCases.size() );
  11028. for (auto const& testCase : testCases) {
  11029. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11030. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11031. filtered.push_back(testCase);
  11032. }
  11033. }
  11034. return filtered;
  11035. }
  11036. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11037. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11038. }
  11039. void TestRegistry::registerTest( TestCase const& testCase ) {
  11040. std::string name = testCase.getTestCaseInfo().name;
  11041. if( name.empty() ) {
  11042. ReusableStringStream rss;
  11043. rss << "Anonymous test case " << ++m_unnamedCount;
  11044. return registerTest( testCase.withName( rss.str() ) );
  11045. }
  11046. m_functions.push_back( testCase );
  11047. }
  11048. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11049. return m_functions;
  11050. }
  11051. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11052. if( m_sortedFunctions.empty() )
  11053. enforceNoDuplicateTestCases( m_functions );
  11054. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11055. m_sortedFunctions = sortTests( config, m_functions );
  11056. m_currentSortOrder = config.runOrder();
  11057. }
  11058. return m_sortedFunctions;
  11059. }
  11060. ///////////////////////////////////////////////////////////////////////////
  11061. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11062. void TestInvokerAsFunction::invoke() const {
  11063. m_testAsFunction();
  11064. }
  11065. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11066. std::string className = classOrQualifiedMethodName;
  11067. if( startsWith( className, '&' ) )
  11068. {
  11069. std::size_t lastColons = className.rfind( "::" );
  11070. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11071. if( penultimateColons == std::string::npos )
  11072. penultimateColons = 1;
  11073. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11074. }
  11075. return className;
  11076. }
  11077. } // end namespace Catch
  11078. // end catch_test_case_registry_impl.cpp
  11079. // start catch_test_case_tracker.cpp
  11080. #include <algorithm>
  11081. #include <cassert>
  11082. #include <stdexcept>
  11083. #include <memory>
  11084. #include <sstream>
  11085. #if defined(__clang__)
  11086. # pragma clang diagnostic push
  11087. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11088. #endif
  11089. namespace Catch {
  11090. namespace TestCaseTracking {
  11091. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11092. : name( _name ),
  11093. location( _location )
  11094. {}
  11095. ITracker::~ITracker() = default;
  11096. ITracker& TrackerContext::startRun() {
  11097. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11098. m_currentTracker = nullptr;
  11099. m_runState = Executing;
  11100. return *m_rootTracker;
  11101. }
  11102. void TrackerContext::endRun() {
  11103. m_rootTracker.reset();
  11104. m_currentTracker = nullptr;
  11105. m_runState = NotStarted;
  11106. }
  11107. void TrackerContext::startCycle() {
  11108. m_currentTracker = m_rootTracker.get();
  11109. m_runState = Executing;
  11110. }
  11111. void TrackerContext::completeCycle() {
  11112. m_runState = CompletedCycle;
  11113. }
  11114. bool TrackerContext::completedCycle() const {
  11115. return m_runState == CompletedCycle;
  11116. }
  11117. ITracker& TrackerContext::currentTracker() {
  11118. return *m_currentTracker;
  11119. }
  11120. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11121. m_currentTracker = tracker;
  11122. }
  11123. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11124. : m_nameAndLocation( nameAndLocation ),
  11125. m_ctx( ctx ),
  11126. m_parent( parent )
  11127. {}
  11128. NameAndLocation const& TrackerBase::nameAndLocation() const {
  11129. return m_nameAndLocation;
  11130. }
  11131. bool TrackerBase::isComplete() const {
  11132. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11133. }
  11134. bool TrackerBase::isSuccessfullyCompleted() const {
  11135. return m_runState == CompletedSuccessfully;
  11136. }
  11137. bool TrackerBase::isOpen() const {
  11138. return m_runState != NotStarted && !isComplete();
  11139. }
  11140. bool TrackerBase::hasChildren() const {
  11141. return !m_children.empty();
  11142. }
  11143. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11144. m_children.push_back( child );
  11145. }
  11146. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11147. auto it = std::find_if( m_children.begin(), m_children.end(),
  11148. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11149. return
  11150. tracker->nameAndLocation().location == nameAndLocation.location &&
  11151. tracker->nameAndLocation().name == nameAndLocation.name;
  11152. } );
  11153. return( it != m_children.end() )
  11154. ? *it
  11155. : nullptr;
  11156. }
  11157. ITracker& TrackerBase::parent() {
  11158. assert( m_parent ); // Should always be non-null except for root
  11159. return *m_parent;
  11160. }
  11161. void TrackerBase::openChild() {
  11162. if( m_runState != ExecutingChildren ) {
  11163. m_runState = ExecutingChildren;
  11164. if( m_parent )
  11165. m_parent->openChild();
  11166. }
  11167. }
  11168. bool TrackerBase::isSectionTracker() const { return false; }
  11169. bool TrackerBase::isGeneratorTracker() const { return false; }
  11170. void TrackerBase::open() {
  11171. m_runState = Executing;
  11172. moveToThis();
  11173. if( m_parent )
  11174. m_parent->openChild();
  11175. }
  11176. void TrackerBase::close() {
  11177. // Close any still open children (e.g. generators)
  11178. while( &m_ctx.currentTracker() != this )
  11179. m_ctx.currentTracker().close();
  11180. switch( m_runState ) {
  11181. case NeedsAnotherRun:
  11182. break;
  11183. case Executing:
  11184. m_runState = CompletedSuccessfully;
  11185. break;
  11186. case ExecutingChildren:
  11187. if( m_children.empty() || m_children.back()->isComplete() )
  11188. m_runState = CompletedSuccessfully;
  11189. break;
  11190. case NotStarted:
  11191. case CompletedSuccessfully:
  11192. case Failed:
  11193. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11194. default:
  11195. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11196. }
  11197. moveToParent();
  11198. m_ctx.completeCycle();
  11199. }
  11200. void TrackerBase::fail() {
  11201. m_runState = Failed;
  11202. if( m_parent )
  11203. m_parent->markAsNeedingAnotherRun();
  11204. moveToParent();
  11205. m_ctx.completeCycle();
  11206. }
  11207. void TrackerBase::markAsNeedingAnotherRun() {
  11208. m_runState = NeedsAnotherRun;
  11209. }
  11210. void TrackerBase::moveToParent() {
  11211. assert( m_parent );
  11212. m_ctx.setCurrentTracker( m_parent );
  11213. }
  11214. void TrackerBase::moveToThis() {
  11215. m_ctx.setCurrentTracker( this );
  11216. }
  11217. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11218. : TrackerBase( nameAndLocation, ctx, parent )
  11219. {
  11220. if( parent ) {
  11221. while( !parent->isSectionTracker() )
  11222. parent = &parent->parent();
  11223. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11224. addNextFilters( parentSection.m_filters );
  11225. }
  11226. }
  11227. bool SectionTracker::isComplete() const {
  11228. bool complete = true;
  11229. if ((m_filters.empty() || m_filters[0] == "") ||
  11230. std::find(m_filters.begin(), m_filters.end(),
  11231. m_nameAndLocation.name) != m_filters.end())
  11232. complete = TrackerBase::isComplete();
  11233. return complete;
  11234. }
  11235. bool SectionTracker::isSectionTracker() const { return true; }
  11236. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11237. std::shared_ptr<SectionTracker> section;
  11238. ITracker& currentTracker = ctx.currentTracker();
  11239. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11240. assert( childTracker );
  11241. assert( childTracker->isSectionTracker() );
  11242. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11243. }
  11244. else {
  11245. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11246. currentTracker.addChild( section );
  11247. }
  11248. if( !ctx.completedCycle() )
  11249. section->tryOpen();
  11250. return *section;
  11251. }
  11252. void SectionTracker::tryOpen() {
  11253. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  11254. open();
  11255. }
  11256. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11257. if( !filters.empty() ) {
  11258. m_filters.push_back(""); // Root - should never be consulted
  11259. m_filters.push_back(""); // Test Case - not a section filter
  11260. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11261. }
  11262. }
  11263. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11264. if( filters.size() > 1 )
  11265. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  11266. }
  11267. } // namespace TestCaseTracking
  11268. using TestCaseTracking::ITracker;
  11269. using TestCaseTracking::TrackerContext;
  11270. using TestCaseTracking::SectionTracker;
  11271. } // namespace Catch
  11272. #if defined(__clang__)
  11273. # pragma clang diagnostic pop
  11274. #endif
  11275. // end catch_test_case_tracker.cpp
  11276. // start catch_test_registry.cpp
  11277. namespace Catch {
  11278. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11279. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11280. }
  11281. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11282. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11283. CATCH_TRY {
  11284. getMutableRegistryHub()
  11285. .registerTest(
  11286. makeTestCase(
  11287. invoker,
  11288. extractClassName( classOrMethod ),
  11289. nameAndTags,
  11290. lineInfo));
  11291. } CATCH_CATCH_ALL {
  11292. // Do not throw when constructing global objects, instead register the exception to be processed later
  11293. getMutableRegistryHub().registerStartupException();
  11294. }
  11295. }
  11296. AutoReg::~AutoReg() = default;
  11297. }
  11298. // end catch_test_registry.cpp
  11299. // start catch_test_spec.cpp
  11300. #include <algorithm>
  11301. #include <string>
  11302. #include <vector>
  11303. #include <memory>
  11304. namespace Catch {
  11305. TestSpec::Pattern::~Pattern() = default;
  11306. TestSpec::NamePattern::~NamePattern() = default;
  11307. TestSpec::TagPattern::~TagPattern() = default;
  11308. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  11309. TestSpec::NamePattern::NamePattern( std::string const& name )
  11310. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11311. {}
  11312. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11313. return m_wildcardPattern.matches( toLower( testCase.name ) );
  11314. }
  11315. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  11316. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11317. return std::find(begin(testCase.lcaseTags),
  11318. end(testCase.lcaseTags),
  11319. m_tag) != end(testCase.lcaseTags);
  11320. }
  11321. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  11322. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  11323. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11324. // All patterns in a filter must match for the filter to be a match
  11325. for( auto const& pattern : m_patterns ) {
  11326. if( !pattern->matches( testCase ) )
  11327. return false;
  11328. }
  11329. return true;
  11330. }
  11331. bool TestSpec::hasFilters() const {
  11332. return !m_filters.empty();
  11333. }
  11334. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11335. // A TestSpec matches if any filter matches
  11336. for( auto const& filter : m_filters )
  11337. if( filter.matches( testCase ) )
  11338. return true;
  11339. return false;
  11340. }
  11341. }
  11342. // end catch_test_spec.cpp
  11343. // start catch_test_spec_parser.cpp
  11344. namespace Catch {
  11345. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  11346. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  11347. m_mode = None;
  11348. m_exclusion = false;
  11349. m_start = std::string::npos;
  11350. m_arg = m_tagAliases->expandAliases( arg );
  11351. m_escapeChars.clear();
  11352. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  11353. visitChar( m_arg[m_pos] );
  11354. if( m_mode == Name )
  11355. addPattern<TestSpec::NamePattern>();
  11356. return *this;
  11357. }
  11358. TestSpec TestSpecParser::testSpec() {
  11359. addFilter();
  11360. return m_testSpec;
  11361. }
  11362. void TestSpecParser::visitChar( char c ) {
  11363. if( m_mode == None ) {
  11364. switch( c ) {
  11365. case ' ': return;
  11366. case '~': m_exclusion = true; return;
  11367. case '[': return startNewMode( Tag, ++m_pos );
  11368. case '"': return startNewMode( QuotedName, ++m_pos );
  11369. case '\\': return escape();
  11370. default: startNewMode( Name, m_pos ); break;
  11371. }
  11372. }
  11373. if( m_mode == Name ) {
  11374. if( c == ',' ) {
  11375. addPattern<TestSpec::NamePattern>();
  11376. addFilter();
  11377. }
  11378. else if( c == '[' ) {
  11379. if( subString() == "exclude:" )
  11380. m_exclusion = true;
  11381. else
  11382. addPattern<TestSpec::NamePattern>();
  11383. startNewMode( Tag, ++m_pos );
  11384. }
  11385. else if( c == '\\' )
  11386. escape();
  11387. }
  11388. else if( m_mode == EscapedName )
  11389. m_mode = Name;
  11390. else if( m_mode == QuotedName && c == '"' )
  11391. addPattern<TestSpec::NamePattern>();
  11392. else if( m_mode == Tag && c == ']' )
  11393. addPattern<TestSpec::TagPattern>();
  11394. }
  11395. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  11396. m_mode = mode;
  11397. m_start = start;
  11398. }
  11399. void TestSpecParser::escape() {
  11400. if( m_mode == None )
  11401. m_start = m_pos;
  11402. m_mode = EscapedName;
  11403. m_escapeChars.push_back( m_pos );
  11404. }
  11405. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  11406. void TestSpecParser::addFilter() {
  11407. if( !m_currentFilter.m_patterns.empty() ) {
  11408. m_testSpec.m_filters.push_back( m_currentFilter );
  11409. m_currentFilter = TestSpec::Filter();
  11410. }
  11411. }
  11412. TestSpec parseTestSpec( std::string const& arg ) {
  11413. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  11414. }
  11415. } // namespace Catch
  11416. // end catch_test_spec_parser.cpp
  11417. // start catch_timer.cpp
  11418. #include <chrono>
  11419. static const uint64_t nanosecondsInSecond = 1000000000;
  11420. namespace Catch {
  11421. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  11422. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  11423. }
  11424. namespace {
  11425. auto estimateClockResolution() -> uint64_t {
  11426. uint64_t sum = 0;
  11427. static const uint64_t iterations = 1000000;
  11428. auto startTime = getCurrentNanosecondsSinceEpoch();
  11429. for( std::size_t i = 0; i < iterations; ++i ) {
  11430. uint64_t ticks;
  11431. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  11432. do {
  11433. ticks = getCurrentNanosecondsSinceEpoch();
  11434. } while( ticks == baseTicks );
  11435. auto delta = ticks - baseTicks;
  11436. sum += delta;
  11437. // If we have been calibrating for over 3 seconds -- the clock
  11438. // is terrible and we should move on.
  11439. // TBD: How to signal that the measured resolution is probably wrong?
  11440. if (ticks > startTime + 3 * nanosecondsInSecond) {
  11441. return sum / ( i + 1u );
  11442. }
  11443. }
  11444. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  11445. // - and potentially do more iterations if there's a high variance.
  11446. return sum/iterations;
  11447. }
  11448. }
  11449. auto getEstimatedClockResolution() -> uint64_t {
  11450. static auto s_resolution = estimateClockResolution();
  11451. return s_resolution;
  11452. }
  11453. void Timer::start() {
  11454. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  11455. }
  11456. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  11457. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  11458. }
  11459. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  11460. return getElapsedNanoseconds()/1000;
  11461. }
  11462. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  11463. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  11464. }
  11465. auto Timer::getElapsedSeconds() const -> double {
  11466. return getElapsedMicroseconds()/1000000.0;
  11467. }
  11468. } // namespace Catch
  11469. // end catch_timer.cpp
  11470. // start catch_tostring.cpp
  11471. #if defined(__clang__)
  11472. # pragma clang diagnostic push
  11473. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11474. # pragma clang diagnostic ignored "-Wglobal-constructors"
  11475. #endif
  11476. // Enable specific decls locally
  11477. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  11478. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  11479. #endif
  11480. #include <cmath>
  11481. #include <iomanip>
  11482. namespace Catch {
  11483. namespace Detail {
  11484. const std::string unprintableString = "{?}";
  11485. namespace {
  11486. const int hexThreshold = 255;
  11487. struct Endianness {
  11488. enum Arch { Big, Little };
  11489. static Arch which() {
  11490. union _{
  11491. int asInt;
  11492. char asChar[sizeof (int)];
  11493. } u;
  11494. u.asInt = 1;
  11495. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  11496. }
  11497. };
  11498. }
  11499. std::string rawMemoryToString( const void *object, std::size_t size ) {
  11500. // Reverse order for little endian architectures
  11501. int i = 0, end = static_cast<int>( size ), inc = 1;
  11502. if( Endianness::which() == Endianness::Little ) {
  11503. i = end-1;
  11504. end = inc = -1;
  11505. }
  11506. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  11507. ReusableStringStream rss;
  11508. rss << "0x" << std::setfill('0') << std::hex;
  11509. for( ; i != end; i += inc )
  11510. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  11511. return rss.str();
  11512. }
  11513. }
  11514. template<typename T>
  11515. std::string fpToString( T value, int precision ) {
  11516. if (Catch::isnan(value)) {
  11517. return "nan";
  11518. }
  11519. ReusableStringStream rss;
  11520. rss << std::setprecision( precision )
  11521. << std::fixed
  11522. << value;
  11523. std::string d = rss.str();
  11524. std::size_t i = d.find_last_not_of( '0' );
  11525. if( i != std::string::npos && i != d.size()-1 ) {
  11526. if( d[i] == '.' )
  11527. i++;
  11528. d = d.substr( 0, i+1 );
  11529. }
  11530. return d;
  11531. }
  11532. //// ======================================================= ////
  11533. //
  11534. // Out-of-line defs for full specialization of StringMaker
  11535. //
  11536. //// ======================================================= ////
  11537. std::string StringMaker<std::string>::convert(const std::string& str) {
  11538. if (!getCurrentContext().getConfig()->showInvisibles()) {
  11539. return '"' + str + '"';
  11540. }
  11541. std::string s("\"");
  11542. for (char c : str) {
  11543. switch (c) {
  11544. case '\n':
  11545. s.append("\\n");
  11546. break;
  11547. case '\t':
  11548. s.append("\\t");
  11549. break;
  11550. default:
  11551. s.push_back(c);
  11552. break;
  11553. }
  11554. }
  11555. s.append("\"");
  11556. return s;
  11557. }
  11558. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11559. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  11560. return ::Catch::Detail::stringify(std::string{ str });
  11561. }
  11562. #endif
  11563. std::string StringMaker<char const*>::convert(char const* str) {
  11564. if (str) {
  11565. return ::Catch::Detail::stringify(std::string{ str });
  11566. } else {
  11567. return{ "{null string}" };
  11568. }
  11569. }
  11570. std::string StringMaker<char*>::convert(char* str) {
  11571. if (str) {
  11572. return ::Catch::Detail::stringify(std::string{ str });
  11573. } else {
  11574. return{ "{null string}" };
  11575. }
  11576. }
  11577. #ifdef CATCH_CONFIG_WCHAR
  11578. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  11579. std::string s;
  11580. s.reserve(wstr.size());
  11581. for (auto c : wstr) {
  11582. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  11583. }
  11584. return ::Catch::Detail::stringify(s);
  11585. }
  11586. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  11587. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  11588. return StringMaker<std::wstring>::convert(std::wstring(str));
  11589. }
  11590. # endif
  11591. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  11592. if (str) {
  11593. return ::Catch::Detail::stringify(std::wstring{ str });
  11594. } else {
  11595. return{ "{null string}" };
  11596. }
  11597. }
  11598. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  11599. if (str) {
  11600. return ::Catch::Detail::stringify(std::wstring{ str });
  11601. } else {
  11602. return{ "{null string}" };
  11603. }
  11604. }
  11605. #endif
  11606. std::string StringMaker<int>::convert(int value) {
  11607. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11608. }
  11609. std::string StringMaker<long>::convert(long value) {
  11610. return ::Catch::Detail::stringify(static_cast<long long>(value));
  11611. }
  11612. std::string StringMaker<long long>::convert(long long value) {
  11613. ReusableStringStream rss;
  11614. rss << value;
  11615. if (value > Detail::hexThreshold) {
  11616. rss << " (0x" << std::hex << value << ')';
  11617. }
  11618. return rss.str();
  11619. }
  11620. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  11621. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11622. }
  11623. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  11624. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  11625. }
  11626. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  11627. ReusableStringStream rss;
  11628. rss << value;
  11629. if (value > Detail::hexThreshold) {
  11630. rss << " (0x" << std::hex << value << ')';
  11631. }
  11632. return rss.str();
  11633. }
  11634. std::string StringMaker<bool>::convert(bool b) {
  11635. return b ? "true" : "false";
  11636. }
  11637. std::string StringMaker<signed char>::convert(signed char value) {
  11638. if (value == '\r') {
  11639. return "'\\r'";
  11640. } else if (value == '\f') {
  11641. return "'\\f'";
  11642. } else if (value == '\n') {
  11643. return "'\\n'";
  11644. } else if (value == '\t') {
  11645. return "'\\t'";
  11646. } else if ('\0' <= value && value < ' ') {
  11647. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  11648. } else {
  11649. char chstr[] = "' '";
  11650. chstr[1] = value;
  11651. return chstr;
  11652. }
  11653. }
  11654. std::string StringMaker<char>::convert(char c) {
  11655. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  11656. }
  11657. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  11658. return ::Catch::Detail::stringify(static_cast<char>(c));
  11659. }
  11660. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  11661. return "nullptr";
  11662. }
  11663. int StringMaker<float>::precision = 5;
  11664. std::string StringMaker<float>::convert(float value) {
  11665. return fpToString(value, precision) + 'f';
  11666. }
  11667. int StringMaker<double>::precision = 10;
  11668. std::string StringMaker<double>::convert(double value) {
  11669. return fpToString(value, precision);
  11670. }
  11671. std::string ratio_string<std::atto>::symbol() { return "a"; }
  11672. std::string ratio_string<std::femto>::symbol() { return "f"; }
  11673. std::string ratio_string<std::pico>::symbol() { return "p"; }
  11674. std::string ratio_string<std::nano>::symbol() { return "n"; }
  11675. std::string ratio_string<std::micro>::symbol() { return "u"; }
  11676. std::string ratio_string<std::milli>::symbol() { return "m"; }
  11677. } // end namespace Catch
  11678. #if defined(__clang__)
  11679. # pragma clang diagnostic pop
  11680. #endif
  11681. // end catch_tostring.cpp
  11682. // start catch_totals.cpp
  11683. namespace Catch {
  11684. Counts Counts::operator - ( Counts const& other ) const {
  11685. Counts diff;
  11686. diff.passed = passed - other.passed;
  11687. diff.failed = failed - other.failed;
  11688. diff.failedButOk = failedButOk - other.failedButOk;
  11689. return diff;
  11690. }
  11691. Counts& Counts::operator += ( Counts const& other ) {
  11692. passed += other.passed;
  11693. failed += other.failed;
  11694. failedButOk += other.failedButOk;
  11695. return *this;
  11696. }
  11697. std::size_t Counts::total() const {
  11698. return passed + failed + failedButOk;
  11699. }
  11700. bool Counts::allPassed() const {
  11701. return failed == 0 && failedButOk == 0;
  11702. }
  11703. bool Counts::allOk() const {
  11704. return failed == 0;
  11705. }
  11706. Totals Totals::operator - ( Totals const& other ) const {
  11707. Totals diff;
  11708. diff.assertions = assertions - other.assertions;
  11709. diff.testCases = testCases - other.testCases;
  11710. return diff;
  11711. }
  11712. Totals& Totals::operator += ( Totals const& other ) {
  11713. assertions += other.assertions;
  11714. testCases += other.testCases;
  11715. return *this;
  11716. }
  11717. Totals Totals::delta( Totals const& prevTotals ) const {
  11718. Totals diff = *this - prevTotals;
  11719. if( diff.assertions.failed > 0 )
  11720. ++diff.testCases.failed;
  11721. else if( diff.assertions.failedButOk > 0 )
  11722. ++diff.testCases.failedButOk;
  11723. else
  11724. ++diff.testCases.passed;
  11725. return diff;
  11726. }
  11727. }
  11728. // end catch_totals.cpp
  11729. // start catch_uncaught_exceptions.cpp
  11730. #include <exception>
  11731. namespace Catch {
  11732. bool uncaught_exceptions() {
  11733. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  11734. return std::uncaught_exceptions() > 0;
  11735. #else
  11736. return std::uncaught_exception();
  11737. #endif
  11738. }
  11739. } // end namespace Catch
  11740. // end catch_uncaught_exceptions.cpp
  11741. // start catch_version.cpp
  11742. #include <ostream>
  11743. namespace Catch {
  11744. Version::Version
  11745. ( unsigned int _majorVersion,
  11746. unsigned int _minorVersion,
  11747. unsigned int _patchNumber,
  11748. char const * const _branchName,
  11749. unsigned int _buildNumber )
  11750. : majorVersion( _majorVersion ),
  11751. minorVersion( _minorVersion ),
  11752. patchNumber( _patchNumber ),
  11753. branchName( _branchName ),
  11754. buildNumber( _buildNumber )
  11755. {}
  11756. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  11757. os << version.majorVersion << '.'
  11758. << version.minorVersion << '.'
  11759. << version.patchNumber;
  11760. // branchName is never null -> 0th char is \0 if it is empty
  11761. if (version.branchName[0]) {
  11762. os << '-' << version.branchName
  11763. << '.' << version.buildNumber;
  11764. }
  11765. return os;
  11766. }
  11767. Version const& libraryVersion() {
  11768. static Version version( 2, 9, 1, "", 0 );
  11769. return version;
  11770. }
  11771. }
  11772. // end catch_version.cpp
  11773. // start catch_wildcard_pattern.cpp
  11774. #include <sstream>
  11775. namespace Catch {
  11776. WildcardPattern::WildcardPattern( std::string const& pattern,
  11777. CaseSensitive::Choice caseSensitivity )
  11778. : m_caseSensitivity( caseSensitivity ),
  11779. m_pattern( adjustCase( pattern ) )
  11780. {
  11781. if( startsWith( m_pattern, '*' ) ) {
  11782. m_pattern = m_pattern.substr( 1 );
  11783. m_wildcard = WildcardAtStart;
  11784. }
  11785. if( endsWith( m_pattern, '*' ) ) {
  11786. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  11787. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  11788. }
  11789. }
  11790. bool WildcardPattern::matches( std::string const& str ) const {
  11791. switch( m_wildcard ) {
  11792. case NoWildcard:
  11793. return m_pattern == adjustCase( str );
  11794. case WildcardAtStart:
  11795. return endsWith( adjustCase( str ), m_pattern );
  11796. case WildcardAtEnd:
  11797. return startsWith( adjustCase( str ), m_pattern );
  11798. case WildcardAtBothEnds:
  11799. return contains( adjustCase( str ), m_pattern );
  11800. default:
  11801. CATCH_INTERNAL_ERROR( "Unknown enum" );
  11802. }
  11803. }
  11804. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  11805. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  11806. }
  11807. }
  11808. // end catch_wildcard_pattern.cpp
  11809. // start catch_xmlwriter.cpp
  11810. #include <iomanip>
  11811. using uchar = unsigned char;
  11812. namespace Catch {
  11813. namespace {
  11814. size_t trailingBytes(unsigned char c) {
  11815. if ((c & 0xE0) == 0xC0) {
  11816. return 2;
  11817. }
  11818. if ((c & 0xF0) == 0xE0) {
  11819. return 3;
  11820. }
  11821. if ((c & 0xF8) == 0xF0) {
  11822. return 4;
  11823. }
  11824. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  11825. }
  11826. uint32_t headerValue(unsigned char c) {
  11827. if ((c & 0xE0) == 0xC0) {
  11828. return c & 0x1F;
  11829. }
  11830. if ((c & 0xF0) == 0xE0) {
  11831. return c & 0x0F;
  11832. }
  11833. if ((c & 0xF8) == 0xF0) {
  11834. return c & 0x07;
  11835. }
  11836. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  11837. }
  11838. void hexEscapeChar(std::ostream& os, unsigned char c) {
  11839. std::ios_base::fmtflags f(os.flags());
  11840. os << "\\x"
  11841. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  11842. << static_cast<int>(c);
  11843. os.flags(f);
  11844. }
  11845. } // anonymous namespace
  11846. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  11847. : m_str( str ),
  11848. m_forWhat( forWhat )
  11849. {}
  11850. void XmlEncode::encodeTo( std::ostream& os ) const {
  11851. // Apostrophe escaping not necessary if we always use " to write attributes
  11852. // (see: http://www.w3.org/TR/xml/#syntax)
  11853. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  11854. uchar c = m_str[idx];
  11855. switch (c) {
  11856. case '<': os << "&lt;"; break;
  11857. case '&': os << "&amp;"; break;
  11858. case '>':
  11859. // See: http://www.w3.org/TR/xml/#syntax
  11860. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  11861. os << "&gt;";
  11862. else
  11863. os << c;
  11864. break;
  11865. case '\"':
  11866. if (m_forWhat == ForAttributes)
  11867. os << "&quot;";
  11868. else
  11869. os << c;
  11870. break;
  11871. default:
  11872. // Check for control characters and invalid utf-8
  11873. // Escape control characters in standard ascii
  11874. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  11875. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  11876. hexEscapeChar(os, c);
  11877. break;
  11878. }
  11879. // Plain ASCII: Write it to stream
  11880. if (c < 0x7F) {
  11881. os << c;
  11882. break;
  11883. }
  11884. // UTF-8 territory
  11885. // Check if the encoding is valid and if it is not, hex escape bytes.
  11886. // Important: We do not check the exact decoded values for validity, only the encoding format
  11887. // First check that this bytes is a valid lead byte:
  11888. // This means that it is not encoded as 1111 1XXX
  11889. // Or as 10XX XXXX
  11890. if (c < 0xC0 ||
  11891. c >= 0xF8) {
  11892. hexEscapeChar(os, c);
  11893. break;
  11894. }
  11895. auto encBytes = trailingBytes(c);
  11896. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  11897. if (idx + encBytes - 1 >= m_str.size()) {
  11898. hexEscapeChar(os, c);
  11899. break;
  11900. }
  11901. // The header is valid, check data
  11902. // The next encBytes bytes must together be a valid utf-8
  11903. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  11904. bool valid = true;
  11905. uint32_t value = headerValue(c);
  11906. for (std::size_t n = 1; n < encBytes; ++n) {
  11907. uchar nc = m_str[idx + n];
  11908. valid &= ((nc & 0xC0) == 0x80);
  11909. value = (value << 6) | (nc & 0x3F);
  11910. }
  11911. if (
  11912. // Wrong bit pattern of following bytes
  11913. (!valid) ||
  11914. // Overlong encodings
  11915. (value < 0x80) ||
  11916. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  11917. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  11918. // Encoded value out of range
  11919. (value >= 0x110000)
  11920. ) {
  11921. hexEscapeChar(os, c);
  11922. break;
  11923. }
  11924. // If we got here, this is in fact a valid(ish) utf-8 sequence
  11925. for (std::size_t n = 0; n < encBytes; ++n) {
  11926. os << m_str[idx + n];
  11927. }
  11928. idx += encBytes - 1;
  11929. break;
  11930. }
  11931. }
  11932. }
  11933. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  11934. xmlEncode.encodeTo( os );
  11935. return os;
  11936. }
  11937. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  11938. : m_writer( writer )
  11939. {}
  11940. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  11941. : m_writer( other.m_writer ){
  11942. other.m_writer = nullptr;
  11943. }
  11944. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  11945. if ( m_writer ) {
  11946. m_writer->endElement();
  11947. }
  11948. m_writer = other.m_writer;
  11949. other.m_writer = nullptr;
  11950. return *this;
  11951. }
  11952. XmlWriter::ScopedElement::~ScopedElement() {
  11953. if( m_writer )
  11954. m_writer->endElement();
  11955. }
  11956. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  11957. m_writer->writeText( text, indent );
  11958. return *this;
  11959. }
  11960. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  11961. {
  11962. writeDeclaration();
  11963. }
  11964. XmlWriter::~XmlWriter() {
  11965. while( !m_tags.empty() )
  11966. endElement();
  11967. }
  11968. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  11969. ensureTagClosed();
  11970. newlineIfNecessary();
  11971. m_os << m_indent << '<' << name;
  11972. m_tags.push_back( name );
  11973. m_indent += " ";
  11974. m_tagIsOpen = true;
  11975. return *this;
  11976. }
  11977. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  11978. ScopedElement scoped( this );
  11979. startElement( name );
  11980. return scoped;
  11981. }
  11982. XmlWriter& XmlWriter::endElement() {
  11983. newlineIfNecessary();
  11984. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  11985. if( m_tagIsOpen ) {
  11986. m_os << "/>";
  11987. m_tagIsOpen = false;
  11988. }
  11989. else {
  11990. m_os << m_indent << "</" << m_tags.back() << ">";
  11991. }
  11992. m_os << std::endl;
  11993. m_tags.pop_back();
  11994. return *this;
  11995. }
  11996. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  11997. if( !name.empty() && !attribute.empty() )
  11998. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  11999. return *this;
  12000. }
  12001. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12002. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12003. return *this;
  12004. }
  12005. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  12006. if( !text.empty() ){
  12007. bool tagWasOpen = m_tagIsOpen;
  12008. ensureTagClosed();
  12009. if( tagWasOpen && indent )
  12010. m_os << m_indent;
  12011. m_os << XmlEncode( text );
  12012. m_needsNewline = true;
  12013. }
  12014. return *this;
  12015. }
  12016. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  12017. ensureTagClosed();
  12018. m_os << m_indent << "<!--" << text << "-->";
  12019. m_needsNewline = true;
  12020. return *this;
  12021. }
  12022. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12023. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12024. }
  12025. XmlWriter& XmlWriter::writeBlankLine() {
  12026. ensureTagClosed();
  12027. m_os << '\n';
  12028. return *this;
  12029. }
  12030. void XmlWriter::ensureTagClosed() {
  12031. if( m_tagIsOpen ) {
  12032. m_os << ">" << std::endl;
  12033. m_tagIsOpen = false;
  12034. }
  12035. }
  12036. void XmlWriter::writeDeclaration() {
  12037. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12038. }
  12039. void XmlWriter::newlineIfNecessary() {
  12040. if( m_needsNewline ) {
  12041. m_os << std::endl;
  12042. m_needsNewline = false;
  12043. }
  12044. }
  12045. }
  12046. // end catch_xmlwriter.cpp
  12047. // start catch_reporter_bases.cpp
  12048. #include <cstring>
  12049. #include <cfloat>
  12050. #include <cstdio>
  12051. #include <cassert>
  12052. #include <memory>
  12053. namespace Catch {
  12054. void prepareExpandedExpression(AssertionResult& result) {
  12055. result.getExpandedExpression();
  12056. }
  12057. // Because formatting using c++ streams is stateful, drop down to C is required
  12058. // Alternatively we could use stringstream, but its performance is... not good.
  12059. std::string getFormattedDuration( double duration ) {
  12060. // Max exponent + 1 is required to represent the whole part
  12061. // + 1 for decimal point
  12062. // + 3 for the 3 decimal places
  12063. // + 1 for null terminator
  12064. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12065. char buffer[maxDoubleSize];
  12066. // Save previous errno, to prevent sprintf from overwriting it
  12067. ErrnoGuard guard;
  12068. #ifdef _MSC_VER
  12069. sprintf_s(buffer, "%.3f", duration);
  12070. #else
  12071. std::sprintf(buffer, "%.3f", duration);
  12072. #endif
  12073. return std::string(buffer);
  12074. }
  12075. std::string serializeFilters( std::vector<std::string> const& container ) {
  12076. ReusableStringStream oss;
  12077. bool first = true;
  12078. for (auto&& filter : container)
  12079. {
  12080. if (!first)
  12081. oss << ' ';
  12082. else
  12083. first = false;
  12084. oss << filter;
  12085. }
  12086. return oss.str();
  12087. }
  12088. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12089. :StreamingReporterBase(_config) {}
  12090. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12091. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12092. }
  12093. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12094. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12095. return false;
  12096. }
  12097. } // end namespace Catch
  12098. // end catch_reporter_bases.cpp
  12099. // start catch_reporter_compact.cpp
  12100. namespace {
  12101. #ifdef CATCH_PLATFORM_MAC
  12102. const char* failedString() { return "FAILED"; }
  12103. const char* passedString() { return "PASSED"; }
  12104. #else
  12105. const char* failedString() { return "failed"; }
  12106. const char* passedString() { return "passed"; }
  12107. #endif
  12108. // Colour::LightGrey
  12109. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  12110. std::string bothOrAll( std::size_t count ) {
  12111. return count == 1 ? std::string() :
  12112. count == 2 ? "both " : "all " ;
  12113. }
  12114. } // anon namespace
  12115. namespace Catch {
  12116. namespace {
  12117. // Colour, message variants:
  12118. // - white: No tests ran.
  12119. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  12120. // - white: Passed [both/all] N test cases (no assertions).
  12121. // - red: Failed N tests cases, failed M assertions.
  12122. // - green: Passed [both/all] N tests cases with M assertions.
  12123. void printTotals(std::ostream& out, const Totals& totals) {
  12124. if (totals.testCases.total() == 0) {
  12125. out << "No tests ran.";
  12126. } else if (totals.testCases.failed == totals.testCases.total()) {
  12127. Colour colour(Colour::ResultError);
  12128. const std::string qualify_assertions_failed =
  12129. totals.assertions.failed == totals.assertions.total() ?
  12130. bothOrAll(totals.assertions.failed) : std::string();
  12131. out <<
  12132. "Failed " << bothOrAll(totals.testCases.failed)
  12133. << pluralise(totals.testCases.failed, "test case") << ", "
  12134. "failed " << qualify_assertions_failed <<
  12135. pluralise(totals.assertions.failed, "assertion") << '.';
  12136. } else if (totals.assertions.total() == 0) {
  12137. out <<
  12138. "Passed " << bothOrAll(totals.testCases.total())
  12139. << pluralise(totals.testCases.total(), "test case")
  12140. << " (no assertions).";
  12141. } else if (totals.assertions.failed) {
  12142. Colour colour(Colour::ResultError);
  12143. out <<
  12144. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  12145. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  12146. } else {
  12147. Colour colour(Colour::ResultSuccess);
  12148. out <<
  12149. "Passed " << bothOrAll(totals.testCases.passed)
  12150. << pluralise(totals.testCases.passed, "test case") <<
  12151. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  12152. }
  12153. }
  12154. // Implementation of CompactReporter formatting
  12155. class AssertionPrinter {
  12156. public:
  12157. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  12158. AssertionPrinter(AssertionPrinter const&) = delete;
  12159. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12160. : stream(_stream)
  12161. , result(_stats.assertionResult)
  12162. , messages(_stats.infoMessages)
  12163. , itMessage(_stats.infoMessages.begin())
  12164. , printInfoMessages(_printInfoMessages) {}
  12165. void print() {
  12166. printSourceInfo();
  12167. itMessage = messages.begin();
  12168. switch (result.getResultType()) {
  12169. case ResultWas::Ok:
  12170. printResultType(Colour::ResultSuccess, passedString());
  12171. printOriginalExpression();
  12172. printReconstructedExpression();
  12173. if (!result.hasExpression())
  12174. printRemainingMessages(Colour::None);
  12175. else
  12176. printRemainingMessages();
  12177. break;
  12178. case ResultWas::ExpressionFailed:
  12179. if (result.isOk())
  12180. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  12181. else
  12182. printResultType(Colour::Error, failedString());
  12183. printOriginalExpression();
  12184. printReconstructedExpression();
  12185. printRemainingMessages();
  12186. break;
  12187. case ResultWas::ThrewException:
  12188. printResultType(Colour::Error, failedString());
  12189. printIssue("unexpected exception with message:");
  12190. printMessage();
  12191. printExpressionWas();
  12192. printRemainingMessages();
  12193. break;
  12194. case ResultWas::FatalErrorCondition:
  12195. printResultType(Colour::Error, failedString());
  12196. printIssue("fatal error condition with message:");
  12197. printMessage();
  12198. printExpressionWas();
  12199. printRemainingMessages();
  12200. break;
  12201. case ResultWas::DidntThrowException:
  12202. printResultType(Colour::Error, failedString());
  12203. printIssue("expected exception, got none");
  12204. printExpressionWas();
  12205. printRemainingMessages();
  12206. break;
  12207. case ResultWas::Info:
  12208. printResultType(Colour::None, "info");
  12209. printMessage();
  12210. printRemainingMessages();
  12211. break;
  12212. case ResultWas::Warning:
  12213. printResultType(Colour::None, "warning");
  12214. printMessage();
  12215. printRemainingMessages();
  12216. break;
  12217. case ResultWas::ExplicitFailure:
  12218. printResultType(Colour::Error, failedString());
  12219. printIssue("explicitly");
  12220. printRemainingMessages(Colour::None);
  12221. break;
  12222. // These cases are here to prevent compiler warnings
  12223. case ResultWas::Unknown:
  12224. case ResultWas::FailureBit:
  12225. case ResultWas::Exception:
  12226. printResultType(Colour::Error, "** internal error **");
  12227. break;
  12228. }
  12229. }
  12230. private:
  12231. void printSourceInfo() const {
  12232. Colour colourGuard(Colour::FileName);
  12233. stream << result.getSourceInfo() << ':';
  12234. }
  12235. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  12236. if (!passOrFail.empty()) {
  12237. {
  12238. Colour colourGuard(colour);
  12239. stream << ' ' << passOrFail;
  12240. }
  12241. stream << ':';
  12242. }
  12243. }
  12244. void printIssue(std::string const& issue) const {
  12245. stream << ' ' << issue;
  12246. }
  12247. void printExpressionWas() {
  12248. if (result.hasExpression()) {
  12249. stream << ';';
  12250. {
  12251. Colour colour(dimColour());
  12252. stream << " expression was:";
  12253. }
  12254. printOriginalExpression();
  12255. }
  12256. }
  12257. void printOriginalExpression() const {
  12258. if (result.hasExpression()) {
  12259. stream << ' ' << result.getExpression();
  12260. }
  12261. }
  12262. void printReconstructedExpression() const {
  12263. if (result.hasExpandedExpression()) {
  12264. {
  12265. Colour colour(dimColour());
  12266. stream << " for: ";
  12267. }
  12268. stream << result.getExpandedExpression();
  12269. }
  12270. }
  12271. void printMessage() {
  12272. if (itMessage != messages.end()) {
  12273. stream << " '" << itMessage->message << '\'';
  12274. ++itMessage;
  12275. }
  12276. }
  12277. void printRemainingMessages(Colour::Code colour = dimColour()) {
  12278. if (itMessage == messages.end())
  12279. return;
  12280. // using messages.end() directly yields (or auto) compilation error:
  12281. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  12282. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  12283. {
  12284. Colour colourGuard(colour);
  12285. stream << " with " << pluralise(N, "message") << ':';
  12286. }
  12287. for (; itMessage != itEnd; ) {
  12288. // If this assertion is a warning ignore any INFO messages
  12289. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  12290. stream << " '" << itMessage->message << '\'';
  12291. if (++itMessage != itEnd) {
  12292. Colour colourGuard(dimColour());
  12293. stream << " and";
  12294. }
  12295. }
  12296. }
  12297. }
  12298. private:
  12299. std::ostream& stream;
  12300. AssertionResult const& result;
  12301. std::vector<MessageInfo> messages;
  12302. std::vector<MessageInfo>::const_iterator itMessage;
  12303. bool printInfoMessages;
  12304. };
  12305. } // anon namespace
  12306. std::string CompactReporter::getDescription() {
  12307. return "Reports test results on a single line, suitable for IDEs";
  12308. }
  12309. ReporterPreferences CompactReporter::getPreferences() const {
  12310. return m_reporterPrefs;
  12311. }
  12312. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  12313. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12314. }
  12315. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  12316. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  12317. AssertionResult const& result = _assertionStats.assertionResult;
  12318. bool printInfoMessages = true;
  12319. // Drop out if result was successful and we're not printing those
  12320. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  12321. if( result.getResultType() != ResultWas::Warning )
  12322. return false;
  12323. printInfoMessages = false;
  12324. }
  12325. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  12326. printer.print();
  12327. stream << std::endl;
  12328. return true;
  12329. }
  12330. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  12331. if (m_config->showDurations() == ShowDurations::Always) {
  12332. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12333. }
  12334. }
  12335. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  12336. printTotals( stream, _testRunStats.totals );
  12337. stream << '\n' << std::endl;
  12338. StreamingReporterBase::testRunEnded( _testRunStats );
  12339. }
  12340. CompactReporter::~CompactReporter() {}
  12341. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  12342. } // end namespace Catch
  12343. // end catch_reporter_compact.cpp
  12344. // start catch_reporter_console.cpp
  12345. #include <cfloat>
  12346. #include <cstdio>
  12347. #if defined(_MSC_VER)
  12348. #pragma warning(push)
  12349. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  12350. // Note that 4062 (not all labels are handled and default is missing) is enabled
  12351. #endif
  12352. #if defined(__clang__)
  12353. # pragma clang diagnostic push
  12354. // For simplicity, benchmarking-only helpers are always enabled
  12355. # pragma clang diagnostic ignored "-Wunused-function"
  12356. #endif
  12357. namespace Catch {
  12358. namespace {
  12359. // Formatter impl for ConsoleReporter
  12360. class ConsoleAssertionPrinter {
  12361. public:
  12362. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  12363. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  12364. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  12365. : stream(_stream),
  12366. stats(_stats),
  12367. result(_stats.assertionResult),
  12368. colour(Colour::None),
  12369. message(result.getMessage()),
  12370. messages(_stats.infoMessages),
  12371. printInfoMessages(_printInfoMessages) {
  12372. switch (result.getResultType()) {
  12373. case ResultWas::Ok:
  12374. colour = Colour::Success;
  12375. passOrFail = "PASSED";
  12376. //if( result.hasMessage() )
  12377. if (_stats.infoMessages.size() == 1)
  12378. messageLabel = "with message";
  12379. if (_stats.infoMessages.size() > 1)
  12380. messageLabel = "with messages";
  12381. break;
  12382. case ResultWas::ExpressionFailed:
  12383. if (result.isOk()) {
  12384. colour = Colour::Success;
  12385. passOrFail = "FAILED - but was ok";
  12386. } else {
  12387. colour = Colour::Error;
  12388. passOrFail = "FAILED";
  12389. }
  12390. if (_stats.infoMessages.size() == 1)
  12391. messageLabel = "with message";
  12392. if (_stats.infoMessages.size() > 1)
  12393. messageLabel = "with messages";
  12394. break;
  12395. case ResultWas::ThrewException:
  12396. colour = Colour::Error;
  12397. passOrFail = "FAILED";
  12398. messageLabel = "due to unexpected exception with ";
  12399. if (_stats.infoMessages.size() == 1)
  12400. messageLabel += "message";
  12401. if (_stats.infoMessages.size() > 1)
  12402. messageLabel += "messages";
  12403. break;
  12404. case ResultWas::FatalErrorCondition:
  12405. colour = Colour::Error;
  12406. passOrFail = "FAILED";
  12407. messageLabel = "due to a fatal error condition";
  12408. break;
  12409. case ResultWas::DidntThrowException:
  12410. colour = Colour::Error;
  12411. passOrFail = "FAILED";
  12412. messageLabel = "because no exception was thrown where one was expected";
  12413. break;
  12414. case ResultWas::Info:
  12415. messageLabel = "info";
  12416. break;
  12417. case ResultWas::Warning:
  12418. messageLabel = "warning";
  12419. break;
  12420. case ResultWas::ExplicitFailure:
  12421. passOrFail = "FAILED";
  12422. colour = Colour::Error;
  12423. if (_stats.infoMessages.size() == 1)
  12424. messageLabel = "explicitly with message";
  12425. if (_stats.infoMessages.size() > 1)
  12426. messageLabel = "explicitly with messages";
  12427. break;
  12428. // These cases are here to prevent compiler warnings
  12429. case ResultWas::Unknown:
  12430. case ResultWas::FailureBit:
  12431. case ResultWas::Exception:
  12432. passOrFail = "** internal error **";
  12433. colour = Colour::Error;
  12434. break;
  12435. }
  12436. }
  12437. void print() const {
  12438. printSourceInfo();
  12439. if (stats.totals.assertions.total() > 0) {
  12440. printResultType();
  12441. printOriginalExpression();
  12442. printReconstructedExpression();
  12443. } else {
  12444. stream << '\n';
  12445. }
  12446. printMessage();
  12447. }
  12448. private:
  12449. void printResultType() const {
  12450. if (!passOrFail.empty()) {
  12451. Colour colourGuard(colour);
  12452. stream << passOrFail << ":\n";
  12453. }
  12454. }
  12455. void printOriginalExpression() const {
  12456. if (result.hasExpression()) {
  12457. Colour colourGuard(Colour::OriginalExpression);
  12458. stream << " ";
  12459. stream << result.getExpressionInMacro();
  12460. stream << '\n';
  12461. }
  12462. }
  12463. void printReconstructedExpression() const {
  12464. if (result.hasExpandedExpression()) {
  12465. stream << "with expansion:\n";
  12466. Colour colourGuard(Colour::ReconstructedExpression);
  12467. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  12468. }
  12469. }
  12470. void printMessage() const {
  12471. if (!messageLabel.empty())
  12472. stream << messageLabel << ':' << '\n';
  12473. for (auto const& msg : messages) {
  12474. // If this assertion is a warning ignore any INFO messages
  12475. if (printInfoMessages || msg.type != ResultWas::Info)
  12476. stream << Column(msg.message).indent(2) << '\n';
  12477. }
  12478. }
  12479. void printSourceInfo() const {
  12480. Colour colourGuard(Colour::FileName);
  12481. stream << result.getSourceInfo() << ": ";
  12482. }
  12483. std::ostream& stream;
  12484. AssertionStats const& stats;
  12485. AssertionResult const& result;
  12486. Colour::Code colour;
  12487. std::string passOrFail;
  12488. std::string messageLabel;
  12489. std::string message;
  12490. std::vector<MessageInfo> messages;
  12491. bool printInfoMessages;
  12492. };
  12493. std::size_t makeRatio(std::size_t number, std::size_t total) {
  12494. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  12495. return (ratio == 0 && number > 0) ? 1 : ratio;
  12496. }
  12497. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  12498. if (i > j && i > k)
  12499. return i;
  12500. else if (j > k)
  12501. return j;
  12502. else
  12503. return k;
  12504. }
  12505. struct ColumnInfo {
  12506. enum Justification { Left, Right };
  12507. std::string name;
  12508. int width;
  12509. Justification justification;
  12510. };
  12511. struct ColumnBreak {};
  12512. struct RowBreak {};
  12513. class Duration {
  12514. enum class Unit {
  12515. Auto,
  12516. Nanoseconds,
  12517. Microseconds,
  12518. Milliseconds,
  12519. Seconds,
  12520. Minutes
  12521. };
  12522. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  12523. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  12524. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  12525. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  12526. uint64_t m_inNanoseconds;
  12527. Unit m_units;
  12528. public:
  12529. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  12530. : Duration(static_cast<uint64_t>(inNanoseconds), units) {
  12531. }
  12532. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  12533. : m_inNanoseconds(inNanoseconds),
  12534. m_units(units) {
  12535. if (m_units == Unit::Auto) {
  12536. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  12537. m_units = Unit::Nanoseconds;
  12538. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  12539. m_units = Unit::Microseconds;
  12540. else if (m_inNanoseconds < s_nanosecondsInASecond)
  12541. m_units = Unit::Milliseconds;
  12542. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  12543. m_units = Unit::Seconds;
  12544. else
  12545. m_units = Unit::Minutes;
  12546. }
  12547. }
  12548. auto value() const -> double {
  12549. switch (m_units) {
  12550. case Unit::Microseconds:
  12551. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  12552. case Unit::Milliseconds:
  12553. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  12554. case Unit::Seconds:
  12555. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  12556. case Unit::Minutes:
  12557. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  12558. default:
  12559. return static_cast<double>(m_inNanoseconds);
  12560. }
  12561. }
  12562. auto unitsAsString() const -> std::string {
  12563. switch (m_units) {
  12564. case Unit::Nanoseconds:
  12565. return "ns";
  12566. case Unit::Microseconds:
  12567. return "us";
  12568. case Unit::Milliseconds:
  12569. return "ms";
  12570. case Unit::Seconds:
  12571. return "s";
  12572. case Unit::Minutes:
  12573. return "m";
  12574. default:
  12575. return "** internal error **";
  12576. }
  12577. }
  12578. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  12579. return os << duration.value() << " " << duration.unitsAsString();
  12580. }
  12581. };
  12582. } // end anon namespace
  12583. class TablePrinter {
  12584. std::ostream& m_os;
  12585. std::vector<ColumnInfo> m_columnInfos;
  12586. std::ostringstream m_oss;
  12587. int m_currentColumn = -1;
  12588. bool m_isOpen = false;
  12589. public:
  12590. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  12591. : m_os( os ),
  12592. m_columnInfos( std::move( columnInfos ) ) {}
  12593. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  12594. return m_columnInfos;
  12595. }
  12596. void open() {
  12597. if (!m_isOpen) {
  12598. m_isOpen = true;
  12599. *this << RowBreak();
  12600. Columns headerCols;
  12601. Spacer spacer(2);
  12602. for (auto const& info : m_columnInfos) {
  12603. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  12604. headerCols += spacer;
  12605. }
  12606. m_os << headerCols << "\n";
  12607. m_os << Catch::getLineOfChars<'-'>() << "\n";
  12608. }
  12609. }
  12610. void close() {
  12611. if (m_isOpen) {
  12612. *this << RowBreak();
  12613. m_os << std::endl;
  12614. m_isOpen = false;
  12615. }
  12616. }
  12617. template<typename T>
  12618. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  12619. tp.m_oss << value;
  12620. return tp;
  12621. }
  12622. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  12623. auto colStr = tp.m_oss.str();
  12624. // This takes account of utf8 encodings
  12625. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  12626. tp.m_oss.str("");
  12627. tp.open();
  12628. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  12629. tp.m_currentColumn = -1;
  12630. tp.m_os << "\n";
  12631. }
  12632. tp.m_currentColumn++;
  12633. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  12634. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  12635. ? std::string(colInfo.width - (strSize + 2), ' ')
  12636. : std::string();
  12637. if (colInfo.justification == ColumnInfo::Left)
  12638. tp.m_os << colStr << padding << " ";
  12639. else
  12640. tp.m_os << padding << colStr << " ";
  12641. return tp;
  12642. }
  12643. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  12644. if (tp.m_currentColumn > 0) {
  12645. tp.m_os << "\n";
  12646. tp.m_currentColumn = -1;
  12647. }
  12648. return tp;
  12649. }
  12650. };
  12651. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  12652. : StreamingReporterBase(config),
  12653. m_tablePrinter(new TablePrinter(config.stream(),
  12654. {
  12655. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  12656. { "samples mean std dev", 14, ColumnInfo::Right },
  12657. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  12658. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  12659. })) {}
  12660. ConsoleReporter::~ConsoleReporter() = default;
  12661. std::string ConsoleReporter::getDescription() {
  12662. return "Reports test results as plain lines of text";
  12663. }
  12664. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  12665. stream << "No test cases matched '" << spec << '\'' << std::endl;
  12666. }
  12667. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  12668. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  12669. AssertionResult const& result = _assertionStats.assertionResult;
  12670. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  12671. // Drop out if result was successful but we're not printing them.
  12672. if (!includeResults && result.getResultType() != ResultWas::Warning)
  12673. return false;
  12674. lazyPrint();
  12675. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  12676. printer.print();
  12677. stream << std::endl;
  12678. return true;
  12679. }
  12680. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  12681. m_tablePrinter->close();
  12682. m_headerPrinted = false;
  12683. StreamingReporterBase::sectionStarting(_sectionInfo);
  12684. }
  12685. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  12686. m_tablePrinter->close();
  12687. if (_sectionStats.missingAssertions) {
  12688. lazyPrint();
  12689. Colour colour(Colour::ResultError);
  12690. if (m_sectionStack.size() > 1)
  12691. stream << "\nNo assertions in section";
  12692. else
  12693. stream << "\nNo assertions in test case";
  12694. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  12695. }
  12696. if (m_config->showDurations() == ShowDurations::Always) {
  12697. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  12698. }
  12699. if (m_headerPrinted) {
  12700. m_headerPrinted = false;
  12701. }
  12702. StreamingReporterBase::sectionEnded(_sectionStats);
  12703. }
  12704. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  12705. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  12706. lazyPrintWithoutClosingBenchmarkTable();
  12707. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  12708. bool firstLine = true;
  12709. for (auto line : nameCol) {
  12710. if (!firstLine)
  12711. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12712. else
  12713. firstLine = false;
  12714. (*m_tablePrinter) << line << ColumnBreak();
  12715. }
  12716. }
  12717. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  12718. (*m_tablePrinter) << info.samples << ColumnBreak()
  12719. << info.iterations << ColumnBreak()
  12720. << Duration(info.estimatedDuration) << ColumnBreak();
  12721. }
  12722. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  12723. (*m_tablePrinter) << ColumnBreak()
  12724. << Duration(stats.mean.point.count()) << ColumnBreak()
  12725. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  12726. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  12727. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  12728. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  12729. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  12730. }
  12731. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  12732. Colour colour(Colour::Red);
  12733. (*m_tablePrinter)
  12734. << "Benchmark failed (" << error << ")"
  12735. << ColumnBreak() << RowBreak();
  12736. }
  12737. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  12738. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  12739. m_tablePrinter->close();
  12740. StreamingReporterBase::testCaseEnded(_testCaseStats);
  12741. m_headerPrinted = false;
  12742. }
  12743. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  12744. if (currentGroupInfo.used) {
  12745. printSummaryDivider();
  12746. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  12747. printTotals(_testGroupStats.totals);
  12748. stream << '\n' << std::endl;
  12749. }
  12750. StreamingReporterBase::testGroupEnded(_testGroupStats);
  12751. }
  12752. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  12753. printTotalsDivider(_testRunStats.totals);
  12754. printTotals(_testRunStats.totals);
  12755. stream << std::endl;
  12756. StreamingReporterBase::testRunEnded(_testRunStats);
  12757. }
  12758. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  12759. StreamingReporterBase::testRunStarting(_testInfo);
  12760. printTestFilters();
  12761. }
  12762. void ConsoleReporter::lazyPrint() {
  12763. m_tablePrinter->close();
  12764. lazyPrintWithoutClosingBenchmarkTable();
  12765. }
  12766. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  12767. if (!currentTestRunInfo.used)
  12768. lazyPrintRunInfo();
  12769. if (!currentGroupInfo.used)
  12770. lazyPrintGroupInfo();
  12771. if (!m_headerPrinted) {
  12772. printTestCaseAndSectionHeader();
  12773. m_headerPrinted = true;
  12774. }
  12775. }
  12776. void ConsoleReporter::lazyPrintRunInfo() {
  12777. stream << '\n' << getLineOfChars<'~'>() << '\n';
  12778. Colour colour(Colour::SecondaryText);
  12779. stream << currentTestRunInfo->name
  12780. << " is a Catch v" << libraryVersion() << " host application.\n"
  12781. << "Run with -? for options\n\n";
  12782. if (m_config->rngSeed() != 0)
  12783. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  12784. currentTestRunInfo.used = true;
  12785. }
  12786. void ConsoleReporter::lazyPrintGroupInfo() {
  12787. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  12788. printClosedHeader("Group: " + currentGroupInfo->name);
  12789. currentGroupInfo.used = true;
  12790. }
  12791. }
  12792. void ConsoleReporter::printTestCaseAndSectionHeader() {
  12793. assert(!m_sectionStack.empty());
  12794. printOpenHeader(currentTestCaseInfo->name);
  12795. if (m_sectionStack.size() > 1) {
  12796. Colour colourGuard(Colour::Headers);
  12797. auto
  12798. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  12799. itEnd = m_sectionStack.end();
  12800. for (; it != itEnd; ++it)
  12801. printHeaderString(it->name, 2);
  12802. }
  12803. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  12804. if (!lineInfo.empty()) {
  12805. stream << getLineOfChars<'-'>() << '\n';
  12806. Colour colourGuard(Colour::FileName);
  12807. stream << lineInfo << '\n';
  12808. }
  12809. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  12810. }
  12811. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  12812. printOpenHeader(_name);
  12813. stream << getLineOfChars<'.'>() << '\n';
  12814. }
  12815. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  12816. stream << getLineOfChars<'-'>() << '\n';
  12817. {
  12818. Colour colourGuard(Colour::Headers);
  12819. printHeaderString(_name);
  12820. }
  12821. }
  12822. // if string has a : in first line will set indent to follow it on
  12823. // subsequent lines
  12824. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  12825. std::size_t i = _string.find(": ");
  12826. if (i != std::string::npos)
  12827. i += 2;
  12828. else
  12829. i = 0;
  12830. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  12831. }
  12832. struct SummaryColumn {
  12833. SummaryColumn( std::string _label, Colour::Code _colour )
  12834. : label( std::move( _label ) ),
  12835. colour( _colour ) {}
  12836. SummaryColumn addRow( std::size_t count ) {
  12837. ReusableStringStream rss;
  12838. rss << count;
  12839. std::string row = rss.str();
  12840. for (auto& oldRow : rows) {
  12841. while (oldRow.size() < row.size())
  12842. oldRow = ' ' + oldRow;
  12843. while (oldRow.size() > row.size())
  12844. row = ' ' + row;
  12845. }
  12846. rows.push_back(row);
  12847. return *this;
  12848. }
  12849. std::string label;
  12850. Colour::Code colour;
  12851. std::vector<std::string> rows;
  12852. };
  12853. void ConsoleReporter::printTotals( Totals const& totals ) {
  12854. if (totals.testCases.total() == 0) {
  12855. stream << Colour(Colour::Warning) << "No tests ran\n";
  12856. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  12857. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  12858. stream << " ("
  12859. << pluralise(totals.assertions.passed, "assertion") << " in "
  12860. << pluralise(totals.testCases.passed, "test case") << ')'
  12861. << '\n';
  12862. } else {
  12863. std::vector<SummaryColumn> columns;
  12864. columns.push_back(SummaryColumn("", Colour::None)
  12865. .addRow(totals.testCases.total())
  12866. .addRow(totals.assertions.total()));
  12867. columns.push_back(SummaryColumn("passed", Colour::Success)
  12868. .addRow(totals.testCases.passed)
  12869. .addRow(totals.assertions.passed));
  12870. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  12871. .addRow(totals.testCases.failed)
  12872. .addRow(totals.assertions.failed));
  12873. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  12874. .addRow(totals.testCases.failedButOk)
  12875. .addRow(totals.assertions.failedButOk));
  12876. printSummaryRow("test cases", columns, 0);
  12877. printSummaryRow("assertions", columns, 1);
  12878. }
  12879. }
  12880. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  12881. for (auto col : cols) {
  12882. std::string value = col.rows[row];
  12883. if (col.label.empty()) {
  12884. stream << label << ": ";
  12885. if (value != "0")
  12886. stream << value;
  12887. else
  12888. stream << Colour(Colour::Warning) << "- none -";
  12889. } else if (value != "0") {
  12890. stream << Colour(Colour::LightGrey) << " | ";
  12891. stream << Colour(col.colour)
  12892. << value << ' ' << col.label;
  12893. }
  12894. }
  12895. stream << '\n';
  12896. }
  12897. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  12898. if (totals.testCases.total() > 0) {
  12899. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  12900. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  12901. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  12902. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  12903. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  12904. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  12905. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  12906. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  12907. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  12908. if (totals.testCases.allPassed())
  12909. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  12910. else
  12911. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  12912. } else {
  12913. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  12914. }
  12915. stream << '\n';
  12916. }
  12917. void ConsoleReporter::printSummaryDivider() {
  12918. stream << getLineOfChars<'-'>() << '\n';
  12919. }
  12920. void ConsoleReporter::printTestFilters() {
  12921. if (m_config->testSpec().hasFilters())
  12922. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  12923. }
  12924. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  12925. } // end namespace Catch
  12926. #if defined(_MSC_VER)
  12927. #pragma warning(pop)
  12928. #endif
  12929. #if defined(__clang__)
  12930. # pragma clang diagnostic pop
  12931. #endif
  12932. // end catch_reporter_console.cpp
  12933. // start catch_reporter_junit.cpp
  12934. #include <cassert>
  12935. #include <sstream>
  12936. #include <ctime>
  12937. #include <algorithm>
  12938. namespace Catch {
  12939. namespace {
  12940. std::string getCurrentTimestamp() {
  12941. // Beware, this is not reentrant because of backward compatibility issues
  12942. // Also, UTC only, again because of backward compatibility (%z is C++11)
  12943. time_t rawtime;
  12944. std::time(&rawtime);
  12945. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  12946. #ifdef _MSC_VER
  12947. std::tm timeInfo = {};
  12948. gmtime_s(&timeInfo, &rawtime);
  12949. #else
  12950. std::tm* timeInfo;
  12951. timeInfo = std::gmtime(&rawtime);
  12952. #endif
  12953. char timeStamp[timeStampSize];
  12954. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  12955. #ifdef _MSC_VER
  12956. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  12957. #else
  12958. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  12959. #endif
  12960. return std::string(timeStamp);
  12961. }
  12962. std::string fileNameTag(const std::vector<std::string> &tags) {
  12963. auto it = std::find_if(begin(tags),
  12964. end(tags),
  12965. [] (std::string const& tag) {return tag.front() == '#'; });
  12966. if (it != tags.end())
  12967. return it->substr(1);
  12968. return std::string();
  12969. }
  12970. } // anonymous namespace
  12971. JunitReporter::JunitReporter( ReporterConfig const& _config )
  12972. : CumulativeReporterBase( _config ),
  12973. xml( _config.stream() )
  12974. {
  12975. m_reporterPrefs.shouldRedirectStdOut = true;
  12976. m_reporterPrefs.shouldReportAllAssertions = true;
  12977. }
  12978. JunitReporter::~JunitReporter() {}
  12979. std::string JunitReporter::getDescription() {
  12980. return "Reports test results in an XML format that looks like Ant's junitreport target";
  12981. }
  12982. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  12983. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  12984. CumulativeReporterBase::testRunStarting( runInfo );
  12985. xml.startElement( "testsuites" );
  12986. }
  12987. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  12988. suiteTimer.start();
  12989. stdOutForSuite.clear();
  12990. stdErrForSuite.clear();
  12991. unexpectedExceptions = 0;
  12992. CumulativeReporterBase::testGroupStarting( groupInfo );
  12993. }
  12994. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  12995. m_okToFail = testCaseInfo.okToFail();
  12996. }
  12997. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  12998. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  12999. unexpectedExceptions++;
  13000. return CumulativeReporterBase::assertionEnded( assertionStats );
  13001. }
  13002. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13003. stdOutForSuite += testCaseStats.stdOut;
  13004. stdErrForSuite += testCaseStats.stdErr;
  13005. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13006. }
  13007. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13008. double suiteTime = suiteTimer.getElapsedSeconds();
  13009. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13010. writeGroup( *m_testGroups.back(), suiteTime );
  13011. }
  13012. void JunitReporter::testRunEndedCumulative() {
  13013. xml.endElement();
  13014. }
  13015. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13016. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13017. TestGroupStats const& stats = groupNode.value;
  13018. xml.writeAttribute( "name", stats.groupInfo.name );
  13019. xml.writeAttribute( "errors", unexpectedExceptions );
  13020. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13021. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13022. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13023. if( m_config->showDurations() == ShowDurations::Never )
  13024. xml.writeAttribute( "time", "" );
  13025. else
  13026. xml.writeAttribute( "time", suiteTime );
  13027. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13028. // Write properties if there are any
  13029. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13030. auto properties = xml.scopedElement("properties");
  13031. if (m_config->hasTestFilters()) {
  13032. xml.scopedElement("property")
  13033. .writeAttribute("name", "filters")
  13034. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13035. }
  13036. if (m_config->rngSeed() != 0) {
  13037. xml.scopedElement("property")
  13038. .writeAttribute("name", "random-seed")
  13039. .writeAttribute("value", m_config->rngSeed());
  13040. }
  13041. }
  13042. // Write test cases
  13043. for( auto const& child : groupNode.children )
  13044. writeTestCase( *child );
  13045. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  13046. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  13047. }
  13048. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13049. TestCaseStats const& stats = testCaseNode.value;
  13050. // All test cases have exactly one section - which represents the
  13051. // test case itself. That section may have 0-n nested sections
  13052. assert( testCaseNode.children.size() == 1 );
  13053. SectionNode const& rootSection = *testCaseNode.children.front();
  13054. std::string className = stats.testInfo.className;
  13055. if( className.empty() ) {
  13056. className = fileNameTag(stats.testInfo.tags);
  13057. if ( className.empty() )
  13058. className = "global";
  13059. }
  13060. if ( !m_config->name().empty() )
  13061. className = m_config->name() + "." + className;
  13062. writeSection( className, "", rootSection );
  13063. }
  13064. void JunitReporter::writeSection( std::string const& className,
  13065. std::string const& rootName,
  13066. SectionNode const& sectionNode ) {
  13067. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13068. if( !rootName.empty() )
  13069. name = rootName + '/' + name;
  13070. if( !sectionNode.assertions.empty() ||
  13071. !sectionNode.stdOut.empty() ||
  13072. !sectionNode.stdErr.empty() ) {
  13073. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13074. if( className.empty() ) {
  13075. xml.writeAttribute( "classname", name );
  13076. xml.writeAttribute( "name", "root" );
  13077. }
  13078. else {
  13079. xml.writeAttribute( "classname", className );
  13080. xml.writeAttribute( "name", name );
  13081. }
  13082. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  13083. writeAssertions( sectionNode );
  13084. if( !sectionNode.stdOut.empty() )
  13085. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  13086. if( !sectionNode.stdErr.empty() )
  13087. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  13088. }
  13089. for( auto const& childNode : sectionNode.childSections )
  13090. if( className.empty() )
  13091. writeSection( name, "", *childNode );
  13092. else
  13093. writeSection( className, name, *childNode );
  13094. }
  13095. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  13096. for( auto const& assertion : sectionNode.assertions )
  13097. writeAssertion( assertion );
  13098. }
  13099. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  13100. AssertionResult const& result = stats.assertionResult;
  13101. if( !result.isOk() ) {
  13102. std::string elementName;
  13103. switch( result.getResultType() ) {
  13104. case ResultWas::ThrewException:
  13105. case ResultWas::FatalErrorCondition:
  13106. elementName = "error";
  13107. break;
  13108. case ResultWas::ExplicitFailure:
  13109. elementName = "failure";
  13110. break;
  13111. case ResultWas::ExpressionFailed:
  13112. elementName = "failure";
  13113. break;
  13114. case ResultWas::DidntThrowException:
  13115. elementName = "failure";
  13116. break;
  13117. // We should never see these here:
  13118. case ResultWas::Info:
  13119. case ResultWas::Warning:
  13120. case ResultWas::Ok:
  13121. case ResultWas::Unknown:
  13122. case ResultWas::FailureBit:
  13123. case ResultWas::Exception:
  13124. elementName = "internalError";
  13125. break;
  13126. }
  13127. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  13128. xml.writeAttribute( "message", result.getExpandedExpression() );
  13129. xml.writeAttribute( "type", result.getTestMacroName() );
  13130. ReusableStringStream rss;
  13131. if( !result.getMessage().empty() )
  13132. rss << result.getMessage() << '\n';
  13133. for( auto const& msg : stats.infoMessages )
  13134. if( msg.type == ResultWas::Info )
  13135. rss << msg.message << '\n';
  13136. rss << "at " << result.getSourceInfo();
  13137. xml.writeText( rss.str(), false );
  13138. }
  13139. }
  13140. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  13141. } // end namespace Catch
  13142. // end catch_reporter_junit.cpp
  13143. // start catch_reporter_listening.cpp
  13144. #include <cassert>
  13145. namespace Catch {
  13146. ListeningReporter::ListeningReporter() {
  13147. // We will assume that listeners will always want all assertions
  13148. m_preferences.shouldReportAllAssertions = true;
  13149. }
  13150. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  13151. m_listeners.push_back( std::move( listener ) );
  13152. }
  13153. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  13154. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  13155. m_reporter = std::move( reporter );
  13156. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  13157. }
  13158. ReporterPreferences ListeningReporter::getPreferences() const {
  13159. return m_preferences;
  13160. }
  13161. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  13162. return std::set<Verbosity>{ };
  13163. }
  13164. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  13165. for ( auto const& listener : m_listeners ) {
  13166. listener->noMatchingTestCases( spec );
  13167. }
  13168. m_reporter->noMatchingTestCases( spec );
  13169. }
  13170. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13171. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  13172. for (auto const& listener : m_listeners) {
  13173. listener->benchmarkPreparing(name);
  13174. }
  13175. m_reporter->benchmarkPreparing(name);
  13176. }
  13177. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  13178. for ( auto const& listener : m_listeners ) {
  13179. listener->benchmarkStarting( benchmarkInfo );
  13180. }
  13181. m_reporter->benchmarkStarting( benchmarkInfo );
  13182. }
  13183. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  13184. for ( auto const& listener : m_listeners ) {
  13185. listener->benchmarkEnded( benchmarkStats );
  13186. }
  13187. m_reporter->benchmarkEnded( benchmarkStats );
  13188. }
  13189. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  13190. for (auto const& listener : m_listeners) {
  13191. listener->benchmarkFailed(error);
  13192. }
  13193. m_reporter->benchmarkFailed(error);
  13194. }
  13195. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13196. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  13197. for ( auto const& listener : m_listeners ) {
  13198. listener->testRunStarting( testRunInfo );
  13199. }
  13200. m_reporter->testRunStarting( testRunInfo );
  13201. }
  13202. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13203. for ( auto const& listener : m_listeners ) {
  13204. listener->testGroupStarting( groupInfo );
  13205. }
  13206. m_reporter->testGroupStarting( groupInfo );
  13207. }
  13208. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13209. for ( auto const& listener : m_listeners ) {
  13210. listener->testCaseStarting( testInfo );
  13211. }
  13212. m_reporter->testCaseStarting( testInfo );
  13213. }
  13214. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13215. for ( auto const& listener : m_listeners ) {
  13216. listener->sectionStarting( sectionInfo );
  13217. }
  13218. m_reporter->sectionStarting( sectionInfo );
  13219. }
  13220. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  13221. for ( auto const& listener : m_listeners ) {
  13222. listener->assertionStarting( assertionInfo );
  13223. }
  13224. m_reporter->assertionStarting( assertionInfo );
  13225. }
  13226. // The return value indicates if the messages buffer should be cleared:
  13227. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13228. for( auto const& listener : m_listeners ) {
  13229. static_cast<void>( listener->assertionEnded( assertionStats ) );
  13230. }
  13231. return m_reporter->assertionEnded( assertionStats );
  13232. }
  13233. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  13234. for ( auto const& listener : m_listeners ) {
  13235. listener->sectionEnded( sectionStats );
  13236. }
  13237. m_reporter->sectionEnded( sectionStats );
  13238. }
  13239. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13240. for ( auto const& listener : m_listeners ) {
  13241. listener->testCaseEnded( testCaseStats );
  13242. }
  13243. m_reporter->testCaseEnded( testCaseStats );
  13244. }
  13245. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13246. for ( auto const& listener : m_listeners ) {
  13247. listener->testGroupEnded( testGroupStats );
  13248. }
  13249. m_reporter->testGroupEnded( testGroupStats );
  13250. }
  13251. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13252. for ( auto const& listener : m_listeners ) {
  13253. listener->testRunEnded( testRunStats );
  13254. }
  13255. m_reporter->testRunEnded( testRunStats );
  13256. }
  13257. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  13258. for ( auto const& listener : m_listeners ) {
  13259. listener->skipTest( testInfo );
  13260. }
  13261. m_reporter->skipTest( testInfo );
  13262. }
  13263. bool ListeningReporter::isMulti() const {
  13264. return true;
  13265. }
  13266. } // end namespace Catch
  13267. // end catch_reporter_listening.cpp
  13268. // start catch_reporter_xml.cpp
  13269. #if defined(_MSC_VER)
  13270. #pragma warning(push)
  13271. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13272. // Note that 4062 (not all labels are handled
  13273. // and default is missing) is enabled
  13274. #endif
  13275. namespace Catch {
  13276. XmlReporter::XmlReporter( ReporterConfig const& _config )
  13277. : StreamingReporterBase( _config ),
  13278. m_xml(_config.stream())
  13279. {
  13280. m_reporterPrefs.shouldRedirectStdOut = true;
  13281. m_reporterPrefs.shouldReportAllAssertions = true;
  13282. }
  13283. XmlReporter::~XmlReporter() = default;
  13284. std::string XmlReporter::getDescription() {
  13285. return "Reports test results as an XML document";
  13286. }
  13287. std::string XmlReporter::getStylesheetRef() const {
  13288. return std::string();
  13289. }
  13290. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  13291. m_xml
  13292. .writeAttribute( "filename", sourceInfo.file )
  13293. .writeAttribute( "line", sourceInfo.line );
  13294. }
  13295. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  13296. StreamingReporterBase::noMatchingTestCases( s );
  13297. }
  13298. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  13299. StreamingReporterBase::testRunStarting( testInfo );
  13300. std::string stylesheetRef = getStylesheetRef();
  13301. if( !stylesheetRef.empty() )
  13302. m_xml.writeStylesheetRef( stylesheetRef );
  13303. m_xml.startElement( "Catch" );
  13304. if( !m_config->name().empty() )
  13305. m_xml.writeAttribute( "name", m_config->name() );
  13306. if (m_config->testSpec().hasFilters())
  13307. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  13308. if( m_config->rngSeed() != 0 )
  13309. m_xml.scopedElement( "Randomness" )
  13310. .writeAttribute( "seed", m_config->rngSeed() );
  13311. }
  13312. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13313. StreamingReporterBase::testGroupStarting( groupInfo );
  13314. m_xml.startElement( "Group" )
  13315. .writeAttribute( "name", groupInfo.name );
  13316. }
  13317. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  13318. StreamingReporterBase::testCaseStarting(testInfo);
  13319. m_xml.startElement( "TestCase" )
  13320. .writeAttribute( "name", trim( testInfo.name ) )
  13321. .writeAttribute( "description", testInfo.description )
  13322. .writeAttribute( "tags", testInfo.tagsAsString() );
  13323. writeSourceInfo( testInfo.lineInfo );
  13324. if ( m_config->showDurations() == ShowDurations::Always )
  13325. m_testCaseTimer.start();
  13326. m_xml.ensureTagClosed();
  13327. }
  13328. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  13329. StreamingReporterBase::sectionStarting( sectionInfo );
  13330. if( m_sectionDepth++ > 0 ) {
  13331. m_xml.startElement( "Section" )
  13332. .writeAttribute( "name", trim( sectionInfo.name ) );
  13333. writeSourceInfo( sectionInfo.lineInfo );
  13334. m_xml.ensureTagClosed();
  13335. }
  13336. }
  13337. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  13338. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13339. AssertionResult const& result = assertionStats.assertionResult;
  13340. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13341. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  13342. // Print any info messages in <Info> tags.
  13343. for( auto const& msg : assertionStats.infoMessages ) {
  13344. if( msg.type == ResultWas::Info && includeResults ) {
  13345. m_xml.scopedElement( "Info" )
  13346. .writeText( msg.message );
  13347. } else if ( msg.type == ResultWas::Warning ) {
  13348. m_xml.scopedElement( "Warning" )
  13349. .writeText( msg.message );
  13350. }
  13351. }
  13352. }
  13353. // Drop out if result was successful but we're not printing them.
  13354. if( !includeResults && result.getResultType() != ResultWas::Warning )
  13355. return true;
  13356. // Print the expression if there is one.
  13357. if( result.hasExpression() ) {
  13358. m_xml.startElement( "Expression" )
  13359. .writeAttribute( "success", result.succeeded() )
  13360. .writeAttribute( "type", result.getTestMacroName() );
  13361. writeSourceInfo( result.getSourceInfo() );
  13362. m_xml.scopedElement( "Original" )
  13363. .writeText( result.getExpression() );
  13364. m_xml.scopedElement( "Expanded" )
  13365. .writeText( result.getExpandedExpression() );
  13366. }
  13367. // And... Print a result applicable to each result type.
  13368. switch( result.getResultType() ) {
  13369. case ResultWas::ThrewException:
  13370. m_xml.startElement( "Exception" );
  13371. writeSourceInfo( result.getSourceInfo() );
  13372. m_xml.writeText( result.getMessage() );
  13373. m_xml.endElement();
  13374. break;
  13375. case ResultWas::FatalErrorCondition:
  13376. m_xml.startElement( "FatalErrorCondition" );
  13377. writeSourceInfo( result.getSourceInfo() );
  13378. m_xml.writeText( result.getMessage() );
  13379. m_xml.endElement();
  13380. break;
  13381. case ResultWas::Info:
  13382. m_xml.scopedElement( "Info" )
  13383. .writeText( result.getMessage() );
  13384. break;
  13385. case ResultWas::Warning:
  13386. // Warning will already have been written
  13387. break;
  13388. case ResultWas::ExplicitFailure:
  13389. m_xml.startElement( "Failure" );
  13390. writeSourceInfo( result.getSourceInfo() );
  13391. m_xml.writeText( result.getMessage() );
  13392. m_xml.endElement();
  13393. break;
  13394. default:
  13395. break;
  13396. }
  13397. if( result.hasExpression() )
  13398. m_xml.endElement();
  13399. return true;
  13400. }
  13401. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  13402. StreamingReporterBase::sectionEnded( sectionStats );
  13403. if( --m_sectionDepth > 0 ) {
  13404. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  13405. e.writeAttribute( "successes", sectionStats.assertions.passed );
  13406. e.writeAttribute( "failures", sectionStats.assertions.failed );
  13407. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  13408. if ( m_config->showDurations() == ShowDurations::Always )
  13409. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  13410. m_xml.endElement();
  13411. }
  13412. }
  13413. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13414. StreamingReporterBase::testCaseEnded( testCaseStats );
  13415. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  13416. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  13417. if ( m_config->showDurations() == ShowDurations::Always )
  13418. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  13419. if( !testCaseStats.stdOut.empty() )
  13420. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  13421. if( !testCaseStats.stdErr.empty() )
  13422. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  13423. m_xml.endElement();
  13424. }
  13425. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13426. StreamingReporterBase::testGroupEnded( testGroupStats );
  13427. // TODO: Check testGroupStats.aborting and act accordingly.
  13428. m_xml.scopedElement( "OverallResults" )
  13429. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  13430. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  13431. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  13432. m_xml.endElement();
  13433. }
  13434. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  13435. StreamingReporterBase::testRunEnded( testRunStats );
  13436. m_xml.scopedElement( "OverallResults" )
  13437. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  13438. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  13439. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  13440. m_xml.endElement();
  13441. }
  13442. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13443. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  13444. m_xml.startElement("BenchmarkResults")
  13445. .writeAttribute("name", info.name)
  13446. .writeAttribute("samples", info.samples)
  13447. .writeAttribute("resamples", info.resamples)
  13448. .writeAttribute("iterations", info.iterations)
  13449. .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
  13450. .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
  13451. .writeComment("All values in nano seconds");
  13452. }
  13453. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  13454. m_xml.startElement("mean")
  13455. .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
  13456. .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
  13457. .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
  13458. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  13459. m_xml.endElement();
  13460. m_xml.startElement("standardDeviation")
  13461. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  13462. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  13463. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  13464. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  13465. m_xml.endElement();
  13466. m_xml.startElement("outliers")
  13467. .writeAttribute("variance", benchmarkStats.outlierVariance)
  13468. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  13469. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  13470. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  13471. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  13472. m_xml.endElement();
  13473. m_xml.endElement();
  13474. }
  13475. void XmlReporter::benchmarkFailed(std::string const &error) {
  13476. m_xml.scopedElement("failed").
  13477. writeAttribute("message", error);
  13478. m_xml.endElement();
  13479. }
  13480. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13481. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  13482. } // end namespace Catch
  13483. #if defined(_MSC_VER)
  13484. #pragma warning(pop)
  13485. #endif
  13486. // end catch_reporter_xml.cpp
  13487. namespace Catch {
  13488. LeakDetector leakDetector;
  13489. }
  13490. #ifdef __clang__
  13491. #pragma clang diagnostic pop
  13492. #endif
  13493. // end catch_impl.hpp
  13494. #endif
  13495. #ifdef CATCH_CONFIG_MAIN
  13496. // start catch_default_main.hpp
  13497. #ifndef __OBJC__
  13498. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  13499. // Standard C/C++ Win32 Unicode wmain entry point
  13500. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  13501. #else
  13502. // Standard C/C++ main entry point
  13503. int main (int argc, char * argv[]) {
  13504. #endif
  13505. return Catch::Session().run( argc, argv );
  13506. }
  13507. #else // __OBJC__
  13508. // Objective-C entry point
  13509. int main (int argc, char * const argv[]) {
  13510. #if !CATCH_ARC_ENABLED
  13511. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  13512. #endif
  13513. Catch::registerTestMethods();
  13514. int result = Catch::Session().run( argc, (char**)argv );
  13515. #if !CATCH_ARC_ENABLED
  13516. [pool drain];
  13517. #endif
  13518. return result;
  13519. }
  13520. #endif // __OBJC__
  13521. // end catch_default_main.hpp
  13522. #endif
  13523. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  13524. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  13525. # undef CLARA_CONFIG_MAIN
  13526. #endif
  13527. #if !defined(CATCH_CONFIG_DISABLE)
  13528. //////
  13529. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13530. #ifdef CATCH_CONFIG_PREFIX_ALL
  13531. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13532. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13533. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13534. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13535. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13536. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13537. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13538. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13539. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13540. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13541. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13542. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13543. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13544. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13545. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13546. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13547. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13548. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13549. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13550. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13551. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13552. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13553. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13554. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13555. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13556. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  13557. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  13558. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13559. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  13560. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13561. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13562. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13563. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13564. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13565. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13566. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13567. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13568. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13569. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13570. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13571. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13572. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13573. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13574. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13575. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13576. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13577. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13578. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13579. #else
  13580. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13581. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13582. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13583. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13584. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13585. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13586. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13587. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13588. #endif
  13589. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13590. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  13591. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  13592. #else
  13593. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  13594. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  13595. #endif
  13596. // "BDD-style" convenience wrappers
  13597. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  13598. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13599. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13600. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13601. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13602. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13603. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13604. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13605. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13606. #define CATCH_BENCHMARK(...) \
  13607. 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__,,))
  13608. #define CATCH_BENCHMARK_ADVANCED(name) \
  13609. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13610. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13611. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13612. #else
  13613. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13614. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13615. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13616. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  13617. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  13618. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13619. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  13620. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13621. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13622. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13623. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  13624. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13625. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13626. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  13627. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13628. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  13629. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13630. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13631. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  13632. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13633. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13634. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13635. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  13636. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  13637. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13638. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  13639. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  13640. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  13641. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  13642. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  13643. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13644. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  13645. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  13646. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  13647. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  13648. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  13649. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13650. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  13651. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  13652. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13653. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13654. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  13655. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13656. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13657. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  13658. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  13659. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13660. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  13661. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  13662. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13663. #else
  13664. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  13665. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  13666. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13667. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13668. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  13669. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  13670. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13671. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  13672. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  13673. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  13674. #endif
  13675. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  13676. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  13677. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  13678. #else
  13679. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  13680. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  13681. #endif
  13682. #endif
  13683. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  13684. // "BDD-style" convenience wrappers
  13685. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  13686. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  13687. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  13688. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  13689. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  13690. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  13691. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  13692. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  13693. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13694. #define BENCHMARK(...) \
  13695. 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__,,))
  13696. #define BENCHMARK_ADVANCED(name) \
  13697. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
  13698. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13699. using Catch::Detail::Approx;
  13700. #else // CATCH_CONFIG_DISABLE
  13701. //////
  13702. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  13703. #ifdef CATCH_CONFIG_PREFIX_ALL
  13704. #define CATCH_REQUIRE( ... ) (void)(0)
  13705. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  13706. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  13707. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13708. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13709. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13710. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13711. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  13712. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  13713. #define CATCH_CHECK( ... ) (void)(0)
  13714. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  13715. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  13716. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13717. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  13718. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  13719. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13720. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13721. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13722. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13723. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13724. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  13725. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13726. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  13727. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  13728. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13729. #define CATCH_INFO( msg ) (void)(0)
  13730. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  13731. #define CATCH_WARN( msg ) (void)(0)
  13732. #define CATCH_CAPTURE( msg ) (void)(0)
  13733. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13734. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13735. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  13736. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13737. #define CATCH_SECTION( ... )
  13738. #define CATCH_DYNAMIC_SECTION( ... )
  13739. #define CATCH_FAIL( ... ) (void)(0)
  13740. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  13741. #define CATCH_SUCCEED( ... ) (void)(0)
  13742. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13743. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13744. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13745. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13746. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13747. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13748. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13749. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13750. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13751. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13752. #else
  13753. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13754. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13755. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13756. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13757. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13758. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13759. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13760. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13761. #endif
  13762. // "BDD-style" convenience wrappers
  13763. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13764. #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 )
  13765. #define CATCH_GIVEN( desc )
  13766. #define CATCH_AND_GIVEN( desc )
  13767. #define CATCH_WHEN( desc )
  13768. #define CATCH_AND_WHEN( desc )
  13769. #define CATCH_THEN( desc )
  13770. #define CATCH_AND_THEN( desc )
  13771. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  13772. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13773. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  13774. #else
  13775. #define REQUIRE( ... ) (void)(0)
  13776. #define REQUIRE_FALSE( ... ) (void)(0)
  13777. #define REQUIRE_THROWS( ... ) (void)(0)
  13778. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  13779. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  13780. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13781. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13782. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13783. #define REQUIRE_NOTHROW( ... ) (void)(0)
  13784. #define CHECK( ... ) (void)(0)
  13785. #define CHECK_FALSE( ... ) (void)(0)
  13786. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  13787. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  13788. #define CHECK_NOFAIL( ... ) (void)(0)
  13789. #define CHECK_THROWS( ... ) (void)(0)
  13790. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  13791. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  13792. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13793. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  13794. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13795. #define CHECK_NOTHROW( ... ) (void)(0)
  13796. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  13797. #define CHECK_THAT( arg, matcher ) (void)(0)
  13798. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  13799. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  13800. #define INFO( msg ) (void)(0)
  13801. #define UNSCOPED_INFO( msg ) (void)(0)
  13802. #define WARN( msg ) (void)(0)
  13803. #define CAPTURE( msg ) (void)(0)
  13804. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13805. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13806. #define METHOD_AS_TEST_CASE( method, ... )
  13807. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  13808. #define SECTION( ... )
  13809. #define DYNAMIC_SECTION( ... )
  13810. #define FAIL( ... ) (void)(0)
  13811. #define FAIL_CHECK( ... ) (void)(0)
  13812. #define SUCCEED( ... ) (void)(0)
  13813. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  13814. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  13815. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  13816. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  13817. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  13818. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  13819. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13820. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13821. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13822. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13823. #else
  13824. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  13825. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  13826. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13827. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  13828. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13829. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  13830. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13831. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  13832. #endif
  13833. #define STATIC_REQUIRE( ... ) (void)(0)
  13834. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  13835. #endif
  13836. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  13837. // "BDD-style" convenience wrappers
  13838. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  13839. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  13840. #define GIVEN( desc )
  13841. #define AND_GIVEN( desc )
  13842. #define WHEN( desc )
  13843. #define AND_WHEN( desc )
  13844. #define THEN( desc )
  13845. #define AND_THEN( desc )
  13846. using Catch::Detail::Approx;
  13847. #endif
  13848. #endif // ! CATCH_CONFIG_IMPL_ONLY
  13849. // start catch_reenable_warnings.h
  13850. #ifdef __clang__
  13851. # ifdef __ICC // icpc defines the __clang__ macro
  13852. # pragma warning(pop)
  13853. # else
  13854. # pragma clang diagnostic pop
  13855. # endif
  13856. #elif defined __GNUC__
  13857. # pragma GCC diagnostic pop
  13858. #endif
  13859. // end catch_reenable_warnings.h
  13860. // end catch.hpp
  13861. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED