catch.hpp 407 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013
  1. /*
  2. * Catch v2.0.1
  3. * Generated: 2017-11-03 11:53:39.642003
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2017 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #ifdef __clang__
  15. # pragma clang system_header
  16. #elif defined __GNUC__
  17. # pragma GCC system_header
  18. #endif
  19. // start catch_suppress_warnings.h
  20. #ifdef __clang__
  21. # ifdef __ICC // icpc defines the __clang__ macro
  22. # pragma warning(push)
  23. # pragma warning(disable: 161 1682)
  24. # else // __ICC
  25. # pragma clang diagnostic ignored "-Wglobal-constructors"
  26. # pragma clang diagnostic ignored "-Wvariadic-macros"
  27. # pragma clang diagnostic ignored "-Wc99-extensions"
  28. # pragma clang diagnostic ignored "-Wunused-variable"
  29. # pragma clang diagnostic push
  30. # pragma clang diagnostic ignored "-Wpadded"
  31. # pragma clang diagnostic ignored "-Wswitch-enum"
  32. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  33. # endif
  34. #elif defined __GNUC__
  35. # pragma GCC diagnostic ignored "-Wvariadic-macros"
  36. # pragma GCC diagnostic ignored "-Wunused-variable"
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wpadded"
  40. #endif
  41. // end catch_suppress_warnings.h
  42. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  43. # define CATCH_IMPL
  44. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  45. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  46. # undef CATCH_CONFIG_DISABLE_MATCHERS
  47. # endif
  48. #endif
  49. // start catch_platform.h
  50. #ifdef __APPLE__
  51. # include <TargetConditionals.h>
  52. # if TARGET_OS_MAC == 1
  53. # define CATCH_PLATFORM_MAC
  54. # elif TARGET_OS_IPHONE == 1
  55. # define CATCH_PLATFORM_IPHONE
  56. # endif
  57. #elif defined(linux) || defined(__linux) || defined(__linux__)
  58. # define CATCH_PLATFORM_LINUX
  59. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  60. # define CATCH_PLATFORM_WINDOWS
  61. #endif
  62. // end catch_platform.h
  63. #ifdef CATCH_IMPL
  64. # ifndef CLARA_CONFIG_MAIN
  65. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  66. # define CLARA_CONFIG_MAIN
  67. # endif
  68. #endif
  69. // start catch_tag_alias_autoregistrar.h
  70. // start catch_common.h
  71. // start catch_compiler_capabilities.h
  72. // Detect a number of compiler features - by compiler
  73. // The following features are defined:
  74. //
  75. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  76. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  77. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  78. // ****************
  79. // Note to maintainers: if new toggles are added please document them
  80. // in configuration.md, too
  81. // ****************
  82. // In general each macro has a _NO_<feature name> form
  83. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  84. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  85. // can be combined, en-mass, with the _NO_ forms later.
  86. #ifdef __cplusplus
  87. # if __cplusplus >= 201402L
  88. # define CATCH_CPP14_OR_GREATER
  89. # endif
  90. #endif
  91. #ifdef __clang__
  92. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  93. _Pragma( "clang diagnostic push" ) \
  94. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  95. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  96. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  97. _Pragma( "clang diagnostic pop" )
  98. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  99. _Pragma( "clang diagnostic push" ) \
  100. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  101. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  102. _Pragma( "clang diagnostic pop" )
  103. #endif // __clang__
  104. ////////////////////////////////////////////////////////////////////////////////
  105. // We know some environments not to support full POSIX signals
  106. #if defined(__CYGWIN__) || defined(__QNX__)
  107. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  108. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  109. # endif
  110. #endif
  111. #ifdef __OS400__
  112. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  113. # define CATCH_CONFIG_COLOUR_NONE
  114. #endif
  115. ////////////////////////////////////////////////////////////////////////////////
  116. // Cygwin
  117. #ifdef __CYGWIN__
  118. // Required for some versions of Cygwin to declare gettimeofday
  119. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  120. # define _BSD_SOURCE
  121. #endif // __CYGWIN__
  122. ////////////////////////////////////////////////////////////////////////////////
  123. // Visual C++
  124. #ifdef _MSC_VER
  125. // Universal Windows platform does not support SEH
  126. // Or console colours (or console at all...)
  127. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  128. # define CATCH_CONFIG_COLOUR_NONE
  129. # else
  130. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  131. # endif
  132. #endif // _MSC_VER
  133. ////////////////////////////////////////////////////////////////////////////////
  134. // Use of __COUNTER__ is suppressed during code analysis in
  135. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  136. // handled by it.
  137. // Otherwise all supported compilers support COUNTER macro,
  138. // but user still might want to turn it off
  139. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  140. #define CATCH_INTERNAL_CONFIG_COUNTER
  141. #endif
  142. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  143. # define CATCH_CONFIG_COUNTER
  144. #endif
  145. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  146. # define CATCH_CONFIG_WINDOWS_SEH
  147. #endif
  148. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  149. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  150. # define CATCH_CONFIG_POSIX_SIGNALS
  151. #endif
  152. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  153. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  154. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  155. #endif
  156. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  157. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  158. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  159. #endif
  160. // end catch_compiler_capabilities.h
  161. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  162. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  163. #ifdef CATCH_CONFIG_COUNTER
  164. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  165. #else
  166. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  167. #endif
  168. #include <iosfwd>
  169. #include <string>
  170. #include <cstdint>
  171. namespace Catch {
  172. struct CaseSensitive { enum Choice {
  173. Yes,
  174. No
  175. }; };
  176. class NonCopyable {
  177. NonCopyable( NonCopyable const& ) = delete;
  178. NonCopyable( NonCopyable && ) = delete;
  179. NonCopyable& operator = ( NonCopyable const& ) = delete;
  180. NonCopyable& operator = ( NonCopyable && ) = delete;
  181. protected:
  182. NonCopyable();
  183. virtual ~NonCopyable();
  184. };
  185. struct SourceLineInfo {
  186. SourceLineInfo() = delete;
  187. SourceLineInfo( char const* _file, std::size_t _line ) noexcept;
  188. SourceLineInfo( SourceLineInfo const& other ) = default;
  189. SourceLineInfo( SourceLineInfo && ) = default;
  190. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  191. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  192. bool empty() const noexcept;
  193. bool operator == ( SourceLineInfo const& other ) const noexcept;
  194. bool operator < ( SourceLineInfo const& other ) const noexcept;
  195. char const* file;
  196. std::size_t line;
  197. };
  198. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  199. // This is just here to avoid compiler warnings with macro constants and boolean literals
  200. bool isTrue( bool value );
  201. bool alwaysTrue();
  202. bool alwaysFalse();
  203. // Use this in variadic streaming macros to allow
  204. // >> +StreamEndStop
  205. // as well as
  206. // >> stuff +StreamEndStop
  207. struct StreamEndStop {
  208. std::string operator+() const;
  209. };
  210. template<typename T>
  211. T const& operator + ( T const& value, StreamEndStop ) {
  212. return value;
  213. }
  214. }
  215. #define CATCH_INTERNAL_LINEINFO \
  216. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  217. // end catch_common.h
  218. namespace Catch {
  219. struct RegistrarForTagAliases {
  220. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  221. };
  222. } // end namespace Catch
  223. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
  224. // end catch_tag_alias_autoregistrar.h
  225. // start catch_test_registry.h
  226. // start catch_interfaces_testcase.h
  227. #include <vector>
  228. #include <memory>
  229. namespace Catch {
  230. class TestSpec;
  231. struct ITestInvoker {
  232. virtual void invoke () const = 0;
  233. virtual ~ITestInvoker();
  234. };
  235. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  236. class TestCase;
  237. struct IConfig;
  238. struct ITestCaseRegistry {
  239. virtual ~ITestCaseRegistry();
  240. virtual std::vector<TestCase> const& getAllTests() const = 0;
  241. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  242. };
  243. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  244. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  245. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  246. }
  247. // end catch_interfaces_testcase.h
  248. // start catch_stringref.h
  249. #include <cstddef>
  250. #include <string>
  251. #include <iosfwd>
  252. namespace Catch {
  253. class StringData;
  254. /// A non-owning string class (similar to the forthcoming std::string_view)
  255. /// Note that, because a StringRef may be a substring of another string,
  256. /// it may not be null terminated. c_str() must return a null terminated
  257. /// string, however, and so the StringRef will internally take ownership
  258. /// (taking a copy), if necessary. In theory this ownership is not externally
  259. /// visible - but it does mean (substring) StringRefs should not be shared between
  260. /// threads.
  261. class StringRef {
  262. friend struct StringRefTestAccess;
  263. using size_type = std::size_t;
  264. char const* m_start;
  265. size_type m_size;
  266. char* m_data = nullptr;
  267. void takeOwnership();
  268. public: // construction/ assignment
  269. StringRef() noexcept;
  270. StringRef( StringRef const& other ) noexcept;
  271. StringRef( StringRef&& other ) noexcept;
  272. StringRef( char const* rawChars ) noexcept;
  273. StringRef( char const* rawChars, size_type size ) noexcept;
  274. StringRef( std::string const& stdString ) noexcept;
  275. ~StringRef() noexcept;
  276. auto operator = ( StringRef other ) noexcept -> StringRef&;
  277. operator std::string() const;
  278. void swap( StringRef& other ) noexcept;
  279. public: // operators
  280. auto operator == ( StringRef const& other ) const noexcept -> bool;
  281. auto operator != ( StringRef const& other ) const noexcept -> bool;
  282. auto operator[] ( size_type index ) const noexcept -> char;
  283. public: // named queries
  284. auto empty() const noexcept -> bool;
  285. auto size() const noexcept -> size_type;
  286. auto numberOfCharacters() const noexcept -> size_type;
  287. auto c_str() const -> char const*;
  288. public: // substrings and searches
  289. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  290. private: // ownership queries - may not be consistent between calls
  291. auto isOwned() const noexcept -> bool;
  292. auto isSubstring() const noexcept -> bool;
  293. auto data() const noexcept -> char const*;
  294. };
  295. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  296. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  297. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  298. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  299. } // namespace Catch
  300. // end catch_stringref.h
  301. namespace Catch {
  302. template<typename C>
  303. class TestInvokerAsMethod : public ITestInvoker {
  304. void (C::*m_testAsMethod)();
  305. public:
  306. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  307. void invoke() const override {
  308. C obj;
  309. (obj.*m_testAsMethod)();
  310. }
  311. };
  312. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  313. template<typename C>
  314. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  315. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  316. }
  317. struct NameAndTags {
  318. NameAndTags( StringRef name_ = "", StringRef tags_ = "" ) noexcept;
  319. StringRef name;
  320. StringRef tags;
  321. };
  322. struct AutoReg : NonCopyable {
  323. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  324. ~AutoReg();
  325. };
  326. } // end namespace Catch
  327. #if defined(CATCH_CONFIG_DISABLE)
  328. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  329. static void TestName()
  330. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  331. namespace{ \
  332. struct TestName : ClassName { \
  333. void test(); \
  334. }; \
  335. } \
  336. void TestName::test()
  337. #endif
  338. ///////////////////////////////////////////////////////////////////////////////
  339. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  340. static void TestName(); \
  341. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  342. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  343. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  344. static void TestName()
  345. #define INTERNAL_CATCH_TESTCASE( ... ) \
  346. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  347. ///////////////////////////////////////////////////////////////////////////////
  348. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  349. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  350. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  351. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  352. ///////////////////////////////////////////////////////////////////////////////
  353. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  354. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  355. namespace{ \
  356. struct TestName : ClassName{ \
  357. void test(); \
  358. }; \
  359. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  360. } \
  361. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  362. void TestName::test()
  363. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  364. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  365. ///////////////////////////////////////////////////////////////////////////////
  366. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  367. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  368. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  369. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  370. // end catch_test_registry.h
  371. // start catch_capture.hpp
  372. // start catch_assertionhandler.h
  373. // start catch_decomposer.h
  374. // start catch_tostring.h
  375. #include <sstream>
  376. #include <vector>
  377. #include <cstddef>
  378. #include <type_traits>
  379. #include <string>
  380. #ifdef __OBJC__
  381. // start catch_objc_arc.hpp
  382. #import <Foundation/Foundation.h>
  383. #ifdef __has_feature
  384. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  385. #else
  386. #define CATCH_ARC_ENABLED 0
  387. #endif
  388. void arcSafeRelease( NSObject* obj );
  389. id performOptionalSelector( id obj, SEL sel );
  390. #if !CATCH_ARC_ENABLED
  391. inline void arcSafeRelease( NSObject* obj ) {
  392. [obj release];
  393. }
  394. inline id performOptionalSelector( id obj, SEL sel ) {
  395. if( [obj respondsToSelector: sel] )
  396. return [obj performSelector: sel];
  397. return nil;
  398. }
  399. #define CATCH_UNSAFE_UNRETAINED
  400. #define CATCH_ARC_STRONG
  401. #else
  402. inline void arcSafeRelease( NSObject* ){}
  403. inline id performOptionalSelector( id obj, SEL sel ) {
  404. #ifdef __clang__
  405. #pragma clang diagnostic push
  406. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  407. #endif
  408. if( [obj respondsToSelector: sel] )
  409. return [obj performSelector: sel];
  410. #ifdef __clang__
  411. #pragma clang diagnostic pop
  412. #endif
  413. return nil;
  414. }
  415. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  416. #define CATCH_ARC_STRONG __strong
  417. #endif
  418. // end catch_objc_arc.hpp
  419. #endif
  420. #ifdef _MSC_VER
  421. #pragma warning(push)
  422. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  423. #endif
  424. // We need a dummy global operator<< so we can bring it into Catch namespace later
  425. struct Catch_global_namespace_dummy;
  426. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  427. namespace Catch {
  428. // Bring in operator<< from global namespace into Catch namespace
  429. using ::operator<<;
  430. namespace Detail {
  431. extern const std::string unprintableString;
  432. std::string rawMemoryToString( const void *object, std::size_t size );
  433. template<typename T>
  434. std::string rawMemoryToString( const T& object ) {
  435. return rawMemoryToString( &object, sizeof(object) );
  436. }
  437. template<typename T>
  438. class IsStreamInsertable {
  439. template<typename SS, typename TT>
  440. static auto test(int)
  441. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  442. template<typename, typename>
  443. static auto test(...)->std::false_type;
  444. public:
  445. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  446. };
  447. } // namespace Detail
  448. // If we decide for C++14, change these to enable_if_ts
  449. template <typename T>
  450. struct StringMaker {
  451. template <typename Fake = T>
  452. static
  453. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  454. convert(const Fake& t) {
  455. std::ostringstream sstr;
  456. sstr << t;
  457. return sstr.str();
  458. }
  459. template <typename Fake = T>
  460. static
  461. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  462. convert(const Fake&) {
  463. return Detail::unprintableString;
  464. }
  465. };
  466. namespace Detail {
  467. // This function dispatches all stringification requests inside of Catch.
  468. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  469. template <typename T>
  470. std::string stringify(const T& e) {
  471. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  472. }
  473. } // namespace Detail
  474. // Some predefined specializations
  475. template<>
  476. struct StringMaker<std::string> {
  477. static std::string convert(const std::string& str);
  478. };
  479. template<>
  480. struct StringMaker<std::wstring> {
  481. static std::string convert(const std::wstring& wstr);
  482. };
  483. template<>
  484. struct StringMaker<char const *> {
  485. static std::string convert(char const * str);
  486. };
  487. template<>
  488. struct StringMaker<char *> {
  489. static std::string convert(char * str);
  490. };
  491. template<>
  492. struct StringMaker<wchar_t const *> {
  493. static std::string convert(wchar_t const * str);
  494. };
  495. template<>
  496. struct StringMaker<wchar_t *> {
  497. static std::string convert(wchar_t * str);
  498. };
  499. template<int SZ>
  500. struct StringMaker<char[SZ]> {
  501. static std::string convert(const char* str) {
  502. return ::Catch::Detail::stringify(std::string{ str });
  503. }
  504. };
  505. template<int SZ>
  506. struct StringMaker<signed char[SZ]> {
  507. static std::string convert(const char* str) {
  508. return ::Catch::Detail::stringify(std::string{ str });
  509. }
  510. };
  511. template<int SZ>
  512. struct StringMaker<unsigned char[SZ]> {
  513. static std::string convert(const char* str) {
  514. return ::Catch::Detail::stringify(std::string{ str });
  515. }
  516. };
  517. template<>
  518. struct StringMaker<int> {
  519. static std::string convert(int value);
  520. };
  521. template<>
  522. struct StringMaker<long> {
  523. static std::string convert(long value);
  524. };
  525. template<>
  526. struct StringMaker<long long> {
  527. static std::string convert(long long value);
  528. };
  529. template<>
  530. struct StringMaker<unsigned int> {
  531. static std::string convert(unsigned int value);
  532. };
  533. template<>
  534. struct StringMaker<unsigned long> {
  535. static std::string convert(unsigned long value);
  536. };
  537. template<>
  538. struct StringMaker<unsigned long long> {
  539. static std::string convert(unsigned long long value);
  540. };
  541. template<>
  542. struct StringMaker<bool> {
  543. static std::string convert(bool b);
  544. };
  545. template<>
  546. struct StringMaker<char> {
  547. static std::string convert(char c);
  548. };
  549. template<>
  550. struct StringMaker<signed char> {
  551. static std::string convert(signed char c);
  552. };
  553. template<>
  554. struct StringMaker<unsigned char> {
  555. static std::string convert(unsigned char c);
  556. };
  557. template<>
  558. struct StringMaker<std::nullptr_t> {
  559. static std::string convert(std::nullptr_t);
  560. };
  561. template<>
  562. struct StringMaker<float> {
  563. static std::string convert(float value);
  564. };
  565. template<>
  566. struct StringMaker<double> {
  567. static std::string convert(double value);
  568. };
  569. template <typename T>
  570. struct StringMaker<T*> {
  571. template <typename U>
  572. static std::string convert(U* p) {
  573. if (p) {
  574. return ::Catch::Detail::rawMemoryToString(p);
  575. } else {
  576. return "nullptr";
  577. }
  578. }
  579. };
  580. template <typename R, typename C>
  581. struct StringMaker<R C::*> {
  582. static std::string convert(R C::* p) {
  583. if (p) {
  584. return ::Catch::Detail::rawMemoryToString(p);
  585. } else {
  586. return "nullptr";
  587. }
  588. }
  589. };
  590. namespace Detail {
  591. template<typename InputIterator>
  592. std::string rangeToString(InputIterator first, InputIterator last) {
  593. std::ostringstream oss;
  594. oss << "{ ";
  595. if (first != last) {
  596. oss << ::Catch::Detail::stringify(*first);
  597. for (++first; first != last; ++first)
  598. oss << ", " << ::Catch::Detail::stringify(*first);
  599. }
  600. oss << " }";
  601. return oss.str();
  602. }
  603. }
  604. template<typename T, typename Allocator>
  605. struct StringMaker<std::vector<T, Allocator> > {
  606. static std::string convert( std::vector<T,Allocator> const& v ) {
  607. return ::Catch::Detail::rangeToString( v.begin(), v.end() );
  608. }
  609. };
  610. template<typename T>
  611. struct EnumStringMaker {
  612. static std::string convert(const T& t) {
  613. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<T>::type>(t));
  614. }
  615. };
  616. #ifdef __OBJC__
  617. template<>
  618. struct StringMaker<NSString*> {
  619. static std::string convert(NSString * nsstring) {
  620. if (!nsstring)
  621. return "nil";
  622. return std::string("@") + [nsstring UTF8String];
  623. }
  624. };
  625. template<>
  626. struct StringMaker<NSObject*> {
  627. static std::string convert(NSObject* nsObject) {
  628. return ::Catch::Detail::stringify([nsObject description]);
  629. }
  630. };
  631. namespace Detail {
  632. inline std::string stringify( NSString* nsstring ) {
  633. return StringMaker<NSString*>::convert( nsstring );
  634. }
  635. } // namespace Detail
  636. #endif // __OBJC__
  637. } // namespace Catch
  638. //////////////////////////////////////////////////////
  639. // Separate std-lib types stringification, so it can be selectively enabled
  640. // This means that we do not bring in
  641. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  642. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  643. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  644. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  645. #endif
  646. // Separate std::pair specialization
  647. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  648. #include <utility>
  649. namespace Catch {
  650. template<typename T1, typename T2>
  651. struct StringMaker<std::pair<T1, T2> > {
  652. static std::string convert(const std::pair<T1, T2>& pair) {
  653. std::ostringstream oss;
  654. oss << "{ "
  655. << ::Catch::Detail::stringify(pair.first)
  656. << ", "
  657. << ::Catch::Detail::stringify(pair.second)
  658. << " }";
  659. return oss.str();
  660. }
  661. };
  662. }
  663. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  664. // Separate std::tuple specialization
  665. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  666. #include <tuple>
  667. namespace Catch {
  668. namespace Detail {
  669. template<
  670. typename Tuple,
  671. std::size_t N = 0,
  672. bool = (N < std::tuple_size<Tuple>::value)
  673. >
  674. struct TupleElementPrinter {
  675. static void print(const Tuple& tuple, std::ostream& os) {
  676. os << (N ? ", " : " ")
  677. << ::Catch::Detail::stringify(std::get<N>(tuple));
  678. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  679. }
  680. };
  681. template<
  682. typename Tuple,
  683. std::size_t N
  684. >
  685. struct TupleElementPrinter<Tuple, N, false> {
  686. static void print(const Tuple&, std::ostream&) {}
  687. };
  688. }
  689. template<typename ...Types>
  690. struct StringMaker<std::tuple<Types...>> {
  691. static std::string convert(const std::tuple<Types...>& tuple) {
  692. std::ostringstream os;
  693. os << '{';
  694. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, os);
  695. os << " }";
  696. return os.str();
  697. }
  698. };
  699. }
  700. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  701. // Separate std::chrono::duration specialization
  702. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  703. #include <ctime>
  704. #include <ratio>
  705. #include <chrono>
  706. template <class Ratio>
  707. struct ratio_string {
  708. static std::string symbol();
  709. };
  710. template <class Ratio>
  711. std::string ratio_string<Ratio>::symbol() {
  712. std::ostringstream oss;
  713. oss << '[' << Ratio::num << '/'
  714. << Ratio::den << ']';
  715. return oss.str();
  716. }
  717. template <>
  718. struct ratio_string<std::atto> {
  719. static std::string symbol() { return "a"; }
  720. };
  721. template <>
  722. struct ratio_string<std::femto> {
  723. static std::string symbol() { return "f"; }
  724. };
  725. template <>
  726. struct ratio_string<std::pico> {
  727. static std::string symbol() { return "p"; }
  728. };
  729. template <>
  730. struct ratio_string<std::nano> {
  731. static std::string symbol() { return "n"; }
  732. };
  733. template <>
  734. struct ratio_string<std::micro> {
  735. static std::string symbol() { return "u"; }
  736. };
  737. template <>
  738. struct ratio_string<std::milli> {
  739. static std::string symbol() { return "m"; }
  740. };
  741. namespace Catch {
  742. ////////////
  743. // std::chrono::duration specializations
  744. template<typename Value, typename Ratio>
  745. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  746. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  747. std::ostringstream oss;
  748. oss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  749. return oss.str();
  750. }
  751. };
  752. template<typename Value>
  753. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  754. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  755. std::ostringstream oss;
  756. oss << duration.count() << " s";
  757. return oss.str();
  758. }
  759. };
  760. template<typename Value>
  761. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  762. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  763. std::ostringstream oss;
  764. oss << duration.count() << " m";
  765. return oss.str();
  766. }
  767. };
  768. template<typename Value>
  769. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  770. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  771. std::ostringstream oss;
  772. oss << duration.count() << " h";
  773. return oss.str();
  774. }
  775. };
  776. ////////////
  777. // std::chrono::time_point specialization
  778. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  779. template<typename Clock, typename Duration>
  780. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  781. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  782. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  783. }
  784. };
  785. // std::chrono::time_point<system_clock> specialization
  786. template<typename Duration>
  787. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  788. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  789. auto converted = std::chrono::system_clock::to_time_t(time_point);
  790. #ifdef _MSC_VER
  791. std::tm timeInfo = {};
  792. gmtime_s(&timeInfo, &converted);
  793. #else
  794. std::tm* timeInfo = std::gmtime(&converted);
  795. #endif
  796. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  797. char timeStamp[timeStampSize];
  798. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  799. #ifdef _MSC_VER
  800. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  801. #else
  802. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  803. #endif
  804. return std::string(timeStamp);
  805. }
  806. };
  807. }
  808. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  809. #ifdef _MSC_VER
  810. #pragma warning(pop)
  811. #endif
  812. // end catch_tostring.h
  813. #include <ostream>
  814. #ifdef _MSC_VER
  815. #pragma warning(push)
  816. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  817. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  818. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  819. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  820. #endif
  821. namespace Catch {
  822. struct ITransientExpression {
  823. virtual auto isBinaryExpression() const -> bool = 0;
  824. virtual auto getResult() const -> bool = 0;
  825. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  826. // We don't actually need a virtual destructore, but many static analysers
  827. // complain if it's not here :-(
  828. virtual ~ITransientExpression();
  829. };
  830. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  831. template<typename LhsT, typename RhsT>
  832. class BinaryExpr : public ITransientExpression {
  833. bool m_result;
  834. LhsT m_lhs;
  835. StringRef m_op;
  836. RhsT m_rhs;
  837. auto isBinaryExpression() const -> bool override { return true; }
  838. auto getResult() const -> bool override { return m_result; }
  839. void streamReconstructedExpression( std::ostream &os ) const override {
  840. formatReconstructedExpression
  841. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  842. }
  843. public:
  844. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  845. : m_result( comparisonResult ),
  846. m_lhs( lhs ),
  847. m_op( op ),
  848. m_rhs( rhs )
  849. {}
  850. };
  851. template<typename LhsT>
  852. class UnaryExpr : public ITransientExpression {
  853. LhsT m_lhs;
  854. auto isBinaryExpression() const -> bool override { return false; }
  855. auto getResult() const -> bool override { return m_lhs ? true : false; }
  856. void streamReconstructedExpression( std::ostream &os ) const override {
  857. os << Catch::Detail::stringify( m_lhs );
  858. }
  859. public:
  860. UnaryExpr( LhsT lhs ) : m_lhs( lhs ) {}
  861. };
  862. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  863. template<typename LhsT, typename RhsT>
  864. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return lhs == rhs; };
  865. template<typename T>
  866. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  867. template<typename T>
  868. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  869. template<typename T>
  870. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  871. template<typename T>
  872. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  873. template<typename LhsT, typename RhsT>
  874. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return lhs != rhs; };
  875. template<typename T>
  876. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  877. template<typename T>
  878. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  879. template<typename T>
  880. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  881. template<typename T>
  882. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  883. template<typename LhsT>
  884. class ExprLhs {
  885. LhsT m_lhs;
  886. public:
  887. ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  888. template<typename RhsT>
  889. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  890. return BinaryExpr<LhsT, RhsT const&>( compareEqual( m_lhs, rhs ), m_lhs, "==", rhs );
  891. }
  892. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  893. return BinaryExpr<LhsT, bool>( m_lhs == rhs, m_lhs, "==", rhs );
  894. }
  895. template<typename RhsT>
  896. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  897. return BinaryExpr<LhsT, RhsT const&>( compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs );
  898. }
  899. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  900. return BinaryExpr<LhsT, bool>( m_lhs != rhs, m_lhs, "!=", rhs );
  901. }
  902. template<typename RhsT>
  903. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  904. return BinaryExpr<LhsT, RhsT const&>( m_lhs > rhs, m_lhs, ">", rhs );
  905. }
  906. template<typename RhsT>
  907. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  908. return BinaryExpr<LhsT, RhsT const&>( m_lhs < rhs, m_lhs, "<", rhs );
  909. }
  910. template<typename RhsT>
  911. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  912. return BinaryExpr<LhsT, RhsT const&>( m_lhs >= rhs, m_lhs, ">=", rhs );
  913. }
  914. template<typename RhsT>
  915. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  916. return BinaryExpr<LhsT, RhsT const&>( m_lhs <= rhs, m_lhs, "<=", rhs );
  917. }
  918. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  919. return UnaryExpr<LhsT>( m_lhs );
  920. }
  921. };
  922. void handleExpression( ITransientExpression const& expr );
  923. template<typename T>
  924. void handleExpression( ExprLhs<T> const& expr ) {
  925. handleExpression( expr.makeUnaryExpr() );
  926. }
  927. struct Decomposer {
  928. template<typename T>
  929. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  930. return ExprLhs<T const&>( lhs );
  931. }
  932. auto operator <=( bool value ) -> ExprLhs<bool> {
  933. return ExprLhs<bool>( value );
  934. }
  935. };
  936. } // end namespace Catch
  937. #ifdef _MSC_VER
  938. #pragma warning(pop)
  939. #endif
  940. // end catch_decomposer.h
  941. // start catch_assertioninfo.h
  942. // start catch_result_type.h
  943. namespace Catch {
  944. // ResultWas::OfType enum
  945. struct ResultWas { enum OfType {
  946. Unknown = -1,
  947. Ok = 0,
  948. Info = 1,
  949. Warning = 2,
  950. FailureBit = 0x10,
  951. ExpressionFailed = FailureBit | 1,
  952. ExplicitFailure = FailureBit | 2,
  953. Exception = 0x100 | FailureBit,
  954. ThrewException = Exception | 1,
  955. DidntThrowException = Exception | 2,
  956. FatalErrorCondition = 0x200 | FailureBit
  957. }; };
  958. bool isOk( ResultWas::OfType resultType );
  959. bool isJustInfo( int flags );
  960. // ResultDisposition::Flags enum
  961. struct ResultDisposition { enum Flags {
  962. Normal = 0x01,
  963. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  964. FalseTest = 0x04, // Prefix expression with !
  965. SuppressFail = 0x08 // Failures are reported but do not fail the test
  966. }; };
  967. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  968. bool shouldContinueOnFailure( int flags );
  969. bool isFalseTest( int flags );
  970. bool shouldSuppressFailure( int flags );
  971. } // end namespace Catch
  972. // end catch_result_type.h
  973. namespace Catch {
  974. struct AssertionInfo
  975. {
  976. StringRef macroName;
  977. SourceLineInfo lineInfo;
  978. StringRef capturedExpression;
  979. ResultDisposition::Flags resultDisposition;
  980. // We want to delete this constructor but a compiler bug in 4.8 means
  981. // the struct is then treated as non-aggregate
  982. //AssertionInfo() = delete;
  983. };
  984. } // end namespace Catch
  985. // end catch_assertioninfo.h
  986. namespace Catch {
  987. struct TestFailureException{};
  988. struct AssertionResultData;
  989. class LazyExpression {
  990. friend class AssertionHandler;
  991. friend struct AssertionStats;
  992. ITransientExpression const* m_transientExpression = nullptr;
  993. bool m_isNegated;
  994. public:
  995. LazyExpression( bool isNegated );
  996. LazyExpression( LazyExpression const& other );
  997. LazyExpression& operator = ( LazyExpression const& ) = delete;
  998. explicit operator bool() const;
  999. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1000. };
  1001. class AssertionHandler {
  1002. AssertionInfo m_assertionInfo;
  1003. bool m_shouldDebugBreak = false;
  1004. bool m_shouldThrow = false;
  1005. bool m_inExceptionGuard = false;
  1006. public:
  1007. AssertionHandler
  1008. ( StringRef macroName,
  1009. SourceLineInfo const& lineInfo,
  1010. StringRef capturedExpression,
  1011. ResultDisposition::Flags resultDisposition );
  1012. ~AssertionHandler();
  1013. void handle( ITransientExpression const& expr );
  1014. template<typename T>
  1015. void handle( ExprLhs<T> const& expr ) {
  1016. handle( expr.makeUnaryExpr() );
  1017. }
  1018. void handle( ResultWas::OfType resultType );
  1019. void handle( ResultWas::OfType resultType, StringRef const& message );
  1020. void handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated );
  1021. void handle( AssertionResultData const& resultData, ITransientExpression const* expr );
  1022. auto shouldDebugBreak() const -> bool;
  1023. auto allowThrows() const -> bool;
  1024. void reactWithDebugBreak() const;
  1025. void reactWithoutDebugBreak() const;
  1026. void useActiveException();
  1027. void setExceptionGuard();
  1028. void unsetExceptionGuard();
  1029. };
  1030. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1031. } // namespace Catch
  1032. // end catch_assertionhandler.h
  1033. // start catch_message.h
  1034. #include <string>
  1035. #include <sstream>
  1036. namespace Catch {
  1037. struct MessageInfo {
  1038. MessageInfo( std::string const& _macroName,
  1039. SourceLineInfo const& _lineInfo,
  1040. ResultWas::OfType _type );
  1041. std::string macroName;
  1042. std::string message;
  1043. SourceLineInfo lineInfo;
  1044. ResultWas::OfType type;
  1045. unsigned int sequence;
  1046. bool operator == ( MessageInfo const& other ) const;
  1047. bool operator < ( MessageInfo const& other ) const;
  1048. private:
  1049. static unsigned int globalCount;
  1050. };
  1051. struct MessageStream {
  1052. template<typename T>
  1053. MessageStream& operator << ( T const& value ) {
  1054. m_stream << value;
  1055. return *this;
  1056. }
  1057. // !TBD reuse a global/ thread-local stream
  1058. std::ostringstream m_stream;
  1059. };
  1060. struct MessageBuilder : MessageStream {
  1061. MessageBuilder( std::string const& macroName,
  1062. SourceLineInfo const& lineInfo,
  1063. ResultWas::OfType type );
  1064. template<typename T>
  1065. MessageBuilder& operator << ( T const& value ) {
  1066. m_stream << value;
  1067. return *this;
  1068. }
  1069. MessageInfo m_info;
  1070. };
  1071. class ScopedMessage {
  1072. public:
  1073. ScopedMessage( MessageBuilder const& builder );
  1074. ~ScopedMessage();
  1075. MessageInfo m_info;
  1076. };
  1077. } // end namespace Catch
  1078. // end catch_message.h
  1079. // start catch_interfaces_capture.h
  1080. #include <string>
  1081. namespace Catch {
  1082. class AssertionResult;
  1083. struct AssertionInfo;
  1084. struct SectionInfo;
  1085. struct SectionEndInfo;
  1086. struct MessageInfo;
  1087. struct Counts;
  1088. struct BenchmarkInfo;
  1089. struct BenchmarkStats;
  1090. struct IResultCapture {
  1091. virtual ~IResultCapture();
  1092. virtual void assertionStarting( AssertionInfo const& info ) = 0;
  1093. virtual void assertionEnded( AssertionResult const& result ) = 0;
  1094. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1095. Counts& assertions ) = 0;
  1096. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1097. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1098. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1099. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1100. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1101. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1102. virtual std::string getCurrentTestName() const = 0;
  1103. virtual const AssertionResult* getLastResult() const = 0;
  1104. virtual void exceptionEarlyReported() = 0;
  1105. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1106. virtual bool lastAssertionPassed() = 0;
  1107. virtual void assertionPassed() = 0;
  1108. virtual void assertionRun() = 0;
  1109. };
  1110. IResultCapture& getResultCapture();
  1111. }
  1112. // end catch_interfaces_capture.h
  1113. // start catch_debugger.h
  1114. namespace Catch {
  1115. bool isDebuggerActive();
  1116. }
  1117. #ifdef CATCH_PLATFORM_MAC
  1118. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  1119. #elif defined(CATCH_PLATFORM_LINUX)
  1120. // If we can use inline assembler, do it because this allows us to break
  1121. // directly at the location of the failing check instead of breaking inside
  1122. // raise() called from it, i.e. one stack frame below.
  1123. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  1124. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  1125. #else // Fall back to the generic way.
  1126. #include <signal.h>
  1127. #define CATCH_TRAP() raise(SIGTRAP)
  1128. #endif
  1129. #elif defined(_MSC_VER)
  1130. #define CATCH_TRAP() __debugbreak()
  1131. #elif defined(__MINGW32__)
  1132. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  1133. #define CATCH_TRAP() DebugBreak()
  1134. #endif
  1135. #ifdef CATCH_TRAP
  1136. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  1137. #else
  1138. #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
  1139. #endif
  1140. // end catch_debugger.h
  1141. #if !defined(CATCH_CONFIG_DISABLE)
  1142. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1143. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1144. #else
  1145. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1146. #endif
  1147. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1148. ///////////////////////////////////////////////////////////////////////////////
  1149. // We can speedup compilation significantly by breaking into debugger lower in
  1150. // the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
  1151. // macro in each assertion
  1152. #define INTERNAL_CATCH_REACT( handler ) \
  1153. handler.reactWithDebugBreak();
  1154. ///////////////////////////////////////////////////////////////////////////////
  1155. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1156. // macros.
  1157. // This can potentially cause false negative, if the test code catches
  1158. // the exception before it propagates back up to the runner.
  1159. #define INTERNAL_CATCH_TRY( capturer ) capturer.setExceptionGuard();
  1160. #define INTERNAL_CATCH_CATCH( capturer ) capturer.unsetExceptionGuard();
  1161. #else // CATCH_CONFIG_FAST_COMPILE
  1162. ///////////////////////////////////////////////////////////////////////////////
  1163. // In the event of a failure works out if the debugger needs to be invoked
  1164. // and/or an exception thrown and takes appropriate action.
  1165. // This needs to be done as a macro so the debugger will stop in the user
  1166. // source code rather than in Catch library code
  1167. #define INTERNAL_CATCH_REACT( handler ) \
  1168. if( handler.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
  1169. handler.reactWithoutDebugBreak();
  1170. #define INTERNAL_CATCH_TRY( capturer ) try
  1171. #define INTERNAL_CATCH_CATCH( capturer ) catch(...) { capturer.useActiveException(); }
  1172. #endif
  1173. ///////////////////////////////////////////////////////////////////////////////
  1174. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1175. do { \
  1176. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1177. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1178. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1179. catchAssertionHandler.handle( Catch::Decomposer() <= __VA_ARGS__ ); \
  1180. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1181. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1182. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1183. } while( Catch::isTrue( false && static_cast<bool>( !!(__VA_ARGS__) ) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  1184. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1185. ///////////////////////////////////////////////////////////////////////////////
  1186. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1187. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1188. if( Catch::getResultCapture().lastAssertionPassed() )
  1189. ///////////////////////////////////////////////////////////////////////////////
  1190. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1191. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1192. if( !Catch::getResultCapture().lastAssertionPassed() )
  1193. ///////////////////////////////////////////////////////////////////////////////
  1194. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1195. do { \
  1196. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1197. try { \
  1198. static_cast<void>(__VA_ARGS__); \
  1199. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1200. } \
  1201. catch( ... ) { \
  1202. catchAssertionHandler.useActiveException(); \
  1203. } \
  1204. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1205. } while( Catch::alwaysFalse() )
  1206. ///////////////////////////////////////////////////////////////////////////////
  1207. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1208. do { \
  1209. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1210. if( catchAssertionHandler.allowThrows() ) \
  1211. try { \
  1212. static_cast<void>(__VA_ARGS__); \
  1213. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1214. } \
  1215. catch( ... ) { \
  1216. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1217. } \
  1218. else \
  1219. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1220. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1221. } while( Catch::alwaysFalse() )
  1222. ///////////////////////////////////////////////////////////////////////////////
  1223. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1224. do { \
  1225. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1226. if( catchAssertionHandler.allowThrows() ) \
  1227. try { \
  1228. static_cast<void>(expr); \
  1229. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1230. } \
  1231. catch( exceptionType const& ) { \
  1232. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1233. } \
  1234. catch( ... ) { \
  1235. catchAssertionHandler.useActiveException(); \
  1236. } \
  1237. else \
  1238. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1239. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1240. } while( Catch::alwaysFalse() )
  1241. ///////////////////////////////////////////////////////////////////////////////
  1242. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1243. do { \
  1244. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1245. catchAssertionHandler.handle( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1246. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1247. } while( Catch::alwaysFalse() )
  1248. ///////////////////////////////////////////////////////////////////////////////
  1249. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1250. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
  1251. ///////////////////////////////////////////////////////////////////////////////
  1252. // Although this is matcher-based, it can be used with just a string
  1253. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1254. do { \
  1255. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1256. if( catchAssertionHandler.allowThrows() ) \
  1257. try { \
  1258. static_cast<void>(__VA_ARGS__); \
  1259. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1260. } \
  1261. catch( ... ) { \
  1262. handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1263. } \
  1264. else \
  1265. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1266. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1267. } while( Catch::alwaysFalse() )
  1268. #endif // CATCH_CONFIG_DISABLE
  1269. // end catch_capture.hpp
  1270. // start catch_section.h
  1271. // start catch_section_info.h
  1272. // start catch_totals.h
  1273. #include <cstddef>
  1274. namespace Catch {
  1275. struct Counts {
  1276. Counts operator - ( Counts const& other ) const;
  1277. Counts& operator += ( Counts const& other );
  1278. std::size_t total() const;
  1279. bool allPassed() const;
  1280. bool allOk() const;
  1281. std::size_t passed = 0;
  1282. std::size_t failed = 0;
  1283. std::size_t failedButOk = 0;
  1284. };
  1285. struct Totals {
  1286. Totals operator - ( Totals const& other ) const;
  1287. Totals& operator += ( Totals const& other );
  1288. Totals delta( Totals const& prevTotals ) const;
  1289. Counts assertions;
  1290. Counts testCases;
  1291. };
  1292. }
  1293. // end catch_totals.h
  1294. #include <string>
  1295. namespace Catch {
  1296. struct SectionInfo {
  1297. SectionInfo
  1298. ( SourceLineInfo const& _lineInfo,
  1299. std::string const& _name,
  1300. std::string const& _description = std::string() );
  1301. std::string name;
  1302. std::string description;
  1303. SourceLineInfo lineInfo;
  1304. };
  1305. struct SectionEndInfo {
  1306. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1307. SectionInfo sectionInfo;
  1308. Counts prevAssertions;
  1309. double durationInSeconds;
  1310. };
  1311. } // end namespace Catch
  1312. // end catch_section_info.h
  1313. // start catch_timer.h
  1314. #include <cstdint>
  1315. namespace Catch {
  1316. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1317. auto getEstimatedClockResolution() -> uint64_t;
  1318. class Timer {
  1319. uint64_t m_nanoseconds = 0;
  1320. public:
  1321. void start();
  1322. auto getElapsedNanoseconds() const -> unsigned int;
  1323. auto getElapsedMicroseconds() const -> unsigned int;
  1324. auto getElapsedMilliseconds() const -> unsigned int;
  1325. auto getElapsedSeconds() const -> double;
  1326. };
  1327. } // namespace Catch
  1328. // end catch_timer.h
  1329. #include <string>
  1330. namespace Catch {
  1331. class Section : NonCopyable {
  1332. public:
  1333. Section( SectionInfo const& info );
  1334. ~Section();
  1335. // This indicates whether the section should be executed or not
  1336. explicit operator bool() const;
  1337. private:
  1338. SectionInfo m_info;
  1339. std::string m_name;
  1340. Counts m_assertions;
  1341. bool m_sectionIncluded;
  1342. Timer m_timer;
  1343. };
  1344. } // end namespace Catch
  1345. #define INTERNAL_CATCH_SECTION( ... ) \
  1346. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1347. // end catch_section.h
  1348. // start catch_benchmark.h
  1349. #include <cstdint>
  1350. #include <string>
  1351. namespace Catch {
  1352. class BenchmarkLooper {
  1353. std::string m_name;
  1354. std::size_t m_count = 0;
  1355. std::size_t m_iterationsToRun = 1;
  1356. uint64_t m_resolution;
  1357. Timer m_timer;
  1358. static auto getResolution() -> uint64_t;
  1359. public:
  1360. // Keep most of this inline as it's on the code path that is being timed
  1361. BenchmarkLooper( StringRef name )
  1362. : m_name( name ),
  1363. m_resolution( getResolution() )
  1364. {
  1365. reportStart();
  1366. m_timer.start();
  1367. }
  1368. explicit operator bool() {
  1369. if( m_count < m_iterationsToRun )
  1370. return true;
  1371. return needsMoreIterations();
  1372. }
  1373. void increment() {
  1374. ++m_count;
  1375. }
  1376. void reportStart();
  1377. auto needsMoreIterations() -> bool;
  1378. };
  1379. } // end namespace Catch
  1380. #define BENCHMARK( name ) \
  1381. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1382. // end catch_benchmark.h
  1383. // start catch_interfaces_exception.h
  1384. // start catch_interfaces_registry_hub.h
  1385. #include <string>
  1386. #include <memory>
  1387. namespace Catch {
  1388. class TestCase;
  1389. struct ITestCaseRegistry;
  1390. struct IExceptionTranslatorRegistry;
  1391. struct IExceptionTranslator;
  1392. struct IReporterRegistry;
  1393. struct IReporterFactory;
  1394. struct ITagAliasRegistry;
  1395. class StartupExceptionRegistry;
  1396. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1397. struct IRegistryHub {
  1398. virtual ~IRegistryHub();
  1399. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1400. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1401. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1402. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1403. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1404. };
  1405. struct IMutableRegistryHub {
  1406. virtual ~IMutableRegistryHub();
  1407. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1408. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1409. virtual void registerTest( TestCase const& testInfo ) = 0;
  1410. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1411. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1412. virtual void registerStartupException() noexcept = 0;
  1413. };
  1414. IRegistryHub& getRegistryHub();
  1415. IMutableRegistryHub& getMutableRegistryHub();
  1416. void cleanUp();
  1417. std::string translateActiveException();
  1418. }
  1419. // end catch_interfaces_registry_hub.h
  1420. #if defined(CATCH_CONFIG_DISABLE)
  1421. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1422. static std::string translatorName( signature )
  1423. #endif
  1424. #include <exception>
  1425. #include <string>
  1426. #include <vector>
  1427. namespace Catch {
  1428. using exceptionTranslateFunction = std::string(*)();
  1429. struct IExceptionTranslator;
  1430. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1431. struct IExceptionTranslator {
  1432. virtual ~IExceptionTranslator();
  1433. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1434. };
  1435. struct IExceptionTranslatorRegistry {
  1436. virtual ~IExceptionTranslatorRegistry();
  1437. virtual std::string translateActiveException() const = 0;
  1438. };
  1439. class ExceptionTranslatorRegistrar {
  1440. template<typename T>
  1441. class ExceptionTranslator : public IExceptionTranslator {
  1442. public:
  1443. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1444. : m_translateFunction( translateFunction )
  1445. {}
  1446. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1447. try {
  1448. if( it == itEnd )
  1449. std::rethrow_exception(std::current_exception());
  1450. else
  1451. return (*it)->translate( it+1, itEnd );
  1452. }
  1453. catch( T& ex ) {
  1454. return m_translateFunction( ex );
  1455. }
  1456. }
  1457. protected:
  1458. std::string(*m_translateFunction)( T& );
  1459. };
  1460. public:
  1461. template<typename T>
  1462. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1463. getMutableRegistryHub().registerTranslator
  1464. ( new ExceptionTranslator<T>( translateFunction ) );
  1465. }
  1466. };
  1467. }
  1468. ///////////////////////////////////////////////////////////////////////////////
  1469. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1470. static std::string translatorName( signature ); \
  1471. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\
  1472. static std::string translatorName( signature )
  1473. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1474. // end catch_interfaces_exception.h
  1475. // start catch_approx.h
  1476. // start catch_enforce.h
  1477. #include <sstream>
  1478. #include <stdexcept>
  1479. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  1480. type( static_cast<std::ostringstream&&>( std::ostringstream() << msg ).str() )
  1481. #define CATCH_INTERNAL_ERROR( msg ) \
  1482. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  1483. #define CATCH_ERROR( msg ) \
  1484. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  1485. #define CATCH_ENFORCE( condition, msg ) \
  1486. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  1487. // end catch_enforce.h
  1488. #include <type_traits>
  1489. namespace Catch {
  1490. namespace Detail {
  1491. class Approx {
  1492. private:
  1493. bool equalityComparisonImpl(double other) const;
  1494. public:
  1495. explicit Approx ( double value );
  1496. static Approx custom();
  1497. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1498. Approx operator()( T const& value ) {
  1499. Approx approx( static_cast<double>(value) );
  1500. approx.epsilon( m_epsilon );
  1501. approx.margin( m_margin );
  1502. approx.scale( m_scale );
  1503. return approx;
  1504. }
  1505. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1506. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1507. {}
  1508. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1509. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1510. auto lhs_v = static_cast<double>(lhs);
  1511. return rhs.equalityComparisonImpl(lhs_v);
  1512. }
  1513. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1514. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1515. return operator==( rhs, lhs );
  1516. }
  1517. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1518. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1519. return !operator==( lhs, rhs );
  1520. }
  1521. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1522. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1523. return !operator==( rhs, lhs );
  1524. }
  1525. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1526. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1527. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1528. }
  1529. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1530. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1531. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1532. }
  1533. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1534. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1535. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1536. }
  1537. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1538. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1539. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1540. }
  1541. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1542. Approx& epsilon( T const& newEpsilon ) {
  1543. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1544. CATCH_ENFORCE(epsilonAsDouble >= 0 && epsilonAsDouble <= 1.0,
  1545. "Invalid Approx::epsilon: " << epsilonAsDouble
  1546. << ", Approx::epsilon has to be between 0 and 1");
  1547. m_epsilon = epsilonAsDouble;
  1548. return *this;
  1549. }
  1550. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1551. Approx& margin( T const& newMargin ) {
  1552. double marginAsDouble = static_cast<double>(newMargin);
  1553. CATCH_ENFORCE(marginAsDouble >= 0,
  1554. "Invalid Approx::margin: " << marginAsDouble
  1555. << ", Approx::Margin has to be non-negative.");
  1556. m_margin = marginAsDouble;
  1557. return *this;
  1558. }
  1559. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1560. Approx& scale( T const& newScale ) {
  1561. m_scale = static_cast<double>(newScale);
  1562. return *this;
  1563. }
  1564. std::string toString() const;
  1565. private:
  1566. double m_epsilon;
  1567. double m_margin;
  1568. double m_scale;
  1569. double m_value;
  1570. };
  1571. }
  1572. template<>
  1573. struct StringMaker<Catch::Detail::Approx> {
  1574. static std::string convert(Catch::Detail::Approx const& value);
  1575. };
  1576. } // end namespace Catch
  1577. // end catch_approx.h
  1578. // start catch_string_manip.h
  1579. #include <string>
  1580. #include <iosfwd>
  1581. namespace Catch {
  1582. bool startsWith( std::string const& s, std::string const& prefix );
  1583. bool startsWith( std::string const& s, char prefix );
  1584. bool endsWith( std::string const& s, std::string const& suffix );
  1585. bool endsWith( std::string const& s, char suffix );
  1586. bool contains( std::string const& s, std::string const& infix );
  1587. void toLowerInPlace( std::string& s );
  1588. std::string toLower( std::string const& s );
  1589. std::string trim( std::string const& str );
  1590. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1591. struct pluralise {
  1592. pluralise( std::size_t count, std::string const& label );
  1593. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1594. std::size_t m_count;
  1595. std::string m_label;
  1596. };
  1597. }
  1598. // end catch_string_manip.h
  1599. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1600. // start catch_capture_matchers.h
  1601. // start catch_matchers.h
  1602. #include <string>
  1603. #include <vector>
  1604. namespace Catch {
  1605. namespace Matchers {
  1606. namespace Impl {
  1607. template<typename ArgT> struct MatchAllOf;
  1608. template<typename ArgT> struct MatchAnyOf;
  1609. template<typename ArgT> struct MatchNotOf;
  1610. class MatcherUntypedBase {
  1611. public:
  1612. MatcherUntypedBase() = default;
  1613. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1614. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1615. std::string toString() const;
  1616. protected:
  1617. virtual ~MatcherUntypedBase();
  1618. virtual std::string describe() const = 0;
  1619. mutable std::string m_cachedToString;
  1620. };
  1621. template<typename ObjectT>
  1622. struct MatcherMethod {
  1623. virtual bool match( ObjectT const& arg ) const = 0;
  1624. };
  1625. template<typename PtrT>
  1626. struct MatcherMethod<PtrT*> {
  1627. virtual bool match( PtrT* arg ) const = 0;
  1628. };
  1629. template<typename ObjectT, typename ComparatorT = ObjectT>
  1630. struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
  1631. MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
  1632. MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
  1633. MatchNotOf<ComparatorT> operator ! () const;
  1634. };
  1635. template<typename ArgT>
  1636. struct MatchAllOf : MatcherBase<ArgT> {
  1637. bool match( ArgT const& arg ) const override {
  1638. for( auto matcher : m_matchers ) {
  1639. if (!matcher->match(arg))
  1640. return false;
  1641. }
  1642. return true;
  1643. }
  1644. std::string describe() const override {
  1645. std::string description;
  1646. description.reserve( 4 + m_matchers.size()*32 );
  1647. description += "( ";
  1648. bool first = true;
  1649. for( auto matcher : m_matchers ) {
  1650. if( first )
  1651. first = false;
  1652. else
  1653. description += " and ";
  1654. description += matcher->toString();
  1655. }
  1656. description += " )";
  1657. return description;
  1658. }
  1659. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1660. m_matchers.push_back( &other );
  1661. return *this;
  1662. }
  1663. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1664. };
  1665. template<typename ArgT>
  1666. struct MatchAnyOf : MatcherBase<ArgT> {
  1667. bool match( ArgT const& arg ) const override {
  1668. for( auto matcher : m_matchers ) {
  1669. if (matcher->match(arg))
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. std::string describe() const override {
  1675. std::string description;
  1676. description.reserve( 4 + m_matchers.size()*32 );
  1677. description += "( ";
  1678. bool first = true;
  1679. for( auto matcher : m_matchers ) {
  1680. if( first )
  1681. first = false;
  1682. else
  1683. description += " or ";
  1684. description += matcher->toString();
  1685. }
  1686. description += " )";
  1687. return description;
  1688. }
  1689. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1690. m_matchers.push_back( &other );
  1691. return *this;
  1692. }
  1693. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1694. };
  1695. template<typename ArgT>
  1696. struct MatchNotOf : MatcherBase<ArgT> {
  1697. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1698. bool match( ArgT const& arg ) const override {
  1699. return !m_underlyingMatcher.match( arg );
  1700. }
  1701. std::string describe() const override {
  1702. return "not " + m_underlyingMatcher.toString();
  1703. }
  1704. MatcherBase<ArgT> const& m_underlyingMatcher;
  1705. };
  1706. template<typename ObjectT, typename ComparatorT>
  1707. MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
  1708. return MatchAllOf<ComparatorT>() && *this && other;
  1709. }
  1710. template<typename ObjectT, typename ComparatorT>
  1711. MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
  1712. return MatchAnyOf<ComparatorT>() || *this || other;
  1713. }
  1714. template<typename ObjectT, typename ComparatorT>
  1715. MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
  1716. return MatchNotOf<ComparatorT>( *this );
  1717. }
  1718. } // namespace Impl
  1719. } // namespace Matchers
  1720. using namespace Matchers;
  1721. using Matchers::Impl::MatcherBase;
  1722. } // namespace Catch
  1723. // end catch_matchers.h
  1724. // start catch_matchers_string.h
  1725. #include <string>
  1726. namespace Catch {
  1727. namespace Matchers {
  1728. namespace StdString {
  1729. struct CasedString
  1730. {
  1731. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1732. std::string adjustString( std::string const& str ) const;
  1733. std::string caseSensitivitySuffix() const;
  1734. CaseSensitive::Choice m_caseSensitivity;
  1735. std::string m_str;
  1736. };
  1737. struct StringMatcherBase : MatcherBase<std::string> {
  1738. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1739. std::string describe() const override;
  1740. CasedString m_comparator;
  1741. std::string m_operation;
  1742. };
  1743. struct EqualsMatcher : StringMatcherBase {
  1744. EqualsMatcher( CasedString const& comparator );
  1745. bool match( std::string const& source ) const override;
  1746. };
  1747. struct ContainsMatcher : StringMatcherBase {
  1748. ContainsMatcher( CasedString const& comparator );
  1749. bool match( std::string const& source ) const override;
  1750. };
  1751. struct StartsWithMatcher : StringMatcherBase {
  1752. StartsWithMatcher( CasedString const& comparator );
  1753. bool match( std::string const& source ) const override;
  1754. };
  1755. struct EndsWithMatcher : StringMatcherBase {
  1756. EndsWithMatcher( CasedString const& comparator );
  1757. bool match( std::string const& source ) const override;
  1758. };
  1759. } // namespace StdString
  1760. // The following functions create the actual matcher objects.
  1761. // This allows the types to be inferred
  1762. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1763. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1764. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1765. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1766. } // namespace Matchers
  1767. } // namespace Catch
  1768. // end catch_matchers_string.h
  1769. // start catch_matchers_vector.h
  1770. namespace Catch {
  1771. namespace Matchers {
  1772. namespace Vector {
  1773. template<typename T>
  1774. struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
  1775. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1776. bool match(std::vector<T> const &v) const override {
  1777. for (auto const& el : v) {
  1778. if (el == m_comparator) {
  1779. return true;
  1780. }
  1781. }
  1782. return false;
  1783. }
  1784. std::string describe() const override {
  1785. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1786. }
  1787. T const& m_comparator;
  1788. };
  1789. template<typename T>
  1790. struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1791. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1792. bool match(std::vector<T> const &v) const override {
  1793. // !TBD: see note in EqualsMatcher
  1794. if (m_comparator.size() > v.size())
  1795. return false;
  1796. for (auto const& comparator : m_comparator) {
  1797. auto present = false;
  1798. for (const auto& el : v) {
  1799. if (el == comparator) {
  1800. present = true;
  1801. break;
  1802. }
  1803. }
  1804. if (!present) {
  1805. return false;
  1806. }
  1807. }
  1808. return true;
  1809. }
  1810. std::string describe() const override {
  1811. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1812. }
  1813. std::vector<T> const& m_comparator;
  1814. };
  1815. template<typename T>
  1816. struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1817. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1818. bool match(std::vector<T> const &v) const override {
  1819. // !TBD: This currently works if all elements can be compared using !=
  1820. // - a more general approach would be via a compare template that defaults
  1821. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  1822. // - then just call that directly
  1823. if (m_comparator.size() != v.size())
  1824. return false;
  1825. for (std::size_t i = 0; i < v.size(); ++i)
  1826. if (m_comparator[i] != v[i])
  1827. return false;
  1828. return true;
  1829. }
  1830. std::string describe() const override {
  1831. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  1832. }
  1833. std::vector<T> const& m_comparator;
  1834. };
  1835. } // namespace Vector
  1836. // The following functions create the actual matcher objects.
  1837. // This allows the types to be inferred
  1838. template<typename T>
  1839. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  1840. return Vector::ContainsMatcher<T>( comparator );
  1841. }
  1842. template<typename T>
  1843. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  1844. return Vector::ContainsElementMatcher<T>( comparator );
  1845. }
  1846. template<typename T>
  1847. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  1848. return Vector::EqualsMatcher<T>( comparator );
  1849. }
  1850. } // namespace Matchers
  1851. } // namespace Catch
  1852. // end catch_matchers_vector.h
  1853. namespace Catch {
  1854. template<typename ArgT, typename MatcherT>
  1855. class MatchExpr : public ITransientExpression {
  1856. ArgT const& m_arg;
  1857. MatcherT m_matcher;
  1858. StringRef m_matcherString;
  1859. bool m_result;
  1860. public:
  1861. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  1862. : m_arg( arg ),
  1863. m_matcher( matcher ),
  1864. m_matcherString( matcherString ),
  1865. m_result( matcher.match( arg ) )
  1866. {}
  1867. auto isBinaryExpression() const -> bool override { return true; }
  1868. auto getResult() const -> bool override { return m_result; }
  1869. void streamReconstructedExpression( std::ostream &os ) const override {
  1870. auto matcherAsString = m_matcher.toString();
  1871. os << Catch::Detail::stringify( m_arg ) << ' ';
  1872. if( matcherAsString == Detail::unprintableString )
  1873. os << m_matcherString;
  1874. else
  1875. os << matcherAsString;
  1876. }
  1877. };
  1878. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  1879. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  1880. template<typename ArgT, typename MatcherT>
  1881. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  1882. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  1883. }
  1884. } // namespace Catch
  1885. ///////////////////////////////////////////////////////////////////////////////
  1886. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  1887. do { \
  1888. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1889. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1890. catchAssertionHandler.handle( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  1891. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1892. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1893. } while( Catch::alwaysFalse() )
  1894. ///////////////////////////////////////////////////////////////////////////////
  1895. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  1896. do { \
  1897. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1898. if( catchAssertionHandler.allowThrows() ) \
  1899. try { \
  1900. static_cast<void>(__VA_ARGS__ ); \
  1901. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1902. } \
  1903. catch( exceptionType const& ex ) { \
  1904. catchAssertionHandler.handle( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  1905. } \
  1906. catch( ... ) { \
  1907. catchAssertionHandler.useActiveException(); \
  1908. } \
  1909. else \
  1910. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1911. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1912. } while( Catch::alwaysFalse() )
  1913. // end catch_capture_matchers.h
  1914. #endif
  1915. // These files are included here so the single_include script doesn't put them
  1916. // in the conditionally compiled sections
  1917. // start catch_test_case_info.h
  1918. #include <string>
  1919. #include <vector>
  1920. #include <memory>
  1921. #ifdef __clang__
  1922. #pragma clang diagnostic push
  1923. #pragma clang diagnostic ignored "-Wpadded"
  1924. #endif
  1925. namespace Catch {
  1926. struct ITestInvoker;
  1927. struct TestCaseInfo {
  1928. enum SpecialProperties{
  1929. None = 0,
  1930. IsHidden = 1 << 1,
  1931. ShouldFail = 1 << 2,
  1932. MayFail = 1 << 3,
  1933. Throws = 1 << 4,
  1934. NonPortable = 1 << 5,
  1935. Benchmark = 1 << 6
  1936. };
  1937. TestCaseInfo( std::string const& _name,
  1938. std::string const& _className,
  1939. std::string const& _description,
  1940. std::vector<std::string> const& _tags,
  1941. SourceLineInfo const& _lineInfo );
  1942. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  1943. bool isHidden() const;
  1944. bool throws() const;
  1945. bool okToFail() const;
  1946. bool expectedToFail() const;
  1947. std::string tagsAsString() const;
  1948. std::string name;
  1949. std::string className;
  1950. std::string description;
  1951. std::vector<std::string> tags;
  1952. std::vector<std::string> lcaseTags;
  1953. SourceLineInfo lineInfo;
  1954. SpecialProperties properties;
  1955. };
  1956. class TestCase : public TestCaseInfo {
  1957. public:
  1958. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  1959. TestCase withName( std::string const& _newName ) const;
  1960. void invoke() const;
  1961. TestCaseInfo const& getTestCaseInfo() const;
  1962. bool operator == ( TestCase const& other ) const;
  1963. bool operator < ( TestCase const& other ) const;
  1964. private:
  1965. std::shared_ptr<ITestInvoker> test;
  1966. };
  1967. TestCase makeTestCase( ITestInvoker* testCase,
  1968. std::string const& className,
  1969. std::string const& name,
  1970. std::string const& description,
  1971. SourceLineInfo const& lineInfo );
  1972. }
  1973. #ifdef __clang__
  1974. #pragma clang diagnostic pop
  1975. #endif
  1976. // end catch_test_case_info.h
  1977. // start catch_interfaces_runner.h
  1978. namespace Catch {
  1979. struct IRunner {
  1980. virtual ~IRunner();
  1981. virtual bool aborting() const = 0;
  1982. };
  1983. }
  1984. // end catch_interfaces_runner.h
  1985. #ifdef __OBJC__
  1986. // start catch_objc.hpp
  1987. #import <objc/runtime.h>
  1988. #include <string>
  1989. // NB. Any general catch headers included here must be included
  1990. // in catch.hpp first to make sure they are included by the single
  1991. // header for non obj-usage
  1992. ///////////////////////////////////////////////////////////////////////////////
  1993. // This protocol is really only here for (self) documenting purposes, since
  1994. // all its methods are optional.
  1995. @protocol OcFixture
  1996. @optional
  1997. -(void) setUp;
  1998. -(void) tearDown;
  1999. @end
  2000. namespace Catch {
  2001. class OcMethod : public ITestInvoker {
  2002. public:
  2003. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2004. virtual void invoke() const {
  2005. id obj = [[m_cls alloc] init];
  2006. performOptionalSelector( obj, @selector(setUp) );
  2007. performOptionalSelector( obj, m_sel );
  2008. performOptionalSelector( obj, @selector(tearDown) );
  2009. arcSafeRelease( obj );
  2010. }
  2011. private:
  2012. virtual ~OcMethod() {}
  2013. Class m_cls;
  2014. SEL m_sel;
  2015. };
  2016. namespace Detail{
  2017. inline std::string getAnnotation( Class cls,
  2018. std::string const& annotationName,
  2019. std::string const& testCaseName ) {
  2020. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2021. SEL sel = NSSelectorFromString( selStr );
  2022. arcSafeRelease( selStr );
  2023. id value = performOptionalSelector( cls, sel );
  2024. if( value )
  2025. return [(NSString*)value UTF8String];
  2026. return "";
  2027. }
  2028. }
  2029. inline std::size_t registerTestMethods() {
  2030. std::size_t noTestMethods = 0;
  2031. int noClasses = objc_getClassList( nullptr, 0 );
  2032. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2033. objc_getClassList( classes, noClasses );
  2034. for( int c = 0; c < noClasses; c++ ) {
  2035. Class cls = classes[c];
  2036. {
  2037. u_int count;
  2038. Method* methods = class_copyMethodList( cls, &count );
  2039. for( u_int m = 0; m < count ; m++ ) {
  2040. SEL selector = method_getName(methods[m]);
  2041. std::string methodName = sel_getName(selector);
  2042. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2043. std::string testCaseName = methodName.substr( 15 );
  2044. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2045. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2046. const char* className = class_getName( cls );
  2047. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2048. noTestMethods++;
  2049. }
  2050. }
  2051. free(methods);
  2052. }
  2053. }
  2054. return noTestMethods;
  2055. }
  2056. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2057. namespace Matchers {
  2058. namespace Impl {
  2059. namespace NSStringMatchers {
  2060. struct StringHolder : MatcherBase<NSString*>{
  2061. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2062. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2063. StringHolder() {
  2064. arcSafeRelease( m_substr );
  2065. }
  2066. bool match( NSString* arg ) const override {
  2067. return false;
  2068. }
  2069. NSString* CATCH_ARC_STRONG m_substr;
  2070. };
  2071. struct Equals : StringHolder {
  2072. Equals( NSString* substr ) : StringHolder( substr ){}
  2073. bool match( NSString* str ) const override {
  2074. return (str != nil || m_substr == nil ) &&
  2075. [str isEqualToString:m_substr];
  2076. }
  2077. std::string describe() const override {
  2078. return "equals string: " + Catch::Detail::stringify( m_substr );
  2079. }
  2080. };
  2081. struct Contains : StringHolder {
  2082. Contains( NSString* substr ) : StringHolder( substr ){}
  2083. bool match( NSString* str ) const {
  2084. return (str != nil || m_substr == nil ) &&
  2085. [str rangeOfString:m_substr].location != NSNotFound;
  2086. }
  2087. std::string describe() const override {
  2088. return "contains string: " + Catch::Detail::stringify( m_substr );
  2089. }
  2090. };
  2091. struct StartsWith : StringHolder {
  2092. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2093. bool match( NSString* str ) const override {
  2094. return (str != nil || m_substr == nil ) &&
  2095. [str rangeOfString:m_substr].location == 0;
  2096. }
  2097. std::string describe() const override {
  2098. return "starts with: " + Catch::Detail::stringify( m_substr );
  2099. }
  2100. };
  2101. struct EndsWith : StringHolder {
  2102. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2103. bool match( NSString* str ) const override {
  2104. return (str != nil || m_substr == nil ) &&
  2105. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2106. }
  2107. std::string describe() const override {
  2108. return "ends with: " + Catch::Detail::stringify( m_substr );
  2109. }
  2110. };
  2111. } // namespace NSStringMatchers
  2112. } // namespace Impl
  2113. inline Impl::NSStringMatchers::Equals
  2114. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2115. inline Impl::NSStringMatchers::Contains
  2116. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2117. inline Impl::NSStringMatchers::StartsWith
  2118. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2119. inline Impl::NSStringMatchers::EndsWith
  2120. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2121. } // namespace Matchers
  2122. using namespace Matchers;
  2123. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2124. } // namespace Catch
  2125. ///////////////////////////////////////////////////////////////////////////////
  2126. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2127. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2128. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2129. { \
  2130. return @ name; \
  2131. } \
  2132. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2133. { \
  2134. return @ desc; \
  2135. } \
  2136. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2137. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2138. // end catch_objc.hpp
  2139. #endif
  2140. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2141. // start catch_external_interfaces.h
  2142. // start catch_reporter_bases.hpp
  2143. // start catch_interfaces_reporter.h
  2144. // start catch_config.hpp
  2145. // start catch_test_spec_parser.h
  2146. #ifdef __clang__
  2147. #pragma clang diagnostic push
  2148. #pragma clang diagnostic ignored "-Wpadded"
  2149. #endif
  2150. // start catch_test_spec.h
  2151. #ifdef __clang__
  2152. #pragma clang diagnostic push
  2153. #pragma clang diagnostic ignored "-Wpadded"
  2154. #endif
  2155. // start catch_wildcard_pattern.h
  2156. namespace Catch
  2157. {
  2158. class WildcardPattern {
  2159. enum WildcardPosition {
  2160. NoWildcard = 0,
  2161. WildcardAtStart = 1,
  2162. WildcardAtEnd = 2,
  2163. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2164. };
  2165. public:
  2166. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2167. virtual ~WildcardPattern() = default;
  2168. virtual bool matches( std::string const& str ) const;
  2169. private:
  2170. std::string adjustCase( std::string const& str ) const;
  2171. CaseSensitive::Choice m_caseSensitivity;
  2172. WildcardPosition m_wildcard = NoWildcard;
  2173. std::string m_pattern;
  2174. };
  2175. }
  2176. // end catch_wildcard_pattern.h
  2177. #include <string>
  2178. #include <vector>
  2179. #include <memory>
  2180. namespace Catch {
  2181. class TestSpec {
  2182. struct Pattern {
  2183. virtual ~Pattern();
  2184. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2185. };
  2186. using PatternPtr = std::shared_ptr<Pattern>;
  2187. class NamePattern : public Pattern {
  2188. public:
  2189. NamePattern( std::string const& name );
  2190. virtual ~NamePattern();
  2191. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2192. private:
  2193. WildcardPattern m_wildcardPattern;
  2194. };
  2195. class TagPattern : public Pattern {
  2196. public:
  2197. TagPattern( std::string const& tag );
  2198. virtual ~TagPattern();
  2199. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2200. private:
  2201. std::string m_tag;
  2202. };
  2203. class ExcludedPattern : public Pattern {
  2204. public:
  2205. ExcludedPattern( PatternPtr const& underlyingPattern );
  2206. virtual ~ExcludedPattern();
  2207. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2208. private:
  2209. PatternPtr m_underlyingPattern;
  2210. };
  2211. struct Filter {
  2212. std::vector<PatternPtr> m_patterns;
  2213. bool matches( TestCaseInfo const& testCase ) const;
  2214. };
  2215. public:
  2216. bool hasFilters() const;
  2217. bool matches( TestCaseInfo const& testCase ) const;
  2218. private:
  2219. std::vector<Filter> m_filters;
  2220. friend class TestSpecParser;
  2221. };
  2222. }
  2223. #ifdef __clang__
  2224. #pragma clang diagnostic pop
  2225. #endif
  2226. // end catch_test_spec.h
  2227. // start catch_interfaces_tag_alias_registry.h
  2228. #include <string>
  2229. namespace Catch {
  2230. struct TagAlias;
  2231. struct ITagAliasRegistry {
  2232. virtual ~ITagAliasRegistry();
  2233. // Nullptr if not present
  2234. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2235. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2236. static ITagAliasRegistry const& get();
  2237. };
  2238. } // end namespace Catch
  2239. // end catch_interfaces_tag_alias_registry.h
  2240. namespace Catch {
  2241. class TestSpecParser {
  2242. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2243. Mode m_mode = None;
  2244. bool m_exclusion = false;
  2245. std::size_t m_start = std::string::npos, m_pos = 0;
  2246. std::string m_arg;
  2247. std::vector<std::size_t> m_escapeChars;
  2248. TestSpec::Filter m_currentFilter;
  2249. TestSpec m_testSpec;
  2250. ITagAliasRegistry const* m_tagAliases = nullptr;
  2251. public:
  2252. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2253. TestSpecParser& parse( std::string const& arg );
  2254. TestSpec testSpec();
  2255. private:
  2256. void visitChar( char c );
  2257. void startNewMode( Mode mode, std::size_t start );
  2258. void escape();
  2259. std::string subString() const;
  2260. template<typename T>
  2261. void addPattern() {
  2262. std::string token = subString();
  2263. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2264. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2265. m_escapeChars.clear();
  2266. if( startsWith( token, "exclude:" ) ) {
  2267. m_exclusion = true;
  2268. token = token.substr( 8 );
  2269. }
  2270. if( !token.empty() ) {
  2271. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2272. if( m_exclusion )
  2273. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2274. m_currentFilter.m_patterns.push_back( pattern );
  2275. }
  2276. m_exclusion = false;
  2277. m_mode = None;
  2278. }
  2279. void addFilter();
  2280. };
  2281. TestSpec parseTestSpec( std::string const& arg );
  2282. } // namespace Catch
  2283. #ifdef __clang__
  2284. #pragma clang diagnostic pop
  2285. #endif
  2286. // end catch_test_spec_parser.h
  2287. // start catch_interfaces_config.h
  2288. #include <iosfwd>
  2289. #include <string>
  2290. #include <vector>
  2291. #include <memory>
  2292. namespace Catch {
  2293. enum class Verbosity {
  2294. Quiet = 0,
  2295. Normal,
  2296. High
  2297. };
  2298. struct WarnAbout { enum What {
  2299. Nothing = 0x00,
  2300. NoAssertions = 0x01
  2301. }; };
  2302. struct ShowDurations { enum OrNot {
  2303. DefaultForReporter,
  2304. Always,
  2305. Never
  2306. }; };
  2307. struct RunTests { enum InWhatOrder {
  2308. InDeclarationOrder,
  2309. InLexicographicalOrder,
  2310. InRandomOrder
  2311. }; };
  2312. struct UseColour { enum YesOrNo {
  2313. Auto,
  2314. Yes,
  2315. No
  2316. }; };
  2317. struct WaitForKeypress { enum When {
  2318. Never,
  2319. BeforeStart = 1,
  2320. BeforeExit = 2,
  2321. BeforeStartAndExit = BeforeStart | BeforeExit
  2322. }; };
  2323. class TestSpec;
  2324. struct IConfig : NonCopyable {
  2325. virtual ~IConfig();
  2326. virtual bool allowThrows() const = 0;
  2327. virtual std::ostream& stream() const = 0;
  2328. virtual std::string name() const = 0;
  2329. virtual bool includeSuccessfulResults() const = 0;
  2330. virtual bool shouldDebugBreak() const = 0;
  2331. virtual bool warnAboutMissingAssertions() const = 0;
  2332. virtual int abortAfter() const = 0;
  2333. virtual bool showInvisibles() const = 0;
  2334. virtual ShowDurations::OrNot showDurations() const = 0;
  2335. virtual TestSpec const& testSpec() const = 0;
  2336. virtual RunTests::InWhatOrder runOrder() const = 0;
  2337. virtual unsigned int rngSeed() const = 0;
  2338. virtual int benchmarkResolutionMultiple() const = 0;
  2339. virtual UseColour::YesOrNo useColour() const = 0;
  2340. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2341. virtual Verbosity verbosity() const = 0;
  2342. };
  2343. using IConfigPtr = std::shared_ptr<IConfig const>;
  2344. }
  2345. // end catch_interfaces_config.h
  2346. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2347. // start catch_stream.h
  2348. // start catch_streambuf.h
  2349. #include <streambuf>
  2350. namespace Catch {
  2351. class StreamBufBase : public std::streambuf {
  2352. public:
  2353. virtual ~StreamBufBase();
  2354. };
  2355. }
  2356. // end catch_streambuf.h
  2357. #include <streambuf>
  2358. #include <ostream>
  2359. #include <fstream>
  2360. #include <memory>
  2361. namespace Catch {
  2362. std::ostream& cout();
  2363. std::ostream& cerr();
  2364. std::ostream& clog();
  2365. struct IStream {
  2366. virtual ~IStream();
  2367. virtual std::ostream& stream() const = 0;
  2368. };
  2369. class FileStream : public IStream {
  2370. mutable std::ofstream m_ofs;
  2371. public:
  2372. FileStream( std::string const& filename );
  2373. ~FileStream() override = default;
  2374. public: // IStream
  2375. std::ostream& stream() const override;
  2376. };
  2377. class CoutStream : public IStream {
  2378. mutable std::ostream m_os;
  2379. public:
  2380. CoutStream();
  2381. ~CoutStream() override = default;
  2382. public: // IStream
  2383. std::ostream& stream() const override;
  2384. };
  2385. class DebugOutStream : public IStream {
  2386. std::unique_ptr<StreamBufBase> m_streamBuf;
  2387. mutable std::ostream m_os;
  2388. public:
  2389. DebugOutStream();
  2390. ~DebugOutStream() override = default;
  2391. public: // IStream
  2392. std::ostream& stream() const override;
  2393. };
  2394. }
  2395. // end catch_stream.h
  2396. #include <memory>
  2397. #include <vector>
  2398. #include <string>
  2399. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2400. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2401. #endif
  2402. namespace Catch {
  2403. struct IStream;
  2404. struct ConfigData {
  2405. bool listTests = false;
  2406. bool listTags = false;
  2407. bool listReporters = false;
  2408. bool listTestNamesOnly = false;
  2409. bool showSuccessfulTests = false;
  2410. bool shouldDebugBreak = false;
  2411. bool noThrow = false;
  2412. bool showHelp = false;
  2413. bool showInvisibles = false;
  2414. bool filenamesAsTags = false;
  2415. bool libIdentify = false;
  2416. int abortAfter = -1;
  2417. unsigned int rngSeed = 0;
  2418. int benchmarkResolutionMultiple = 100;
  2419. Verbosity verbosity = Verbosity::Normal;
  2420. WarnAbout::What warnings = WarnAbout::Nothing;
  2421. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2422. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2423. UseColour::YesOrNo useColour = UseColour::Auto;
  2424. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2425. std::string outputFilename;
  2426. std::string name;
  2427. std::string processName;
  2428. std::vector<std::string> reporterNames;
  2429. std::vector<std::string> testsOrTags;
  2430. std::vector<std::string> sectionsToRun;
  2431. };
  2432. class Config : public IConfig {
  2433. public:
  2434. Config() = default;
  2435. Config( ConfigData const& data );
  2436. virtual ~Config() = default;
  2437. std::string const& getFilename() const;
  2438. bool listTests() const;
  2439. bool listTestNamesOnly() const;
  2440. bool listTags() const;
  2441. bool listReporters() const;
  2442. std::string getProcessName() const;
  2443. std::vector<std::string> const& getReporterNames() const;
  2444. std::vector<std::string> const& getSectionsToRun() const override;
  2445. virtual TestSpec const& testSpec() const override;
  2446. bool showHelp() const;
  2447. // IConfig interface
  2448. bool allowThrows() const override;
  2449. std::ostream& stream() const override;
  2450. std::string name() const override;
  2451. bool includeSuccessfulResults() const override;
  2452. bool warnAboutMissingAssertions() const override;
  2453. ShowDurations::OrNot showDurations() const override;
  2454. RunTests::InWhatOrder runOrder() const override;
  2455. unsigned int rngSeed() const override;
  2456. int benchmarkResolutionMultiple() const override;
  2457. UseColour::YesOrNo useColour() const override;
  2458. bool shouldDebugBreak() const override;
  2459. int abortAfter() const override;
  2460. bool showInvisibles() const override;
  2461. Verbosity verbosity() const override;
  2462. private:
  2463. IStream const* openStream();
  2464. ConfigData m_data;
  2465. std::unique_ptr<IStream const> m_stream;
  2466. TestSpec m_testSpec;
  2467. };
  2468. } // end namespace Catch
  2469. // end catch_config.hpp
  2470. // start catch_assertionresult.h
  2471. #include <string>
  2472. namespace Catch {
  2473. struct AssertionResultData
  2474. {
  2475. AssertionResultData() = delete;
  2476. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2477. std::string message;
  2478. mutable std::string reconstructedExpression;
  2479. LazyExpression lazyExpression;
  2480. ResultWas::OfType resultType;
  2481. std::string reconstructExpression() const;
  2482. };
  2483. class AssertionResult {
  2484. public:
  2485. AssertionResult() = delete;
  2486. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2487. bool isOk() const;
  2488. bool succeeded() const;
  2489. ResultWas::OfType getResultType() const;
  2490. bool hasExpression() const;
  2491. bool hasMessage() const;
  2492. std::string getExpression() const;
  2493. std::string getExpressionInMacro() const;
  2494. bool hasExpandedExpression() const;
  2495. std::string getExpandedExpression() const;
  2496. std::string getMessage() const;
  2497. SourceLineInfo getSourceInfo() const;
  2498. std::string getTestMacroName() const;
  2499. //protected:
  2500. AssertionInfo m_info;
  2501. AssertionResultData m_resultData;
  2502. };
  2503. } // end namespace Catch
  2504. // end catch_assertionresult.h
  2505. // start catch_option.hpp
  2506. namespace Catch {
  2507. // An optional type
  2508. template<typename T>
  2509. class Option {
  2510. public:
  2511. Option() : nullableValue( nullptr ) {}
  2512. Option( T const& _value )
  2513. : nullableValue( new( storage ) T( _value ) )
  2514. {}
  2515. Option( Option const& _other )
  2516. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2517. {}
  2518. ~Option() {
  2519. reset();
  2520. }
  2521. Option& operator= ( Option const& _other ) {
  2522. if( &_other != this ) {
  2523. reset();
  2524. if( _other )
  2525. nullableValue = new( storage ) T( *_other );
  2526. }
  2527. return *this;
  2528. }
  2529. Option& operator = ( T const& _value ) {
  2530. reset();
  2531. nullableValue = new( storage ) T( _value );
  2532. return *this;
  2533. }
  2534. void reset() {
  2535. if( nullableValue )
  2536. nullableValue->~T();
  2537. nullableValue = nullptr;
  2538. }
  2539. T& operator*() { return *nullableValue; }
  2540. T const& operator*() const { return *nullableValue; }
  2541. T* operator->() { return nullableValue; }
  2542. const T* operator->() const { return nullableValue; }
  2543. T valueOr( T const& defaultValue ) const {
  2544. return nullableValue ? *nullableValue : defaultValue;
  2545. }
  2546. bool some() const { return nullableValue != nullptr; }
  2547. bool none() const { return nullableValue == nullptr; }
  2548. bool operator !() const { return nullableValue == nullptr; }
  2549. explicit operator bool() const {
  2550. return some();
  2551. }
  2552. private:
  2553. T *nullableValue;
  2554. alignas(alignof(T)) char storage[sizeof(T)];
  2555. };
  2556. } // end namespace Catch
  2557. // end catch_option.hpp
  2558. #include <string>
  2559. #include <iosfwd>
  2560. #include <map>
  2561. #include <set>
  2562. #include <memory>
  2563. namespace Catch {
  2564. struct ReporterConfig {
  2565. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2566. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2567. std::ostream& stream() const;
  2568. IConfigPtr fullConfig() const;
  2569. private:
  2570. std::ostream* m_stream;
  2571. IConfigPtr m_fullConfig;
  2572. };
  2573. struct ReporterPreferences {
  2574. bool shouldRedirectStdOut = false;
  2575. };
  2576. template<typename T>
  2577. struct LazyStat : Option<T> {
  2578. LazyStat& operator=( T const& _value ) {
  2579. Option<T>::operator=( _value );
  2580. used = false;
  2581. return *this;
  2582. }
  2583. void reset() {
  2584. Option<T>::reset();
  2585. used = false;
  2586. }
  2587. bool used = false;
  2588. };
  2589. struct TestRunInfo {
  2590. TestRunInfo( std::string const& _name );
  2591. std::string name;
  2592. };
  2593. struct GroupInfo {
  2594. GroupInfo( std::string const& _name,
  2595. std::size_t _groupIndex,
  2596. std::size_t _groupsCount );
  2597. std::string name;
  2598. std::size_t groupIndex;
  2599. std::size_t groupsCounts;
  2600. };
  2601. struct AssertionStats {
  2602. AssertionStats( AssertionResult const& _assertionResult,
  2603. std::vector<MessageInfo> const& _infoMessages,
  2604. Totals const& _totals );
  2605. AssertionStats( AssertionStats const& ) = default;
  2606. AssertionStats( AssertionStats && ) = default;
  2607. AssertionStats& operator = ( AssertionStats const& ) = default;
  2608. AssertionStats& operator = ( AssertionStats && ) = default;
  2609. virtual ~AssertionStats();
  2610. AssertionResult assertionResult;
  2611. std::vector<MessageInfo> infoMessages;
  2612. Totals totals;
  2613. };
  2614. struct SectionStats {
  2615. SectionStats( SectionInfo const& _sectionInfo,
  2616. Counts const& _assertions,
  2617. double _durationInSeconds,
  2618. bool _missingAssertions );
  2619. SectionStats( SectionStats const& ) = default;
  2620. SectionStats( SectionStats && ) = default;
  2621. SectionStats& operator = ( SectionStats const& ) = default;
  2622. SectionStats& operator = ( SectionStats && ) = default;
  2623. virtual ~SectionStats();
  2624. SectionInfo sectionInfo;
  2625. Counts assertions;
  2626. double durationInSeconds;
  2627. bool missingAssertions;
  2628. };
  2629. struct TestCaseStats {
  2630. TestCaseStats( TestCaseInfo const& _testInfo,
  2631. Totals const& _totals,
  2632. std::string const& _stdOut,
  2633. std::string const& _stdErr,
  2634. bool _aborting );
  2635. TestCaseStats( TestCaseStats const& ) = default;
  2636. TestCaseStats( TestCaseStats && ) = default;
  2637. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2638. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2639. virtual ~TestCaseStats();
  2640. TestCaseInfo testInfo;
  2641. Totals totals;
  2642. std::string stdOut;
  2643. std::string stdErr;
  2644. bool aborting;
  2645. };
  2646. struct TestGroupStats {
  2647. TestGroupStats( GroupInfo const& _groupInfo,
  2648. Totals const& _totals,
  2649. bool _aborting );
  2650. TestGroupStats( GroupInfo const& _groupInfo );
  2651. TestGroupStats( TestGroupStats const& ) = default;
  2652. TestGroupStats( TestGroupStats && ) = default;
  2653. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2654. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2655. virtual ~TestGroupStats();
  2656. GroupInfo groupInfo;
  2657. Totals totals;
  2658. bool aborting;
  2659. };
  2660. struct TestRunStats {
  2661. TestRunStats( TestRunInfo const& _runInfo,
  2662. Totals const& _totals,
  2663. bool _aborting );
  2664. TestRunStats( TestRunStats const& ) = default;
  2665. TestRunStats( TestRunStats && ) = default;
  2666. TestRunStats& operator = ( TestRunStats const& ) = default;
  2667. TestRunStats& operator = ( TestRunStats && ) = default;
  2668. virtual ~TestRunStats();
  2669. TestRunInfo runInfo;
  2670. Totals totals;
  2671. bool aborting;
  2672. };
  2673. struct BenchmarkInfo {
  2674. std::string name;
  2675. };
  2676. struct BenchmarkStats {
  2677. BenchmarkInfo info;
  2678. std::size_t iterations;
  2679. uint64_t elapsedTimeInNanoseconds;
  2680. };
  2681. struct IStreamingReporter {
  2682. virtual ~IStreamingReporter() = default;
  2683. // Implementing class must also provide the following static methods:
  2684. // static std::string getDescription();
  2685. // static std::set<Verbosity> getSupportedVerbosities()
  2686. virtual ReporterPreferences getPreferences() const = 0;
  2687. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2688. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2689. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2690. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2691. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2692. // *** experimental ***
  2693. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2694. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2695. // The return value indicates if the messages buffer should be cleared:
  2696. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2697. // *** experimental ***
  2698. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2699. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2700. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2701. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2702. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2703. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2704. // Default empty implementation provided
  2705. virtual void fatalErrorEncountered( StringRef name );
  2706. virtual bool isMulti() const;
  2707. };
  2708. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2709. struct IReporterFactory {
  2710. virtual ~IReporterFactory();
  2711. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2712. virtual std::string getDescription() const = 0;
  2713. };
  2714. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2715. struct IReporterRegistry {
  2716. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2717. using Listeners = std::vector<IReporterFactoryPtr>;
  2718. virtual ~IReporterRegistry();
  2719. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2720. virtual FactoryMap const& getFactories() const = 0;
  2721. virtual Listeners const& getListeners() const = 0;
  2722. };
  2723. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2724. } // end namespace Catch
  2725. // end catch_interfaces_reporter.h
  2726. #include <algorithm>
  2727. #include <cstring>
  2728. #include <cfloat>
  2729. #include <cstdio>
  2730. #include <assert.h>
  2731. #include <memory>
  2732. namespace Catch {
  2733. void prepareExpandedExpression(AssertionResult& result);
  2734. // Returns double formatted as %.3f (format expected on output)
  2735. std::string getFormattedDuration( double duration );
  2736. template<typename DerivedT>
  2737. struct StreamingReporterBase : IStreamingReporter {
  2738. StreamingReporterBase( ReporterConfig const& _config )
  2739. : m_config( _config.fullConfig() ),
  2740. stream( _config.stream() )
  2741. {
  2742. m_reporterPrefs.shouldRedirectStdOut = false;
  2743. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2744. }
  2745. ReporterPreferences getPreferences() const override {
  2746. return m_reporterPrefs;
  2747. }
  2748. static std::set<Verbosity> getSupportedVerbosities() {
  2749. return { Verbosity::Normal };
  2750. }
  2751. ~StreamingReporterBase() override = default;
  2752. void noMatchingTestCases(std::string const&) override {}
  2753. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2754. currentTestRunInfo = _testRunInfo;
  2755. }
  2756. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2757. currentGroupInfo = _groupInfo;
  2758. }
  2759. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2760. currentTestCaseInfo = _testInfo;
  2761. }
  2762. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2763. m_sectionStack.push_back(_sectionInfo);
  2764. }
  2765. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2766. m_sectionStack.pop_back();
  2767. }
  2768. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2769. currentTestCaseInfo.reset();
  2770. }
  2771. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2772. currentGroupInfo.reset();
  2773. }
  2774. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2775. currentTestCaseInfo.reset();
  2776. currentGroupInfo.reset();
  2777. currentTestRunInfo.reset();
  2778. }
  2779. void skipTest(TestCaseInfo const&) override {
  2780. // Don't do anything with this by default.
  2781. // It can optionally be overridden in the derived class.
  2782. }
  2783. IConfigPtr m_config;
  2784. std::ostream& stream;
  2785. LazyStat<TestRunInfo> currentTestRunInfo;
  2786. LazyStat<GroupInfo> currentGroupInfo;
  2787. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2788. std::vector<SectionInfo> m_sectionStack;
  2789. ReporterPreferences m_reporterPrefs;
  2790. };
  2791. template<typename DerivedT>
  2792. struct CumulativeReporterBase : IStreamingReporter {
  2793. template<typename T, typename ChildNodeT>
  2794. struct Node {
  2795. explicit Node( T const& _value ) : value( _value ) {}
  2796. virtual ~Node() {}
  2797. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2798. T value;
  2799. ChildNodes children;
  2800. };
  2801. struct SectionNode {
  2802. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2803. virtual ~SectionNode() = default;
  2804. bool operator == (SectionNode const& other) const {
  2805. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2806. }
  2807. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2808. return operator==(*other);
  2809. }
  2810. SectionStats stats;
  2811. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2812. using Assertions = std::vector<AssertionStats>;
  2813. ChildSections childSections;
  2814. Assertions assertions;
  2815. std::string stdOut;
  2816. std::string stdErr;
  2817. };
  2818. struct BySectionInfo {
  2819. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  2820. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  2821. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  2822. return ((node->stats.sectionInfo.name == m_other.name) &&
  2823. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  2824. }
  2825. void operator=(BySectionInfo const&) = delete;
  2826. private:
  2827. SectionInfo const& m_other;
  2828. };
  2829. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  2830. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  2831. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  2832. CumulativeReporterBase( ReporterConfig const& _config )
  2833. : m_config( _config.fullConfig() ),
  2834. stream( _config.stream() )
  2835. {
  2836. m_reporterPrefs.shouldRedirectStdOut = false;
  2837. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2838. }
  2839. ~CumulativeReporterBase() override = default;
  2840. ReporterPreferences getPreferences() const override {
  2841. return m_reporterPrefs;
  2842. }
  2843. static std::set<Verbosity> getSupportedVerbosities() {
  2844. return { Verbosity::Normal };
  2845. }
  2846. void testRunStarting( TestRunInfo const& ) override {}
  2847. void testGroupStarting( GroupInfo const& ) override {}
  2848. void testCaseStarting( TestCaseInfo const& ) override {}
  2849. void sectionStarting( SectionInfo const& sectionInfo ) override {
  2850. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  2851. std::shared_ptr<SectionNode> node;
  2852. if( m_sectionStack.empty() ) {
  2853. if( !m_rootSection )
  2854. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  2855. node = m_rootSection;
  2856. }
  2857. else {
  2858. SectionNode& parentNode = *m_sectionStack.back();
  2859. auto it =
  2860. std::find_if( parentNode.childSections.begin(),
  2861. parentNode.childSections.end(),
  2862. BySectionInfo( sectionInfo ) );
  2863. if( it == parentNode.childSections.end() ) {
  2864. node = std::make_shared<SectionNode>( incompleteStats );
  2865. parentNode.childSections.push_back( node );
  2866. }
  2867. else
  2868. node = *it;
  2869. }
  2870. m_sectionStack.push_back( node );
  2871. m_deepestSection = std::move(node);
  2872. }
  2873. void assertionStarting(AssertionInfo const&) override {}
  2874. bool assertionEnded(AssertionStats const& assertionStats) override {
  2875. assert(!m_sectionStack.empty());
  2876. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  2877. // which getExpandedExpression() calls to build the expression string.
  2878. // Our section stack copy of the assertionResult will likely outlive the
  2879. // temporary, so it must be expanded or discarded now to avoid calling
  2880. // a destroyed object later.
  2881. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  2882. SectionNode& sectionNode = *m_sectionStack.back();
  2883. sectionNode.assertions.push_back(assertionStats);
  2884. return true;
  2885. }
  2886. void sectionEnded(SectionStats const& sectionStats) override {
  2887. assert(!m_sectionStack.empty());
  2888. SectionNode& node = *m_sectionStack.back();
  2889. node.stats = sectionStats;
  2890. m_sectionStack.pop_back();
  2891. }
  2892. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  2893. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  2894. assert(m_sectionStack.size() == 0);
  2895. node->children.push_back(m_rootSection);
  2896. m_testCases.push_back(node);
  2897. m_rootSection.reset();
  2898. assert(m_deepestSection);
  2899. m_deepestSection->stdOut = testCaseStats.stdOut;
  2900. m_deepestSection->stdErr = testCaseStats.stdErr;
  2901. }
  2902. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  2903. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  2904. node->children.swap(m_testCases);
  2905. m_testGroups.push_back(node);
  2906. }
  2907. void testRunEnded(TestRunStats const& testRunStats) override {
  2908. auto node = std::make_shared<TestRunNode>(testRunStats);
  2909. node->children.swap(m_testGroups);
  2910. m_testRuns.push_back(node);
  2911. testRunEndedCumulative();
  2912. }
  2913. virtual void testRunEndedCumulative() = 0;
  2914. void skipTest(TestCaseInfo const&) override {}
  2915. IConfigPtr m_config;
  2916. std::ostream& stream;
  2917. std::vector<AssertionStats> m_assertions;
  2918. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  2919. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  2920. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  2921. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  2922. std::shared_ptr<SectionNode> m_rootSection;
  2923. std::shared_ptr<SectionNode> m_deepestSection;
  2924. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  2925. ReporterPreferences m_reporterPrefs;
  2926. };
  2927. template<char C>
  2928. char const* getLineOfChars() {
  2929. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  2930. if( !*line ) {
  2931. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  2932. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  2933. }
  2934. return line;
  2935. }
  2936. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  2937. TestEventListenerBase( ReporterConfig const& _config );
  2938. void assertionStarting(AssertionInfo const&) override;
  2939. bool assertionEnded(AssertionStats const&) override;
  2940. };
  2941. } // end namespace Catch
  2942. // end catch_reporter_bases.hpp
  2943. // start catch_console_colour.h
  2944. namespace Catch {
  2945. struct Colour {
  2946. enum Code {
  2947. None = 0,
  2948. White,
  2949. Red,
  2950. Green,
  2951. Blue,
  2952. Cyan,
  2953. Yellow,
  2954. Grey,
  2955. Bright = 0x10,
  2956. BrightRed = Bright | Red,
  2957. BrightGreen = Bright | Green,
  2958. LightGrey = Bright | Grey,
  2959. BrightWhite = Bright | White,
  2960. // By intention
  2961. FileName = LightGrey,
  2962. Warning = Yellow,
  2963. ResultError = BrightRed,
  2964. ResultSuccess = BrightGreen,
  2965. ResultExpectedFailure = Warning,
  2966. Error = BrightRed,
  2967. Success = Green,
  2968. OriginalExpression = Cyan,
  2969. ReconstructedExpression = Yellow,
  2970. SecondaryText = LightGrey,
  2971. Headers = White
  2972. };
  2973. // Use constructed object for RAII guard
  2974. Colour( Code _colourCode );
  2975. Colour( Colour&& other ) noexcept;
  2976. Colour& operator=( Colour&& other ) noexcept;
  2977. ~Colour();
  2978. // Use static method for one-shot changes
  2979. static void use( Code _colourCode );
  2980. private:
  2981. bool m_moved = false;
  2982. };
  2983. std::ostream& operator << ( std::ostream& os, Colour const& );
  2984. } // end namespace Catch
  2985. // end catch_console_colour.h
  2986. // start catch_reporter_registrars.hpp
  2987. namespace Catch {
  2988. template<typename T>
  2989. class ReporterRegistrar {
  2990. class ReporterFactory : public IReporterFactory {
  2991. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  2992. return std::unique_ptr<T>( new T( config ) );
  2993. }
  2994. virtual std::string getDescription() const override {
  2995. return T::getDescription();
  2996. }
  2997. };
  2998. public:
  2999. ReporterRegistrar( std::string const& name ) {
  3000. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3001. }
  3002. };
  3003. template<typename T>
  3004. class ListenerRegistrar {
  3005. class ListenerFactory : public IReporterFactory {
  3006. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3007. return std::unique_ptr<T>( new T( config ) );
  3008. }
  3009. virtual std::string getDescription() const override {
  3010. return std::string();
  3011. }
  3012. };
  3013. public:
  3014. ListenerRegistrar() {
  3015. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3016. }
  3017. };
  3018. }
  3019. #if !defined(CATCH_CONFIG_DISABLE)
  3020. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3021. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3022. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3023. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3024. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3025. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3026. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3027. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3028. #else // CATCH_CONFIG_DISABLE
  3029. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3030. #define CATCH_REGISTER_LISTENER(listenerType)
  3031. #endif // CATCH_CONFIG_DISABLE
  3032. // end catch_reporter_registrars.hpp
  3033. // end catch_external_interfaces.h
  3034. #endif
  3035. #ifdef CATCH_IMPL
  3036. // start catch_impl.hpp
  3037. #ifdef __clang__
  3038. #pragma clang diagnostic push
  3039. #pragma clang diagnostic ignored "-Wweak-vtables"
  3040. #endif
  3041. // Keep these here for external reporters
  3042. // start catch_test_case_tracker.h
  3043. #include <string>
  3044. #include <vector>
  3045. #include <memory>
  3046. namespace Catch {
  3047. namespace TestCaseTracking {
  3048. struct NameAndLocation {
  3049. std::string name;
  3050. SourceLineInfo location;
  3051. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3052. };
  3053. struct ITracker;
  3054. using ITrackerPtr = std::shared_ptr<ITracker>;
  3055. struct ITracker {
  3056. virtual ~ITracker();
  3057. // static queries
  3058. virtual NameAndLocation const& nameAndLocation() const = 0;
  3059. // dynamic queries
  3060. virtual bool isComplete() const = 0; // Successfully completed or failed
  3061. virtual bool isSuccessfullyCompleted() const = 0;
  3062. virtual bool isOpen() const = 0; // Started but not complete
  3063. virtual bool hasChildren() const = 0;
  3064. virtual ITracker& parent() = 0;
  3065. // actions
  3066. virtual void close() = 0; // Successfully complete
  3067. virtual void fail() = 0;
  3068. virtual void markAsNeedingAnotherRun() = 0;
  3069. virtual void addChild( ITrackerPtr const& child ) = 0;
  3070. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3071. virtual void openChild() = 0;
  3072. // Debug/ checking
  3073. virtual bool isSectionTracker() const = 0;
  3074. virtual bool isIndexTracker() const = 0;
  3075. };
  3076. class TrackerContext {
  3077. enum RunState {
  3078. NotStarted,
  3079. Executing,
  3080. CompletedCycle
  3081. };
  3082. ITrackerPtr m_rootTracker;
  3083. ITracker* m_currentTracker = nullptr;
  3084. RunState m_runState = NotStarted;
  3085. public:
  3086. static TrackerContext& instance();
  3087. ITracker& startRun();
  3088. void endRun();
  3089. void startCycle();
  3090. void completeCycle();
  3091. bool completedCycle() const;
  3092. ITracker& currentTracker();
  3093. void setCurrentTracker( ITracker* tracker );
  3094. };
  3095. class TrackerBase : public ITracker {
  3096. protected:
  3097. enum CycleState {
  3098. NotStarted,
  3099. Executing,
  3100. ExecutingChildren,
  3101. NeedsAnotherRun,
  3102. CompletedSuccessfully,
  3103. Failed
  3104. };
  3105. class TrackerHasName {
  3106. NameAndLocation m_nameAndLocation;
  3107. public:
  3108. TrackerHasName( NameAndLocation const& nameAndLocation );
  3109. bool operator ()( ITrackerPtr const& tracker ) const;
  3110. };
  3111. using Children = std::vector<ITrackerPtr>;
  3112. NameAndLocation m_nameAndLocation;
  3113. TrackerContext& m_ctx;
  3114. ITracker* m_parent;
  3115. Children m_children;
  3116. CycleState m_runState = NotStarted;
  3117. public:
  3118. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3119. NameAndLocation const& nameAndLocation() const override;
  3120. bool isComplete() const override;
  3121. bool isSuccessfullyCompleted() const override;
  3122. bool isOpen() const override;
  3123. bool hasChildren() const override;
  3124. void addChild( ITrackerPtr const& child ) override;
  3125. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3126. ITracker& parent() override;
  3127. void openChild() override;
  3128. bool isSectionTracker() const override;
  3129. bool isIndexTracker() const override;
  3130. void open();
  3131. void close() override;
  3132. void fail() override;
  3133. void markAsNeedingAnotherRun() override;
  3134. private:
  3135. void moveToParent();
  3136. void moveToThis();
  3137. };
  3138. class SectionTracker : public TrackerBase {
  3139. std::vector<std::string> m_filters;
  3140. public:
  3141. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3142. bool isSectionTracker() const override;
  3143. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3144. void tryOpen();
  3145. void addInitialFilters( std::vector<std::string> const& filters );
  3146. void addNextFilters( std::vector<std::string> const& filters );
  3147. };
  3148. class IndexTracker : public TrackerBase {
  3149. int m_size;
  3150. int m_index = -1;
  3151. public:
  3152. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3153. bool isIndexTracker() const override;
  3154. void close() override;
  3155. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3156. int index() const;
  3157. void moveNext();
  3158. };
  3159. } // namespace TestCaseTracking
  3160. using TestCaseTracking::ITracker;
  3161. using TestCaseTracking::TrackerContext;
  3162. using TestCaseTracking::SectionTracker;
  3163. using TestCaseTracking::IndexTracker;
  3164. } // namespace Catch
  3165. // end catch_test_case_tracker.h
  3166. // start catch_leak_detector.h
  3167. namespace Catch {
  3168. struct LeakDetector {
  3169. LeakDetector();
  3170. };
  3171. }
  3172. // end catch_leak_detector.h
  3173. // Cpp files will be included in the single-header file here
  3174. // start catch_approx.cpp
  3175. #include <cmath>
  3176. #include <limits>
  3177. namespace {
  3178. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3179. // But without the subtraction to allow for INFINITY in comparison
  3180. bool marginComparison(double lhs, double rhs, double margin) {
  3181. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3182. }
  3183. }
  3184. namespace Catch {
  3185. namespace Detail {
  3186. Approx::Approx ( double value )
  3187. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3188. m_margin( 0.0 ),
  3189. m_scale( 0.0 ),
  3190. m_value( value )
  3191. {}
  3192. Approx Approx::custom() {
  3193. return Approx( 0 );
  3194. }
  3195. std::string Approx::toString() const {
  3196. std::ostringstream oss;
  3197. oss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3198. return oss.str();
  3199. }
  3200. bool Approx::equalityComparisonImpl(const double other) const {
  3201. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3202. // Thanks to Richard Harris for his help refining the scaled margin value
  3203. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3204. }
  3205. } // end namespace Detail
  3206. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3207. return value.toString();
  3208. }
  3209. } // end namespace Catch
  3210. // end catch_approx.cpp
  3211. // start catch_assertionhandler.cpp
  3212. // start catch_context.h
  3213. #include <memory>
  3214. namespace Catch {
  3215. struct IResultCapture;
  3216. struct IRunner;
  3217. struct IConfig;
  3218. using IConfigPtr = std::shared_ptr<IConfig const>;
  3219. struct IContext
  3220. {
  3221. virtual ~IContext();
  3222. virtual IResultCapture* getResultCapture() = 0;
  3223. virtual IRunner* getRunner() = 0;
  3224. virtual IConfigPtr getConfig() const = 0;
  3225. };
  3226. struct IMutableContext : IContext
  3227. {
  3228. virtual ~IMutableContext();
  3229. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3230. virtual void setRunner( IRunner* runner ) = 0;
  3231. virtual void setConfig( IConfigPtr const& config ) = 0;
  3232. };
  3233. IContext& getCurrentContext();
  3234. IMutableContext& getCurrentMutableContext();
  3235. void cleanUpContext();
  3236. }
  3237. // end catch_context.h
  3238. #include <cassert>
  3239. namespace Catch {
  3240. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3241. expr.streamReconstructedExpression( os );
  3242. return os;
  3243. }
  3244. LazyExpression::LazyExpression( bool isNegated )
  3245. : m_isNegated( isNegated )
  3246. {}
  3247. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3248. LazyExpression::operator bool() const {
  3249. return m_transientExpression != nullptr;
  3250. }
  3251. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3252. if( lazyExpr.m_isNegated )
  3253. os << "!";
  3254. if( lazyExpr ) {
  3255. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3256. os << "(" << *lazyExpr.m_transientExpression << ")";
  3257. else
  3258. os << *lazyExpr.m_transientExpression;
  3259. }
  3260. else {
  3261. os << "{** error - unchecked empty expression requested **}";
  3262. }
  3263. return os;
  3264. }
  3265. AssertionHandler::AssertionHandler
  3266. ( StringRef macroName,
  3267. SourceLineInfo const& lineInfo,
  3268. StringRef capturedExpression,
  3269. ResultDisposition::Flags resultDisposition )
  3270. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }
  3271. {
  3272. getCurrentContext().getResultCapture()->assertionStarting( m_assertionInfo );
  3273. }
  3274. AssertionHandler::~AssertionHandler() {
  3275. if ( m_inExceptionGuard ) {
  3276. handle( ResultWas::ThrewException, "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE" );
  3277. getCurrentContext().getResultCapture()->exceptionEarlyReported();
  3278. }
  3279. }
  3280. void AssertionHandler::handle( ITransientExpression const& expr ) {
  3281. bool negated = isFalseTest( m_assertionInfo.resultDisposition );
  3282. bool result = expr.getResult() != negated;
  3283. handle( result ? ResultWas::Ok : ResultWas::ExpressionFailed, &expr, negated );
  3284. }
  3285. void AssertionHandler::handle( ResultWas::OfType resultType ) {
  3286. handle( resultType, nullptr, false );
  3287. }
  3288. void AssertionHandler::handle( ResultWas::OfType resultType, StringRef const& message ) {
  3289. AssertionResultData data( resultType, LazyExpression( false ) );
  3290. data.message = message;
  3291. handle( data, nullptr );
  3292. }
  3293. void AssertionHandler::handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated ) {
  3294. AssertionResultData data( resultType, LazyExpression( negated ) );
  3295. handle( data, expr );
  3296. }
  3297. void AssertionHandler::handle( AssertionResultData const& resultData, ITransientExpression const* expr ) {
  3298. getResultCapture().assertionRun();
  3299. AssertionResult assertionResult{ m_assertionInfo, resultData };
  3300. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  3301. getResultCapture().assertionEnded( assertionResult );
  3302. if( !assertionResult.isOk() ) {
  3303. m_shouldDebugBreak = getCurrentContext().getConfig()->shouldDebugBreak();
  3304. m_shouldThrow =
  3305. getCurrentContext().getRunner()->aborting() ||
  3306. (m_assertionInfo.resultDisposition & ResultDisposition::Normal);
  3307. }
  3308. }
  3309. auto AssertionHandler::allowThrows() const -> bool {
  3310. return getCurrentContext().getConfig()->allowThrows();
  3311. }
  3312. auto AssertionHandler::shouldDebugBreak() const -> bool {
  3313. return m_shouldDebugBreak;
  3314. }
  3315. void AssertionHandler::reactWithDebugBreak() const {
  3316. if (m_shouldDebugBreak) {
  3317. ///////////////////////////////////////////////////////////////////
  3318. // To inspect the state during test, you need to go one level up the callstack
  3319. // To go back to the test and change execution, jump over the reactWithoutDebugBreak() call
  3320. ///////////////////////////////////////////////////////////////////
  3321. CATCH_BREAK_INTO_DEBUGGER();
  3322. }
  3323. reactWithoutDebugBreak();
  3324. }
  3325. void AssertionHandler::reactWithoutDebugBreak() const {
  3326. if( m_shouldThrow )
  3327. throw Catch::TestFailureException();
  3328. }
  3329. void AssertionHandler::useActiveException() {
  3330. handle( ResultWas::ThrewException, Catch::translateActiveException() );
  3331. }
  3332. void AssertionHandler::setExceptionGuard() {
  3333. assert( m_inExceptionGuard == false );
  3334. m_inExceptionGuard = true;
  3335. }
  3336. void AssertionHandler::unsetExceptionGuard() {
  3337. assert( m_inExceptionGuard == true );
  3338. m_inExceptionGuard = false;
  3339. }
  3340. // This is the overload that takes a string and infers the Equals matcher from it
  3341. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3342. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3343. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3344. }
  3345. } // namespace Catch
  3346. // end catch_assertionhandler.cpp
  3347. // start catch_assertionresult.cpp
  3348. namespace Catch {
  3349. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3350. lazyExpression(_lazyExpression),
  3351. resultType(_resultType) {}
  3352. std::string AssertionResultData::reconstructExpression() const {
  3353. if( reconstructedExpression.empty() ) {
  3354. if( lazyExpression ) {
  3355. // !TBD Use stringstream for now, but rework above to pass stream in
  3356. std::ostringstream oss;
  3357. oss << lazyExpression;
  3358. reconstructedExpression = oss.str();
  3359. }
  3360. }
  3361. return reconstructedExpression;
  3362. }
  3363. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3364. : m_info( info ),
  3365. m_resultData( data )
  3366. {}
  3367. // Result was a success
  3368. bool AssertionResult::succeeded() const {
  3369. return Catch::isOk( m_resultData.resultType );
  3370. }
  3371. // Result was a success, or failure is suppressed
  3372. bool AssertionResult::isOk() const {
  3373. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3374. }
  3375. ResultWas::OfType AssertionResult::getResultType() const {
  3376. return m_resultData.resultType;
  3377. }
  3378. bool AssertionResult::hasExpression() const {
  3379. return m_info.capturedExpression[0] != 0;
  3380. }
  3381. bool AssertionResult::hasMessage() const {
  3382. return !m_resultData.message.empty();
  3383. }
  3384. std::string AssertionResult::getExpression() const {
  3385. if( isFalseTest( m_info.resultDisposition ) )
  3386. return "!(" + std::string(m_info.capturedExpression) + ")";
  3387. else
  3388. return m_info.capturedExpression;
  3389. }
  3390. std::string AssertionResult::getExpressionInMacro() const {
  3391. std::string expr;
  3392. if( m_info.macroName[0] == 0 )
  3393. expr = m_info.capturedExpression;
  3394. else {
  3395. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3396. expr += m_info.macroName;
  3397. expr += "( ";
  3398. expr += m_info.capturedExpression;
  3399. expr += " )";
  3400. }
  3401. return expr;
  3402. }
  3403. bool AssertionResult::hasExpandedExpression() const {
  3404. return hasExpression() && getExpandedExpression() != getExpression();
  3405. }
  3406. std::string AssertionResult::getExpandedExpression() const {
  3407. std::string expr = m_resultData.reconstructExpression();
  3408. return expr.empty()
  3409. ? getExpression()
  3410. : expr;
  3411. }
  3412. std::string AssertionResult::getMessage() const {
  3413. return m_resultData.message;
  3414. }
  3415. SourceLineInfo AssertionResult::getSourceInfo() const {
  3416. return m_info.lineInfo;
  3417. }
  3418. std::string AssertionResult::getTestMacroName() const {
  3419. return m_info.macroName;
  3420. }
  3421. } // end namespace Catch
  3422. // end catch_assertionresult.cpp
  3423. // start catch_benchmark.cpp
  3424. namespace Catch {
  3425. auto BenchmarkLooper::getResolution() -> uint64_t {
  3426. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3427. }
  3428. void BenchmarkLooper::reportStart() {
  3429. getResultCapture().benchmarkStarting( { m_name } );
  3430. }
  3431. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3432. auto elapsed = m_timer.getElapsedNanoseconds();
  3433. // Exponentially increasing iterations until we're confident in our timer resolution
  3434. if( elapsed < m_resolution ) {
  3435. m_iterationsToRun *= 10;
  3436. return true;
  3437. }
  3438. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3439. return false;
  3440. }
  3441. } // end namespace Catch
  3442. // end catch_benchmark.cpp
  3443. // start catch_capture_matchers.cpp
  3444. namespace Catch {
  3445. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3446. // This is the general overload that takes a any string matcher
  3447. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3448. // the Equals matcher (so the header does not mention matchers)
  3449. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3450. std::string exceptionMessage = Catch::translateActiveException();
  3451. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3452. handler.handle( expr );
  3453. }
  3454. } // namespace Catch
  3455. // end catch_capture_matchers.cpp
  3456. // start catch_commandline.cpp
  3457. // start catch_commandline.h
  3458. // start catch_clara.h
  3459. // Use Catch's value for console width (store Clara's off to the side, if present)
  3460. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  3461. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3462. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3463. #endif
  3464. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  3465. #ifdef __clang__
  3466. #pragma clang diagnostic push
  3467. #pragma clang diagnostic ignored "-Wweak-vtables"
  3468. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  3469. #pragma clang diagnostic ignored "-Wshadow"
  3470. #endif
  3471. // start clara.hpp
  3472. // v1.0-develop.2
  3473. // See https://github.com/philsquared/Clara
  3474. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3475. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  3476. #endif
  3477. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3478. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3479. #endif
  3480. // ----------- #included from clara_textflow.hpp -----------
  3481. // TextFlowCpp
  3482. //
  3483. // A single-header library for wrapping and laying out basic text, by Phil Nash
  3484. //
  3485. // This work is licensed under the BSD 2-Clause license.
  3486. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  3487. //
  3488. // This project is hosted at https://github.com/philsquared/textflowcpp
  3489. #include <cassert>
  3490. #include <ostream>
  3491. #include <sstream>
  3492. #include <vector>
  3493. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3494. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  3495. #endif
  3496. namespace Catch { namespace clara { namespace TextFlow {
  3497. inline auto isWhitespace( char c ) -> bool {
  3498. static std::string chars = " \t\n\r";
  3499. return chars.find( c ) != std::string::npos;
  3500. }
  3501. inline auto isBreakableBefore( char c ) -> bool {
  3502. static std::string chars = "[({<|";
  3503. return chars.find( c ) != std::string::npos;
  3504. }
  3505. inline auto isBreakableAfter( char c ) -> bool {
  3506. static std::string chars = "])}>.,:;*+-=&/\\";
  3507. return chars.find( c ) != std::string::npos;
  3508. }
  3509. class Columns;
  3510. class Column {
  3511. std::vector<std::string> m_strings;
  3512. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  3513. size_t m_indent = 0;
  3514. size_t m_initialIndent = std::string::npos;
  3515. public:
  3516. class iterator {
  3517. friend Column;
  3518. Column const& m_column;
  3519. size_t m_stringIndex = 0;
  3520. size_t m_pos = 0;
  3521. size_t m_len = 0;
  3522. size_t m_end = 0;
  3523. bool m_suffix = false;
  3524. iterator( Column const& column, size_t stringIndex )
  3525. : m_column( column ),
  3526. m_stringIndex( stringIndex )
  3527. {}
  3528. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  3529. auto isBoundary( size_t at ) const -> bool {
  3530. assert( at > 0 );
  3531. assert( at <= line().size() );
  3532. return at == line().size() ||
  3533. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  3534. isBreakableBefore( line()[at] ) ||
  3535. isBreakableAfter( line()[at-1] );
  3536. }
  3537. void calcLength() {
  3538. assert( m_stringIndex < m_column.m_strings.size() );
  3539. m_suffix = false;
  3540. auto width = m_column.m_width-indent();
  3541. m_end = m_pos;
  3542. while( m_end < line().size() && line()[m_end] != '\n' )
  3543. ++m_end;
  3544. if( m_end < m_pos + width ) {
  3545. m_len = m_end - m_pos;
  3546. }
  3547. else {
  3548. size_t len = width;
  3549. while (len > 0 && !isBoundary(m_pos + len))
  3550. --len;
  3551. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  3552. --len;
  3553. if (len > 0) {
  3554. m_len = len;
  3555. } else {
  3556. m_suffix = true;
  3557. m_len = width - 1;
  3558. }
  3559. }
  3560. }
  3561. auto indent() const -> size_t {
  3562. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  3563. return initial == std::string::npos ? m_column.m_indent : initial;
  3564. }
  3565. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  3566. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  3567. }
  3568. public:
  3569. explicit iterator( Column const& column ) : m_column( column ) {
  3570. assert( m_column.m_width > m_column.m_indent );
  3571. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  3572. calcLength();
  3573. if( m_len == 0 )
  3574. m_stringIndex++; // Empty string
  3575. }
  3576. auto operator *() const -> std::string {
  3577. assert( m_stringIndex < m_column.m_strings.size() );
  3578. assert( m_pos <= m_end );
  3579. if( m_pos + m_column.m_width < m_end )
  3580. return addIndentAndSuffix(line().substr(m_pos, m_len));
  3581. else
  3582. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  3583. }
  3584. auto operator ++() -> iterator& {
  3585. m_pos += m_len;
  3586. if( m_pos < line().size() && line()[m_pos] == '\n' )
  3587. m_pos += 1;
  3588. else
  3589. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  3590. ++m_pos;
  3591. if( m_pos == line().size() ) {
  3592. m_pos = 0;
  3593. ++m_stringIndex;
  3594. }
  3595. if( m_stringIndex < m_column.m_strings.size() )
  3596. calcLength();
  3597. return *this;
  3598. }
  3599. auto operator ++(int) -> iterator {
  3600. iterator prev( *this );
  3601. operator++();
  3602. return prev;
  3603. }
  3604. auto operator ==( iterator const& other ) const -> bool {
  3605. return
  3606. m_pos == other.m_pos &&
  3607. m_stringIndex == other.m_stringIndex &&
  3608. &m_column == &other.m_column;
  3609. }
  3610. auto operator !=( iterator const& other ) const -> bool {
  3611. return !operator==( other );
  3612. }
  3613. };
  3614. using const_iterator = iterator;
  3615. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  3616. auto width( size_t newWidth ) -> Column& {
  3617. assert( newWidth > 0 );
  3618. m_width = newWidth;
  3619. return *this;
  3620. }
  3621. auto indent( size_t newIndent ) -> Column& {
  3622. m_indent = newIndent;
  3623. return *this;
  3624. }
  3625. auto initialIndent( size_t newIndent ) -> Column& {
  3626. m_initialIndent = newIndent;
  3627. return *this;
  3628. }
  3629. auto width() const -> size_t { return m_width; }
  3630. auto begin() const -> iterator { return iterator( *this ); }
  3631. auto end() const -> iterator { return { *this, m_strings.size() }; }
  3632. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  3633. bool first = true;
  3634. for( auto line : col ) {
  3635. if( first )
  3636. first = false;
  3637. else
  3638. os << "\n";
  3639. os << line;
  3640. }
  3641. return os;
  3642. }
  3643. auto operator + ( Column const& other ) -> Columns;
  3644. auto toString() const -> std::string {
  3645. std::ostringstream oss;
  3646. oss << *this;
  3647. return oss.str();
  3648. }
  3649. };
  3650. class Spacer : public Column {
  3651. public:
  3652. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  3653. width( spaceWidth );
  3654. }
  3655. };
  3656. class Columns {
  3657. std::vector<Column> m_columns;
  3658. public:
  3659. class iterator {
  3660. friend Columns;
  3661. struct EndTag {};
  3662. std::vector<Column> const& m_columns;
  3663. std::vector<Column::iterator> m_iterators;
  3664. size_t m_activeIterators;
  3665. iterator( Columns const& columns, EndTag )
  3666. : m_columns( columns.m_columns ),
  3667. m_activeIterators( 0 )
  3668. {
  3669. m_iterators.reserve( m_columns.size() );
  3670. for( auto const& col : m_columns )
  3671. m_iterators.push_back( col.end() );
  3672. }
  3673. public:
  3674. explicit iterator( Columns const& columns )
  3675. : m_columns( columns.m_columns ),
  3676. m_activeIterators( m_columns.size() )
  3677. {
  3678. m_iterators.reserve( m_columns.size() );
  3679. for( auto const& col : m_columns )
  3680. m_iterators.push_back( col.begin() );
  3681. }
  3682. auto operator ==( iterator const& other ) const -> bool {
  3683. return m_iterators == other.m_iterators;
  3684. }
  3685. auto operator !=( iterator const& other ) const -> bool {
  3686. return m_iterators != other.m_iterators;
  3687. }
  3688. auto operator *() const -> std::string {
  3689. std::string row, padding;
  3690. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3691. auto width = m_columns[i].width();
  3692. if( m_iterators[i] != m_columns[i].end() ) {
  3693. std::string col = *m_iterators[i];
  3694. row += padding + col;
  3695. if( col.size() < width )
  3696. padding = std::string( width - col.size(), ' ' );
  3697. else
  3698. padding = "";
  3699. }
  3700. else {
  3701. padding += std::string( width, ' ' );
  3702. }
  3703. }
  3704. return row;
  3705. }
  3706. auto operator ++() -> iterator& {
  3707. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3708. if (m_iterators[i] != m_columns[i].end())
  3709. ++m_iterators[i];
  3710. }
  3711. return *this;
  3712. }
  3713. auto operator ++(int) -> iterator {
  3714. iterator prev( *this );
  3715. operator++();
  3716. return prev;
  3717. }
  3718. };
  3719. using const_iterator = iterator;
  3720. auto begin() const -> iterator { return iterator( *this ); }
  3721. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  3722. auto operator += ( Column const& col ) -> Columns& {
  3723. m_columns.push_back( col );
  3724. return *this;
  3725. }
  3726. auto operator + ( Column const& col ) -> Columns {
  3727. Columns combined = *this;
  3728. combined += col;
  3729. return combined;
  3730. }
  3731. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  3732. bool first = true;
  3733. for( auto line : cols ) {
  3734. if( first )
  3735. first = false;
  3736. else
  3737. os << "\n";
  3738. os << line;
  3739. }
  3740. return os;
  3741. }
  3742. auto toString() const -> std::string {
  3743. std::ostringstream oss;
  3744. oss << *this;
  3745. return oss.str();
  3746. }
  3747. };
  3748. inline auto Column::operator + ( Column const& other ) -> Columns {
  3749. Columns cols;
  3750. cols += *this;
  3751. cols += other;
  3752. return cols;
  3753. }
  3754. }}} // namespace Catch::clara::TextFlow
  3755. // ----------- end of #include from clara_textflow.hpp -----------
  3756. // ........... back in clara.hpp
  3757. #include <memory>
  3758. #include <set>
  3759. #include <algorithm>
  3760. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  3761. #define CATCH_PLATFORM_WINDOWS
  3762. #endif
  3763. namespace Catch { namespace clara {
  3764. namespace detail {
  3765. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  3766. template<typename L>
  3767. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  3768. template<typename ClassT, typename ReturnT, typename... Args>
  3769. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  3770. static const bool isValid = false;
  3771. };
  3772. template<typename ClassT, typename ReturnT, typename ArgT>
  3773. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  3774. static const bool isValid = true;
  3775. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;;
  3776. using ReturnType = ReturnT;
  3777. };
  3778. class TokenStream;
  3779. // Transport for raw args (copied from main args, or supplied via init list for testing)
  3780. class Args {
  3781. friend TokenStream;
  3782. std::string m_exeName;
  3783. std::vector<std::string> m_args;
  3784. public:
  3785. Args( int argc, char *argv[] ) {
  3786. m_exeName = argv[0];
  3787. for( int i = 1; i < argc; ++i )
  3788. m_args.push_back( argv[i] );
  3789. }
  3790. Args( std::initializer_list<std::string> args )
  3791. : m_exeName( *args.begin() ),
  3792. m_args( args.begin()+1, args.end() )
  3793. {}
  3794. auto exeName() const -> std::string {
  3795. return m_exeName;
  3796. }
  3797. };
  3798. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  3799. // may encode an option + its argument if the : or = form is used
  3800. enum class TokenType {
  3801. Option, Argument
  3802. };
  3803. struct Token {
  3804. TokenType type;
  3805. std::string token;
  3806. };
  3807. inline auto isOptPrefix( char c ) -> bool {
  3808. return c == '-'
  3809. #ifdef CATCH_PLATFORM_WINDOWS
  3810. || c == '/'
  3811. #endif
  3812. ;
  3813. }
  3814. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  3815. class TokenStream {
  3816. using Iterator = std::vector<std::string>::const_iterator;
  3817. Iterator it;
  3818. Iterator itEnd;
  3819. std::vector<Token> m_tokenBuffer;
  3820. void loadBuffer() {
  3821. m_tokenBuffer.resize( 0 );
  3822. // Skip any empty strings
  3823. while( it != itEnd && it->empty() )
  3824. ++it;
  3825. if( it != itEnd ) {
  3826. auto const &next = *it;
  3827. if( isOptPrefix( next[0] ) ) {
  3828. auto delimiterPos = next.find_first_of( " :=" );
  3829. if( delimiterPos != std::string::npos ) {
  3830. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  3831. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  3832. } else {
  3833. if( next[1] != '-' && next.size() > 2 ) {
  3834. std::string opt = "- ";
  3835. for( size_t i = 1; i < next.size(); ++i ) {
  3836. opt[1] = next[i];
  3837. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  3838. }
  3839. } else {
  3840. m_tokenBuffer.push_back( { TokenType::Option, next } );
  3841. }
  3842. }
  3843. } else {
  3844. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  3845. }
  3846. }
  3847. }
  3848. public:
  3849. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  3850. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  3851. loadBuffer();
  3852. }
  3853. explicit operator bool() const {
  3854. return !m_tokenBuffer.empty() || it != itEnd;
  3855. }
  3856. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  3857. auto operator*() const -> Token {
  3858. assert( !m_tokenBuffer.empty() );
  3859. return m_tokenBuffer.front();
  3860. }
  3861. auto operator->() const -> Token const * {
  3862. assert( !m_tokenBuffer.empty() );
  3863. return &m_tokenBuffer.front();
  3864. }
  3865. auto operator++() -> TokenStream & {
  3866. if( m_tokenBuffer.size() >= 2 ) {
  3867. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  3868. } else {
  3869. if( it != itEnd )
  3870. ++it;
  3871. loadBuffer();
  3872. }
  3873. return *this;
  3874. }
  3875. };
  3876. class ResultBase {
  3877. public:
  3878. enum Type {
  3879. Ok, LogicError, RuntimeError
  3880. };
  3881. protected:
  3882. ResultBase( Type type ) : m_type( type ) {}
  3883. virtual ~ResultBase() = default;
  3884. virtual void enforceOk() const = 0;
  3885. Type m_type;
  3886. };
  3887. template<typename T>
  3888. class ResultValueBase : public ResultBase {
  3889. public:
  3890. auto value() const -> T const & {
  3891. enforceOk();
  3892. return m_value;
  3893. }
  3894. protected:
  3895. ResultValueBase( Type type ) : ResultBase( type ) {}
  3896. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  3897. if( m_type == ResultBase::Ok )
  3898. new( &m_value ) T( other.m_value );
  3899. }
  3900. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  3901. new( &m_value ) T( value );
  3902. }
  3903. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  3904. if( m_type == ResultBase::Ok )
  3905. m_value.~T();
  3906. ResultBase::operator=(other);
  3907. if( m_type == ResultBase::Ok )
  3908. new( &m_value ) T( other.m_value );
  3909. return *this;
  3910. }
  3911. ~ResultValueBase() {
  3912. if( m_type == Ok )
  3913. m_value.~T();
  3914. }
  3915. union {
  3916. T m_value;
  3917. };
  3918. };
  3919. template<>
  3920. class ResultValueBase<void> : public ResultBase {
  3921. protected:
  3922. using ResultBase::ResultBase;
  3923. };
  3924. template<typename T = void>
  3925. class BasicResult : public ResultValueBase<T> {
  3926. public:
  3927. template<typename U>
  3928. explicit BasicResult( BasicResult<U> const &other )
  3929. : ResultValueBase<T>( other.type() ),
  3930. m_errorMessage( other.errorMessage() )
  3931. {
  3932. assert( type() != ResultBase::Ok );
  3933. }
  3934. template<typename U>
  3935. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  3936. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  3937. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  3938. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  3939. explicit operator bool() const { return m_type == ResultBase::Ok; }
  3940. auto type() const -> ResultBase::Type { return m_type; }
  3941. auto errorMessage() const -> std::string { return m_errorMessage; }
  3942. protected:
  3943. virtual void enforceOk() const {
  3944. // !TBD: If no exceptions, std::terminate here or something
  3945. switch( m_type ) {
  3946. case ResultBase::LogicError:
  3947. throw std::logic_error( m_errorMessage );
  3948. case ResultBase::RuntimeError:
  3949. throw std::runtime_error( m_errorMessage );
  3950. case ResultBase::Ok:
  3951. break;
  3952. }
  3953. }
  3954. std::string m_errorMessage; // Only populated if resultType is an error
  3955. BasicResult( ResultBase::Type type, std::string const &message )
  3956. : ResultValueBase<T>(type),
  3957. m_errorMessage(message)
  3958. {
  3959. assert( m_type != ResultBase::Ok );
  3960. }
  3961. using ResultValueBase<T>::ResultValueBase;
  3962. using ResultBase::m_type;
  3963. };
  3964. enum class ParseResultType {
  3965. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  3966. };
  3967. class ParseState {
  3968. public:
  3969. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  3970. : m_type(type),
  3971. m_remainingTokens( remainingTokens )
  3972. {}
  3973. auto type() const -> ParseResultType { return m_type; }
  3974. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  3975. private:
  3976. ParseResultType m_type;
  3977. TokenStream m_remainingTokens;
  3978. };
  3979. using Result = BasicResult<void>;
  3980. using ParserResult = BasicResult<ParseResultType>;
  3981. using InternalParseResult = BasicResult<ParseState>;
  3982. struct HelpColumns {
  3983. std::string left;
  3984. std::string right;
  3985. };
  3986. template<typename T>
  3987. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  3988. std::stringstream ss;
  3989. ss << source;
  3990. ss >> target;
  3991. if( ss.fail() )
  3992. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  3993. else
  3994. return ParserResult::ok( ParseResultType::Matched );
  3995. }
  3996. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  3997. target = source;
  3998. return ParserResult::ok( ParseResultType::Matched );
  3999. }
  4000. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4001. std::string srcLC = source;
  4002. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4003. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4004. target = true;
  4005. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4006. target = false;
  4007. else
  4008. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4009. return ParserResult::ok( ParseResultType::Matched );
  4010. }
  4011. struct BoundRefBase {
  4012. BoundRefBase() = default;
  4013. BoundRefBase( BoundRefBase const & ) = delete;
  4014. BoundRefBase( BoundRefBase && ) = delete;
  4015. BoundRefBase &operator=( BoundRefBase const & ) = delete;
  4016. BoundRefBase &operator=( BoundRefBase && ) = delete;
  4017. virtual ~BoundRefBase() = default;
  4018. virtual auto isFlag() const -> bool = 0;
  4019. virtual auto isContainer() const -> bool { return false; }
  4020. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4021. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4022. };
  4023. struct BoundValueRefBase : BoundRefBase {
  4024. auto isFlag() const -> bool override { return false; }
  4025. auto setFlag( bool ) -> ParserResult override {
  4026. return ParserResult::logicError( "Flags can only be set on boolean fields" );
  4027. }
  4028. };
  4029. struct BoundFlagRefBase : BoundRefBase {
  4030. auto isFlag() const -> bool override { return true; }
  4031. auto setValue( std::string const &arg ) -> ParserResult override {
  4032. bool flag;
  4033. auto result = convertInto( arg, flag );
  4034. if( result )
  4035. setFlag( flag );
  4036. return result;
  4037. }
  4038. };
  4039. template<typename T>
  4040. struct BoundRef : BoundValueRefBase {
  4041. T &m_ref;
  4042. explicit BoundRef( T &ref ) : m_ref( ref ) {}
  4043. auto setValue( std::string const &arg ) -> ParserResult override {
  4044. return convertInto( arg, m_ref );
  4045. }
  4046. };
  4047. template<typename T>
  4048. struct BoundRef<std::vector<T>> : BoundValueRefBase {
  4049. std::vector<T> &m_ref;
  4050. explicit BoundRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4051. auto isContainer() const -> bool override { return true; }
  4052. auto setValue( std::string const &arg ) -> ParserResult override {
  4053. T temp;
  4054. auto result = convertInto( arg, temp );
  4055. if( result )
  4056. m_ref.push_back( temp );
  4057. return result;
  4058. }
  4059. };
  4060. struct BoundFlagRef : BoundFlagRefBase {
  4061. bool &m_ref;
  4062. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4063. auto setFlag( bool flag ) -> ParserResult override {
  4064. m_ref = flag;
  4065. return ParserResult::ok( ParseResultType::Matched );
  4066. }
  4067. };
  4068. template<typename ReturnType>
  4069. struct LambdaInvoker {
  4070. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4071. template<typename L, typename ArgType>
  4072. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4073. return lambda( arg );
  4074. }
  4075. };
  4076. template<>
  4077. struct LambdaInvoker<void> {
  4078. template<typename L, typename ArgType>
  4079. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4080. lambda( arg );
  4081. return ParserResult::ok( ParseResultType::Matched );
  4082. }
  4083. };
  4084. template<typename ArgType, typename L>
  4085. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4086. ArgType temp;
  4087. auto result = convertInto( arg, temp );
  4088. return !result
  4089. ? result
  4090. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4091. };
  4092. template<typename L>
  4093. struct BoundLambda : BoundValueRefBase {
  4094. L m_lambda;
  4095. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4096. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4097. auto setValue( std::string const &arg ) -> ParserResult override {
  4098. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4099. }
  4100. };
  4101. template<typename L>
  4102. struct BoundFlagLambda : BoundFlagRefBase {
  4103. L m_lambda;
  4104. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4105. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4106. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4107. auto setFlag( bool flag ) -> ParserResult override {
  4108. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4109. }
  4110. };
  4111. enum class Optionality { Optional, Required };
  4112. struct Parser;
  4113. class ParserBase {
  4114. public:
  4115. virtual ~ParserBase() = default;
  4116. virtual auto validate() const -> Result { return Result::ok(); }
  4117. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4118. virtual auto cardinality() const -> size_t { return 1; }
  4119. auto parse( Args const &args ) const -> InternalParseResult {
  4120. return parse( args.exeName(), TokenStream( args ) );
  4121. }
  4122. };
  4123. template<typename DerivedT>
  4124. class ComposableParserImpl : public ParserBase {
  4125. public:
  4126. template<typename T>
  4127. auto operator|( T const &other ) const -> Parser;
  4128. };
  4129. // Common code and state for Args and Opts
  4130. template<typename DerivedT>
  4131. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4132. protected:
  4133. Optionality m_optionality = Optionality::Optional;
  4134. std::shared_ptr<BoundRefBase> m_ref;
  4135. std::string m_hint;
  4136. std::string m_description;
  4137. explicit ParserRefImpl( std::shared_ptr<BoundRefBase> const &ref ) : m_ref( ref ) {}
  4138. public:
  4139. template<typename T>
  4140. ParserRefImpl( T &ref, std::string const &hint )
  4141. : m_ref( std::make_shared<BoundRef<T>>( ref ) ),
  4142. m_hint( hint )
  4143. {}
  4144. template<typename LambdaT>
  4145. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4146. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4147. m_hint(hint)
  4148. {}
  4149. auto operator()( std::string const &description ) -> DerivedT & {
  4150. m_description = description;
  4151. return static_cast<DerivedT &>( *this );
  4152. }
  4153. auto optional() -> DerivedT & {
  4154. m_optionality = Optionality::Optional;
  4155. return static_cast<DerivedT &>( *this );
  4156. };
  4157. auto required() -> DerivedT & {
  4158. m_optionality = Optionality::Required;
  4159. return static_cast<DerivedT &>( *this );
  4160. };
  4161. auto isOptional() const -> bool {
  4162. return m_optionality == Optionality::Optional;
  4163. }
  4164. auto cardinality() const -> size_t override {
  4165. if( m_ref->isContainer() )
  4166. return 0;
  4167. else
  4168. return 1;
  4169. }
  4170. auto hint() const -> std::string { return m_hint; }
  4171. };
  4172. class ExeName : public ComposableParserImpl<ExeName> {
  4173. std::shared_ptr<std::string> m_name;
  4174. std::shared_ptr<BoundRefBase> m_ref;
  4175. template<typename LambdaT>
  4176. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundRefBase> {
  4177. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4178. }
  4179. public:
  4180. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4181. explicit ExeName( std::string &ref ) : ExeName() {
  4182. m_ref = std::make_shared<BoundRef<std::string>>( ref );
  4183. }
  4184. template<typename LambdaT>
  4185. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4186. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4187. }
  4188. // The exe name is not parsed out of the normal tokens, but is handled specially
  4189. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4190. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4191. }
  4192. auto name() const -> std::string { return *m_name; }
  4193. auto set( std::string const& newName ) -> ParserResult {
  4194. auto lastSlash = newName.find_last_of( "\\/" );
  4195. auto filename = ( lastSlash == std::string::npos )
  4196. ? newName
  4197. : newName.substr( lastSlash+1 );
  4198. *m_name = filename;
  4199. if( m_ref )
  4200. return m_ref->setValue( filename );
  4201. else
  4202. return ParserResult::ok( ParseResultType::Matched );
  4203. }
  4204. };
  4205. class Arg : public ParserRefImpl<Arg> {
  4206. public:
  4207. using ParserRefImpl::ParserRefImpl;
  4208. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4209. auto validationResult = validate();
  4210. if( !validationResult )
  4211. return InternalParseResult( validationResult );
  4212. auto remainingTokens = tokens;
  4213. auto const &token = *remainingTokens;
  4214. if( token.type != TokenType::Argument )
  4215. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4216. auto result = m_ref->setValue( remainingTokens->token );
  4217. if( !result )
  4218. return InternalParseResult( result );
  4219. else
  4220. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4221. }
  4222. };
  4223. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4224. #ifdef CATCH_PLATFORM_WINDOWS
  4225. if( optName[0] == '/' )
  4226. return "-" + optName.substr( 1 );
  4227. else
  4228. #endif
  4229. return optName;
  4230. }
  4231. class Opt : public ParserRefImpl<Opt> {
  4232. protected:
  4233. std::vector<std::string> m_optNames;
  4234. public:
  4235. template<typename LambdaT>
  4236. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4237. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4238. template<typename LambdaT>
  4239. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4240. template<typename T>
  4241. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4242. auto operator[]( std::string const &optName ) -> Opt & {
  4243. m_optNames.push_back( optName );
  4244. return *this;
  4245. }
  4246. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4247. std::ostringstream oss;
  4248. bool first = true;
  4249. for( auto const &opt : m_optNames ) {
  4250. if (first)
  4251. first = false;
  4252. else
  4253. oss << ", ";
  4254. oss << opt;
  4255. }
  4256. if( !m_hint.empty() )
  4257. oss << " <" << m_hint << ">";
  4258. return { { oss.str(), m_description } };
  4259. }
  4260. auto isMatch( std::string const &optToken ) const -> bool {
  4261. auto normalisedToken = normaliseOpt( optToken );
  4262. for( auto const &name : m_optNames ) {
  4263. if( normaliseOpt( name ) == normalisedToken )
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. using ParserBase::parse;
  4269. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4270. auto validationResult = validate();
  4271. if( !validationResult )
  4272. return InternalParseResult( validationResult );
  4273. auto remainingTokens = tokens;
  4274. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4275. auto const &token = *remainingTokens;
  4276. if( isMatch(token.token ) ) {
  4277. if( m_ref->isFlag() ) {
  4278. auto result = m_ref->setFlag( true );
  4279. if( !result )
  4280. return InternalParseResult( result );
  4281. if( result.value() == ParseResultType::ShortCircuitAll )
  4282. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4283. } else {
  4284. ++remainingTokens;
  4285. if( !remainingTokens )
  4286. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4287. auto const &argToken = *remainingTokens;
  4288. if( argToken.type != TokenType::Argument )
  4289. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4290. auto result = m_ref->setValue( argToken.token );
  4291. if( !result )
  4292. return InternalParseResult( result );
  4293. if( result.value() == ParseResultType::ShortCircuitAll )
  4294. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4295. }
  4296. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4297. }
  4298. }
  4299. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4300. }
  4301. auto validate() const -> Result override {
  4302. if( m_optNames.empty() )
  4303. return Result::logicError( "No options supplied to Opt" );
  4304. for( auto const &name : m_optNames ) {
  4305. if( name.empty() )
  4306. return Result::logicError( "Option name cannot be empty" );
  4307. #ifdef CATCH_PLATFORM_WINDOWS
  4308. if( name[0] != '-' && name[0] != '/' )
  4309. return Result::logicError( "Option name must begin with '-' or '/'" );
  4310. #else
  4311. if( name[0] != '-' )
  4312. return Result::logicError( "Option name must begin with '-'" );
  4313. #endif
  4314. }
  4315. return ParserRefImpl::validate();
  4316. }
  4317. };
  4318. struct Help : Opt {
  4319. Help( bool &showHelpFlag )
  4320. : Opt([&]( bool flag ) {
  4321. showHelpFlag = flag;
  4322. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4323. })
  4324. {
  4325. static_cast<Opt &>( *this )
  4326. ("display usage information")
  4327. ["-?"]["-h"]["--help"]
  4328. .optional();
  4329. }
  4330. };
  4331. struct Parser : ParserBase {
  4332. mutable ExeName m_exeName;
  4333. std::vector<Opt> m_options;
  4334. std::vector<Arg> m_args;
  4335. auto operator|=( ExeName const &exeName ) -> Parser & {
  4336. m_exeName = exeName;
  4337. return *this;
  4338. }
  4339. auto operator|=( Arg const &arg ) -> Parser & {
  4340. m_args.push_back(arg);
  4341. return *this;
  4342. }
  4343. auto operator|=( Opt const &opt ) -> Parser & {
  4344. m_options.push_back(opt);
  4345. return *this;
  4346. }
  4347. auto operator|=( Parser const &other ) -> Parser & {
  4348. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4349. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4350. return *this;
  4351. }
  4352. template<typename T>
  4353. auto operator|( T const &other ) const -> Parser {
  4354. return Parser( *this ) |= other;
  4355. }
  4356. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4357. std::vector<HelpColumns> cols;
  4358. for (auto const &o : m_options) {
  4359. auto childCols = o.getHelpColumns();
  4360. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4361. }
  4362. return cols;
  4363. }
  4364. void writeToStream( std::ostream &os ) const {
  4365. if (!m_exeName.name().empty()) {
  4366. os << "usage:\n" << " " << m_exeName.name() << " ";
  4367. bool required = true, first = true;
  4368. for( auto const &arg : m_args ) {
  4369. if (first)
  4370. first = false;
  4371. else
  4372. os << " ";
  4373. if( arg.isOptional() && required ) {
  4374. os << "[";
  4375. required = false;
  4376. }
  4377. os << "<" << arg.hint() << ">";
  4378. if( arg.cardinality() == 0 )
  4379. os << " ... ";
  4380. }
  4381. if( !required )
  4382. os << "]";
  4383. if( !m_options.empty() )
  4384. os << " options";
  4385. os << "\n\nwhere options are:" << std::endl;
  4386. }
  4387. auto rows = getHelpColumns();
  4388. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4389. size_t optWidth = 0;
  4390. for( auto const &cols : rows )
  4391. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4392. for( auto const &cols : rows ) {
  4393. auto row =
  4394. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4395. TextFlow::Spacer(4) +
  4396. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4397. os << row << std::endl;
  4398. }
  4399. }
  4400. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4401. parser.writeToStream( os );
  4402. return os;
  4403. }
  4404. auto validate() const -> Result override {
  4405. for( auto const &opt : m_options ) {
  4406. auto result = opt.validate();
  4407. if( !result )
  4408. return result;
  4409. }
  4410. for( auto const &arg : m_args ) {
  4411. auto result = arg.validate();
  4412. if( !result )
  4413. return result;
  4414. }
  4415. return Result::ok();
  4416. }
  4417. using ParserBase::parse;
  4418. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  4419. struct ParserInfo {
  4420. ParserBase const* parser = nullptr;
  4421. size_t count = 0;
  4422. };
  4423. const size_t totalParsers = m_options.size() + m_args.size();
  4424. assert( totalParsers < 512 );
  4425. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  4426. ParserInfo parseInfos[512];
  4427. {
  4428. size_t i = 0;
  4429. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  4430. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  4431. }
  4432. m_exeName.set( exeName );
  4433. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4434. while( result.value().remainingTokens() ) {
  4435. bool tokenParsed = false;
  4436. for( size_t i = 0; i < totalParsers; ++i ) {
  4437. auto& parseInfo = parseInfos[i];
  4438. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  4439. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  4440. if (!result)
  4441. return result;
  4442. if (result.value().type() != ParseResultType::NoMatch) {
  4443. tokenParsed = true;
  4444. ++parseInfo.count;
  4445. break;
  4446. }
  4447. }
  4448. }
  4449. if( result.value().type() == ParseResultType::ShortCircuitAll )
  4450. return result;
  4451. if( !tokenParsed )
  4452. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  4453. }
  4454. // !TBD Check missing required options
  4455. return result;
  4456. }
  4457. };
  4458. template<typename DerivedT>
  4459. template<typename T>
  4460. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  4461. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  4462. }
  4463. } // namespace detail
  4464. // A Combined parser
  4465. using detail::Parser;
  4466. // A parser for options
  4467. using detail::Opt;
  4468. // A parser for arguments
  4469. using detail::Arg;
  4470. // Wrapper for argc, argv from main()
  4471. using detail::Args;
  4472. // Specifies the name of the executable
  4473. using detail::ExeName;
  4474. // Convenience wrapper for option parser that specifies the help option
  4475. using detail::Help;
  4476. // enum of result types from a parse
  4477. using detail::ParseResultType;
  4478. // Result type for parser operation
  4479. using detail::ParserResult;
  4480. }} // namespace Catch::clara
  4481. // end clara.hpp
  4482. #ifdef __clang__
  4483. #pragma clang diagnostic pop
  4484. #endif
  4485. // Restore Clara's value for console width, if present
  4486. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4487. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4488. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4489. #endif
  4490. // end catch_clara.h
  4491. namespace Catch {
  4492. clara::Parser makeCommandLineParser( ConfigData& config );
  4493. } // end namespace Catch
  4494. // end catch_commandline.h
  4495. #include <fstream>
  4496. #include <ctime>
  4497. namespace Catch {
  4498. clara::Parser makeCommandLineParser( ConfigData& config ) {
  4499. using namespace clara;
  4500. auto const setWarning = [&]( std::string const& warning ) {
  4501. if( warning != "NoAssertions" )
  4502. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  4503. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  4504. return ParserResult::ok( ParseResultType::Matched );
  4505. };
  4506. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  4507. std::ifstream f( filename.c_str() );
  4508. if( !f.is_open() )
  4509. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  4510. std::string line;
  4511. while( std::getline( f, line ) ) {
  4512. line = trim(line);
  4513. if( !line.empty() && !startsWith( line, '#' ) ) {
  4514. if( !startsWith( line, '"' ) )
  4515. line = '"' + line + '"';
  4516. config.testsOrTags.push_back( line + ',' );
  4517. }
  4518. }
  4519. return ParserResult::ok( ParseResultType::Matched );
  4520. };
  4521. auto const setTestOrder = [&]( std::string const& order ) {
  4522. if( startsWith( "declared", order ) )
  4523. config.runOrder = RunTests::InDeclarationOrder;
  4524. else if( startsWith( "lexical", order ) )
  4525. config.runOrder = RunTests::InLexicographicalOrder;
  4526. else if( startsWith( "random", order ) )
  4527. config.runOrder = RunTests::InRandomOrder;
  4528. else
  4529. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  4530. return ParserResult::ok( ParseResultType::Matched );
  4531. };
  4532. auto const setRngSeed = [&]( std::string const& seed ) {
  4533. if( seed != "time" )
  4534. return clara::detail::convertInto( seed, config.rngSeed );
  4535. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  4536. return ParserResult::ok( ParseResultType::Matched );
  4537. };
  4538. auto const setColourUsage = [&]( std::string const& useColour ) {
  4539. auto mode = toLower( useColour );
  4540. if( mode == "yes" )
  4541. config.useColour = UseColour::Yes;
  4542. else if( mode == "no" )
  4543. config.useColour = UseColour::No;
  4544. else if( mode == "auto" )
  4545. config.useColour = UseColour::Auto;
  4546. else
  4547. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  4548. return ParserResult::ok( ParseResultType::Matched );
  4549. };
  4550. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  4551. auto keypressLc = toLower( keypress );
  4552. if( keypressLc == "start" )
  4553. config.waitForKeypress = WaitForKeypress::BeforeStart;
  4554. else if( keypressLc == "exit" )
  4555. config.waitForKeypress = WaitForKeypress::BeforeExit;
  4556. else if( keypressLc == "both" )
  4557. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  4558. else
  4559. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  4560. return ParserResult::ok( ParseResultType::Matched );
  4561. };
  4562. auto const setVerbosity = [&]( std::string const& verbosity ) {
  4563. auto lcVerbosity = toLower( verbosity );
  4564. if( lcVerbosity == "quiet" )
  4565. config.verbosity = Verbosity::Quiet;
  4566. else if( lcVerbosity == "normal" )
  4567. config.verbosity = Verbosity::Normal;
  4568. else if( lcVerbosity == "high" )
  4569. config.verbosity = Verbosity::High;
  4570. else
  4571. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  4572. return ParserResult::ok( ParseResultType::Matched );
  4573. };
  4574. auto cli
  4575. = ExeName( config.processName )
  4576. | Help( config.showHelp )
  4577. | Opt( config.listTests )
  4578. ["-l"]["--list-tests"]
  4579. ( "list all/matching test cases" )
  4580. | Opt( config.listTags )
  4581. ["-t"]["--list-tags"]
  4582. ( "list all/matching tags" )
  4583. | Opt( config.showSuccessfulTests )
  4584. ["-s"]["--success"]
  4585. ( "include successful tests in output" )
  4586. | Opt( config.shouldDebugBreak )
  4587. ["-b"]["--break"]
  4588. ( "break into debugger on failure" )
  4589. | Opt( config.noThrow )
  4590. ["-e"]["--nothrow"]
  4591. ( "skip exception tests" )
  4592. | Opt( config.showInvisibles )
  4593. ["-i"]["--invisibles"]
  4594. ( "show invisibles (tabs, newlines)" )
  4595. | Opt( config.outputFilename, "filename" )
  4596. ["-o"]["--out"]
  4597. ( "output filename" )
  4598. | Opt( config.reporterNames, "name" )
  4599. ["-r"]["--reporter"]
  4600. ( "reporter to use (defaults to console)" )
  4601. | Opt( config.name, "name" )
  4602. ["-n"]["--name"]
  4603. ( "suite name" )
  4604. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  4605. ["-a"]["--abort"]
  4606. ( "abort at first failure" )
  4607. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  4608. ["-x"]["--abortx"]
  4609. ( "abort after x failures" )
  4610. | Opt( setWarning, "warning name" )
  4611. ["-w"]["--warn"]
  4612. ( "enable warnings" )
  4613. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  4614. ["-d"]["--durations"]
  4615. ( "show test durations" )
  4616. | Opt( loadTestNamesFromFile, "filename" )
  4617. ["-f"]["--input-file"]
  4618. ( "load test names to run from a file" )
  4619. | Opt( config.filenamesAsTags )
  4620. ["-#"]["--filenames-as-tags"]
  4621. ( "adds a tag for the filename" )
  4622. | Opt( config.sectionsToRun, "section name" )
  4623. ["-c"]["--section"]
  4624. ( "specify section to run" )
  4625. | Opt( setVerbosity, "quiet|normal|high" )
  4626. ["-v"]["--verbosity"]
  4627. ( "set output verbosity" )
  4628. | Opt( config.listTestNamesOnly )
  4629. ["--list-test-names-only"]
  4630. ( "list all/matching test cases names only" )
  4631. | Opt( config.listReporters )
  4632. ["--list-reporters"]
  4633. ( "list all reporters" )
  4634. | Opt( setTestOrder, "decl|lex|rand" )
  4635. ["--order"]
  4636. ( "test case order (defaults to decl)" )
  4637. | Opt( setRngSeed, "'time'|number" )
  4638. ["--rng-seed"]
  4639. ( "set a specific seed for random numbers" )
  4640. | Opt( setColourUsage, "yes|no" )
  4641. ["--use-colour"]
  4642. ( "should output be colourised" )
  4643. | Opt( config.libIdentify )
  4644. ["--libidentify"]
  4645. ( "report name and version according to libidentify standard" )
  4646. | Opt( setWaitForKeypress, "start|exit|both" )
  4647. ["--wait-for-keypress"]
  4648. ( "waits for a keypress before exiting" )
  4649. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  4650. ["--benchmark-resolution-multiple"]
  4651. ( "multiple of clock resolution to run benchmarks" )
  4652. | Arg( config.testsOrTags, "test name|pattern|tags" )
  4653. ( "which test or tests to use" );
  4654. return cli;
  4655. }
  4656. } // end namespace Catch
  4657. // end catch_commandline.cpp
  4658. // start catch_common.cpp
  4659. #include <cstring>
  4660. #include <ostream>
  4661. namespace Catch {
  4662. SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  4663. : file( _file ),
  4664. line( _line )
  4665. {}
  4666. bool SourceLineInfo::empty() const noexcept {
  4667. return file[0] == '\0';
  4668. }
  4669. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  4670. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  4671. }
  4672. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  4673. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  4674. }
  4675. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  4676. #ifndef __GNUG__
  4677. os << info.file << '(' << info.line << ')';
  4678. #else
  4679. os << info.file << ':' << info.line;
  4680. #endif
  4681. return os;
  4682. }
  4683. bool isTrue( bool value ){ return value; }
  4684. bool alwaysTrue() { return true; }
  4685. bool alwaysFalse() { return false; }
  4686. std::string StreamEndStop::operator+() const {
  4687. return std::string();
  4688. }
  4689. NonCopyable::NonCopyable() = default;
  4690. NonCopyable::~NonCopyable() = default;
  4691. }
  4692. // end catch_common.cpp
  4693. // start catch_config.cpp
  4694. namespace Catch {
  4695. Config::Config( ConfigData const& data )
  4696. : m_data( data ),
  4697. m_stream( openStream() )
  4698. {
  4699. if( !data.testsOrTags.empty() ) {
  4700. TestSpecParser parser( ITagAliasRegistry::get() );
  4701. for( auto const& testOrTags : data.testsOrTags )
  4702. parser.parse( testOrTags );
  4703. m_testSpec = parser.testSpec();
  4704. }
  4705. }
  4706. std::string const& Config::getFilename() const {
  4707. return m_data.outputFilename ;
  4708. }
  4709. bool Config::listTests() const { return m_data.listTests; }
  4710. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  4711. bool Config::listTags() const { return m_data.listTags; }
  4712. bool Config::listReporters() const { return m_data.listReporters; }
  4713. std::string Config::getProcessName() const { return m_data.processName; }
  4714. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  4715. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  4716. TestSpec const& Config::testSpec() const { return m_testSpec; }
  4717. bool Config::showHelp() const { return m_data.showHelp; }
  4718. // IConfig interface
  4719. bool Config::allowThrows() const { return !m_data.noThrow; }
  4720. std::ostream& Config::stream() const { return m_stream->stream(); }
  4721. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  4722. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  4723. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  4724. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  4725. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  4726. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  4727. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  4728. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  4729. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  4730. int Config::abortAfter() const { return m_data.abortAfter; }
  4731. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  4732. Verbosity Config::verbosity() const { return m_data.verbosity; }
  4733. IStream const* Config::openStream() {
  4734. if( m_data.outputFilename.empty() )
  4735. return new CoutStream();
  4736. else if( m_data.outputFilename[0] == '%' ) {
  4737. if( m_data.outputFilename == "%debug" )
  4738. return new DebugOutStream();
  4739. else
  4740. CATCH_ERROR( "Unrecognised stream: '" << m_data.outputFilename << "'" );
  4741. }
  4742. else
  4743. return new FileStream( m_data.outputFilename );
  4744. }
  4745. } // end namespace Catch
  4746. // end catch_config.cpp
  4747. // start catch_console_colour.cpp
  4748. #if defined(__clang__)
  4749. # pragma clang diagnostic push
  4750. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  4751. #endif
  4752. // start catch_errno_guard.h
  4753. namespace Catch {
  4754. class ErrnoGuard {
  4755. public:
  4756. ErrnoGuard();
  4757. ~ErrnoGuard();
  4758. private:
  4759. int m_oldErrno;
  4760. };
  4761. }
  4762. // end catch_errno_guard.h
  4763. // start catch_windows_h_proxy.h
  4764. #if defined(CATCH_PLATFORM_WINDOWS)
  4765. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4766. # define CATCH_DEFINED_NOMINMAX
  4767. # define NOMINMAX
  4768. #endif
  4769. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4770. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4771. # define WIN32_LEAN_AND_MEAN
  4772. #endif
  4773. #ifdef __AFXDLL
  4774. #include <AfxWin.h>
  4775. #else
  4776. #include <windows.h>
  4777. #endif
  4778. #ifdef CATCH_DEFINED_NOMINMAX
  4779. # undef NOMINMAX
  4780. #endif
  4781. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4782. # undef WIN32_LEAN_AND_MEAN
  4783. #endif
  4784. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4785. // end catch_windows_h_proxy.h
  4786. namespace Catch {
  4787. namespace {
  4788. struct IColourImpl {
  4789. virtual ~IColourImpl() = default;
  4790. virtual void use( Colour::Code _colourCode ) = 0;
  4791. };
  4792. struct NoColourImpl : IColourImpl {
  4793. void use( Colour::Code ) {}
  4794. static IColourImpl* instance() {
  4795. static NoColourImpl s_instance;
  4796. return &s_instance;
  4797. }
  4798. };
  4799. } // anon namespace
  4800. } // namespace Catch
  4801. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  4802. # ifdef CATCH_PLATFORM_WINDOWS
  4803. # define CATCH_CONFIG_COLOUR_WINDOWS
  4804. # else
  4805. # define CATCH_CONFIG_COLOUR_ANSI
  4806. # endif
  4807. #endif
  4808. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  4809. namespace Catch {
  4810. namespace {
  4811. class Win32ColourImpl : public IColourImpl {
  4812. public:
  4813. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  4814. {
  4815. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  4816. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  4817. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  4818. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  4819. }
  4820. virtual void use( Colour::Code _colourCode ) override {
  4821. switch( _colourCode ) {
  4822. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  4823. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4824. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  4825. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  4826. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  4827. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  4828. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  4829. case Colour::Grey: return setTextAttribute( 0 );
  4830. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  4831. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  4832. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  4833. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4834. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4835. }
  4836. }
  4837. private:
  4838. void setTextAttribute( WORD _textAttribute ) {
  4839. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  4840. }
  4841. HANDLE stdoutHandle;
  4842. WORD originalForegroundAttributes;
  4843. WORD originalBackgroundAttributes;
  4844. };
  4845. IColourImpl* platformColourInstance() {
  4846. static Win32ColourImpl s_instance;
  4847. IConfigPtr config = getCurrentContext().getConfig();
  4848. UseColour::YesOrNo colourMode = config
  4849. ? config->useColour()
  4850. : UseColour::Auto;
  4851. if( colourMode == UseColour::Auto )
  4852. colourMode = UseColour::Yes;
  4853. return colourMode == UseColour::Yes
  4854. ? &s_instance
  4855. : NoColourImpl::instance();
  4856. }
  4857. } // end anon namespace
  4858. } // end namespace Catch
  4859. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  4860. #include <unistd.h>
  4861. namespace Catch {
  4862. namespace {
  4863. // use POSIX/ ANSI console terminal codes
  4864. // Thanks to Adam Strzelecki for original contribution
  4865. // (http://github.com/nanoant)
  4866. // https://github.com/philsquared/Catch/pull/131
  4867. class PosixColourImpl : public IColourImpl {
  4868. public:
  4869. virtual void use( Colour::Code _colourCode ) override {
  4870. switch( _colourCode ) {
  4871. case Colour::None:
  4872. case Colour::White: return setColour( "[0m" );
  4873. case Colour::Red: return setColour( "[0;31m" );
  4874. case Colour::Green: return setColour( "[0;32m" );
  4875. case Colour::Blue: return setColour( "[0;34m" );
  4876. case Colour::Cyan: return setColour( "[0;36m" );
  4877. case Colour::Yellow: return setColour( "[0;33m" );
  4878. case Colour::Grey: return setColour( "[1;30m" );
  4879. case Colour::LightGrey: return setColour( "[0;37m" );
  4880. case Colour::BrightRed: return setColour( "[1;31m" );
  4881. case Colour::BrightGreen: return setColour( "[1;32m" );
  4882. case Colour::BrightWhite: return setColour( "[1;37m" );
  4883. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4884. }
  4885. }
  4886. static IColourImpl* instance() {
  4887. static PosixColourImpl s_instance;
  4888. return &s_instance;
  4889. }
  4890. private:
  4891. void setColour( const char* _escapeCode ) {
  4892. Catch::cout() << '\033' << _escapeCode;
  4893. }
  4894. };
  4895. bool useColourOnPlatform() {
  4896. return
  4897. #ifdef CATCH_PLATFORM_MAC
  4898. !isDebuggerActive() &&
  4899. #endif
  4900. isatty(STDOUT_FILENO);
  4901. }
  4902. IColourImpl* platformColourInstance() {
  4903. ErrnoGuard guard;
  4904. IConfigPtr config = getCurrentContext().getConfig();
  4905. UseColour::YesOrNo colourMode = config
  4906. ? config->useColour()
  4907. : UseColour::Auto;
  4908. if( colourMode == UseColour::Auto )
  4909. colourMode = useColourOnPlatform()
  4910. ? UseColour::Yes
  4911. : UseColour::No;
  4912. return colourMode == UseColour::Yes
  4913. ? PosixColourImpl::instance()
  4914. : NoColourImpl::instance();
  4915. }
  4916. } // end anon namespace
  4917. } // end namespace Catch
  4918. #else // not Windows or ANSI ///////////////////////////////////////////////
  4919. namespace Catch {
  4920. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  4921. } // end namespace Catch
  4922. #endif // Windows/ ANSI/ None
  4923. namespace Catch {
  4924. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  4925. Colour::Colour( Colour&& rhs ) noexcept {
  4926. m_moved = rhs.m_moved;
  4927. rhs.m_moved = true;
  4928. }
  4929. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  4930. m_moved = rhs.m_moved;
  4931. rhs.m_moved = true;
  4932. return *this;
  4933. }
  4934. Colour::~Colour(){ if( !m_moved ) use( None ); }
  4935. void Colour::use( Code _colourCode ) {
  4936. static IColourImpl* impl = platformColourInstance();
  4937. impl->use( _colourCode );
  4938. }
  4939. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  4940. return os;
  4941. }
  4942. } // end namespace Catch
  4943. #if defined(__clang__)
  4944. # pragma clang diagnostic pop
  4945. #endif
  4946. // end catch_console_colour.cpp
  4947. // start catch_context.cpp
  4948. namespace Catch {
  4949. class Context : public IMutableContext, NonCopyable {
  4950. public: // IContext
  4951. virtual IResultCapture* getResultCapture() override {
  4952. return m_resultCapture;
  4953. }
  4954. virtual IRunner* getRunner() override {
  4955. return m_runner;
  4956. }
  4957. virtual IConfigPtr getConfig() const override {
  4958. return m_config;
  4959. }
  4960. virtual ~Context() override;
  4961. public: // IMutableContext
  4962. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  4963. m_resultCapture = resultCapture;
  4964. }
  4965. virtual void setRunner( IRunner* runner ) override {
  4966. m_runner = runner;
  4967. }
  4968. virtual void setConfig( IConfigPtr const& config ) override {
  4969. m_config = config;
  4970. }
  4971. friend IMutableContext& getCurrentMutableContext();
  4972. private:
  4973. IConfigPtr m_config;
  4974. IRunner* m_runner = nullptr;
  4975. IResultCapture* m_resultCapture = nullptr;
  4976. };
  4977. namespace {
  4978. Context* currentContext = nullptr;
  4979. }
  4980. IMutableContext& getCurrentMutableContext() {
  4981. if( !currentContext )
  4982. currentContext = new Context();
  4983. return *currentContext;
  4984. }
  4985. IContext& getCurrentContext() {
  4986. return getCurrentMutableContext();
  4987. }
  4988. void cleanUpContext() {
  4989. delete currentContext;
  4990. currentContext = nullptr;
  4991. }
  4992. IContext::~IContext() = default;
  4993. IMutableContext::~IMutableContext() = default;
  4994. Context::~Context() = default;
  4995. }
  4996. // end catch_context.cpp
  4997. // start catch_debug_console.cpp
  4998. // start catch_debug_console.h
  4999. #include <string>
  5000. namespace Catch {
  5001. void writeToDebugConsole( std::string const& text );
  5002. }
  5003. // end catch_debug_console.h
  5004. #ifdef CATCH_PLATFORM_WINDOWS
  5005. namespace Catch {
  5006. void writeToDebugConsole( std::string const& text ) {
  5007. ::OutputDebugStringA( text.c_str() );
  5008. }
  5009. }
  5010. #else
  5011. namespace Catch {
  5012. void writeToDebugConsole( std::string const& text ) {
  5013. // !TBD: Need a version for Mac/ XCode and other IDEs
  5014. Catch::cout() << text;
  5015. }
  5016. }
  5017. #endif // Platform
  5018. // end catch_debug_console.cpp
  5019. // start catch_debugger.cpp
  5020. #ifdef CATCH_PLATFORM_MAC
  5021. #include <assert.h>
  5022. #include <stdbool.h>
  5023. #include <sys/types.h>
  5024. #include <unistd.h>
  5025. #include <sys/sysctl.h>
  5026. namespace Catch {
  5027. // The following function is taken directly from the following technical note:
  5028. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5029. // Returns true if the current process is being debugged (either
  5030. // running under the debugger or has a debugger attached post facto).
  5031. bool isDebuggerActive(){
  5032. int mib[4];
  5033. struct kinfo_proc info;
  5034. std::size_t size;
  5035. // Initialize the flags so that, if sysctl fails for some bizarre
  5036. // reason, we get a predictable result.
  5037. info.kp_proc.p_flag = 0;
  5038. // Initialize mib, which tells sysctl the info we want, in this case
  5039. // we're looking for information about a specific process ID.
  5040. mib[0] = CTL_KERN;
  5041. mib[1] = KERN_PROC;
  5042. mib[2] = KERN_PROC_PID;
  5043. mib[3] = getpid();
  5044. // Call sysctl.
  5045. size = sizeof(info);
  5046. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5047. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5048. return false;
  5049. }
  5050. // We're being debugged if the P_TRACED flag is set.
  5051. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5052. }
  5053. } // namespace Catch
  5054. #elif defined(CATCH_PLATFORM_LINUX)
  5055. #include <fstream>
  5056. #include <string>
  5057. namespace Catch{
  5058. // The standard POSIX way of detecting a debugger is to attempt to
  5059. // ptrace() the process, but this needs to be done from a child and not
  5060. // this process itself to still allow attaching to this process later
  5061. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5062. // "debugger" (which doesn't need to be gdb, of course, it could also
  5063. // be strace, for example) in /proc/$PID/status, so just get it from
  5064. // there instead.
  5065. bool isDebuggerActive(){
  5066. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5067. // This way our users can properly assert over errno values
  5068. ErrnoGuard guard;
  5069. std::ifstream in("/proc/self/status");
  5070. for( std::string line; std::getline(in, line); ) {
  5071. static const int PREFIX_LEN = 11;
  5072. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5073. // We're traced if the PID is not 0 and no other PID starts
  5074. // with 0 digit, so it's enough to check for just a single
  5075. // character.
  5076. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5077. }
  5078. }
  5079. return false;
  5080. }
  5081. } // namespace Catch
  5082. #elif defined(_MSC_VER)
  5083. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5084. namespace Catch {
  5085. bool isDebuggerActive() {
  5086. return IsDebuggerPresent() != 0;
  5087. }
  5088. }
  5089. #elif defined(__MINGW32__)
  5090. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5091. namespace Catch {
  5092. bool isDebuggerActive() {
  5093. return IsDebuggerPresent() != 0;
  5094. }
  5095. }
  5096. #else
  5097. namespace Catch {
  5098. bool isDebuggerActive() { return false; }
  5099. }
  5100. #endif // Platform
  5101. // end catch_debugger.cpp
  5102. // start catch_decomposer.cpp
  5103. namespace Catch {
  5104. ITransientExpression::~ITransientExpression() = default;
  5105. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5106. if( lhs.size() + rhs.size() < 40 &&
  5107. lhs.find('\n') == std::string::npos &&
  5108. rhs.find('\n') == std::string::npos )
  5109. os << lhs << " " << op << " " << rhs;
  5110. else
  5111. os << lhs << "\n" << op << "\n" << rhs;
  5112. }
  5113. }
  5114. // end catch_decomposer.cpp
  5115. // start catch_errno_guard.cpp
  5116. #include <cerrno>
  5117. namespace Catch {
  5118. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5119. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5120. }
  5121. // end catch_errno_guard.cpp
  5122. // start catch_exception_translator_registry.cpp
  5123. // start catch_exception_translator_registry.h
  5124. #include <vector>
  5125. #include <string>
  5126. #include <memory>
  5127. namespace Catch {
  5128. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5129. public:
  5130. ~ExceptionTranslatorRegistry();
  5131. virtual void registerTranslator( const IExceptionTranslator* translator );
  5132. virtual std::string translateActiveException() const override;
  5133. std::string tryTranslators() const;
  5134. private:
  5135. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5136. };
  5137. }
  5138. // end catch_exception_translator_registry.h
  5139. #ifdef __OBJC__
  5140. #import "Foundation/Foundation.h"
  5141. #endif
  5142. namespace Catch {
  5143. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5144. }
  5145. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5146. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5147. }
  5148. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5149. try {
  5150. #ifdef __OBJC__
  5151. // In Objective-C try objective-c exceptions first
  5152. @try {
  5153. return tryTranslators();
  5154. }
  5155. @catch (NSException *exception) {
  5156. return Catch::Detail::stringify( [exception description] );
  5157. }
  5158. #else
  5159. return tryTranslators();
  5160. #endif
  5161. }
  5162. catch( TestFailureException& ) {
  5163. std::rethrow_exception(std::current_exception());
  5164. }
  5165. catch( std::exception& ex ) {
  5166. return ex.what();
  5167. }
  5168. catch( std::string& msg ) {
  5169. return msg;
  5170. }
  5171. catch( const char* msg ) {
  5172. return msg;
  5173. }
  5174. catch(...) {
  5175. return "Unknown exception";
  5176. }
  5177. }
  5178. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5179. if( m_translators.empty() )
  5180. std::rethrow_exception(std::current_exception());
  5181. else
  5182. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5183. }
  5184. }
  5185. // end catch_exception_translator_registry.cpp
  5186. // start catch_fatal_condition.cpp
  5187. // start catch_fatal_condition.h
  5188. #include <string>
  5189. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5190. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5191. namespace Catch {
  5192. struct FatalConditionHandler {
  5193. void reset();
  5194. };
  5195. }
  5196. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5197. namespace Catch {
  5198. struct FatalConditionHandler {
  5199. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  5200. FatalConditionHandler();
  5201. static void reset();
  5202. ~FatalConditionHandler();
  5203. private:
  5204. static bool isSet;
  5205. static ULONG guaranteeSize;
  5206. static PVOID exceptionHandlerHandle;
  5207. };
  5208. } // namespace Catch
  5209. # endif // CATCH_CONFIG_WINDOWS_SEH
  5210. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5211. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5212. namespace Catch {
  5213. struct FatalConditionHandler {
  5214. void reset();
  5215. };
  5216. }
  5217. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5218. #include <signal.h>
  5219. namespace Catch {
  5220. struct FatalConditionHandler {
  5221. static bool isSet;
  5222. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  5223. static stack_t oldSigStack;
  5224. static char altStackMem[];
  5225. static void handleSignal( int sig );
  5226. FatalConditionHandler();
  5227. ~FatalConditionHandler();
  5228. static void reset();
  5229. };
  5230. } // namespace Catch
  5231. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5232. #endif // not Windows
  5233. // end catch_fatal_condition.h
  5234. namespace {
  5235. // Report the error condition
  5236. void reportFatal( char const * const message ) {
  5237. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5238. }
  5239. }
  5240. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5241. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5242. namespace Catch {
  5243. void FatalConditionHandler::reset() {}
  5244. }
  5245. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5246. namespace Catch {
  5247. struct SignalDefs { DWORD id; const char* name; };
  5248. // There is no 1-1 mapping between signals and windows exceptions.
  5249. // Windows can easily distinguish between SO and SigSegV,
  5250. // but SigInt, SigTerm, etc are handled differently.
  5251. static SignalDefs signalDefs[] = {
  5252. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5253. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5254. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5255. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5256. };
  5257. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5258. for (auto const& def : signalDefs) {
  5259. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5260. reportFatal(def.name);
  5261. }
  5262. }
  5263. // If its not an exception we care about, pass it along.
  5264. // This stops us from eating debugger breaks etc.
  5265. return EXCEPTION_CONTINUE_SEARCH;
  5266. }
  5267. FatalConditionHandler::FatalConditionHandler() {
  5268. isSet = true;
  5269. // 32k seems enough for Catch to handle stack overflow,
  5270. // but the value was found experimentally, so there is no strong guarantee
  5271. guaranteeSize = 32 * 1024;
  5272. exceptionHandlerHandle = nullptr;
  5273. // Register as first handler in current chain
  5274. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5275. // Pass in guarantee size to be filled
  5276. SetThreadStackGuarantee(&guaranteeSize);
  5277. }
  5278. void FatalConditionHandler::reset() {
  5279. if (isSet) {
  5280. // Unregister handler and restore the old guarantee
  5281. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5282. SetThreadStackGuarantee(&guaranteeSize);
  5283. exceptionHandlerHandle = nullptr;
  5284. isSet = false;
  5285. }
  5286. }
  5287. FatalConditionHandler::~FatalConditionHandler() {
  5288. reset();
  5289. }
  5290. bool FatalConditionHandler::isSet = false;
  5291. ULONG FatalConditionHandler::guaranteeSize = 0;
  5292. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5293. } // namespace Catch
  5294. # endif // CATCH_CONFIG_WINDOWS_SEH
  5295. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5296. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5297. namespace Catch {
  5298. void FatalConditionHandler::reset() {}
  5299. }
  5300. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5301. #include <signal.h>
  5302. namespace Catch {
  5303. struct SignalDefs {
  5304. int id;
  5305. const char* name;
  5306. };
  5307. static SignalDefs signalDefs[] = {
  5308. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5309. { SIGILL, "SIGILL - Illegal instruction signal" },
  5310. { SIGFPE, "SIGFPE - Floating point error signal" },
  5311. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5312. { SIGTERM, "SIGTERM - Termination request signal" },
  5313. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5314. };
  5315. void FatalConditionHandler::handleSignal( int sig ) {
  5316. char const * name = "<unknown signal>";
  5317. for (auto const& def : signalDefs) {
  5318. if (sig == def.id) {
  5319. name = def.name;
  5320. break;
  5321. }
  5322. }
  5323. reset();
  5324. reportFatal(name);
  5325. raise( sig );
  5326. }
  5327. FatalConditionHandler::FatalConditionHandler() {
  5328. isSet = true;
  5329. stack_t sigStack;
  5330. sigStack.ss_sp = altStackMem;
  5331. sigStack.ss_size = SIGSTKSZ;
  5332. sigStack.ss_flags = 0;
  5333. sigaltstack(&sigStack, &oldSigStack);
  5334. struct sigaction sa = { };
  5335. sa.sa_handler = handleSignal;
  5336. sa.sa_flags = SA_ONSTACK;
  5337. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5338. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5339. }
  5340. }
  5341. FatalConditionHandler::~FatalConditionHandler() {
  5342. reset();
  5343. }
  5344. void FatalConditionHandler::reset() {
  5345. if( isSet ) {
  5346. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5347. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5348. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5349. }
  5350. // Return the old stack
  5351. sigaltstack(&oldSigStack, nullptr);
  5352. isSet = false;
  5353. }
  5354. }
  5355. bool FatalConditionHandler::isSet = false;
  5356. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5357. stack_t FatalConditionHandler::oldSigStack = {};
  5358. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5359. } // namespace Catch
  5360. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5361. #endif // not Windows
  5362. // end catch_fatal_condition.cpp
  5363. // start catch_interfaces_capture.cpp
  5364. namespace Catch {
  5365. IResultCapture::~IResultCapture() = default;
  5366. }
  5367. // end catch_interfaces_capture.cpp
  5368. // start catch_interfaces_config.cpp
  5369. namespace Catch {
  5370. IConfig::~IConfig() = default;
  5371. }
  5372. // end catch_interfaces_config.cpp
  5373. // start catch_interfaces_exception.cpp
  5374. namespace Catch {
  5375. IExceptionTranslator::~IExceptionTranslator() = default;
  5376. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5377. }
  5378. // end catch_interfaces_exception.cpp
  5379. // start catch_interfaces_registry_hub.cpp
  5380. namespace Catch {
  5381. IRegistryHub::~IRegistryHub() = default;
  5382. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5383. }
  5384. // end catch_interfaces_registry_hub.cpp
  5385. // start catch_interfaces_reporter.cpp
  5386. // start catch_reporter_multi.h
  5387. namespace Catch {
  5388. class MultipleReporters : public IStreamingReporter {
  5389. using Reporters = std::vector<IStreamingReporterPtr>;
  5390. Reporters m_reporters;
  5391. public:
  5392. void add( IStreamingReporterPtr&& reporter );
  5393. public: // IStreamingReporter
  5394. ReporterPreferences getPreferences() const override;
  5395. void noMatchingTestCases( std::string const& spec ) override;
  5396. static std::set<Verbosity> getSupportedVerbosities();
  5397. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5398. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5399. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5400. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5401. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5402. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5403. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5404. // The return value indicates if the messages buffer should be cleared:
  5405. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5406. void sectionEnded( SectionStats const& sectionStats ) override;
  5407. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5408. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5409. void testRunEnded( TestRunStats const& testRunStats ) override;
  5410. void skipTest( TestCaseInfo const& testInfo ) override;
  5411. bool isMulti() const override;
  5412. };
  5413. } // end namespace Catch
  5414. // end catch_reporter_multi.h
  5415. namespace Catch {
  5416. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5417. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5418. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5419. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5420. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5421. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5422. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5423. GroupInfo::GroupInfo( std::string const& _name,
  5424. std::size_t _groupIndex,
  5425. std::size_t _groupsCount )
  5426. : name( _name ),
  5427. groupIndex( _groupIndex ),
  5428. groupsCounts( _groupsCount )
  5429. {}
  5430. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5431. std::vector<MessageInfo> const& _infoMessages,
  5432. Totals const& _totals )
  5433. : assertionResult( _assertionResult ),
  5434. infoMessages( _infoMessages ),
  5435. totals( _totals )
  5436. {
  5437. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5438. if( assertionResult.hasMessage() ) {
  5439. // Copy message into messages list.
  5440. // !TBD This should have been done earlier, somewhere
  5441. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5442. builder << assertionResult.getMessage();
  5443. builder.m_info.message = builder.m_stream.str();
  5444. infoMessages.push_back( builder.m_info );
  5445. }
  5446. }
  5447. AssertionStats::~AssertionStats() = default;
  5448. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5449. Counts const& _assertions,
  5450. double _durationInSeconds,
  5451. bool _missingAssertions )
  5452. : sectionInfo( _sectionInfo ),
  5453. assertions( _assertions ),
  5454. durationInSeconds( _durationInSeconds ),
  5455. missingAssertions( _missingAssertions )
  5456. {}
  5457. SectionStats::~SectionStats() = default;
  5458. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5459. Totals const& _totals,
  5460. std::string const& _stdOut,
  5461. std::string const& _stdErr,
  5462. bool _aborting )
  5463. : testInfo( _testInfo ),
  5464. totals( _totals ),
  5465. stdOut( _stdOut ),
  5466. stdErr( _stdErr ),
  5467. aborting( _aborting )
  5468. {}
  5469. TestCaseStats::~TestCaseStats() = default;
  5470. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5471. Totals const& _totals,
  5472. bool _aborting )
  5473. : groupInfo( _groupInfo ),
  5474. totals( _totals ),
  5475. aborting( _aborting )
  5476. {}
  5477. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5478. : groupInfo( _groupInfo ),
  5479. aborting( false )
  5480. {}
  5481. TestGroupStats::~TestGroupStats() = default;
  5482. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5483. Totals const& _totals,
  5484. bool _aborting )
  5485. : runInfo( _runInfo ),
  5486. totals( _totals ),
  5487. aborting( _aborting )
  5488. {}
  5489. TestRunStats::~TestRunStats() = default;
  5490. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5491. bool IStreamingReporter::isMulti() const { return false; }
  5492. IReporterFactory::~IReporterFactory() = default;
  5493. IReporterRegistry::~IReporterRegistry() = default;
  5494. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5495. if( !existingReporter ) {
  5496. existingReporter = std::move( additionalReporter );
  5497. return;
  5498. }
  5499. MultipleReporters* multi = nullptr;
  5500. if( existingReporter->isMulti() ) {
  5501. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5502. }
  5503. else {
  5504. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  5505. newMulti->add( std::move( existingReporter ) );
  5506. multi = newMulti.get();
  5507. existingReporter = std::move( newMulti );
  5508. }
  5509. multi->add( std::move( additionalReporter ) );
  5510. }
  5511. } // end namespace Catch
  5512. // end catch_interfaces_reporter.cpp
  5513. // start catch_interfaces_runner.cpp
  5514. namespace Catch {
  5515. IRunner::~IRunner() = default;
  5516. }
  5517. // end catch_interfaces_runner.cpp
  5518. // start catch_interfaces_testcase.cpp
  5519. namespace Catch {
  5520. ITestInvoker::~ITestInvoker() = default;
  5521. ITestCaseRegistry::~ITestCaseRegistry() = default;
  5522. }
  5523. // end catch_interfaces_testcase.cpp
  5524. // start catch_leak_detector.cpp
  5525. namespace Catch {
  5526. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  5527. #include <crtdbg.h>
  5528. LeakDetector::LeakDetector() {
  5529. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  5530. flag |= _CRTDBG_LEAK_CHECK_DF;
  5531. flag |= _CRTDBG_ALLOC_MEM_DF;
  5532. _CrtSetDbgFlag(flag);
  5533. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5534. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  5535. // Change this to leaking allocation's number to break there
  5536. _CrtSetBreakAlloc(-1);
  5537. }
  5538. #else
  5539. LeakDetector::LeakDetector(){}
  5540. #endif
  5541. }
  5542. // end catch_leak_detector.cpp
  5543. // start catch_list.cpp
  5544. // start catch_list.h
  5545. #include <set>
  5546. namespace Catch {
  5547. std::size_t listTests( Config const& config );
  5548. std::size_t listTestsNamesOnly( Config const& config );
  5549. struct TagInfo {
  5550. void add( std::string const& spelling );
  5551. std::string all() const;
  5552. std::set<std::string> spellings;
  5553. std::size_t count = 0;
  5554. };
  5555. std::size_t listTags( Config const& config );
  5556. std::size_t listReporters( Config const& /*config*/ );
  5557. Option<std::size_t> list( Config const& config );
  5558. } // end namespace Catch
  5559. // end catch_list.h
  5560. // start catch_text.h
  5561. namespace Catch {
  5562. using namespace clara::TextFlow;
  5563. }
  5564. // end catch_text.h
  5565. #include <limits>
  5566. #include <algorithm>
  5567. #include <iomanip>
  5568. namespace Catch {
  5569. std::size_t listTests( Config const& config ) {
  5570. TestSpec testSpec = config.testSpec();
  5571. if( config.testSpec().hasFilters() )
  5572. Catch::cout() << "Matching test cases:\n";
  5573. else {
  5574. Catch::cout() << "All available test cases:\n";
  5575. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5576. }
  5577. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5578. for( auto const& testCaseInfo : matchedTestCases ) {
  5579. Colour::Code colour = testCaseInfo.isHidden()
  5580. ? Colour::SecondaryText
  5581. : Colour::None;
  5582. Colour colourGuard( colour );
  5583. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  5584. if( config.verbosity() >= Verbosity::High ) {
  5585. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  5586. std::string description = testCaseInfo.description;
  5587. if( description.empty() )
  5588. description = "(NO DESCRIPTION)";
  5589. Catch::cout() << Column( description ).indent(4) << std::endl;
  5590. }
  5591. if( !testCaseInfo.tags.empty() )
  5592. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  5593. }
  5594. if( !config.testSpec().hasFilters() )
  5595. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  5596. else
  5597. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  5598. return matchedTestCases.size();
  5599. }
  5600. std::size_t listTestsNamesOnly( Config const& config ) {
  5601. TestSpec testSpec = config.testSpec();
  5602. if( !config.testSpec().hasFilters() )
  5603. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5604. std::size_t matchedTests = 0;
  5605. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5606. for( auto const& testCaseInfo : matchedTestCases ) {
  5607. matchedTests++;
  5608. if( startsWith( testCaseInfo.name, '#' ) )
  5609. Catch::cout() << '"' << testCaseInfo.name << '"';
  5610. else
  5611. Catch::cout() << testCaseInfo.name;
  5612. if ( config.verbosity() >= Verbosity::High )
  5613. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  5614. Catch::cout() << std::endl;
  5615. }
  5616. return matchedTests;
  5617. }
  5618. void TagInfo::add( std::string const& spelling ) {
  5619. ++count;
  5620. spellings.insert( spelling );
  5621. }
  5622. std::string TagInfo::all() const {
  5623. std::string out;
  5624. for( auto const& spelling : spellings )
  5625. out += "[" + spelling + "]";
  5626. return out;
  5627. }
  5628. std::size_t listTags( Config const& config ) {
  5629. TestSpec testSpec = config.testSpec();
  5630. if( config.testSpec().hasFilters() )
  5631. Catch::cout() << "Tags for matching test cases:\n";
  5632. else {
  5633. Catch::cout() << "All available tags:\n";
  5634. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5635. }
  5636. std::map<std::string, TagInfo> tagCounts;
  5637. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5638. for( auto const& testCase : matchedTestCases ) {
  5639. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  5640. std::string lcaseTagName = toLower( tagName );
  5641. auto countIt = tagCounts.find( lcaseTagName );
  5642. if( countIt == tagCounts.end() )
  5643. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  5644. countIt->second.add( tagName );
  5645. }
  5646. }
  5647. for( auto const& tagCount : tagCounts ) {
  5648. std::ostringstream oss;
  5649. oss << " " << std::setw(2) << tagCount.second.count << " ";
  5650. auto wrapper = Column( tagCount.second.all() )
  5651. .initialIndent( 0 )
  5652. .indent( oss.str().size() )
  5653. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  5654. Catch::cout() << oss.str() << wrapper << '\n';
  5655. }
  5656. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  5657. return tagCounts.size();
  5658. }
  5659. std::size_t listReporters( Config const& /*config*/ ) {
  5660. Catch::cout() << "Available reporters:\n";
  5661. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  5662. std::size_t maxNameLen = 0;
  5663. for( auto const& factoryKvp : factories )
  5664. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  5665. for( auto const& factoryKvp : factories ) {
  5666. Catch::cout()
  5667. << Column( factoryKvp.first + ":" )
  5668. .indent(2)
  5669. .width( 5+maxNameLen )
  5670. + Column( factoryKvp.second->getDescription() )
  5671. .initialIndent(0)
  5672. .indent(2)
  5673. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  5674. << "\n";
  5675. }
  5676. Catch::cout() << std::endl;
  5677. return factories.size();
  5678. }
  5679. Option<std::size_t> list( Config const& config ) {
  5680. Option<std::size_t> listedCount;
  5681. if( config.listTests() )
  5682. listedCount = listedCount.valueOr(0) + listTests( config );
  5683. if( config.listTestNamesOnly() )
  5684. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  5685. if( config.listTags() )
  5686. listedCount = listedCount.valueOr(0) + listTags( config );
  5687. if( config.listReporters() )
  5688. listedCount = listedCount.valueOr(0) + listReporters( config );
  5689. return listedCount;
  5690. }
  5691. } // end namespace Catch
  5692. // end catch_list.cpp
  5693. // start catch_matchers.cpp
  5694. namespace Catch {
  5695. namespace Matchers {
  5696. namespace Impl {
  5697. std::string MatcherUntypedBase::toString() const {
  5698. if( m_cachedToString.empty() )
  5699. m_cachedToString = describe();
  5700. return m_cachedToString;
  5701. }
  5702. MatcherUntypedBase::~MatcherUntypedBase() = default;
  5703. } // namespace Impl
  5704. } // namespace Matchers
  5705. using namespace Matchers;
  5706. using Matchers::Impl::MatcherBase;
  5707. } // namespace Catch
  5708. // end catch_matchers.cpp
  5709. // start catch_matchers_string.cpp
  5710. namespace Catch {
  5711. namespace Matchers {
  5712. namespace StdString {
  5713. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  5714. : m_caseSensitivity( caseSensitivity ),
  5715. m_str( adjustString( str ) )
  5716. {}
  5717. std::string CasedString::adjustString( std::string const& str ) const {
  5718. return m_caseSensitivity == CaseSensitive::No
  5719. ? toLower( str )
  5720. : str;
  5721. }
  5722. std::string CasedString::caseSensitivitySuffix() const {
  5723. return m_caseSensitivity == CaseSensitive::No
  5724. ? " (case insensitive)"
  5725. : std::string();
  5726. }
  5727. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  5728. : m_comparator( comparator ),
  5729. m_operation( operation ) {
  5730. }
  5731. std::string StringMatcherBase::describe() const {
  5732. std::string description;
  5733. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  5734. m_comparator.caseSensitivitySuffix().size());
  5735. description += m_operation;
  5736. description += ": \"";
  5737. description += m_comparator.m_str;
  5738. description += "\"";
  5739. description += m_comparator.caseSensitivitySuffix();
  5740. return description;
  5741. }
  5742. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  5743. bool EqualsMatcher::match( std::string const& source ) const {
  5744. return m_comparator.adjustString( source ) == m_comparator.m_str;
  5745. }
  5746. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  5747. bool ContainsMatcher::match( std::string const& source ) const {
  5748. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  5749. }
  5750. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  5751. bool StartsWithMatcher::match( std::string const& source ) const {
  5752. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5753. }
  5754. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  5755. bool EndsWithMatcher::match( std::string const& source ) const {
  5756. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5757. }
  5758. } // namespace StdString
  5759. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5760. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  5761. }
  5762. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5763. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  5764. }
  5765. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5766. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5767. }
  5768. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5769. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5770. }
  5771. } // namespace Matchers
  5772. } // namespace Catch
  5773. // end catch_matchers_string.cpp
  5774. // start catch_message.cpp
  5775. namespace Catch {
  5776. MessageInfo::MessageInfo( std::string const& _macroName,
  5777. SourceLineInfo const& _lineInfo,
  5778. ResultWas::OfType _type )
  5779. : macroName( _macroName ),
  5780. lineInfo( _lineInfo ),
  5781. type( _type ),
  5782. sequence( ++globalCount )
  5783. {}
  5784. bool MessageInfo::operator==( MessageInfo const& other ) const {
  5785. return sequence == other.sequence;
  5786. }
  5787. bool MessageInfo::operator<( MessageInfo const& other ) const {
  5788. return sequence < other.sequence;
  5789. }
  5790. // This may need protecting if threading support is added
  5791. unsigned int MessageInfo::globalCount = 0;
  5792. ////////////////////////////////////////////////////////////////////////////
  5793. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  5794. SourceLineInfo const& lineInfo,
  5795. ResultWas::OfType type )
  5796. :m_info(macroName, lineInfo, type) {}
  5797. ////////////////////////////////////////////////////////////////////////////
  5798. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  5799. : m_info( builder.m_info )
  5800. {
  5801. m_info.message = builder.m_stream.str();
  5802. getResultCapture().pushScopedMessage( m_info );
  5803. }
  5804. ScopedMessage::~ScopedMessage() {
  5805. if ( !std::uncaught_exception() ){
  5806. getResultCapture().popScopedMessage(m_info);
  5807. }
  5808. }
  5809. } // end namespace Catch
  5810. // end catch_message.cpp
  5811. // start catch_random_number_generator.cpp
  5812. // start catch_random_number_generator.h
  5813. #include <algorithm>
  5814. namespace Catch {
  5815. struct IConfig;
  5816. void seedRng( IConfig const& config );
  5817. unsigned int rngSeed();
  5818. struct RandomNumberGenerator {
  5819. using result_type = unsigned int;
  5820. static constexpr result_type (min)() { return 0; }
  5821. static constexpr result_type (max)() { return 1000000; }
  5822. result_type operator()( result_type n ) const;
  5823. result_type operator()() const;
  5824. template<typename V>
  5825. static void shuffle( V& vector ) {
  5826. RandomNumberGenerator rng;
  5827. std::shuffle( vector.begin(), vector.end(), rng );
  5828. }
  5829. };
  5830. }
  5831. // end catch_random_number_generator.h
  5832. #include <cstdlib>
  5833. namespace Catch {
  5834. void seedRng( IConfig const& config ) {
  5835. if( config.rngSeed() != 0 )
  5836. std::srand( config.rngSeed() );
  5837. }
  5838. unsigned int rngSeed() {
  5839. return getCurrentContext().getConfig()->rngSeed();
  5840. }
  5841. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  5842. return std::rand() % n;
  5843. }
  5844. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  5845. return std::rand() % (max)();
  5846. }
  5847. }
  5848. // end catch_random_number_generator.cpp
  5849. // start catch_registry_hub.cpp
  5850. // start catch_test_case_registry_impl.h
  5851. #include <vector>
  5852. #include <set>
  5853. #include <algorithm>
  5854. #include <ios>
  5855. namespace Catch {
  5856. class TestCase;
  5857. struct IConfig;
  5858. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  5859. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  5860. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  5861. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  5862. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  5863. class TestRegistry : public ITestCaseRegistry {
  5864. public:
  5865. virtual ~TestRegistry() = default;
  5866. virtual void registerTest( TestCase const& testCase );
  5867. std::vector<TestCase> const& getAllTests() const override;
  5868. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  5869. private:
  5870. std::vector<TestCase> m_functions;
  5871. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  5872. mutable std::vector<TestCase> m_sortedFunctions;
  5873. std::size_t m_unnamedCount = 0;
  5874. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  5875. };
  5876. ///////////////////////////////////////////////////////////////////////////
  5877. class TestInvokerAsFunction : public ITestInvoker {
  5878. void(*m_testAsFunction)();
  5879. public:
  5880. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  5881. void invoke() const override;
  5882. };
  5883. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  5884. ///////////////////////////////////////////////////////////////////////////
  5885. } // end namespace Catch
  5886. // end catch_test_case_registry_impl.h
  5887. // start catch_reporter_registry.h
  5888. #include <map>
  5889. namespace Catch {
  5890. class ReporterRegistry : public IReporterRegistry {
  5891. public:
  5892. ~ReporterRegistry() override;
  5893. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  5894. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  5895. void registerListener( IReporterFactoryPtr const& factory );
  5896. FactoryMap const& getFactories() const override;
  5897. Listeners const& getListeners() const override;
  5898. private:
  5899. FactoryMap m_factories;
  5900. Listeners m_listeners;
  5901. };
  5902. }
  5903. // end catch_reporter_registry.h
  5904. // start catch_tag_alias_registry.h
  5905. // start catch_tag_alias.h
  5906. #include <string>
  5907. namespace Catch {
  5908. struct TagAlias {
  5909. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  5910. std::string tag;
  5911. SourceLineInfo lineInfo;
  5912. };
  5913. } // end namespace Catch
  5914. // end catch_tag_alias.h
  5915. #include <map>
  5916. namespace Catch {
  5917. class TagAliasRegistry : public ITagAliasRegistry {
  5918. public:
  5919. ~TagAliasRegistry() override;
  5920. TagAlias const* find( std::string const& alias ) const override;
  5921. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  5922. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  5923. private:
  5924. std::map<std::string, TagAlias> m_registry;
  5925. };
  5926. } // end namespace Catch
  5927. // end catch_tag_alias_registry.h
  5928. // start catch_startup_exception_registry.h
  5929. #include <vector>
  5930. #include <exception>
  5931. namespace Catch {
  5932. class StartupExceptionRegistry {
  5933. public:
  5934. void add(std::exception_ptr const& exception) noexcept;
  5935. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  5936. private:
  5937. std::vector<std::exception_ptr> m_exceptions;
  5938. };
  5939. } // end namespace Catch
  5940. // end catch_startup_exception_registry.h
  5941. namespace Catch {
  5942. namespace {
  5943. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  5944. private NonCopyable {
  5945. public: // IRegistryHub
  5946. RegistryHub() = default;
  5947. IReporterRegistry const& getReporterRegistry() const override {
  5948. return m_reporterRegistry;
  5949. }
  5950. ITestCaseRegistry const& getTestCaseRegistry() const override {
  5951. return m_testCaseRegistry;
  5952. }
  5953. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  5954. return m_exceptionTranslatorRegistry;
  5955. }
  5956. ITagAliasRegistry const& getTagAliasRegistry() const override {
  5957. return m_tagAliasRegistry;
  5958. }
  5959. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  5960. return m_exceptionRegistry;
  5961. }
  5962. public: // IMutableRegistryHub
  5963. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  5964. m_reporterRegistry.registerReporter( name, factory );
  5965. }
  5966. void registerListener( IReporterFactoryPtr const& factory ) override {
  5967. m_reporterRegistry.registerListener( factory );
  5968. }
  5969. void registerTest( TestCase const& testInfo ) override {
  5970. m_testCaseRegistry.registerTest( testInfo );
  5971. }
  5972. void registerTranslator( const IExceptionTranslator* translator ) override {
  5973. m_exceptionTranslatorRegistry.registerTranslator( translator );
  5974. }
  5975. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  5976. m_tagAliasRegistry.add( alias, tag, lineInfo );
  5977. }
  5978. void registerStartupException() noexcept override {
  5979. m_exceptionRegistry.add(std::current_exception());
  5980. }
  5981. private:
  5982. TestRegistry m_testCaseRegistry;
  5983. ReporterRegistry m_reporterRegistry;
  5984. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  5985. TagAliasRegistry m_tagAliasRegistry;
  5986. StartupExceptionRegistry m_exceptionRegistry;
  5987. };
  5988. // Single, global, instance
  5989. RegistryHub*& getTheRegistryHub() {
  5990. static RegistryHub* theRegistryHub = nullptr;
  5991. if( !theRegistryHub )
  5992. theRegistryHub = new RegistryHub();
  5993. return theRegistryHub;
  5994. }
  5995. }
  5996. IRegistryHub& getRegistryHub() {
  5997. return *getTheRegistryHub();
  5998. }
  5999. IMutableRegistryHub& getMutableRegistryHub() {
  6000. return *getTheRegistryHub();
  6001. }
  6002. void cleanUp() {
  6003. delete getTheRegistryHub();
  6004. getTheRegistryHub() = nullptr;
  6005. cleanUpContext();
  6006. }
  6007. std::string translateActiveException() {
  6008. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6009. }
  6010. } // end namespace Catch
  6011. // end catch_registry_hub.cpp
  6012. // start catch_reporter_registry.cpp
  6013. namespace Catch {
  6014. ReporterRegistry::~ReporterRegistry() = default;
  6015. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6016. auto it = m_factories.find( name );
  6017. if( it == m_factories.end() )
  6018. return nullptr;
  6019. return it->second->create( ReporterConfig( config ) );
  6020. }
  6021. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6022. m_factories.emplace(name, factory);
  6023. }
  6024. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6025. m_listeners.push_back( factory );
  6026. }
  6027. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6028. return m_factories;
  6029. }
  6030. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6031. return m_listeners;
  6032. }
  6033. }
  6034. // end catch_reporter_registry.cpp
  6035. // start catch_result_type.cpp
  6036. namespace Catch {
  6037. bool isOk( ResultWas::OfType resultType ) {
  6038. return ( resultType & ResultWas::FailureBit ) == 0;
  6039. }
  6040. bool isJustInfo( int flags ) {
  6041. return flags == ResultWas::Info;
  6042. }
  6043. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6044. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6045. }
  6046. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6047. bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  6048. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6049. } // end namespace Catch
  6050. // end catch_result_type.cpp
  6051. // start catch_run_context.cpp
  6052. // start catch_run_context.h
  6053. #include <string>
  6054. namespace Catch {
  6055. struct IMutableContext;
  6056. class StreamRedirect {
  6057. public:
  6058. StreamRedirect(std::ostream& stream, std::string& targetString);
  6059. ~StreamRedirect();
  6060. private:
  6061. std::ostream& m_stream;
  6062. std::streambuf* m_prevBuf;
  6063. std::ostringstream m_oss;
  6064. std::string& m_targetString;
  6065. };
  6066. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6067. // This means that we need to redirect 2 streams into 1 to keep proper
  6068. // order of writes and cannot use StreamRedirect on its own
  6069. class StdErrRedirect {
  6070. public:
  6071. StdErrRedirect(std::string& targetString);
  6072. ~StdErrRedirect();
  6073. private:
  6074. std::streambuf* m_cerrBuf;
  6075. std::streambuf* m_clogBuf;
  6076. std::ostringstream m_oss;
  6077. std::string& m_targetString;
  6078. };
  6079. ///////////////////////////////////////////////////////////////////////////
  6080. class RunContext : public IResultCapture, public IRunner {
  6081. public:
  6082. RunContext( RunContext const& ) = delete;
  6083. RunContext& operator =( RunContext const& ) = delete;
  6084. explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
  6085. virtual ~RunContext();
  6086. void testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount);
  6087. void testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount);
  6088. Totals runTest(TestCase const& testCase);
  6089. IConfigPtr config() const;
  6090. IStreamingReporter& reporter() const;
  6091. private: // IResultCapture
  6092. void assertionStarting(AssertionInfo const& info) override;
  6093. void assertionEnded(AssertionResult const& result) override;
  6094. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6095. bool testForMissingAssertions(Counts& assertions);
  6096. void sectionEnded(SectionEndInfo const& endInfo) override;
  6097. void sectionEndedEarly(SectionEndInfo const& endInfo) override;
  6098. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6099. void benchmarkEnded( BenchmarkStats const& stats ) override;
  6100. void pushScopedMessage(MessageInfo const& message) override;
  6101. void popScopedMessage(MessageInfo const& message) override;
  6102. std::string getCurrentTestName() const override;
  6103. const AssertionResult* getLastResult() const override;
  6104. void exceptionEarlyReported() override;
  6105. void handleFatalErrorCondition( StringRef message ) override;
  6106. bool lastAssertionPassed() override;
  6107. void assertionPassed() override;
  6108. void assertionRun() override;
  6109. public:
  6110. // !TBD We need to do this another way!
  6111. bool aborting() const override;
  6112. private:
  6113. void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
  6114. void invokeActiveTestCase();
  6115. private:
  6116. void handleUnfinishedSections();
  6117. TestRunInfo m_runInfo;
  6118. IMutableContext& m_context;
  6119. TestCase const* m_activeTestCase = nullptr;
  6120. ITracker* m_testCaseTracker;
  6121. Option<AssertionResult> m_lastResult;
  6122. IConfigPtr m_config;
  6123. Totals m_totals;
  6124. IStreamingReporterPtr m_reporter;
  6125. std::vector<MessageInfo> m_messages;
  6126. AssertionInfo m_lastAssertionInfo;
  6127. std::vector<SectionEndInfo> m_unfinishedSections;
  6128. std::vector<ITracker*> m_activeSections;
  6129. TrackerContext m_trackerContext;
  6130. std::size_t m_prevPassed = 0;
  6131. bool m_shouldReportUnexpected = true;
  6132. };
  6133. IResultCapture& getResultCapture();
  6134. } // end namespace Catch
  6135. // end catch_run_context.h
  6136. #include <cassert>
  6137. #include <algorithm>
  6138. namespace Catch {
  6139. StreamRedirect::StreamRedirect(std::ostream& stream, std::string& targetString)
  6140. : m_stream(stream),
  6141. m_prevBuf(stream.rdbuf()),
  6142. m_targetString(targetString) {
  6143. stream.rdbuf(m_oss.rdbuf());
  6144. }
  6145. StreamRedirect::~StreamRedirect() {
  6146. m_targetString += m_oss.str();
  6147. m_stream.rdbuf(m_prevBuf);
  6148. }
  6149. StdErrRedirect::StdErrRedirect(std::string & targetString)
  6150. :m_cerrBuf(cerr().rdbuf()), m_clogBuf(clog().rdbuf()),
  6151. m_targetString(targetString) {
  6152. cerr().rdbuf(m_oss.rdbuf());
  6153. clog().rdbuf(m_oss.rdbuf());
  6154. }
  6155. StdErrRedirect::~StdErrRedirect() {
  6156. m_targetString += m_oss.str();
  6157. cerr().rdbuf(m_cerrBuf);
  6158. clog().rdbuf(m_clogBuf);
  6159. }
  6160. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6161. : m_runInfo(_config->name()),
  6162. m_context(getCurrentMutableContext()),
  6163. m_config(_config),
  6164. m_reporter(std::move(reporter)),
  6165. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal }
  6166. {
  6167. m_context.setRunner(this);
  6168. m_context.setConfig(m_config);
  6169. m_context.setResultCapture(this);
  6170. m_reporter->testRunStarting(m_runInfo);
  6171. }
  6172. RunContext::~RunContext() {
  6173. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6174. }
  6175. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6176. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6177. }
  6178. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6179. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6180. }
  6181. Totals RunContext::runTest(TestCase const& testCase) {
  6182. Totals prevTotals = m_totals;
  6183. std::string redirectedCout;
  6184. std::string redirectedCerr;
  6185. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6186. m_reporter->testCaseStarting(testInfo);
  6187. m_activeTestCase = &testCase;
  6188. ITracker& rootTracker = m_trackerContext.startRun();
  6189. assert(rootTracker.isSectionTracker());
  6190. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6191. do {
  6192. m_trackerContext.startCycle();
  6193. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6194. runCurrentTest(redirectedCout, redirectedCerr);
  6195. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6196. Totals deltaTotals = m_totals.delta(prevTotals);
  6197. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6198. deltaTotals.assertions.failed++;
  6199. deltaTotals.testCases.passed--;
  6200. deltaTotals.testCases.failed++;
  6201. }
  6202. m_totals.testCases += deltaTotals.testCases;
  6203. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6204. deltaTotals,
  6205. redirectedCout,
  6206. redirectedCerr,
  6207. aborting()));
  6208. m_activeTestCase = nullptr;
  6209. m_testCaseTracker = nullptr;
  6210. return deltaTotals;
  6211. }
  6212. IConfigPtr RunContext::config() const {
  6213. return m_config;
  6214. }
  6215. IStreamingReporter& RunContext::reporter() const {
  6216. return *m_reporter;
  6217. }
  6218. void RunContext::assertionStarting(AssertionInfo const& info) {
  6219. m_reporter->assertionStarting( info );
  6220. }
  6221. void RunContext::assertionEnded(AssertionResult const & result) {
  6222. if (result.getResultType() == ResultWas::Ok) {
  6223. m_totals.assertions.passed++;
  6224. } else if (!result.isOk()) {
  6225. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6226. m_totals.assertions.failedButOk++;
  6227. else
  6228. m_totals.assertions.failed++;
  6229. }
  6230. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6231. // and should be let to clear themselves out.
  6232. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6233. // Reset working state
  6234. m_lastAssertionInfo = { "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}", m_lastAssertionInfo.resultDisposition };
  6235. m_lastResult = result;
  6236. }
  6237. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6238. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6239. if (!sectionTracker.isOpen())
  6240. return false;
  6241. m_activeSections.push_back(&sectionTracker);
  6242. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6243. m_reporter->sectionStarting(sectionInfo);
  6244. assertions = m_totals.assertions;
  6245. return true;
  6246. }
  6247. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6248. if (assertions.total() != 0)
  6249. return false;
  6250. if (!m_config->warnAboutMissingAssertions())
  6251. return false;
  6252. if (m_trackerContext.currentTracker().hasChildren())
  6253. return false;
  6254. m_totals.assertions.failed++;
  6255. assertions.failed++;
  6256. return true;
  6257. }
  6258. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6259. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6260. bool missingAssertions = testForMissingAssertions(assertions);
  6261. if (!m_activeSections.empty()) {
  6262. m_activeSections.back()->close();
  6263. m_activeSections.pop_back();
  6264. }
  6265. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6266. m_messages.clear();
  6267. }
  6268. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6269. if (m_unfinishedSections.empty())
  6270. m_activeSections.back()->fail();
  6271. else
  6272. m_activeSections.back()->close();
  6273. m_activeSections.pop_back();
  6274. m_unfinishedSections.push_back(endInfo);
  6275. }
  6276. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6277. m_reporter->benchmarkStarting( info );
  6278. }
  6279. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6280. m_reporter->benchmarkEnded( stats );
  6281. }
  6282. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6283. m_messages.push_back(message);
  6284. }
  6285. void RunContext::popScopedMessage(MessageInfo const & message) {
  6286. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6287. }
  6288. std::string RunContext::getCurrentTestName() const {
  6289. return m_activeTestCase
  6290. ? m_activeTestCase->getTestCaseInfo().name
  6291. : std::string();
  6292. }
  6293. const AssertionResult * RunContext::getLastResult() const {
  6294. return &(*m_lastResult);
  6295. }
  6296. void RunContext::exceptionEarlyReported() {
  6297. m_shouldReportUnexpected = false;
  6298. }
  6299. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6300. // First notify reporter that bad things happened
  6301. m_reporter->fatalErrorEncountered(message);
  6302. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6303. // Instead, fake a result data.
  6304. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6305. tempResult.message = message;
  6306. AssertionResult result(m_lastAssertionInfo, tempResult);
  6307. getResultCapture().assertionEnded(result);
  6308. handleUnfinishedSections();
  6309. // Recreate section for test case (as we will lose the one that was in scope)
  6310. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6311. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6312. Counts assertions;
  6313. assertions.failed = 1;
  6314. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6315. m_reporter->sectionEnded(testCaseSectionStats);
  6316. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6317. Totals deltaTotals;
  6318. deltaTotals.testCases.failed = 1;
  6319. deltaTotals.assertions.failed = 1;
  6320. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6321. deltaTotals,
  6322. std::string(),
  6323. std::string(),
  6324. false));
  6325. m_totals.testCases.failed++;
  6326. testGroupEnded(std::string(), m_totals, 1, 1);
  6327. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6328. }
  6329. bool RunContext::lastAssertionPassed() {
  6330. return m_totals.assertions.passed == (m_prevPassed + 1);
  6331. }
  6332. void RunContext::assertionPassed() {
  6333. ++m_totals.assertions.passed;
  6334. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}";
  6335. m_lastAssertionInfo.macroName = "";
  6336. }
  6337. void RunContext::assertionRun() {
  6338. m_prevPassed = m_totals.assertions.passed;
  6339. }
  6340. bool RunContext::aborting() const {
  6341. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6342. }
  6343. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6344. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6345. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6346. m_reporter->sectionStarting(testCaseSection);
  6347. Counts prevAssertions = m_totals.assertions;
  6348. double duration = 0;
  6349. m_shouldReportUnexpected = true;
  6350. try {
  6351. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6352. seedRng(*m_config);
  6353. Timer timer;
  6354. timer.start();
  6355. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6356. StreamRedirect coutRedir(cout(), redirectedCout);
  6357. StdErrRedirect errRedir(redirectedCerr);
  6358. invokeActiveTestCase();
  6359. } else {
  6360. invokeActiveTestCase();
  6361. }
  6362. duration = timer.getElapsedSeconds();
  6363. } catch (TestFailureException&) {
  6364. // This just means the test was aborted due to failure
  6365. } catch (...) {
  6366. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6367. // are reported without translation at the point of origin.
  6368. if (m_shouldReportUnexpected) {
  6369. AssertionHandler
  6370. ( m_lastAssertionInfo.macroName,
  6371. m_lastAssertionInfo.lineInfo,
  6372. m_lastAssertionInfo.capturedExpression,
  6373. m_lastAssertionInfo.resultDisposition ).useActiveException();
  6374. }
  6375. }
  6376. m_testCaseTracker->close();
  6377. handleUnfinishedSections();
  6378. m_messages.clear();
  6379. Counts assertions = m_totals.assertions - prevAssertions;
  6380. bool missingAssertions = testForMissingAssertions(assertions);
  6381. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6382. m_reporter->sectionEnded(testCaseSectionStats);
  6383. }
  6384. void RunContext::invokeActiveTestCase() {
  6385. FatalConditionHandler fatalConditionHandler; // Handle signals
  6386. m_activeTestCase->invoke();
  6387. fatalConditionHandler.reset();
  6388. }
  6389. void RunContext::handleUnfinishedSections() {
  6390. // If sections ended prematurely due to an exception we stored their
  6391. // infos here so we can tear them down outside the unwind process.
  6392. for (auto it = m_unfinishedSections.rbegin(),
  6393. itEnd = m_unfinishedSections.rend();
  6394. it != itEnd;
  6395. ++it)
  6396. sectionEnded(*it);
  6397. m_unfinishedSections.clear();
  6398. }
  6399. IResultCapture& getResultCapture() {
  6400. if (auto* capture = getCurrentContext().getResultCapture())
  6401. return *capture;
  6402. else
  6403. CATCH_INTERNAL_ERROR("No result capture instance");
  6404. }
  6405. }
  6406. // end catch_run_context.cpp
  6407. // start catch_section.cpp
  6408. namespace Catch {
  6409. Section::Section( SectionInfo const& info )
  6410. : m_info( info ),
  6411. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  6412. {
  6413. m_timer.start();
  6414. }
  6415. #if defined(_MSC_VER)
  6416. #pragma warning(push)
  6417. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  6418. #endif
  6419. Section::~Section() {
  6420. if( m_sectionIncluded ) {
  6421. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  6422. if( std::uncaught_exception() )
  6423. getResultCapture().sectionEndedEarly( endInfo );
  6424. else
  6425. getResultCapture().sectionEnded( endInfo );
  6426. }
  6427. }
  6428. #if defined(_MSC_VER)
  6429. #pragma warning(pop)
  6430. #endif
  6431. // This indicates whether the section should be executed or not
  6432. Section::operator bool() const {
  6433. return m_sectionIncluded;
  6434. }
  6435. } // end namespace Catch
  6436. // end catch_section.cpp
  6437. // start catch_section_info.cpp
  6438. namespace Catch {
  6439. SectionInfo::SectionInfo
  6440. ( SourceLineInfo const& _lineInfo,
  6441. std::string const& _name,
  6442. std::string const& _description )
  6443. : name( _name ),
  6444. description( _description ),
  6445. lineInfo( _lineInfo )
  6446. {}
  6447. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  6448. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  6449. {}
  6450. } // end namespace Catch
  6451. // end catch_section_info.cpp
  6452. // start catch_session.cpp
  6453. // start catch_session.h
  6454. #include <memory>
  6455. namespace Catch {
  6456. class Session : NonCopyable {
  6457. public:
  6458. Session();
  6459. ~Session() override;
  6460. void showHelp() const;
  6461. void libIdentify();
  6462. int applyCommandLine( int argc, char* argv[] );
  6463. void useConfigData( ConfigData const& configData );
  6464. int run( int argc, char* argv[] );
  6465. #if defined(WIN32) && defined(UNICODE)
  6466. int run( int argc, wchar_t* const argv[] );
  6467. #endif
  6468. int run();
  6469. clara::Parser const& cli() const;
  6470. void cli( clara::Parser const& newParser );
  6471. ConfigData& configData();
  6472. Config& config();
  6473. private:
  6474. int runInternal();
  6475. clara::Parser m_cli;
  6476. ConfigData m_configData;
  6477. std::shared_ptr<Config> m_config;
  6478. bool m_startupExceptions = false;
  6479. };
  6480. } // end namespace Catch
  6481. // end catch_session.h
  6482. // start catch_version.h
  6483. #include <iosfwd>
  6484. namespace Catch {
  6485. // Versioning information
  6486. struct Version {
  6487. Version( Version const& ) = delete;
  6488. Version& operator=( Version const& ) = delete;
  6489. Version( unsigned int _majorVersion,
  6490. unsigned int _minorVersion,
  6491. unsigned int _patchNumber,
  6492. char const * const _branchName,
  6493. unsigned int _buildNumber );
  6494. unsigned int const majorVersion;
  6495. unsigned int const minorVersion;
  6496. unsigned int const patchNumber;
  6497. // buildNumber is only used if branchName is not null
  6498. char const * const branchName;
  6499. unsigned int const buildNumber;
  6500. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  6501. };
  6502. Version const& libraryVersion();
  6503. }
  6504. // end catch_version.h
  6505. #include <cstdlib>
  6506. #include <iomanip>
  6507. namespace {
  6508. const int MaxExitCode = 255;
  6509. using Catch::IStreamingReporterPtr;
  6510. using Catch::IConfigPtr;
  6511. using Catch::Config;
  6512. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  6513. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  6514. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  6515. return reporter;
  6516. }
  6517. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  6518. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  6519. #endif
  6520. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  6521. auto const& reporterNames = config->getReporterNames();
  6522. if (reporterNames.empty())
  6523. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  6524. IStreamingReporterPtr reporter;
  6525. for (auto const& name : reporterNames)
  6526. addReporter(reporter, createReporter(name, config));
  6527. return reporter;
  6528. }
  6529. #undef CATCH_CONFIG_DEFAULT_REPORTER
  6530. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  6531. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  6532. for (auto const& listener : listeners)
  6533. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  6534. }
  6535. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  6536. using namespace Catch;
  6537. IStreamingReporterPtr reporter = makeReporter(config);
  6538. addListeners(reporter, config);
  6539. RunContext context(config, std::move(reporter));
  6540. Totals totals;
  6541. context.testGroupStarting(config->name(), 1, 1);
  6542. TestSpec testSpec = config->testSpec();
  6543. if (!testSpec.hasFilters())
  6544. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  6545. auto const& allTestCases = getAllTestCasesSorted(*config);
  6546. for (auto const& testCase : allTestCases) {
  6547. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  6548. totals += context.runTest(testCase);
  6549. else
  6550. context.reporter().skipTest(testCase);
  6551. }
  6552. context.testGroupEnded(config->name(), totals, 1, 1);
  6553. return totals;
  6554. }
  6555. void applyFilenamesAsTags(Catch::IConfig const& config) {
  6556. using namespace Catch;
  6557. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  6558. for (auto& testCase : tests) {
  6559. auto tags = testCase.tags;
  6560. std::string filename = testCase.lineInfo.file;
  6561. auto lastSlash = filename.find_last_of("\\/");
  6562. if (lastSlash != std::string::npos) {
  6563. filename.erase(0, lastSlash);
  6564. filename[0] = '#';
  6565. }
  6566. auto lastDot = filename.find_last_of('.');
  6567. if (lastDot != std::string::npos) {
  6568. filename.erase(lastDot);
  6569. }
  6570. tags.push_back(std::move(filename));
  6571. setTags(testCase, tags);
  6572. }
  6573. }
  6574. }
  6575. namespace Catch {
  6576. Session::Session() {
  6577. static bool alreadyInstantiated = false;
  6578. if( alreadyInstantiated ) {
  6579. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  6580. catch(...) { getMutableRegistryHub().registerStartupException(); }
  6581. }
  6582. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  6583. if ( !exceptions.empty() ) {
  6584. m_startupExceptions = true;
  6585. Colour colourGuard( Colour::Red );
  6586. Catch::cerr() << "Errors occured during startup!" << '\n';
  6587. // iterate over all exceptions and notify user
  6588. for ( const auto& ex_ptr : exceptions ) {
  6589. try {
  6590. std::rethrow_exception(ex_ptr);
  6591. } catch ( std::exception const& ex ) {
  6592. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  6593. }
  6594. }
  6595. }
  6596. alreadyInstantiated = true;
  6597. m_cli = makeCommandLineParser( m_configData );
  6598. }
  6599. Session::~Session() {
  6600. Catch::cleanUp();
  6601. }
  6602. void Session::showHelp() const {
  6603. Catch::cout()
  6604. << "\nCatch v" << libraryVersion() << "\n"
  6605. << m_cli << std::endl
  6606. << "For more detailed usage please see the project docs\n" << std::endl;
  6607. }
  6608. void Session::libIdentify() {
  6609. Catch::cout()
  6610. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  6611. << std::left << std::setw(16) << "category: " << "testframework\n"
  6612. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  6613. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  6614. }
  6615. int Session::applyCommandLine( int argc, char* argv[] ) {
  6616. if( m_startupExceptions )
  6617. return 1;
  6618. auto result = m_cli.parse( clara::Args( argc, argv ) );
  6619. if( !result ) {
  6620. Catch::cerr()
  6621. << Colour( Colour::Red )
  6622. << "\nError(s) in input:\n"
  6623. << Column( result.errorMessage() ).indent( 2 )
  6624. << "\n\n";
  6625. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  6626. return MaxExitCode;
  6627. }
  6628. if( m_configData.showHelp )
  6629. showHelp();
  6630. if( m_configData.libIdentify )
  6631. libIdentify();
  6632. m_config.reset();
  6633. return 0;
  6634. }
  6635. void Session::useConfigData( ConfigData const& configData ) {
  6636. m_configData = configData;
  6637. m_config.reset();
  6638. }
  6639. int Session::run( int argc, char* argv[] ) {
  6640. if( m_startupExceptions )
  6641. return 1;
  6642. int returnCode = applyCommandLine( argc, argv );
  6643. if( returnCode == 0 )
  6644. returnCode = run();
  6645. return returnCode;
  6646. }
  6647. #if defined(WIN32) && defined(UNICODE)
  6648. int Session::run( int argc, wchar_t* const argv[] ) {
  6649. char **utf8Argv = new char *[ argc ];
  6650. for ( int i = 0; i < argc; ++i ) {
  6651. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  6652. utf8Argv[ i ] = new char[ bufSize ];
  6653. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  6654. }
  6655. int returnCode = run( argc, utf8Argv );
  6656. for ( int i = 0; i < argc; ++i )
  6657. delete [] utf8Argv[ i ];
  6658. delete [] utf8Argv;
  6659. return returnCode;
  6660. }
  6661. #endif
  6662. int Session::run() {
  6663. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  6664. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  6665. static_cast<void>(std::getchar());
  6666. }
  6667. int exitCode = runInternal();
  6668. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  6669. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  6670. static_cast<void>(std::getchar());
  6671. }
  6672. return exitCode;
  6673. }
  6674. clara::Parser const& Session::cli() const {
  6675. return m_cli;
  6676. }
  6677. void Session::cli( clara::Parser const& newParser ) {
  6678. m_cli = newParser;
  6679. }
  6680. ConfigData& Session::configData() {
  6681. return m_configData;
  6682. }
  6683. Config& Session::config() {
  6684. if( !m_config )
  6685. m_config = std::make_shared<Config>( m_configData );
  6686. return *m_config;
  6687. }
  6688. int Session::runInternal() {
  6689. if( m_startupExceptions )
  6690. return 1;
  6691. if( m_configData.showHelp || m_configData.libIdentify )
  6692. return 0;
  6693. try
  6694. {
  6695. config(); // Force config to be constructed
  6696. seedRng( *m_config );
  6697. if( m_configData.filenamesAsTags )
  6698. applyFilenamesAsTags( *m_config );
  6699. // Handle list request
  6700. if( Option<std::size_t> listed = list( config() ) )
  6701. return static_cast<int>( *listed );
  6702. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  6703. }
  6704. catch( std::exception& ex ) {
  6705. Catch::cerr() << ex.what() << std::endl;
  6706. return MaxExitCode;
  6707. }
  6708. }
  6709. } // end namespace Catch
  6710. // end catch_session.cpp
  6711. // start catch_startup_exception_registry.cpp
  6712. namespace Catch {
  6713. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  6714. try {
  6715. m_exceptions.push_back(exception);
  6716. }
  6717. catch(...) {
  6718. // If we run out of memory during start-up there's really not a lot more we can do about it
  6719. std::terminate();
  6720. }
  6721. }
  6722. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  6723. return m_exceptions;
  6724. }
  6725. } // end namespace Catch
  6726. // end catch_startup_exception_registry.cpp
  6727. // start catch_stream.cpp
  6728. #include <stdexcept>
  6729. #include <cstdio>
  6730. #include <iostream>
  6731. namespace Catch {
  6732. template<typename WriterF, std::size_t bufferSize=256>
  6733. class StreamBufImpl : public StreamBufBase {
  6734. char data[bufferSize];
  6735. WriterF m_writer;
  6736. public:
  6737. StreamBufImpl() {
  6738. setp( data, data + sizeof(data) );
  6739. }
  6740. ~StreamBufImpl() noexcept {
  6741. StreamBufImpl::sync();
  6742. }
  6743. private:
  6744. int overflow( int c ) override {
  6745. sync();
  6746. if( c != EOF ) {
  6747. if( pbase() == epptr() )
  6748. m_writer( std::string( 1, static_cast<char>( c ) ) );
  6749. else
  6750. sputc( static_cast<char>( c ) );
  6751. }
  6752. return 0;
  6753. }
  6754. int sync() override {
  6755. if( pbase() != pptr() ) {
  6756. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  6757. setp( pbase(), epptr() );
  6758. }
  6759. return 0;
  6760. }
  6761. };
  6762. ///////////////////////////////////////////////////////////////////////////
  6763. Catch::IStream::~IStream() = default;
  6764. FileStream::FileStream( std::string const& filename ) {
  6765. m_ofs.open( filename.c_str() );
  6766. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  6767. }
  6768. std::ostream& FileStream::stream() const {
  6769. return m_ofs;
  6770. }
  6771. struct OutputDebugWriter {
  6772. void operator()( std::string const&str ) {
  6773. writeToDebugConsole( str );
  6774. }
  6775. };
  6776. DebugOutStream::DebugOutStream()
  6777. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  6778. m_os( m_streamBuf.get() )
  6779. {}
  6780. std::ostream& DebugOutStream::stream() const {
  6781. return m_os;
  6782. }
  6783. // Store the streambuf from cout up-front because
  6784. // cout may get redirected when running tests
  6785. CoutStream::CoutStream()
  6786. : m_os( Catch::cout().rdbuf() )
  6787. {}
  6788. std::ostream& CoutStream::stream() const {
  6789. return m_os;
  6790. }
  6791. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  6792. std::ostream& cout() {
  6793. return std::cout;
  6794. }
  6795. std::ostream& cerr() {
  6796. return std::cerr;
  6797. }
  6798. std::ostream& clog() {
  6799. return std::clog;
  6800. }
  6801. #endif
  6802. }
  6803. // end catch_stream.cpp
  6804. // start catch_streambuf.cpp
  6805. namespace Catch {
  6806. StreamBufBase::~StreamBufBase() = default;
  6807. }
  6808. // end catch_streambuf.cpp
  6809. // start catch_string_manip.cpp
  6810. #include <algorithm>
  6811. #include <ostream>
  6812. #include <cstring>
  6813. #include <cctype>
  6814. namespace Catch {
  6815. bool startsWith( std::string const& s, std::string const& prefix ) {
  6816. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  6817. }
  6818. bool startsWith( std::string const& s, char prefix ) {
  6819. return !s.empty() && s[0] == prefix;
  6820. }
  6821. bool endsWith( std::string const& s, std::string const& suffix ) {
  6822. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  6823. }
  6824. bool endsWith( std::string const& s, char suffix ) {
  6825. return !s.empty() && s[s.size()-1] == suffix;
  6826. }
  6827. bool contains( std::string const& s, std::string const& infix ) {
  6828. return s.find( infix ) != std::string::npos;
  6829. }
  6830. char toLowerCh(char c) {
  6831. return static_cast<char>( std::tolower( c ) );
  6832. }
  6833. void toLowerInPlace( std::string& s ) {
  6834. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  6835. }
  6836. std::string toLower( std::string const& s ) {
  6837. std::string lc = s;
  6838. toLowerInPlace( lc );
  6839. return lc;
  6840. }
  6841. std::string trim( std::string const& str ) {
  6842. static char const* whitespaceChars = "\n\r\t ";
  6843. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  6844. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  6845. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  6846. }
  6847. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  6848. bool replaced = false;
  6849. std::size_t i = str.find( replaceThis );
  6850. while( i != std::string::npos ) {
  6851. replaced = true;
  6852. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  6853. if( i < str.size()-withThis.size() )
  6854. i = str.find( replaceThis, i+withThis.size() );
  6855. else
  6856. i = std::string::npos;
  6857. }
  6858. return replaced;
  6859. }
  6860. pluralise::pluralise( std::size_t count, std::string const& label )
  6861. : m_count( count ),
  6862. m_label( label )
  6863. {}
  6864. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  6865. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  6866. if( pluraliser.m_count != 1 )
  6867. os << 's';
  6868. return os;
  6869. }
  6870. }
  6871. // end catch_string_manip.cpp
  6872. // start catch_stringref.cpp
  6873. #if defined(__clang__)
  6874. # pragma clang diagnostic push
  6875. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6876. #endif
  6877. #include <ostream>
  6878. #include <cassert>
  6879. #include <cstring>
  6880. namespace Catch {
  6881. auto getEmptyStringRef() -> StringRef {
  6882. static StringRef s_emptyStringRef("");
  6883. return s_emptyStringRef;
  6884. }
  6885. StringRef::StringRef() noexcept
  6886. : StringRef( getEmptyStringRef() )
  6887. {}
  6888. StringRef::StringRef( StringRef const& other ) noexcept
  6889. : m_start( other.m_start ),
  6890. m_size( other.m_size )
  6891. {}
  6892. StringRef::StringRef( StringRef&& other ) noexcept
  6893. : m_start( other.m_start ),
  6894. m_size( other.m_size ),
  6895. m_data( other.m_data )
  6896. {
  6897. other.m_data = nullptr;
  6898. }
  6899. StringRef::StringRef( char const* rawChars ) noexcept
  6900. : m_start( rawChars ),
  6901. m_size( static_cast<size_type>( std::strlen( rawChars ) ) )
  6902. {
  6903. assert( rawChars != nullptr );
  6904. }
  6905. StringRef::StringRef( char const* rawChars, size_type size ) noexcept
  6906. : m_start( rawChars ),
  6907. m_size( size )
  6908. {
  6909. size_type rawSize = rawChars == nullptr ? 0 : static_cast<size_type>( std::strlen( rawChars ) );
  6910. if( rawSize < size )
  6911. m_size = rawSize;
  6912. }
  6913. StringRef::StringRef( std::string const& stdString ) noexcept
  6914. : m_start( stdString.c_str() ),
  6915. m_size( stdString.size() )
  6916. {}
  6917. StringRef::~StringRef() noexcept {
  6918. delete[] m_data;
  6919. }
  6920. auto StringRef::operator = ( StringRef other ) noexcept -> StringRef& {
  6921. swap( other );
  6922. return *this;
  6923. }
  6924. StringRef::operator std::string() const {
  6925. return std::string( m_start, m_size );
  6926. }
  6927. void StringRef::swap( StringRef& other ) noexcept {
  6928. std::swap( m_start, other.m_start );
  6929. std::swap( m_size, other.m_size );
  6930. std::swap( m_data, other.m_data );
  6931. }
  6932. auto StringRef::c_str() const -> char const* {
  6933. if( isSubstring() )
  6934. const_cast<StringRef*>( this )->takeOwnership();
  6935. return m_start;
  6936. }
  6937. auto StringRef::data() const noexcept -> char const* {
  6938. return m_start;
  6939. }
  6940. auto StringRef::isOwned() const noexcept -> bool {
  6941. return m_data != nullptr;
  6942. }
  6943. auto StringRef::isSubstring() const noexcept -> bool {
  6944. return m_start[m_size] != '\0';
  6945. }
  6946. void StringRef::takeOwnership() {
  6947. if( !isOwned() ) {
  6948. m_data = new char[m_size+1];
  6949. memcpy( m_data, m_start, m_size );
  6950. m_data[m_size] = '\0';
  6951. m_start = m_data;
  6952. }
  6953. }
  6954. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  6955. if( start < m_size )
  6956. return StringRef( m_start+start, size );
  6957. else
  6958. return StringRef();
  6959. }
  6960. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  6961. return
  6962. size() == other.size() &&
  6963. (std::strncmp( m_start, other.m_start, size() ) == 0);
  6964. }
  6965. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  6966. return !operator==( other );
  6967. }
  6968. auto StringRef::operator[](size_type index) const noexcept -> char {
  6969. return m_start[index];
  6970. }
  6971. auto StringRef::empty() const noexcept -> bool {
  6972. return m_size == 0;
  6973. }
  6974. auto StringRef::size() const noexcept -> size_type {
  6975. return m_size;
  6976. }
  6977. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  6978. size_type noChars = m_size;
  6979. // Make adjustments for uft encodings
  6980. for( size_type i=0; i < m_size; ++i ) {
  6981. char c = m_start[i];
  6982. if( ( c & 0b11000000 ) == 0b11000000 ) {
  6983. if( ( c & 0b11100000 ) == 0b11000000 )
  6984. noChars--;
  6985. else if( ( c & 0b11110000 ) == 0b11100000 )
  6986. noChars-=2;
  6987. else if( ( c & 0b11111000 ) == 0b11110000 )
  6988. noChars-=3;
  6989. }
  6990. }
  6991. return noChars;
  6992. }
  6993. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  6994. std::string str;
  6995. str.reserve( lhs.size() + rhs.size() );
  6996. str += lhs;
  6997. str += rhs;
  6998. return str;
  6999. }
  7000. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7001. return std::string( lhs ) + std::string( rhs );
  7002. }
  7003. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7004. return std::string( lhs ) + std::string( rhs );
  7005. }
  7006. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7007. return os << str.c_str();
  7008. }
  7009. } // namespace Catch
  7010. #if defined(__clang__)
  7011. # pragma clang diagnostic pop
  7012. #endif
  7013. // end catch_stringref.cpp
  7014. // start catch_tag_alias.cpp
  7015. namespace Catch {
  7016. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7017. }
  7018. // end catch_tag_alias.cpp
  7019. // start catch_tag_alias_autoregistrar.cpp
  7020. namespace Catch {
  7021. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7022. try {
  7023. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7024. } catch (...) {
  7025. // Do not throw when constructing global objects, instead register the exception to be processed later
  7026. getMutableRegistryHub().registerStartupException();
  7027. }
  7028. }
  7029. }
  7030. // end catch_tag_alias_autoregistrar.cpp
  7031. // start catch_tag_alias_registry.cpp
  7032. namespace Catch {
  7033. TagAliasRegistry::~TagAliasRegistry() {}
  7034. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7035. auto it = m_registry.find( alias );
  7036. if( it != m_registry.end() )
  7037. return &(it->second);
  7038. else
  7039. return nullptr;
  7040. }
  7041. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7042. std::string expandedTestSpec = unexpandedTestSpec;
  7043. for( auto const& registryKvp : m_registry ) {
  7044. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7045. if( pos != std::string::npos ) {
  7046. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7047. registryKvp.second.tag +
  7048. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7049. }
  7050. }
  7051. return expandedTestSpec;
  7052. }
  7053. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7054. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7055. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7056. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7057. "error: tag alias, '" << alias << "' already registered.\n"
  7058. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7059. << "\tRedefined at: " << lineInfo );
  7060. }
  7061. ITagAliasRegistry::~ITagAliasRegistry() {}
  7062. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7063. return getRegistryHub().getTagAliasRegistry();
  7064. }
  7065. } // end namespace Catch
  7066. // end catch_tag_alias_registry.cpp
  7067. // start catch_test_case_info.cpp
  7068. #include <cctype>
  7069. #include <exception>
  7070. #include <algorithm>
  7071. namespace Catch {
  7072. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7073. if( startsWith( tag, '.' ) ||
  7074. tag == "!hide" )
  7075. return TestCaseInfo::IsHidden;
  7076. else if( tag == "!throws" )
  7077. return TestCaseInfo::Throws;
  7078. else if( tag == "!shouldfail" )
  7079. return TestCaseInfo::ShouldFail;
  7080. else if( tag == "!mayfail" )
  7081. return TestCaseInfo::MayFail;
  7082. else if( tag == "!nonportable" )
  7083. return TestCaseInfo::NonPortable;
  7084. else if( tag == "!benchmark" )
  7085. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7086. else
  7087. return TestCaseInfo::None;
  7088. }
  7089. bool isReservedTag( std::string const& tag ) {
  7090. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7091. }
  7092. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7093. CATCH_ENFORCE( !isReservedTag(tag),
  7094. "Tag name: [" << tag << "] is not allowed.\n"
  7095. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7096. << _lineInfo );
  7097. }
  7098. TestCase makeTestCase( ITestInvoker* _testCase,
  7099. std::string const& _className,
  7100. std::string const& _name,
  7101. std::string const& _descOrTags,
  7102. SourceLineInfo const& _lineInfo )
  7103. {
  7104. bool isHidden = false;
  7105. // Parse out tags
  7106. std::vector<std::string> tags;
  7107. std::string desc, tag;
  7108. bool inTag = false;
  7109. for (char c : _descOrTags) {
  7110. if( !inTag ) {
  7111. if( c == '[' )
  7112. inTag = true;
  7113. else
  7114. desc += c;
  7115. }
  7116. else {
  7117. if( c == ']' ) {
  7118. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7119. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7120. isHidden = true;
  7121. else if( prop == TestCaseInfo::None )
  7122. enforceNotReservedTag( tag, _lineInfo );
  7123. tags.push_back( tag );
  7124. tag.clear();
  7125. inTag = false;
  7126. }
  7127. else
  7128. tag += c;
  7129. }
  7130. }
  7131. if( isHidden ) {
  7132. tags.push_back( "." );
  7133. }
  7134. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  7135. return TestCase( _testCase, info );
  7136. }
  7137. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7138. std::sort(begin(tags), end(tags));
  7139. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7140. testCaseInfo.lcaseTags.clear();
  7141. for( auto const& tag : tags ) {
  7142. std::string lcaseTag = toLower( tag );
  7143. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7144. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7145. }
  7146. testCaseInfo.tags = std::move(tags);
  7147. }
  7148. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7149. std::string const& _className,
  7150. std::string const& _description,
  7151. std::vector<std::string> const& _tags,
  7152. SourceLineInfo const& _lineInfo )
  7153. : name( _name ),
  7154. className( _className ),
  7155. description( _description ),
  7156. lineInfo( _lineInfo ),
  7157. properties( None )
  7158. {
  7159. setTags( *this, _tags );
  7160. }
  7161. bool TestCaseInfo::isHidden() const {
  7162. return ( properties & IsHidden ) != 0;
  7163. }
  7164. bool TestCaseInfo::throws() const {
  7165. return ( properties & Throws ) != 0;
  7166. }
  7167. bool TestCaseInfo::okToFail() const {
  7168. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7169. }
  7170. bool TestCaseInfo::expectedToFail() const {
  7171. return ( properties & (ShouldFail ) ) != 0;
  7172. }
  7173. std::string TestCaseInfo::tagsAsString() const {
  7174. std::string ret;
  7175. // '[' and ']' per tag
  7176. std::size_t full_size = 2 * tags.size();
  7177. for (const auto& tag : tags) {
  7178. full_size += tag.size();
  7179. }
  7180. ret.reserve(full_size);
  7181. for (const auto& tag : tags) {
  7182. ret.push_back('[');
  7183. ret.append(tag);
  7184. ret.push_back(']');
  7185. }
  7186. return ret;
  7187. }
  7188. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7189. TestCase TestCase::withName( std::string const& _newName ) const {
  7190. TestCase other( *this );
  7191. other.name = _newName;
  7192. return other;
  7193. }
  7194. void TestCase::invoke() const {
  7195. test->invoke();
  7196. }
  7197. bool TestCase::operator == ( TestCase const& other ) const {
  7198. return test.get() == other.test.get() &&
  7199. name == other.name &&
  7200. className == other.className;
  7201. }
  7202. bool TestCase::operator < ( TestCase const& other ) const {
  7203. return name < other.name;
  7204. }
  7205. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7206. {
  7207. return *this;
  7208. }
  7209. } // end namespace Catch
  7210. // end catch_test_case_info.cpp
  7211. // start catch_test_case_registry_impl.cpp
  7212. #include <sstream>
  7213. namespace Catch {
  7214. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7215. std::vector<TestCase> sorted = unsortedTestCases;
  7216. switch( config.runOrder() ) {
  7217. case RunTests::InLexicographicalOrder:
  7218. std::sort( sorted.begin(), sorted.end() );
  7219. break;
  7220. case RunTests::InRandomOrder:
  7221. seedRng( config );
  7222. RandomNumberGenerator::shuffle( sorted );
  7223. break;
  7224. case RunTests::InDeclarationOrder:
  7225. // already in declaration order
  7226. break;
  7227. }
  7228. return sorted;
  7229. }
  7230. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7231. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7232. }
  7233. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7234. std::set<TestCase> seenFunctions;
  7235. for( auto const& function : functions ) {
  7236. auto prev = seenFunctions.insert( function );
  7237. CATCH_ENFORCE( prev.second,
  7238. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7239. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7240. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7241. }
  7242. }
  7243. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7244. std::vector<TestCase> filtered;
  7245. filtered.reserve( testCases.size() );
  7246. for( auto const& testCase : testCases )
  7247. if( matchTest( testCase, testSpec, config ) )
  7248. filtered.push_back( testCase );
  7249. return filtered;
  7250. }
  7251. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7252. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7253. }
  7254. void TestRegistry::registerTest( TestCase const& testCase ) {
  7255. std::string name = testCase.getTestCaseInfo().name;
  7256. if( name.empty() ) {
  7257. std::ostringstream oss;
  7258. oss << "Anonymous test case " << ++m_unnamedCount;
  7259. return registerTest( testCase.withName( oss.str() ) );
  7260. }
  7261. m_functions.push_back( testCase );
  7262. }
  7263. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7264. return m_functions;
  7265. }
  7266. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7267. if( m_sortedFunctions.empty() )
  7268. enforceNoDuplicateTestCases( m_functions );
  7269. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7270. m_sortedFunctions = sortTests( config, m_functions );
  7271. m_currentSortOrder = config.runOrder();
  7272. }
  7273. return m_sortedFunctions;
  7274. }
  7275. ///////////////////////////////////////////////////////////////////////////
  7276. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7277. void TestInvokerAsFunction::invoke() const {
  7278. m_testAsFunction();
  7279. }
  7280. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7281. std::string className = classOrQualifiedMethodName;
  7282. if( startsWith( className, '&' ) )
  7283. {
  7284. std::size_t lastColons = className.rfind( "::" );
  7285. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7286. if( penultimateColons == std::string::npos )
  7287. penultimateColons = 1;
  7288. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7289. }
  7290. return className;
  7291. }
  7292. } // end namespace Catch
  7293. // end catch_test_case_registry_impl.cpp
  7294. // start catch_test_case_tracker.cpp
  7295. #include <algorithm>
  7296. #include <assert.h>
  7297. #include <stdexcept>
  7298. #include <memory>
  7299. #if defined(__clang__)
  7300. # pragma clang diagnostic push
  7301. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7302. #endif
  7303. namespace Catch {
  7304. namespace TestCaseTracking {
  7305. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7306. : name( _name ),
  7307. location( _location )
  7308. {}
  7309. ITracker::~ITracker() = default;
  7310. TrackerContext& TrackerContext::instance() {
  7311. static TrackerContext s_instance;
  7312. return s_instance;
  7313. }
  7314. ITracker& TrackerContext::startRun() {
  7315. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7316. m_currentTracker = nullptr;
  7317. m_runState = Executing;
  7318. return *m_rootTracker;
  7319. }
  7320. void TrackerContext::endRun() {
  7321. m_rootTracker.reset();
  7322. m_currentTracker = nullptr;
  7323. m_runState = NotStarted;
  7324. }
  7325. void TrackerContext::startCycle() {
  7326. m_currentTracker = m_rootTracker.get();
  7327. m_runState = Executing;
  7328. }
  7329. void TrackerContext::completeCycle() {
  7330. m_runState = CompletedCycle;
  7331. }
  7332. bool TrackerContext::completedCycle() const {
  7333. return m_runState == CompletedCycle;
  7334. }
  7335. ITracker& TrackerContext::currentTracker() {
  7336. return *m_currentTracker;
  7337. }
  7338. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  7339. m_currentTracker = tracker;
  7340. }
  7341. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  7342. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  7343. return
  7344. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  7345. tracker->nameAndLocation().location == m_nameAndLocation.location;
  7346. }
  7347. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7348. : m_nameAndLocation( nameAndLocation ),
  7349. m_ctx( ctx ),
  7350. m_parent( parent )
  7351. {}
  7352. NameAndLocation const& TrackerBase::nameAndLocation() const {
  7353. return m_nameAndLocation;
  7354. }
  7355. bool TrackerBase::isComplete() const {
  7356. return m_runState == CompletedSuccessfully || m_runState == Failed;
  7357. }
  7358. bool TrackerBase::isSuccessfullyCompleted() const {
  7359. return m_runState == CompletedSuccessfully;
  7360. }
  7361. bool TrackerBase::isOpen() const {
  7362. return m_runState != NotStarted && !isComplete();
  7363. }
  7364. bool TrackerBase::hasChildren() const {
  7365. return !m_children.empty();
  7366. }
  7367. void TrackerBase::addChild( ITrackerPtr const& child ) {
  7368. m_children.push_back( child );
  7369. }
  7370. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  7371. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  7372. return( it != m_children.end() )
  7373. ? *it
  7374. : nullptr;
  7375. }
  7376. ITracker& TrackerBase::parent() {
  7377. assert( m_parent ); // Should always be non-null except for root
  7378. return *m_parent;
  7379. }
  7380. void TrackerBase::openChild() {
  7381. if( m_runState != ExecutingChildren ) {
  7382. m_runState = ExecutingChildren;
  7383. if( m_parent )
  7384. m_parent->openChild();
  7385. }
  7386. }
  7387. bool TrackerBase::isSectionTracker() const { return false; }
  7388. bool TrackerBase::isIndexTracker() const { return false; }
  7389. void TrackerBase::open() {
  7390. m_runState = Executing;
  7391. moveToThis();
  7392. if( m_parent )
  7393. m_parent->openChild();
  7394. }
  7395. void TrackerBase::close() {
  7396. // Close any still open children (e.g. generators)
  7397. while( &m_ctx.currentTracker() != this )
  7398. m_ctx.currentTracker().close();
  7399. switch( m_runState ) {
  7400. case NeedsAnotherRun:
  7401. break;
  7402. case Executing:
  7403. m_runState = CompletedSuccessfully;
  7404. break;
  7405. case ExecutingChildren:
  7406. if( m_children.empty() || m_children.back()->isComplete() )
  7407. m_runState = CompletedSuccessfully;
  7408. break;
  7409. case NotStarted:
  7410. case CompletedSuccessfully:
  7411. case Failed:
  7412. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  7413. default:
  7414. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  7415. }
  7416. moveToParent();
  7417. m_ctx.completeCycle();
  7418. }
  7419. void TrackerBase::fail() {
  7420. m_runState = Failed;
  7421. if( m_parent )
  7422. m_parent->markAsNeedingAnotherRun();
  7423. moveToParent();
  7424. m_ctx.completeCycle();
  7425. }
  7426. void TrackerBase::markAsNeedingAnotherRun() {
  7427. m_runState = NeedsAnotherRun;
  7428. }
  7429. void TrackerBase::moveToParent() {
  7430. assert( m_parent );
  7431. m_ctx.setCurrentTracker( m_parent );
  7432. }
  7433. void TrackerBase::moveToThis() {
  7434. m_ctx.setCurrentTracker( this );
  7435. }
  7436. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7437. : TrackerBase( nameAndLocation, ctx, parent )
  7438. {
  7439. if( parent ) {
  7440. while( !parent->isSectionTracker() )
  7441. parent = &parent->parent();
  7442. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  7443. addNextFilters( parentSection.m_filters );
  7444. }
  7445. }
  7446. bool SectionTracker::isSectionTracker() const { return true; }
  7447. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  7448. std::shared_ptr<SectionTracker> section;
  7449. ITracker& currentTracker = ctx.currentTracker();
  7450. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7451. assert( childTracker );
  7452. assert( childTracker->isSectionTracker() );
  7453. section = std::static_pointer_cast<SectionTracker>( childTracker );
  7454. }
  7455. else {
  7456. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  7457. currentTracker.addChild( section );
  7458. }
  7459. if( !ctx.completedCycle() )
  7460. section->tryOpen();
  7461. return *section;
  7462. }
  7463. void SectionTracker::tryOpen() {
  7464. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  7465. open();
  7466. }
  7467. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  7468. if( !filters.empty() ) {
  7469. m_filters.push_back(""); // Root - should never be consulted
  7470. m_filters.push_back(""); // Test Case - not a section filter
  7471. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  7472. }
  7473. }
  7474. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  7475. if( filters.size() > 1 )
  7476. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  7477. }
  7478. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  7479. : TrackerBase( nameAndLocation, ctx, parent ),
  7480. m_size( size )
  7481. {}
  7482. bool IndexTracker::isIndexTracker() const { return true; }
  7483. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  7484. std::shared_ptr<IndexTracker> tracker;
  7485. ITracker& currentTracker = ctx.currentTracker();
  7486. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7487. assert( childTracker );
  7488. assert( childTracker->isIndexTracker() );
  7489. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  7490. }
  7491. else {
  7492. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  7493. currentTracker.addChild( tracker );
  7494. }
  7495. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7496. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7497. tracker->moveNext();
  7498. tracker->open();
  7499. }
  7500. return *tracker;
  7501. }
  7502. int IndexTracker::index() const { return m_index; }
  7503. void IndexTracker::moveNext() {
  7504. m_index++;
  7505. m_children.clear();
  7506. }
  7507. void IndexTracker::close() {
  7508. TrackerBase::close();
  7509. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  7510. m_runState = Executing;
  7511. }
  7512. } // namespace TestCaseTracking
  7513. using TestCaseTracking::ITracker;
  7514. using TestCaseTracking::TrackerContext;
  7515. using TestCaseTracking::SectionTracker;
  7516. using TestCaseTracking::IndexTracker;
  7517. } // namespace Catch
  7518. #if defined(__clang__)
  7519. # pragma clang diagnostic pop
  7520. #endif
  7521. // end catch_test_case_tracker.cpp
  7522. // start catch_test_registry.cpp
  7523. namespace Catch {
  7524. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  7525. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  7526. }
  7527. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  7528. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  7529. try {
  7530. getMutableRegistryHub()
  7531. .registerTest(
  7532. makeTestCase(
  7533. invoker,
  7534. extractClassName( classOrMethod ),
  7535. nameAndTags.name,
  7536. nameAndTags.tags,
  7537. lineInfo));
  7538. } catch (...) {
  7539. // Do not throw when constructing global objects, instead register the exception to be processed later
  7540. getMutableRegistryHub().registerStartupException();
  7541. }
  7542. }
  7543. AutoReg::~AutoReg() = default;
  7544. }
  7545. // end catch_test_registry.cpp
  7546. // start catch_test_spec.cpp
  7547. #include <algorithm>
  7548. #include <string>
  7549. #include <vector>
  7550. #include <memory>
  7551. namespace Catch {
  7552. TestSpec::Pattern::~Pattern() = default;
  7553. TestSpec::NamePattern::~NamePattern() = default;
  7554. TestSpec::TagPattern::~TagPattern() = default;
  7555. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  7556. TestSpec::NamePattern::NamePattern( std::string const& name )
  7557. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  7558. {}
  7559. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  7560. return m_wildcardPattern.matches( toLower( testCase.name ) );
  7561. }
  7562. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  7563. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  7564. return std::find(begin(testCase.lcaseTags),
  7565. end(testCase.lcaseTags),
  7566. m_tag) != end(testCase.lcaseTags);
  7567. }
  7568. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  7569. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  7570. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  7571. // All patterns in a filter must match for the filter to be a match
  7572. for( auto const& pattern : m_patterns ) {
  7573. if( !pattern->matches( testCase ) )
  7574. return false;
  7575. }
  7576. return true;
  7577. }
  7578. bool TestSpec::hasFilters() const {
  7579. return !m_filters.empty();
  7580. }
  7581. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  7582. // A TestSpec matches if any filter matches
  7583. for( auto const& filter : m_filters )
  7584. if( filter.matches( testCase ) )
  7585. return true;
  7586. return false;
  7587. }
  7588. }
  7589. // end catch_test_spec.cpp
  7590. // start catch_test_spec_parser.cpp
  7591. namespace Catch {
  7592. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  7593. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  7594. m_mode = None;
  7595. m_exclusion = false;
  7596. m_start = std::string::npos;
  7597. m_arg = m_tagAliases->expandAliases( arg );
  7598. m_escapeChars.clear();
  7599. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  7600. visitChar( m_arg[m_pos] );
  7601. if( m_mode == Name )
  7602. addPattern<TestSpec::NamePattern>();
  7603. return *this;
  7604. }
  7605. TestSpec TestSpecParser::testSpec() {
  7606. addFilter();
  7607. return m_testSpec;
  7608. }
  7609. void TestSpecParser::visitChar( char c ) {
  7610. if( m_mode == None ) {
  7611. switch( c ) {
  7612. case ' ': return;
  7613. case '~': m_exclusion = true; return;
  7614. case '[': return startNewMode( Tag, ++m_pos );
  7615. case '"': return startNewMode( QuotedName, ++m_pos );
  7616. case '\\': return escape();
  7617. default: startNewMode( Name, m_pos ); break;
  7618. }
  7619. }
  7620. if( m_mode == Name ) {
  7621. if( c == ',' ) {
  7622. addPattern<TestSpec::NamePattern>();
  7623. addFilter();
  7624. }
  7625. else if( c == '[' ) {
  7626. if( subString() == "exclude:" )
  7627. m_exclusion = true;
  7628. else
  7629. addPattern<TestSpec::NamePattern>();
  7630. startNewMode( Tag, ++m_pos );
  7631. }
  7632. else if( c == '\\' )
  7633. escape();
  7634. }
  7635. else if( m_mode == EscapedName )
  7636. m_mode = Name;
  7637. else if( m_mode == QuotedName && c == '"' )
  7638. addPattern<TestSpec::NamePattern>();
  7639. else if( m_mode == Tag && c == ']' )
  7640. addPattern<TestSpec::TagPattern>();
  7641. }
  7642. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  7643. m_mode = mode;
  7644. m_start = start;
  7645. }
  7646. void TestSpecParser::escape() {
  7647. if( m_mode == None )
  7648. m_start = m_pos;
  7649. m_mode = EscapedName;
  7650. m_escapeChars.push_back( m_pos );
  7651. }
  7652. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  7653. void TestSpecParser::addFilter() {
  7654. if( !m_currentFilter.m_patterns.empty() ) {
  7655. m_testSpec.m_filters.push_back( m_currentFilter );
  7656. m_currentFilter = TestSpec::Filter();
  7657. }
  7658. }
  7659. TestSpec parseTestSpec( std::string const& arg ) {
  7660. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  7661. }
  7662. } // namespace Catch
  7663. // end catch_test_spec_parser.cpp
  7664. // start catch_timer.cpp
  7665. #include <chrono>
  7666. namespace Catch {
  7667. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  7668. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  7669. }
  7670. auto estimateClockResolution() -> uint64_t {
  7671. uint64_t sum = 0;
  7672. static const uint64_t iterations = 1000000;
  7673. for( std::size_t i = 0; i < iterations; ++i ) {
  7674. uint64_t ticks;
  7675. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  7676. do {
  7677. ticks = getCurrentNanosecondsSinceEpoch();
  7678. }
  7679. while( ticks == baseTicks );
  7680. auto delta = ticks - baseTicks;
  7681. sum += delta;
  7682. }
  7683. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  7684. // - and potentially do more iterations if there's a high variance.
  7685. return sum/iterations;
  7686. }
  7687. auto getEstimatedClockResolution() -> uint64_t {
  7688. static auto s_resolution = estimateClockResolution();
  7689. return s_resolution;
  7690. }
  7691. void Timer::start() {
  7692. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  7693. }
  7694. auto Timer::getElapsedNanoseconds() const -> unsigned int {
  7695. return static_cast<unsigned int>(getCurrentNanosecondsSinceEpoch() - m_nanoseconds);
  7696. }
  7697. auto Timer::getElapsedMicroseconds() const -> unsigned int {
  7698. return static_cast<unsigned int>(getElapsedNanoseconds()/1000);
  7699. }
  7700. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  7701. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  7702. }
  7703. auto Timer::getElapsedSeconds() const -> double {
  7704. return getElapsedMicroseconds()/1000000.0;
  7705. }
  7706. } // namespace Catch
  7707. // end catch_timer.cpp
  7708. // start catch_tostring.cpp
  7709. #if defined(__clang__)
  7710. # pragma clang diagnostic push
  7711. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7712. # pragma clang diagnostic ignored "-Wglobal-constructors"
  7713. #endif
  7714. #include <iomanip>
  7715. namespace Catch {
  7716. namespace Detail {
  7717. const std::string unprintableString = "{?}";
  7718. namespace {
  7719. const int hexThreshold = 255;
  7720. struct Endianness {
  7721. enum Arch { Big, Little };
  7722. static Arch which() {
  7723. union _{
  7724. int asInt;
  7725. char asChar[sizeof (int)];
  7726. } u;
  7727. u.asInt = 1;
  7728. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  7729. }
  7730. };
  7731. }
  7732. std::string rawMemoryToString( const void *object, std::size_t size ) {
  7733. // Reverse order for little endian architectures
  7734. int i = 0, end = static_cast<int>( size ), inc = 1;
  7735. if( Endianness::which() == Endianness::Little ) {
  7736. i = end-1;
  7737. end = inc = -1;
  7738. }
  7739. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  7740. std::ostringstream os;
  7741. os << "0x" << std::setfill('0') << std::hex;
  7742. for( ; i != end; i += inc )
  7743. os << std::setw(2) << static_cast<unsigned>(bytes[i]);
  7744. return os.str();
  7745. }
  7746. }
  7747. template<typename T>
  7748. std::string fpToString( T value, int precision ) {
  7749. std::ostringstream oss;
  7750. oss << std::setprecision( precision )
  7751. << std::fixed
  7752. << value;
  7753. std::string d = oss.str();
  7754. std::size_t i = d.find_last_not_of( '0' );
  7755. if( i != std::string::npos && i != d.size()-1 ) {
  7756. if( d[i] == '.' )
  7757. i++;
  7758. d = d.substr( 0, i+1 );
  7759. }
  7760. return d;
  7761. }
  7762. //// ======================================================= ////
  7763. //
  7764. // Out-of-line defs for full specialization of StringMaker
  7765. //
  7766. //// ======================================================= ////
  7767. std::string StringMaker<std::string>::convert(const std::string& str) {
  7768. if (!getCurrentContext().getConfig()->showInvisibles()) {
  7769. return '"' + str + '"';
  7770. }
  7771. std::string s("\"");
  7772. for (char c : str) {
  7773. switch (c) {
  7774. case '\n':
  7775. s.append("\\n");
  7776. break;
  7777. case '\t':
  7778. s.append("\\t");
  7779. break;
  7780. default:
  7781. s.push_back(c);
  7782. break;
  7783. }
  7784. }
  7785. s.append("\"");
  7786. return s;
  7787. }
  7788. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  7789. std::string s;
  7790. s.reserve(wstr.size());
  7791. for (auto c : wstr) {
  7792. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  7793. }
  7794. return ::Catch::Detail::stringify(s);
  7795. }
  7796. std::string StringMaker<char const*>::convert(char const* str) {
  7797. if (str) {
  7798. return ::Catch::Detail::stringify(std::string{ str });
  7799. } else {
  7800. return{ "{null string}" };
  7801. }
  7802. }
  7803. std::string StringMaker<char*>::convert(char* str) {
  7804. if (str) {
  7805. return ::Catch::Detail::stringify(std::string{ str });
  7806. } else {
  7807. return{ "{null string}" };
  7808. }
  7809. }
  7810. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  7811. if (str) {
  7812. return ::Catch::Detail::stringify(std::wstring{ str });
  7813. } else {
  7814. return{ "{null string}" };
  7815. }
  7816. }
  7817. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  7818. if (str) {
  7819. return ::Catch::Detail::stringify(std::wstring{ str });
  7820. } else {
  7821. return{ "{null string}" };
  7822. }
  7823. }
  7824. std::string StringMaker<int>::convert(int value) {
  7825. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7826. }
  7827. std::string StringMaker<long>::convert(long value) {
  7828. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7829. }
  7830. std::string StringMaker<long long>::convert(long long value) {
  7831. std::ostringstream oss;
  7832. oss << value;
  7833. if (value > Detail::hexThreshold) {
  7834. oss << " (0x" << std::hex << value << ')';
  7835. }
  7836. return oss.str();
  7837. }
  7838. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  7839. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7840. }
  7841. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  7842. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7843. }
  7844. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  7845. std::ostringstream oss;
  7846. oss << value;
  7847. if (value > Detail::hexThreshold) {
  7848. oss << " (0x" << std::hex << value << ')';
  7849. }
  7850. return oss.str();
  7851. }
  7852. std::string StringMaker<bool>::convert(bool b) {
  7853. return b ? "true" : "false";
  7854. }
  7855. std::string StringMaker<char>::convert(char value) {
  7856. if (value == '\r') {
  7857. return "'\\r'";
  7858. } else if (value == '\f') {
  7859. return "'\\f'";
  7860. } else if (value == '\n') {
  7861. return "'\\n'";
  7862. } else if (value == '\t') {
  7863. return "'\\t'";
  7864. } else if ('\0' <= value && value < ' ') {
  7865. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  7866. } else {
  7867. char chstr[] = "' '";
  7868. chstr[1] = value;
  7869. return chstr;
  7870. }
  7871. }
  7872. std::string StringMaker<signed char>::convert(signed char c) {
  7873. return ::Catch::Detail::stringify(static_cast<char>(c));
  7874. }
  7875. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  7876. return ::Catch::Detail::stringify(static_cast<char>(c));
  7877. }
  7878. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  7879. return "nullptr";
  7880. }
  7881. std::string StringMaker<float>::convert(float value) {
  7882. return fpToString(value, 5) + 'f';
  7883. }
  7884. std::string StringMaker<double>::convert(double value) {
  7885. return fpToString(value, 10);
  7886. }
  7887. } // end namespace Catch
  7888. #if defined(__clang__)
  7889. # pragma clang diagnostic pop
  7890. #endif
  7891. // end catch_tostring.cpp
  7892. // start catch_totals.cpp
  7893. namespace Catch {
  7894. Counts Counts::operator - ( Counts const& other ) const {
  7895. Counts diff;
  7896. diff.passed = passed - other.passed;
  7897. diff.failed = failed - other.failed;
  7898. diff.failedButOk = failedButOk - other.failedButOk;
  7899. return diff;
  7900. }
  7901. Counts& Counts::operator += ( Counts const& other ) {
  7902. passed += other.passed;
  7903. failed += other.failed;
  7904. failedButOk += other.failedButOk;
  7905. return *this;
  7906. }
  7907. std::size_t Counts::total() const {
  7908. return passed + failed + failedButOk;
  7909. }
  7910. bool Counts::allPassed() const {
  7911. return failed == 0 && failedButOk == 0;
  7912. }
  7913. bool Counts::allOk() const {
  7914. return failed == 0;
  7915. }
  7916. Totals Totals::operator - ( Totals const& other ) const {
  7917. Totals diff;
  7918. diff.assertions = assertions - other.assertions;
  7919. diff.testCases = testCases - other.testCases;
  7920. return diff;
  7921. }
  7922. Totals& Totals::operator += ( Totals const& other ) {
  7923. assertions += other.assertions;
  7924. testCases += other.testCases;
  7925. return *this;
  7926. }
  7927. Totals Totals::delta( Totals const& prevTotals ) const {
  7928. Totals diff = *this - prevTotals;
  7929. if( diff.assertions.failed > 0 )
  7930. ++diff.testCases.failed;
  7931. else if( diff.assertions.failedButOk > 0 )
  7932. ++diff.testCases.failedButOk;
  7933. else
  7934. ++diff.testCases.passed;
  7935. return diff;
  7936. }
  7937. }
  7938. // end catch_totals.cpp
  7939. // start catch_version.cpp
  7940. #include <ostream>
  7941. namespace Catch {
  7942. Version::Version
  7943. ( unsigned int _majorVersion,
  7944. unsigned int _minorVersion,
  7945. unsigned int _patchNumber,
  7946. char const * const _branchName,
  7947. unsigned int _buildNumber )
  7948. : majorVersion( _majorVersion ),
  7949. minorVersion( _minorVersion ),
  7950. patchNumber( _patchNumber ),
  7951. branchName( _branchName ),
  7952. buildNumber( _buildNumber )
  7953. {}
  7954. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  7955. os << version.majorVersion << '.'
  7956. << version.minorVersion << '.'
  7957. << version.patchNumber;
  7958. // branchName is never null -> 0th char is \0 if it is empty
  7959. if (version.branchName[0]) {
  7960. os << '-' << version.branchName
  7961. << '.' << version.buildNumber;
  7962. }
  7963. return os;
  7964. }
  7965. Version const& libraryVersion() {
  7966. static Version version( 2, 0, 1, "", 0 );
  7967. return version;
  7968. }
  7969. }
  7970. // end catch_version.cpp
  7971. // start catch_wildcard_pattern.cpp
  7972. namespace Catch {
  7973. WildcardPattern::WildcardPattern( std::string const& pattern,
  7974. CaseSensitive::Choice caseSensitivity )
  7975. : m_caseSensitivity( caseSensitivity ),
  7976. m_pattern( adjustCase( pattern ) )
  7977. {
  7978. if( startsWith( m_pattern, '*' ) ) {
  7979. m_pattern = m_pattern.substr( 1 );
  7980. m_wildcard = WildcardAtStart;
  7981. }
  7982. if( endsWith( m_pattern, '*' ) ) {
  7983. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  7984. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  7985. }
  7986. }
  7987. bool WildcardPattern::matches( std::string const& str ) const {
  7988. switch( m_wildcard ) {
  7989. case NoWildcard:
  7990. return m_pattern == adjustCase( str );
  7991. case WildcardAtStart:
  7992. return endsWith( adjustCase( str ), m_pattern );
  7993. case WildcardAtEnd:
  7994. return startsWith( adjustCase( str ), m_pattern );
  7995. case WildcardAtBothEnds:
  7996. return contains( adjustCase( str ), m_pattern );
  7997. default:
  7998. CATCH_INTERNAL_ERROR( "Unknown enum" );
  7999. }
  8000. }
  8001. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8002. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8003. }
  8004. }
  8005. // end catch_wildcard_pattern.cpp
  8006. // start catch_xmlwriter.cpp
  8007. // start catch_xmlwriter.h
  8008. #include <sstream>
  8009. #include <vector>
  8010. namespace Catch {
  8011. class XmlEncode {
  8012. public:
  8013. enum ForWhat { ForTextNodes, ForAttributes };
  8014. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  8015. void encodeTo( std::ostream& os ) const;
  8016. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  8017. private:
  8018. std::string m_str;
  8019. ForWhat m_forWhat;
  8020. };
  8021. class XmlWriter {
  8022. public:
  8023. class ScopedElement {
  8024. public:
  8025. ScopedElement( XmlWriter* writer );
  8026. ScopedElement( ScopedElement&& other ) noexcept;
  8027. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  8028. ~ScopedElement();
  8029. ScopedElement& writeText( std::string const& text, bool indent = true );
  8030. template<typename T>
  8031. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  8032. m_writer->writeAttribute( name, attribute );
  8033. return *this;
  8034. }
  8035. private:
  8036. mutable XmlWriter* m_writer = nullptr;
  8037. };
  8038. XmlWriter( std::ostream& os = Catch::cout() );
  8039. ~XmlWriter();
  8040. XmlWriter( XmlWriter const& ) = delete;
  8041. XmlWriter& operator=( XmlWriter const& ) = delete;
  8042. XmlWriter& startElement( std::string const& name );
  8043. ScopedElement scopedElement( std::string const& name );
  8044. XmlWriter& endElement();
  8045. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  8046. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  8047. template<typename T>
  8048. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  8049. m_oss.clear();
  8050. m_oss.str(std::string());
  8051. m_oss << attribute;
  8052. return writeAttribute( name, m_oss.str() );
  8053. }
  8054. XmlWriter& writeText( std::string const& text, bool indent = true );
  8055. XmlWriter& writeComment( std::string const& text );
  8056. void writeStylesheetRef( std::string const& url );
  8057. XmlWriter& writeBlankLine();
  8058. void ensureTagClosed();
  8059. private:
  8060. void writeDeclaration();
  8061. void newlineIfNecessary();
  8062. bool m_tagIsOpen = false;
  8063. bool m_needsNewline = false;
  8064. std::vector<std::string> m_tags;
  8065. std::string m_indent;
  8066. std::ostream& m_os;
  8067. std::ostringstream m_oss;
  8068. };
  8069. }
  8070. // end catch_xmlwriter.h
  8071. #include <iomanip>
  8072. namespace Catch {
  8073. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8074. : m_str( str ),
  8075. m_forWhat( forWhat )
  8076. {}
  8077. void XmlEncode::encodeTo( std::ostream& os ) const {
  8078. // Apostrophe escaping not necessary if we always use " to write attributes
  8079. // (see: http://www.w3.org/TR/xml/#syntax)
  8080. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8081. char c = m_str[i];
  8082. switch( c ) {
  8083. case '<': os << "&lt;"; break;
  8084. case '&': os << "&amp;"; break;
  8085. case '>':
  8086. // See: http://www.w3.org/TR/xml/#syntax
  8087. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8088. os << "&gt;";
  8089. else
  8090. os << c;
  8091. break;
  8092. case '\"':
  8093. if( m_forWhat == ForAttributes )
  8094. os << "&quot;";
  8095. else
  8096. os << c;
  8097. break;
  8098. default:
  8099. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8100. // by @mrpi PR #588
  8101. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8102. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8103. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8104. << static_cast<int>( c );
  8105. }
  8106. else
  8107. os << c;
  8108. }
  8109. }
  8110. }
  8111. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8112. xmlEncode.encodeTo( os );
  8113. return os;
  8114. }
  8115. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8116. : m_writer( writer )
  8117. {}
  8118. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8119. : m_writer( other.m_writer ){
  8120. other.m_writer = nullptr;
  8121. }
  8122. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8123. if ( m_writer ) {
  8124. m_writer->endElement();
  8125. }
  8126. m_writer = other.m_writer;
  8127. other.m_writer = nullptr;
  8128. return *this;
  8129. }
  8130. XmlWriter::ScopedElement::~ScopedElement() {
  8131. if( m_writer )
  8132. m_writer->endElement();
  8133. }
  8134. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8135. m_writer->writeText( text, indent );
  8136. return *this;
  8137. }
  8138. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8139. {
  8140. writeDeclaration();
  8141. }
  8142. XmlWriter::~XmlWriter() {
  8143. while( !m_tags.empty() )
  8144. endElement();
  8145. }
  8146. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8147. ensureTagClosed();
  8148. newlineIfNecessary();
  8149. m_os << m_indent << '<' << name;
  8150. m_tags.push_back( name );
  8151. m_indent += " ";
  8152. m_tagIsOpen = true;
  8153. return *this;
  8154. }
  8155. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8156. ScopedElement scoped( this );
  8157. startElement( name );
  8158. return scoped;
  8159. }
  8160. XmlWriter& XmlWriter::endElement() {
  8161. newlineIfNecessary();
  8162. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8163. if( m_tagIsOpen ) {
  8164. m_os << "/>";
  8165. m_tagIsOpen = false;
  8166. }
  8167. else {
  8168. m_os << m_indent << "</" << m_tags.back() << ">";
  8169. }
  8170. m_os << std::endl;
  8171. m_tags.pop_back();
  8172. return *this;
  8173. }
  8174. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8175. if( !name.empty() && !attribute.empty() )
  8176. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8177. return *this;
  8178. }
  8179. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8180. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8181. return *this;
  8182. }
  8183. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8184. if( !text.empty() ){
  8185. bool tagWasOpen = m_tagIsOpen;
  8186. ensureTagClosed();
  8187. if( tagWasOpen && indent )
  8188. m_os << m_indent;
  8189. m_os << XmlEncode( text );
  8190. m_needsNewline = true;
  8191. }
  8192. return *this;
  8193. }
  8194. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8195. ensureTagClosed();
  8196. m_os << m_indent << "<!--" << text << "-->";
  8197. m_needsNewline = true;
  8198. return *this;
  8199. }
  8200. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8201. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8202. }
  8203. XmlWriter& XmlWriter::writeBlankLine() {
  8204. ensureTagClosed();
  8205. m_os << '\n';
  8206. return *this;
  8207. }
  8208. void XmlWriter::ensureTagClosed() {
  8209. if( m_tagIsOpen ) {
  8210. m_os << ">" << std::endl;
  8211. m_tagIsOpen = false;
  8212. }
  8213. }
  8214. void XmlWriter::writeDeclaration() {
  8215. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8216. }
  8217. void XmlWriter::newlineIfNecessary() {
  8218. if( m_needsNewline ) {
  8219. m_os << std::endl;
  8220. m_needsNewline = false;
  8221. }
  8222. }
  8223. }
  8224. // end catch_xmlwriter.cpp
  8225. // start catch_reporter_bases.cpp
  8226. #include <cstring>
  8227. #include <cfloat>
  8228. #include <cstdio>
  8229. #include <assert.h>
  8230. #include <memory>
  8231. namespace Catch {
  8232. void prepareExpandedExpression(AssertionResult& result) {
  8233. result.getExpandedExpression();
  8234. }
  8235. // Because formatting using c++ streams is stateful, drop down to C is required
  8236. // Alternatively we could use stringstream, but its performance is... not good.
  8237. std::string getFormattedDuration( double duration ) {
  8238. // Max exponent + 1 is required to represent the whole part
  8239. // + 1 for decimal point
  8240. // + 3 for the 3 decimal places
  8241. // + 1 for null terminator
  8242. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8243. char buffer[maxDoubleSize];
  8244. // Save previous errno, to prevent sprintf from overwriting it
  8245. ErrnoGuard guard;
  8246. #ifdef _MSC_VER
  8247. sprintf_s(buffer, "%.3f", duration);
  8248. #else
  8249. sprintf(buffer, "%.3f", duration);
  8250. #endif
  8251. return std::string(buffer);
  8252. }
  8253. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8254. :StreamingReporterBase(_config) {}
  8255. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8256. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8257. return false;
  8258. }
  8259. } // end namespace Catch
  8260. // end catch_reporter_bases.cpp
  8261. // start catch_reporter_compact.cpp
  8262. namespace {
  8263. #ifdef CATCH_PLATFORM_MAC
  8264. const char* failedString() { return "FAILED"; }
  8265. const char* passedString() { return "PASSED"; }
  8266. #else
  8267. const char* failedString() { return "failed"; }
  8268. const char* passedString() { return "passed"; }
  8269. #endif
  8270. // Colour::LightGrey
  8271. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8272. std::string bothOrAll( std::size_t count ) {
  8273. return count == 1 ? std::string() :
  8274. count == 2 ? "both " : "all " ;
  8275. }
  8276. }
  8277. namespace Catch {
  8278. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  8279. using StreamingReporterBase::StreamingReporterBase;
  8280. ~CompactReporter() override;
  8281. static std::string getDescription() {
  8282. return "Reports test results on a single line, suitable for IDEs";
  8283. }
  8284. ReporterPreferences getPreferences() const override {
  8285. ReporterPreferences prefs;
  8286. prefs.shouldRedirectStdOut = false;
  8287. return prefs;
  8288. }
  8289. void noMatchingTestCases( std::string const& spec ) override {
  8290. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8291. }
  8292. void assertionStarting( AssertionInfo const& ) override {}
  8293. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8294. AssertionResult const& result = _assertionStats.assertionResult;
  8295. bool printInfoMessages = true;
  8296. // Drop out if result was successful and we're not printing those
  8297. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  8298. if( result.getResultType() != ResultWas::Warning )
  8299. return false;
  8300. printInfoMessages = false;
  8301. }
  8302. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  8303. printer.print();
  8304. stream << std::endl;
  8305. return true;
  8306. }
  8307. void sectionEnded(SectionStats const& _sectionStats) override {
  8308. if (m_config->showDurations() == ShowDurations::Always) {
  8309. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8310. }
  8311. }
  8312. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8313. printTotals( _testRunStats.totals );
  8314. stream << '\n' << std::endl;
  8315. StreamingReporterBase::testRunEnded( _testRunStats );
  8316. }
  8317. private:
  8318. class AssertionPrinter {
  8319. public:
  8320. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8321. AssertionPrinter( AssertionPrinter const& ) = delete;
  8322. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8323. : stream( _stream )
  8324. , result( _stats.assertionResult )
  8325. , messages( _stats.infoMessages )
  8326. , itMessage( _stats.infoMessages.begin() )
  8327. , printInfoMessages( _printInfoMessages )
  8328. {}
  8329. void print() {
  8330. printSourceInfo();
  8331. itMessage = messages.begin();
  8332. switch( result.getResultType() ) {
  8333. case ResultWas::Ok:
  8334. printResultType( Colour::ResultSuccess, passedString() );
  8335. printOriginalExpression();
  8336. printReconstructedExpression();
  8337. if ( ! result.hasExpression() )
  8338. printRemainingMessages( Colour::None );
  8339. else
  8340. printRemainingMessages();
  8341. break;
  8342. case ResultWas::ExpressionFailed:
  8343. if( result.isOk() )
  8344. printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
  8345. else
  8346. printResultType( Colour::Error, failedString() );
  8347. printOriginalExpression();
  8348. printReconstructedExpression();
  8349. printRemainingMessages();
  8350. break;
  8351. case ResultWas::ThrewException:
  8352. printResultType( Colour::Error, failedString() );
  8353. printIssue( "unexpected exception with message:" );
  8354. printMessage();
  8355. printExpressionWas();
  8356. printRemainingMessages();
  8357. break;
  8358. case ResultWas::FatalErrorCondition:
  8359. printResultType( Colour::Error, failedString() );
  8360. printIssue( "fatal error condition with message:" );
  8361. printMessage();
  8362. printExpressionWas();
  8363. printRemainingMessages();
  8364. break;
  8365. case ResultWas::DidntThrowException:
  8366. printResultType( Colour::Error, failedString() );
  8367. printIssue( "expected exception, got none" );
  8368. printExpressionWas();
  8369. printRemainingMessages();
  8370. break;
  8371. case ResultWas::Info:
  8372. printResultType( Colour::None, "info" );
  8373. printMessage();
  8374. printRemainingMessages();
  8375. break;
  8376. case ResultWas::Warning:
  8377. printResultType( Colour::None, "warning" );
  8378. printMessage();
  8379. printRemainingMessages();
  8380. break;
  8381. case ResultWas::ExplicitFailure:
  8382. printResultType( Colour::Error, failedString() );
  8383. printIssue( "explicitly" );
  8384. printRemainingMessages( Colour::None );
  8385. break;
  8386. // These cases are here to prevent compiler warnings
  8387. case ResultWas::Unknown:
  8388. case ResultWas::FailureBit:
  8389. case ResultWas::Exception:
  8390. printResultType( Colour::Error, "** internal error **" );
  8391. break;
  8392. }
  8393. }
  8394. private:
  8395. void printSourceInfo() const {
  8396. Colour colourGuard( Colour::FileName );
  8397. stream << result.getSourceInfo() << ':';
  8398. }
  8399. void printResultType( Colour::Code colour, std::string const& passOrFail ) const {
  8400. if( !passOrFail.empty() ) {
  8401. {
  8402. Colour colourGuard( colour );
  8403. stream << ' ' << passOrFail;
  8404. }
  8405. stream << ':';
  8406. }
  8407. }
  8408. void printIssue( std::string const& issue ) const {
  8409. stream << ' ' << issue;
  8410. }
  8411. void printExpressionWas() {
  8412. if( result.hasExpression() ) {
  8413. stream << ';';
  8414. {
  8415. Colour colour( dimColour() );
  8416. stream << " expression was:";
  8417. }
  8418. printOriginalExpression();
  8419. }
  8420. }
  8421. void printOriginalExpression() const {
  8422. if( result.hasExpression() ) {
  8423. stream << ' ' << result.getExpression();
  8424. }
  8425. }
  8426. void printReconstructedExpression() const {
  8427. if( result.hasExpandedExpression() ) {
  8428. {
  8429. Colour colour( dimColour() );
  8430. stream << " for: ";
  8431. }
  8432. stream << result.getExpandedExpression();
  8433. }
  8434. }
  8435. void printMessage() {
  8436. if ( itMessage != messages.end() ) {
  8437. stream << " '" << itMessage->message << '\'';
  8438. ++itMessage;
  8439. }
  8440. }
  8441. void printRemainingMessages( Colour::Code colour = dimColour() ) {
  8442. if ( itMessage == messages.end() )
  8443. return;
  8444. // using messages.end() directly yields (or auto) compilation error:
  8445. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  8446. const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
  8447. {
  8448. Colour colourGuard( colour );
  8449. stream << " with " << pluralise( N, "message" ) << ':';
  8450. }
  8451. for(; itMessage != itEnd; ) {
  8452. // If this assertion is a warning ignore any INFO messages
  8453. if( printInfoMessages || itMessage->type != ResultWas::Info ) {
  8454. stream << " '" << itMessage->message << '\'';
  8455. if ( ++itMessage != itEnd ) {
  8456. Colour colourGuard( dimColour() );
  8457. stream << " and";
  8458. }
  8459. }
  8460. }
  8461. }
  8462. private:
  8463. std::ostream& stream;
  8464. AssertionResult const& result;
  8465. std::vector<MessageInfo> messages;
  8466. std::vector<MessageInfo>::const_iterator itMessage;
  8467. bool printInfoMessages;
  8468. };
  8469. // Colour, message variants:
  8470. // - white: No tests ran.
  8471. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8472. // - white: Passed [both/all] N test cases (no assertions).
  8473. // - red: Failed N tests cases, failed M assertions.
  8474. // - green: Passed [both/all] N tests cases with M assertions.
  8475. void printTotals( const Totals& totals ) const {
  8476. if( totals.testCases.total() == 0 ) {
  8477. stream << "No tests ran.";
  8478. }
  8479. else if( totals.testCases.failed == totals.testCases.total() ) {
  8480. Colour colour( Colour::ResultError );
  8481. const std::string qualify_assertions_failed =
  8482. totals.assertions.failed == totals.assertions.total() ?
  8483. bothOrAll( totals.assertions.failed ) : std::string();
  8484. stream <<
  8485. "Failed " << bothOrAll( totals.testCases.failed )
  8486. << pluralise( totals.testCases.failed, "test case" ) << ", "
  8487. "failed " << qualify_assertions_failed <<
  8488. pluralise( totals.assertions.failed, "assertion" ) << '.';
  8489. }
  8490. else if( totals.assertions.total() == 0 ) {
  8491. stream <<
  8492. "Passed " << bothOrAll( totals.testCases.total() )
  8493. << pluralise( totals.testCases.total(), "test case" )
  8494. << " (no assertions).";
  8495. }
  8496. else if( totals.assertions.failed ) {
  8497. Colour colour( Colour::ResultError );
  8498. stream <<
  8499. "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
  8500. "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
  8501. }
  8502. else {
  8503. Colour colour( Colour::ResultSuccess );
  8504. stream <<
  8505. "Passed " << bothOrAll( totals.testCases.passed )
  8506. << pluralise( totals.testCases.passed, "test case" ) <<
  8507. " with " << pluralise( totals.assertions.passed, "assertion" ) << '.';
  8508. }
  8509. }
  8510. };
  8511. CompactReporter::~CompactReporter() {}
  8512. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  8513. } // end namespace Catch
  8514. // end catch_reporter_compact.cpp
  8515. // start catch_reporter_console.cpp
  8516. #include <cfloat>
  8517. #include <cstdio>
  8518. #if defined(_MSC_VER)
  8519. #pragma warning(push)
  8520. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  8521. // Note that 4062 (not all labels are handled
  8522. // and default is missing) is enabled
  8523. #endif
  8524. namespace Catch {
  8525. namespace {
  8526. std::size_t makeRatio( std::size_t number, std::size_t total ) {
  8527. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
  8528. return ( ratio == 0 && number > 0 ) ? 1 : ratio;
  8529. }
  8530. std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
  8531. if( i > j && i > k )
  8532. return i;
  8533. else if( j > k )
  8534. return j;
  8535. else
  8536. return k;
  8537. }
  8538. struct ColumnInfo {
  8539. enum Justification { Left, Right };
  8540. std::string name;
  8541. int width;
  8542. Justification justification;
  8543. };
  8544. struct ColumnBreak {};
  8545. struct RowBreak {};
  8546. class TablePrinter {
  8547. std::ostream& m_os;
  8548. std::vector<ColumnInfo> m_columnInfos;
  8549. std::ostringstream m_oss;
  8550. int m_currentColumn = -1;
  8551. bool m_isOpen = false;
  8552. public:
  8553. TablePrinter( std::ostream& os, std::vector<ColumnInfo> const& columnInfos )
  8554. : m_os( os ),
  8555. m_columnInfos( columnInfos )
  8556. {}
  8557. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  8558. return m_columnInfos;
  8559. }
  8560. void open() {
  8561. if( !m_isOpen ) {
  8562. m_isOpen = true;
  8563. *this << RowBreak();
  8564. for( auto const& info : m_columnInfos )
  8565. *this << info.name << ColumnBreak();
  8566. *this << RowBreak();
  8567. m_os << Catch::getLineOfChars<'-'>() << "\n";
  8568. }
  8569. }
  8570. void close() {
  8571. if( m_isOpen ) {
  8572. *this << RowBreak();
  8573. m_os << std::endl;
  8574. m_isOpen = false;
  8575. }
  8576. }
  8577. template<typename T>
  8578. friend TablePrinter& operator << ( TablePrinter& tp, T const& value ) {
  8579. tp.m_oss << value;
  8580. return tp;
  8581. }
  8582. friend TablePrinter& operator << ( TablePrinter& tp, ColumnBreak ) {
  8583. auto colStr = tp.m_oss.str();
  8584. // This takes account of utf8 encodings
  8585. auto strSize = Catch::StringRef( colStr ).numberOfCharacters();
  8586. tp.m_oss.str("");
  8587. tp.open();
  8588. if( tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size()-1) ) {
  8589. tp.m_currentColumn = -1;
  8590. tp.m_os << "\n";
  8591. }
  8592. tp.m_currentColumn++;
  8593. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  8594. auto padding = ( strSize+2 < static_cast<std::size_t>( colInfo.width ) )
  8595. ? std::string( colInfo.width-(strSize+2), ' ' )
  8596. : std::string();
  8597. if( colInfo.justification == ColumnInfo::Left )
  8598. tp.m_os << colStr << padding << " ";
  8599. else
  8600. tp.m_os << padding << colStr << " ";
  8601. return tp;
  8602. }
  8603. friend TablePrinter& operator << ( TablePrinter& tp, RowBreak ) {
  8604. if( tp.m_currentColumn > 0 ) {
  8605. tp.m_os << "\n";
  8606. tp.m_currentColumn = -1;
  8607. }
  8608. return tp;
  8609. }
  8610. };
  8611. class Duration {
  8612. enum class Unit {
  8613. Auto,
  8614. Nanoseconds,
  8615. Microseconds,
  8616. Milliseconds,
  8617. Seconds,
  8618. Minutes
  8619. };
  8620. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  8621. static const uint64_t s_nanosecondsInAMillisecond = 1000*s_nanosecondsInAMicrosecond;
  8622. static const uint64_t s_nanosecondsInASecond = 1000*s_nanosecondsInAMillisecond;
  8623. static const uint64_t s_nanosecondsInAMinute = 60*s_nanosecondsInASecond;
  8624. uint64_t m_inNanoseconds;
  8625. Unit m_units;
  8626. public:
  8627. Duration( uint64_t inNanoseconds, Unit units = Unit::Auto )
  8628. : m_inNanoseconds( inNanoseconds ),
  8629. m_units( units )
  8630. {
  8631. if( m_units == Unit::Auto ) {
  8632. if( m_inNanoseconds < s_nanosecondsInAMicrosecond )
  8633. m_units = Unit::Nanoseconds;
  8634. else if( m_inNanoseconds < s_nanosecondsInAMillisecond )
  8635. m_units = Unit::Microseconds;
  8636. else if( m_inNanoseconds < s_nanosecondsInASecond )
  8637. m_units = Unit::Milliseconds;
  8638. else if( m_inNanoseconds < s_nanosecondsInAMinute )
  8639. m_units = Unit::Seconds;
  8640. else
  8641. m_units = Unit::Minutes;
  8642. }
  8643. }
  8644. auto value() const -> double {
  8645. switch( m_units ) {
  8646. case Unit::Microseconds:
  8647. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMicrosecond );
  8648. case Unit::Milliseconds:
  8649. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMillisecond );
  8650. case Unit::Seconds:
  8651. return m_inNanoseconds / static_cast<double>( s_nanosecondsInASecond );
  8652. case Unit::Minutes:
  8653. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMinute );
  8654. default:
  8655. return static_cast<double>( m_inNanoseconds );
  8656. }
  8657. }
  8658. auto unitsAsString() const -> std::string {
  8659. switch( m_units ) {
  8660. case Unit::Nanoseconds:
  8661. return "ns";
  8662. case Unit::Microseconds:
  8663. return "µs";
  8664. case Unit::Milliseconds:
  8665. return "ms";
  8666. case Unit::Seconds:
  8667. return "s";
  8668. case Unit::Minutes:
  8669. return "m";
  8670. default:
  8671. return "** internal error **";
  8672. }
  8673. }
  8674. friend auto operator << ( std::ostream& os, Duration const& duration ) -> std::ostream& {
  8675. return os << duration.value() << " " << duration.unitsAsString();
  8676. }
  8677. };
  8678. } // end anon namespace
  8679. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  8680. TablePrinter m_tablePrinter;
  8681. ConsoleReporter( ReporterConfig const& config )
  8682. : StreamingReporterBase( config ),
  8683. m_tablePrinter( config.stream(),
  8684. {
  8685. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH-32, ColumnInfo::Left },
  8686. { "iters", 8, ColumnInfo::Right },
  8687. { "elapsed ns", 14, ColumnInfo::Right },
  8688. { "average", 14, ColumnInfo::Right }
  8689. } )
  8690. {}
  8691. ~ConsoleReporter() override;
  8692. static std::string getDescription() {
  8693. return "Reports test results as plain lines of text";
  8694. }
  8695. void noMatchingTestCases( std::string const& spec ) override {
  8696. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8697. }
  8698. void assertionStarting( AssertionInfo const& ) override {
  8699. }
  8700. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8701. AssertionResult const& result = _assertionStats.assertionResult;
  8702. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  8703. // Drop out if result was successful but we're not printing them.
  8704. if( !includeResults && result.getResultType() != ResultWas::Warning )
  8705. return false;
  8706. lazyPrint();
  8707. AssertionPrinter printer( stream, _assertionStats, includeResults );
  8708. printer.print();
  8709. stream << std::endl;
  8710. return true;
  8711. }
  8712. void sectionStarting( SectionInfo const& _sectionInfo ) override {
  8713. m_headerPrinted = false;
  8714. StreamingReporterBase::sectionStarting( _sectionInfo );
  8715. }
  8716. void sectionEnded( SectionStats const& _sectionStats ) override {
  8717. m_tablePrinter.close();
  8718. if( _sectionStats.missingAssertions ) {
  8719. lazyPrint();
  8720. Colour colour( Colour::ResultError );
  8721. if( m_sectionStack.size() > 1 )
  8722. stream << "\nNo assertions in section";
  8723. else
  8724. stream << "\nNo assertions in test case";
  8725. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  8726. }
  8727. if( m_config->showDurations() == ShowDurations::Always ) {
  8728. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8729. }
  8730. if( m_headerPrinted ) {
  8731. m_headerPrinted = false;
  8732. }
  8733. StreamingReporterBase::sectionEnded( _sectionStats );
  8734. }
  8735. void benchmarkStarting( BenchmarkInfo const& info ) override {
  8736. lazyPrintWithoutClosingBenchmarkTable();
  8737. auto nameCol = Column( info.name ).width( m_tablePrinter.columnInfos()[0].width-2 );
  8738. bool firstLine = true;
  8739. for( auto line : nameCol ) {
  8740. if( !firstLine )
  8741. m_tablePrinter << ColumnBreak() << ColumnBreak() << ColumnBreak();
  8742. else
  8743. firstLine = false;
  8744. m_tablePrinter << line << ColumnBreak();
  8745. }
  8746. }
  8747. void benchmarkEnded( BenchmarkStats const& stats ) override {
  8748. Duration average( stats.elapsedTimeInNanoseconds/stats.iterations );
  8749. m_tablePrinter
  8750. << stats.iterations << ColumnBreak()
  8751. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  8752. << average << ColumnBreak();
  8753. }
  8754. void testCaseEnded( TestCaseStats const& _testCaseStats ) override {
  8755. m_tablePrinter.close();
  8756. StreamingReporterBase::testCaseEnded( _testCaseStats );
  8757. m_headerPrinted = false;
  8758. }
  8759. void testGroupEnded( TestGroupStats const& _testGroupStats ) override {
  8760. if( currentGroupInfo.used ) {
  8761. printSummaryDivider();
  8762. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  8763. printTotals( _testGroupStats.totals );
  8764. stream << '\n' << std::endl;
  8765. }
  8766. StreamingReporterBase::testGroupEnded( _testGroupStats );
  8767. }
  8768. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8769. printTotalsDivider( _testRunStats.totals );
  8770. printTotals( _testRunStats.totals );
  8771. stream << std::endl;
  8772. StreamingReporterBase::testRunEnded( _testRunStats );
  8773. }
  8774. private:
  8775. class AssertionPrinter {
  8776. public:
  8777. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8778. AssertionPrinter( AssertionPrinter const& ) = delete;
  8779. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8780. : stream( _stream ),
  8781. stats( _stats ),
  8782. result( _stats.assertionResult ),
  8783. colour( Colour::None ),
  8784. message( result.getMessage() ),
  8785. messages( _stats.infoMessages ),
  8786. printInfoMessages( _printInfoMessages )
  8787. {
  8788. switch( result.getResultType() ) {
  8789. case ResultWas::Ok:
  8790. colour = Colour::Success;
  8791. passOrFail = "PASSED";
  8792. //if( result.hasMessage() )
  8793. if( _stats.infoMessages.size() == 1 )
  8794. messageLabel = "with message";
  8795. if( _stats.infoMessages.size() > 1 )
  8796. messageLabel = "with messages";
  8797. break;
  8798. case ResultWas::ExpressionFailed:
  8799. if( result.isOk() ) {
  8800. colour = Colour::Success;
  8801. passOrFail = "FAILED - but was ok";
  8802. }
  8803. else {
  8804. colour = Colour::Error;
  8805. passOrFail = "FAILED";
  8806. }
  8807. if( _stats.infoMessages.size() == 1 )
  8808. messageLabel = "with message";
  8809. if( _stats.infoMessages.size() > 1 )
  8810. messageLabel = "with messages";
  8811. break;
  8812. case ResultWas::ThrewException:
  8813. colour = Colour::Error;
  8814. passOrFail = "FAILED";
  8815. messageLabel = "due to unexpected exception with ";
  8816. if (_stats.infoMessages.size() == 1)
  8817. messageLabel += "message";
  8818. if (_stats.infoMessages.size() > 1)
  8819. messageLabel += "messages";
  8820. break;
  8821. case ResultWas::FatalErrorCondition:
  8822. colour = Colour::Error;
  8823. passOrFail = "FAILED";
  8824. messageLabel = "due to a fatal error condition";
  8825. break;
  8826. case ResultWas::DidntThrowException:
  8827. colour = Colour::Error;
  8828. passOrFail = "FAILED";
  8829. messageLabel = "because no exception was thrown where one was expected";
  8830. break;
  8831. case ResultWas::Info:
  8832. messageLabel = "info";
  8833. break;
  8834. case ResultWas::Warning:
  8835. messageLabel = "warning";
  8836. break;
  8837. case ResultWas::ExplicitFailure:
  8838. passOrFail = "FAILED";
  8839. colour = Colour::Error;
  8840. if( _stats.infoMessages.size() == 1 )
  8841. messageLabel = "explicitly with message";
  8842. if( _stats.infoMessages.size() > 1 )
  8843. messageLabel = "explicitly with messages";
  8844. break;
  8845. // These cases are here to prevent compiler warnings
  8846. case ResultWas::Unknown:
  8847. case ResultWas::FailureBit:
  8848. case ResultWas::Exception:
  8849. passOrFail = "** internal error **";
  8850. colour = Colour::Error;
  8851. break;
  8852. }
  8853. }
  8854. void print() const {
  8855. printSourceInfo();
  8856. if( stats.totals.assertions.total() > 0 ) {
  8857. if( result.isOk() )
  8858. stream << '\n';
  8859. printResultType();
  8860. printOriginalExpression();
  8861. printReconstructedExpression();
  8862. }
  8863. else {
  8864. stream << '\n';
  8865. }
  8866. printMessage();
  8867. }
  8868. private:
  8869. void printResultType() const {
  8870. if( !passOrFail.empty() ) {
  8871. Colour colourGuard( colour );
  8872. stream << passOrFail << ":\n";
  8873. }
  8874. }
  8875. void printOriginalExpression() const {
  8876. if( result.hasExpression() ) {
  8877. Colour colourGuard( Colour::OriginalExpression );
  8878. stream << " ";
  8879. stream << result.getExpressionInMacro();
  8880. stream << '\n';
  8881. }
  8882. }
  8883. void printReconstructedExpression() const {
  8884. if( result.hasExpandedExpression() ) {
  8885. stream << "with expansion:\n";
  8886. Colour colourGuard( Colour::ReconstructedExpression );
  8887. stream << Column( result.getExpandedExpression() ).indent(2) << '\n';
  8888. }
  8889. }
  8890. void printMessage() const {
  8891. if( !messageLabel.empty() )
  8892. stream << messageLabel << ':' << '\n';
  8893. for( auto const& msg : messages ) {
  8894. // If this assertion is a warning ignore any INFO messages
  8895. if( printInfoMessages || msg.type != ResultWas::Info )
  8896. stream << Column( msg.message ).indent(2) << '\n';
  8897. }
  8898. }
  8899. void printSourceInfo() const {
  8900. Colour colourGuard( Colour::FileName );
  8901. stream << result.getSourceInfo() << ": ";
  8902. }
  8903. std::ostream& stream;
  8904. AssertionStats const& stats;
  8905. AssertionResult const& result;
  8906. Colour::Code colour;
  8907. std::string passOrFail;
  8908. std::string messageLabel;
  8909. std::string message;
  8910. std::vector<MessageInfo> messages;
  8911. bool printInfoMessages;
  8912. };
  8913. void lazyPrint() {
  8914. m_tablePrinter.close();
  8915. lazyPrintWithoutClosingBenchmarkTable();
  8916. }
  8917. void lazyPrintWithoutClosingBenchmarkTable() {
  8918. if( !currentTestRunInfo.used )
  8919. lazyPrintRunInfo();
  8920. if( !currentGroupInfo.used )
  8921. lazyPrintGroupInfo();
  8922. if( !m_headerPrinted ) {
  8923. printTestCaseAndSectionHeader();
  8924. m_headerPrinted = true;
  8925. }
  8926. }
  8927. void lazyPrintRunInfo() {
  8928. stream << '\n' << getLineOfChars<'~'>() << '\n';
  8929. Colour colour( Colour::SecondaryText );
  8930. stream << currentTestRunInfo->name
  8931. << " is a Catch v" << libraryVersion() << " host application.\n"
  8932. << "Run with -? for options\n\n";
  8933. if( m_config->rngSeed() != 0 )
  8934. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  8935. currentTestRunInfo.used = true;
  8936. }
  8937. void lazyPrintGroupInfo() {
  8938. if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
  8939. printClosedHeader( "Group: " + currentGroupInfo->name );
  8940. currentGroupInfo.used = true;
  8941. }
  8942. }
  8943. void printTestCaseAndSectionHeader() {
  8944. assert( !m_sectionStack.empty() );
  8945. printOpenHeader( currentTestCaseInfo->name );
  8946. if( m_sectionStack.size() > 1 ) {
  8947. Colour colourGuard( Colour::Headers );
  8948. auto
  8949. it = m_sectionStack.begin()+1, // Skip first section (test case)
  8950. itEnd = m_sectionStack.end();
  8951. for( ; it != itEnd; ++it )
  8952. printHeaderString( it->name, 2 );
  8953. }
  8954. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  8955. if( !lineInfo.empty() ){
  8956. stream << getLineOfChars<'-'>() << '\n';
  8957. Colour colourGuard( Colour::FileName );
  8958. stream << lineInfo << '\n';
  8959. }
  8960. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  8961. }
  8962. void printClosedHeader( std::string const& _name ) {
  8963. printOpenHeader( _name );
  8964. stream << getLineOfChars<'.'>() << '\n';
  8965. }
  8966. void printOpenHeader( std::string const& _name ) {
  8967. stream << getLineOfChars<'-'>() << '\n';
  8968. {
  8969. Colour colourGuard( Colour::Headers );
  8970. printHeaderString( _name );
  8971. }
  8972. }
  8973. // if string has a : in first line will set indent to follow it on
  8974. // subsequent lines
  8975. void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
  8976. std::size_t i = _string.find( ": " );
  8977. if( i != std::string::npos )
  8978. i+=2;
  8979. else
  8980. i = 0;
  8981. stream << Column( _string ).indent( indent+i ).initialIndent( indent ) << '\n';
  8982. }
  8983. struct SummaryColumn {
  8984. SummaryColumn( std::string const& _label, Colour::Code _colour )
  8985. : label( _label ),
  8986. colour( _colour )
  8987. {}
  8988. SummaryColumn addRow( std::size_t count ) {
  8989. std::ostringstream oss;
  8990. oss << count;
  8991. std::string row = oss.str();
  8992. for( auto& oldRow : rows ) {
  8993. while( oldRow.size() < row.size() )
  8994. oldRow = ' ' + oldRow;
  8995. while( oldRow.size() > row.size() )
  8996. row = ' ' + row;
  8997. }
  8998. rows.push_back( row );
  8999. return *this;
  9000. }
  9001. std::string label;
  9002. Colour::Code colour;
  9003. std::vector<std::string> rows;
  9004. };
  9005. void printTotals( Totals const& totals ) {
  9006. if( totals.testCases.total() == 0 ) {
  9007. stream << Colour( Colour::Warning ) << "No tests ran\n";
  9008. }
  9009. else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
  9010. stream << Colour( Colour::ResultSuccess ) << "All tests passed";
  9011. stream << " ("
  9012. << pluralise( totals.assertions.passed, "assertion" ) << " in "
  9013. << pluralise( totals.testCases.passed, "test case" ) << ')'
  9014. << '\n';
  9015. }
  9016. else {
  9017. std::vector<SummaryColumn> columns;
  9018. columns.push_back( SummaryColumn( "", Colour::None )
  9019. .addRow( totals.testCases.total() )
  9020. .addRow( totals.assertions.total() ) );
  9021. columns.push_back( SummaryColumn( "passed", Colour::Success )
  9022. .addRow( totals.testCases.passed )
  9023. .addRow( totals.assertions.passed ) );
  9024. columns.push_back( SummaryColumn( "failed", Colour::ResultError )
  9025. .addRow( totals.testCases.failed )
  9026. .addRow( totals.assertions.failed ) );
  9027. columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
  9028. .addRow( totals.testCases.failedButOk )
  9029. .addRow( totals.assertions.failedButOk ) );
  9030. printSummaryRow( "test cases", columns, 0 );
  9031. printSummaryRow( "assertions", columns, 1 );
  9032. }
  9033. }
  9034. void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
  9035. for( auto col : cols ) {
  9036. std::string value = col.rows[row];
  9037. if( col.label.empty() ) {
  9038. stream << label << ": ";
  9039. if( value != "0" )
  9040. stream << value;
  9041. else
  9042. stream << Colour( Colour::Warning ) << "- none -";
  9043. }
  9044. else if( value != "0" ) {
  9045. stream << Colour( Colour::LightGrey ) << " | ";
  9046. stream << Colour( col.colour )
  9047. << value << ' ' << col.label;
  9048. }
  9049. }
  9050. stream << '\n';
  9051. }
  9052. void printTotalsDivider( Totals const& totals ) {
  9053. if( totals.testCases.total() > 0 ) {
  9054. std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
  9055. std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
  9056. std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
  9057. while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
  9058. findMax( failedRatio, failedButOkRatio, passedRatio )++;
  9059. while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
  9060. findMax( failedRatio, failedButOkRatio, passedRatio )--;
  9061. stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
  9062. stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
  9063. if( totals.testCases.allPassed() )
  9064. stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
  9065. else
  9066. stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
  9067. }
  9068. else {
  9069. stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
  9070. }
  9071. stream << '\n';
  9072. }
  9073. void printSummaryDivider() {
  9074. stream << getLineOfChars<'-'>() << '\n';
  9075. }
  9076. private:
  9077. bool m_headerPrinted = false;
  9078. };
  9079. CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
  9080. ConsoleReporter::~ConsoleReporter() {}
  9081. } // end namespace Catch
  9082. #if defined(_MSC_VER)
  9083. #pragma warning(pop)
  9084. #endif
  9085. // end catch_reporter_console.cpp
  9086. // start catch_reporter_junit.cpp
  9087. #include <assert.h>
  9088. #include <ctime>
  9089. #include <algorithm>
  9090. namespace Catch {
  9091. namespace {
  9092. std::string getCurrentTimestamp() {
  9093. // Beware, this is not reentrant because of backward compatibility issues
  9094. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9095. time_t rawtime;
  9096. std::time(&rawtime);
  9097. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9098. #ifdef _MSC_VER
  9099. std::tm timeInfo = {};
  9100. gmtime_s(&timeInfo, &rawtime);
  9101. #else
  9102. std::tm* timeInfo;
  9103. timeInfo = std::gmtime(&rawtime);
  9104. #endif
  9105. char timeStamp[timeStampSize];
  9106. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9107. #ifdef _MSC_VER
  9108. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9109. #else
  9110. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9111. #endif
  9112. return std::string(timeStamp);
  9113. }
  9114. std::string fileNameTag(const std::vector<std::string> &tags) {
  9115. auto it = std::find_if(begin(tags),
  9116. end(tags),
  9117. [] (std::string const& tag) {return tag.front() == '#'; });
  9118. if (it != tags.end())
  9119. return it->substr(1);
  9120. return std::string();
  9121. }
  9122. }
  9123. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  9124. public:
  9125. JunitReporter( ReporterConfig const& _config )
  9126. : CumulativeReporterBase( _config ),
  9127. xml( _config.stream() )
  9128. {
  9129. m_reporterPrefs.shouldRedirectStdOut = true;
  9130. }
  9131. ~JunitReporter() override;
  9132. static std::string getDescription() {
  9133. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9134. }
  9135. void noMatchingTestCases( std::string const& /*spec*/ ) override {}
  9136. void testRunStarting( TestRunInfo const& runInfo ) override {
  9137. CumulativeReporterBase::testRunStarting( runInfo );
  9138. xml.startElement( "testsuites" );
  9139. }
  9140. void testGroupStarting( GroupInfo const& groupInfo ) override {
  9141. suiteTimer.start();
  9142. stdOutForSuite.str("");
  9143. stdErrForSuite.str("");
  9144. unexpectedExceptions = 0;
  9145. CumulativeReporterBase::testGroupStarting( groupInfo );
  9146. }
  9147. void testCaseStarting( TestCaseInfo const& testCaseInfo ) override {
  9148. m_okToFail = testCaseInfo.okToFail();
  9149. }
  9150. bool assertionEnded( AssertionStats const& assertionStats ) override {
  9151. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9152. unexpectedExceptions++;
  9153. return CumulativeReporterBase::assertionEnded( assertionStats );
  9154. }
  9155. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  9156. stdOutForSuite << testCaseStats.stdOut;
  9157. stdErrForSuite << testCaseStats.stdErr;
  9158. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9159. }
  9160. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  9161. double suiteTime = suiteTimer.getElapsedSeconds();
  9162. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9163. writeGroup( *m_testGroups.back(), suiteTime );
  9164. }
  9165. void testRunEndedCumulative() override {
  9166. xml.endElement();
  9167. }
  9168. void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9169. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9170. TestGroupStats const& stats = groupNode.value;
  9171. xml.writeAttribute( "name", stats.groupInfo.name );
  9172. xml.writeAttribute( "errors", unexpectedExceptions );
  9173. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9174. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9175. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9176. if( m_config->showDurations() == ShowDurations::Never )
  9177. xml.writeAttribute( "time", "" );
  9178. else
  9179. xml.writeAttribute( "time", suiteTime );
  9180. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9181. // Write test cases
  9182. for( auto const& child : groupNode.children )
  9183. writeTestCase( *child );
  9184. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
  9185. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
  9186. }
  9187. void writeTestCase( TestCaseNode const& testCaseNode ) {
  9188. TestCaseStats const& stats = testCaseNode.value;
  9189. // All test cases have exactly one section - which represents the
  9190. // test case itself. That section may have 0-n nested sections
  9191. assert( testCaseNode.children.size() == 1 );
  9192. SectionNode const& rootSection = *testCaseNode.children.front();
  9193. std::string className = stats.testInfo.className;
  9194. if( className.empty() ) {
  9195. className = fileNameTag(stats.testInfo.tags);
  9196. if ( className.empty() )
  9197. className = "global";
  9198. }
  9199. if ( !m_config->name().empty() )
  9200. className = m_config->name() + "." + className;
  9201. writeSection( className, "", rootSection );
  9202. }
  9203. void writeSection( std::string const& className,
  9204. std::string const& rootName,
  9205. SectionNode const& sectionNode ) {
  9206. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9207. if( !rootName.empty() )
  9208. name = rootName + '/' + name;
  9209. if( !sectionNode.assertions.empty() ||
  9210. !sectionNode.stdOut.empty() ||
  9211. !sectionNode.stdErr.empty() ) {
  9212. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9213. if( className.empty() ) {
  9214. xml.writeAttribute( "classname", name );
  9215. xml.writeAttribute( "name", "root" );
  9216. }
  9217. else {
  9218. xml.writeAttribute( "classname", className );
  9219. xml.writeAttribute( "name", name );
  9220. }
  9221. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9222. writeAssertions( sectionNode );
  9223. if( !sectionNode.stdOut.empty() )
  9224. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9225. if( !sectionNode.stdErr.empty() )
  9226. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9227. }
  9228. for( auto const& childNode : sectionNode.childSections )
  9229. if( className.empty() )
  9230. writeSection( name, "", *childNode );
  9231. else
  9232. writeSection( className, name, *childNode );
  9233. }
  9234. void writeAssertions( SectionNode const& sectionNode ) {
  9235. for( auto const& assertion : sectionNode.assertions )
  9236. writeAssertion( assertion );
  9237. }
  9238. void writeAssertion( AssertionStats const& stats ) {
  9239. AssertionResult const& result = stats.assertionResult;
  9240. if( !result.isOk() ) {
  9241. std::string elementName;
  9242. switch( result.getResultType() ) {
  9243. case ResultWas::ThrewException:
  9244. case ResultWas::FatalErrorCondition:
  9245. elementName = "error";
  9246. break;
  9247. case ResultWas::ExplicitFailure:
  9248. elementName = "failure";
  9249. break;
  9250. case ResultWas::ExpressionFailed:
  9251. elementName = "failure";
  9252. break;
  9253. case ResultWas::DidntThrowException:
  9254. elementName = "failure";
  9255. break;
  9256. // We should never see these here:
  9257. case ResultWas::Info:
  9258. case ResultWas::Warning:
  9259. case ResultWas::Ok:
  9260. case ResultWas::Unknown:
  9261. case ResultWas::FailureBit:
  9262. case ResultWas::Exception:
  9263. elementName = "internalError";
  9264. break;
  9265. }
  9266. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9267. xml.writeAttribute( "message", result.getExpandedExpression() );
  9268. xml.writeAttribute( "type", result.getTestMacroName() );
  9269. std::ostringstream oss;
  9270. if( !result.getMessage().empty() )
  9271. oss << result.getMessage() << '\n';
  9272. for( auto const& msg : stats.infoMessages )
  9273. if( msg.type == ResultWas::Info )
  9274. oss << msg.message << '\n';
  9275. oss << "at " << result.getSourceInfo();
  9276. xml.writeText( oss.str(), false );
  9277. }
  9278. }
  9279. XmlWriter xml;
  9280. Timer suiteTimer;
  9281. std::ostringstream stdOutForSuite;
  9282. std::ostringstream stdErrForSuite;
  9283. unsigned int unexpectedExceptions = 0;
  9284. bool m_okToFail = false;
  9285. };
  9286. JunitReporter::~JunitReporter() {}
  9287. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9288. } // end namespace Catch
  9289. // end catch_reporter_junit.cpp
  9290. // start catch_reporter_multi.cpp
  9291. namespace Catch {
  9292. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9293. m_reporters.push_back( std::move( reporter ) );
  9294. }
  9295. ReporterPreferences MultipleReporters::getPreferences() const {
  9296. return m_reporters[0]->getPreferences();
  9297. }
  9298. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9299. return std::set<Verbosity>{ };
  9300. }
  9301. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9302. for( auto const& reporter : m_reporters )
  9303. reporter->noMatchingTestCases( spec );
  9304. }
  9305. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9306. for( auto const& reporter : m_reporters )
  9307. reporter->benchmarkStarting( benchmarkInfo );
  9308. }
  9309. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9310. for( auto const& reporter : m_reporters )
  9311. reporter->benchmarkEnded( benchmarkStats );
  9312. }
  9313. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9314. for( auto const& reporter : m_reporters )
  9315. reporter->testRunStarting( testRunInfo );
  9316. }
  9317. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9318. for( auto const& reporter : m_reporters )
  9319. reporter->testGroupStarting( groupInfo );
  9320. }
  9321. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9322. for( auto const& reporter : m_reporters )
  9323. reporter->testCaseStarting( testInfo );
  9324. }
  9325. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9326. for( auto const& reporter : m_reporters )
  9327. reporter->sectionStarting( sectionInfo );
  9328. }
  9329. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9330. for( auto const& reporter : m_reporters )
  9331. reporter->assertionStarting( assertionInfo );
  9332. }
  9333. // The return value indicates if the messages buffer should be cleared:
  9334. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9335. bool clearBuffer = false;
  9336. for( auto const& reporter : m_reporters )
  9337. clearBuffer |= reporter->assertionEnded( assertionStats );
  9338. return clearBuffer;
  9339. }
  9340. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9341. for( auto const& reporter : m_reporters )
  9342. reporter->sectionEnded( sectionStats );
  9343. }
  9344. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9345. for( auto const& reporter : m_reporters )
  9346. reporter->testCaseEnded( testCaseStats );
  9347. }
  9348. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9349. for( auto const& reporter : m_reporters )
  9350. reporter->testGroupEnded( testGroupStats );
  9351. }
  9352. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9353. for( auto const& reporter : m_reporters )
  9354. reporter->testRunEnded( testRunStats );
  9355. }
  9356. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9357. for( auto const& reporter : m_reporters )
  9358. reporter->skipTest( testInfo );
  9359. }
  9360. bool MultipleReporters::isMulti() const {
  9361. return true;
  9362. }
  9363. } // end namespace Catch
  9364. // end catch_reporter_multi.cpp
  9365. // start catch_reporter_xml.cpp
  9366. #if defined(_MSC_VER)
  9367. #pragma warning(push)
  9368. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9369. // Note that 4062 (not all labels are handled
  9370. // and default is missing) is enabled
  9371. #endif
  9372. namespace Catch {
  9373. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  9374. public:
  9375. XmlReporter( ReporterConfig const& _config )
  9376. : StreamingReporterBase( _config ),
  9377. m_xml(_config.stream())
  9378. {
  9379. m_reporterPrefs.shouldRedirectStdOut = true;
  9380. }
  9381. ~XmlReporter() override;
  9382. static std::string getDescription() {
  9383. return "Reports test results as an XML document";
  9384. }
  9385. virtual std::string getStylesheetRef() const {
  9386. return std::string();
  9387. }
  9388. void writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9389. m_xml
  9390. .writeAttribute( "filename", sourceInfo.file )
  9391. .writeAttribute( "line", sourceInfo.line );
  9392. }
  9393. public: // StreamingReporterBase
  9394. void noMatchingTestCases( std::string const& s ) override {
  9395. StreamingReporterBase::noMatchingTestCases( s );
  9396. }
  9397. void testRunStarting( TestRunInfo const& testInfo ) override {
  9398. StreamingReporterBase::testRunStarting( testInfo );
  9399. std::string stylesheetRef = getStylesheetRef();
  9400. if( !stylesheetRef.empty() )
  9401. m_xml.writeStylesheetRef( stylesheetRef );
  9402. m_xml.startElement( "Catch" );
  9403. if( !m_config->name().empty() )
  9404. m_xml.writeAttribute( "name", m_config->name() );
  9405. }
  9406. void testGroupStarting( GroupInfo const& groupInfo ) override {
  9407. StreamingReporterBase::testGroupStarting( groupInfo );
  9408. m_xml.startElement( "Group" )
  9409. .writeAttribute( "name", groupInfo.name );
  9410. }
  9411. void testCaseStarting( TestCaseInfo const& testInfo ) override {
  9412. StreamingReporterBase::testCaseStarting(testInfo);
  9413. m_xml.startElement( "TestCase" )
  9414. .writeAttribute( "name", trim( testInfo.name ) )
  9415. .writeAttribute( "description", testInfo.description )
  9416. .writeAttribute( "tags", testInfo.tagsAsString() );
  9417. writeSourceInfo( testInfo.lineInfo );
  9418. if ( m_config->showDurations() == ShowDurations::Always )
  9419. m_testCaseTimer.start();
  9420. m_xml.ensureTagClosed();
  9421. }
  9422. void sectionStarting( SectionInfo const& sectionInfo ) override {
  9423. StreamingReporterBase::sectionStarting( sectionInfo );
  9424. if( m_sectionDepth++ > 0 ) {
  9425. m_xml.startElement( "Section" )
  9426. .writeAttribute( "name", trim( sectionInfo.name ) )
  9427. .writeAttribute( "description", sectionInfo.description );
  9428. writeSourceInfo( sectionInfo.lineInfo );
  9429. m_xml.ensureTagClosed();
  9430. }
  9431. }
  9432. void assertionStarting( AssertionInfo const& ) override { }
  9433. bool assertionEnded( AssertionStats const& assertionStats ) override {
  9434. AssertionResult const& result = assertionStats.assertionResult;
  9435. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9436. if( includeResults ) {
  9437. // Print any info messages in <Info> tags.
  9438. for( auto const& msg : assertionStats.infoMessages ) {
  9439. if( msg.type == ResultWas::Info ) {
  9440. m_xml.scopedElement( "Info" )
  9441. .writeText( msg.message );
  9442. } else if ( msg.type == ResultWas::Warning ) {
  9443. m_xml.scopedElement( "Warning" )
  9444. .writeText( msg.message );
  9445. }
  9446. }
  9447. }
  9448. // Drop out if result was successful but we're not printing them.
  9449. if( !includeResults && result.getResultType() != ResultWas::Warning )
  9450. return true;
  9451. // Print the expression if there is one.
  9452. if( result.hasExpression() ) {
  9453. m_xml.startElement( "Expression" )
  9454. .writeAttribute( "success", result.succeeded() )
  9455. .writeAttribute( "type", result.getTestMacroName() );
  9456. writeSourceInfo( result.getSourceInfo() );
  9457. m_xml.scopedElement( "Original" )
  9458. .writeText( result.getExpression() );
  9459. m_xml.scopedElement( "Expanded" )
  9460. .writeText( result.getExpandedExpression() );
  9461. }
  9462. // And... Print a result applicable to each result type.
  9463. switch( result.getResultType() ) {
  9464. case ResultWas::ThrewException:
  9465. m_xml.startElement( "Exception" );
  9466. writeSourceInfo( result.getSourceInfo() );
  9467. m_xml.writeText( result.getMessage() );
  9468. m_xml.endElement();
  9469. break;
  9470. case ResultWas::FatalErrorCondition:
  9471. m_xml.startElement( "FatalErrorCondition" );
  9472. writeSourceInfo( result.getSourceInfo() );
  9473. m_xml.writeText( result.getMessage() );
  9474. m_xml.endElement();
  9475. break;
  9476. case ResultWas::Info:
  9477. m_xml.scopedElement( "Info" )
  9478. .writeText( result.getMessage() );
  9479. break;
  9480. case ResultWas::Warning:
  9481. // Warning will already have been written
  9482. break;
  9483. case ResultWas::ExplicitFailure:
  9484. m_xml.startElement( "Failure" );
  9485. writeSourceInfo( result.getSourceInfo() );
  9486. m_xml.writeText( result.getMessage() );
  9487. m_xml.endElement();
  9488. break;
  9489. default:
  9490. break;
  9491. }
  9492. if( result.hasExpression() )
  9493. m_xml.endElement();
  9494. return true;
  9495. }
  9496. void sectionEnded( SectionStats const& sectionStats ) override {
  9497. StreamingReporterBase::sectionEnded( sectionStats );
  9498. if( --m_sectionDepth > 0 ) {
  9499. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  9500. e.writeAttribute( "successes", sectionStats.assertions.passed );
  9501. e.writeAttribute( "failures", sectionStats.assertions.failed );
  9502. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  9503. if ( m_config->showDurations() == ShowDurations::Always )
  9504. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  9505. m_xml.endElement();
  9506. }
  9507. }
  9508. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  9509. StreamingReporterBase::testCaseEnded( testCaseStats );
  9510. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  9511. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  9512. if ( m_config->showDurations() == ShowDurations::Always )
  9513. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  9514. if( !testCaseStats.stdOut.empty() )
  9515. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  9516. if( !testCaseStats.stdErr.empty() )
  9517. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  9518. m_xml.endElement();
  9519. }
  9520. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  9521. StreamingReporterBase::testGroupEnded( testGroupStats );
  9522. // TODO: Check testGroupStats.aborting and act accordingly.
  9523. m_xml.scopedElement( "OverallResults" )
  9524. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  9525. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  9526. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  9527. m_xml.endElement();
  9528. }
  9529. void testRunEnded( TestRunStats const& testRunStats ) override {
  9530. StreamingReporterBase::testRunEnded( testRunStats );
  9531. m_xml.scopedElement( "OverallResults" )
  9532. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  9533. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  9534. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  9535. m_xml.endElement();
  9536. }
  9537. private:
  9538. Timer m_testCaseTimer;
  9539. XmlWriter m_xml;
  9540. int m_sectionDepth = 0;
  9541. };
  9542. XmlReporter::~XmlReporter() {}
  9543. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  9544. } // end namespace Catch
  9545. #if defined(_MSC_VER)
  9546. #pragma warning(pop)
  9547. #endif
  9548. // end catch_reporter_xml.cpp
  9549. namespace Catch {
  9550. LeakDetector leakDetector;
  9551. }
  9552. #ifdef __clang__
  9553. #pragma clang diagnostic pop
  9554. #endif
  9555. // end catch_impl.hpp
  9556. #endif
  9557. #ifdef CATCH_CONFIG_MAIN
  9558. // start catch_default_main.hpp
  9559. #ifndef __OBJC__
  9560. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  9561. // Standard C/C++ Win32 Unicode wmain entry point
  9562. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  9563. #else
  9564. // Standard C/C++ main entry point
  9565. int main (int argc, char * argv[]) {
  9566. #endif
  9567. return Catch::Session().run( argc, argv );
  9568. }
  9569. #else // __OBJC__
  9570. // Objective-C entry point
  9571. int main (int argc, char * const argv[]) {
  9572. #if !CATCH_ARC_ENABLED
  9573. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  9574. #endif
  9575. Catch::registerTestMethods();
  9576. int result = Catch::Session().run( argc, (char**)argv );
  9577. #if !CATCH_ARC_ENABLED
  9578. [pool drain];
  9579. #endif
  9580. return result;
  9581. }
  9582. #endif // __OBJC__
  9583. // end catch_default_main.hpp
  9584. #endif
  9585. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  9586. # undef CLARA_CONFIG_MAIN
  9587. #endif
  9588. #if !defined(CATCH_CONFIG_DISABLE)
  9589. //////
  9590. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9591. #ifdef CATCH_CONFIG_PREFIX_ALL
  9592. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9593. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9594. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  9595. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9596. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9597. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9598. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9599. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9600. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9601. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9602. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9603. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9604. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9605. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9606. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  9607. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9608. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9609. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9610. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9611. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9612. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9613. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9614. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9615. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9616. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9617. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  9618. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9619. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9620. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9621. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9622. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9623. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9624. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9625. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9626. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9627. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9628. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9629. // "BDD-style" convenience wrappers
  9630. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  9631. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9632. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  9633. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  9634. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9635. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  9636. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9637. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9638. #else
  9639. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9640. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9641. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9642. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9643. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9644. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9645. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9646. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9647. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9648. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9649. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9650. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9651. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9652. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9653. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9654. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9655. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9656. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9657. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9658. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9659. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9660. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9661. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9662. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9663. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9664. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  9665. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9666. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9667. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9668. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9669. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9670. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9671. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9672. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9673. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9674. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9675. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9676. #endif
  9677. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  9678. // "BDD-style" convenience wrappers
  9679. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  9680. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9681. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  9682. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  9683. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  9684. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  9685. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  9686. using Catch::Detail::Approx;
  9687. #else
  9688. //////
  9689. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9690. #ifdef CATCH_CONFIG_PREFIX_ALL
  9691. #define CATCH_REQUIRE( ... ) (void)(0)
  9692. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  9693. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  9694. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9695. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9696. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9697. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9698. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9699. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  9700. #define CATCH_CHECK( ... ) (void)(0)
  9701. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  9702. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  9703. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9704. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  9705. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  9706. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9707. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9708. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9709. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9710. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9711. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  9712. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9713. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  9714. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  9715. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9716. #define CATCH_INFO( msg ) (void)(0)
  9717. #define CATCH_WARN( msg ) (void)(0)
  9718. #define CATCH_CAPTURE( msg ) (void)(0)
  9719. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9720. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9721. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  9722. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9723. #define CATCH_SECTION( ... )
  9724. #define CATCH_FAIL( ... ) (void)(0)
  9725. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  9726. #define CATCH_SUCCEED( ... ) (void)(0)
  9727. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9728. // "BDD-style" convenience wrappers
  9729. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9730. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  9731. #define CATCH_GIVEN( desc )
  9732. #define CATCH_WHEN( desc )
  9733. #define CATCH_AND_WHEN( desc )
  9734. #define CATCH_THEN( desc )
  9735. #define CATCH_AND_THEN( desc )
  9736. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9737. #else
  9738. #define REQUIRE( ... ) (void)(0)
  9739. #define REQUIRE_FALSE( ... ) (void)(0)
  9740. #define REQUIRE_THROWS( ... ) (void)(0)
  9741. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9742. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9743. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9744. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9745. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9746. #define REQUIRE_NOTHROW( ... ) (void)(0)
  9747. #define CHECK( ... ) (void)(0)
  9748. #define CHECK_FALSE( ... ) (void)(0)
  9749. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  9750. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9751. #define CHECK_NOFAIL( ... ) (void)(0)
  9752. #define CHECK_THROWS( ... ) (void)(0)
  9753. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9754. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9755. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9756. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9757. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9758. #define CHECK_NOTHROW( ... ) (void)(0)
  9759. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9760. #define CHECK_THAT( arg, matcher ) (void)(0)
  9761. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  9762. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9763. #define INFO( msg ) (void)(0)
  9764. #define WARN( msg ) (void)(0)
  9765. #define CAPTURE( msg ) (void)(0)
  9766. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9767. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9768. #define METHOD_AS_TEST_CASE( method, ... )
  9769. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9770. #define SECTION( ... )
  9771. #define FAIL( ... ) (void)(0)
  9772. #define FAIL_CHECK( ... ) (void)(0)
  9773. #define SUCCEED( ... ) (void)(0)
  9774. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9775. #endif
  9776. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  9777. // "BDD-style" convenience wrappers
  9778. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  9779. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  9780. #define GIVEN( desc )
  9781. #define WHEN( desc )
  9782. #define AND_WHEN( desc )
  9783. #define THEN( desc )
  9784. #define AND_THEN( desc )
  9785. using Catch::Detail::Approx;
  9786. #endif
  9787. // start catch_reenable_warnings.h
  9788. #ifdef __clang__
  9789. # ifdef __ICC // icpc defines the __clang__ macro
  9790. # pragma warning(pop)
  9791. # else
  9792. # pragma clang diagnostic pop
  9793. # endif
  9794. #elif defined __GNUC__
  9795. # pragma GCC diagnostic pop
  9796. #endif
  9797. // end catch_reenable_warnings.h
  9798. // end catch.hpp
  9799. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED