catch_amalgamated.cpp 356 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360
  1. // Copyright Catch2 Authors
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // https://www.boost.org/LICENSE_1_0.txt)
  5. // SPDX-License-Identifier: BSL-1.0
  6. // Catch v3.1.0
  7. // Generated: 2022-07-17 20:14:05.885021
  8. // ----------------------------------------------------------
  9. // This file is an amalgamation of multiple different files.
  10. // You probably shouldn't edit it directly.
  11. // ----------------------------------------------------------
  12. #include "catch_amalgamated.hpp"
  13. namespace Catch {
  14. namespace Benchmark {
  15. namespace Detail {
  16. ChronometerConcept::~ChronometerConcept() = default;
  17. } // namespace Detail
  18. } // namespace Benchmark
  19. } // namespace Catch
  20. namespace Catch {
  21. namespace Benchmark {
  22. namespace Detail {
  23. BenchmarkFunction::callable::~callable() = default;
  24. } // namespace Detail
  25. } // namespace Benchmark
  26. } // namespace Catch
  27. #include <exception>
  28. namespace Catch {
  29. namespace Benchmark {
  30. namespace Detail {
  31. struct optimized_away_error : std::exception {
  32. const char* what() const noexcept override;
  33. };
  34. const char* optimized_away_error::what() const noexcept {
  35. return "could not measure benchmark, maybe it was optimized away";
  36. }
  37. void throw_optimized_away_error() {
  38. Catch::throw_exception(optimized_away_error{});
  39. }
  40. } // namespace Detail
  41. } // namespace Benchmark
  42. } // namespace Catch
  43. // Adapted from donated nonius code.
  44. #include <cassert>
  45. #include <cstddef>
  46. #include <iterator>
  47. #include <random>
  48. #if defined(CATCH_CONFIG_USE_ASYNC)
  49. #include <future>
  50. #endif
  51. namespace {
  52. using Catch::Benchmark::Detail::sample;
  53. template <typename URng, typename Estimator>
  54. sample resample(URng& rng, unsigned int resamples, std::vector<double>::iterator first, std::vector<double>::iterator last, Estimator& estimator) {
  55. auto n = static_cast<size_t>(last - first);
  56. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  57. sample out;
  58. out.reserve(resamples);
  59. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  60. std::vector<double> resampled;
  61. resampled.reserve(n);
  62. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[static_cast<std::ptrdiff_t>(dist(rng))]; });
  63. return estimator(resampled.begin(), resampled.end());
  64. });
  65. std::sort(out.begin(), out.end());
  66. return out;
  67. }
  68. double erf_inv(double x) {
  69. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  70. double w, p;
  71. w = -log((1.0 - x) * (1.0 + x));
  72. if (w < 6.250000) {
  73. w = w - 3.125000;
  74. p = -3.6444120640178196996e-21;
  75. p = -1.685059138182016589e-19 + p * w;
  76. p = 1.2858480715256400167e-18 + p * w;
  77. p = 1.115787767802518096e-17 + p * w;
  78. p = -1.333171662854620906e-16 + p * w;
  79. p = 2.0972767875968561637e-17 + p * w;
  80. p = 6.6376381343583238325e-15 + p * w;
  81. p = -4.0545662729752068639e-14 + p * w;
  82. p = -8.1519341976054721522e-14 + p * w;
  83. p = 2.6335093153082322977e-12 + p * w;
  84. p = -1.2975133253453532498e-11 + p * w;
  85. p = -5.4154120542946279317e-11 + p * w;
  86. p = 1.051212273321532285e-09 + p * w;
  87. p = -4.1126339803469836976e-09 + p * w;
  88. p = -2.9070369957882005086e-08 + p * w;
  89. p = 4.2347877827932403518e-07 + p * w;
  90. p = -1.3654692000834678645e-06 + p * w;
  91. p = -1.3882523362786468719e-05 + p * w;
  92. p = 0.0001867342080340571352 + p * w;
  93. p = -0.00074070253416626697512 + p * w;
  94. p = -0.0060336708714301490533 + p * w;
  95. p = 0.24015818242558961693 + p * w;
  96. p = 1.6536545626831027356 + p * w;
  97. } else if (w < 16.000000) {
  98. w = sqrt(w) - 3.250000;
  99. p = 2.2137376921775787049e-09;
  100. p = 9.0756561938885390979e-08 + p * w;
  101. p = -2.7517406297064545428e-07 + p * w;
  102. p = 1.8239629214389227755e-08 + p * w;
  103. p = 1.5027403968909827627e-06 + p * w;
  104. p = -4.013867526981545969e-06 + p * w;
  105. p = 2.9234449089955446044e-06 + p * w;
  106. p = 1.2475304481671778723e-05 + p * w;
  107. p = -4.7318229009055733981e-05 + p * w;
  108. p = 6.8284851459573175448e-05 + p * w;
  109. p = 2.4031110387097893999e-05 + p * w;
  110. p = -0.0003550375203628474796 + p * w;
  111. p = 0.00095328937973738049703 + p * w;
  112. p = -0.0016882755560235047313 + p * w;
  113. p = 0.0024914420961078508066 + p * w;
  114. p = -0.0037512085075692412107 + p * w;
  115. p = 0.005370914553590063617 + p * w;
  116. p = 1.0052589676941592334 + p * w;
  117. p = 3.0838856104922207635 + p * w;
  118. } else {
  119. w = sqrt(w) - 5.000000;
  120. p = -2.7109920616438573243e-11;
  121. p = -2.5556418169965252055e-10 + p * w;
  122. p = 1.5076572693500548083e-09 + p * w;
  123. p = -3.7894654401267369937e-09 + p * w;
  124. p = 7.6157012080783393804e-09 + p * w;
  125. p = -1.4960026627149240478e-08 + p * w;
  126. p = 2.9147953450901080826e-08 + p * w;
  127. p = -6.7711997758452339498e-08 + p * w;
  128. p = 2.2900482228026654717e-07 + p * w;
  129. p = -9.9298272942317002539e-07 + p * w;
  130. p = 4.5260625972231537039e-06 + p * w;
  131. p = -1.9681778105531670567e-05 + p * w;
  132. p = 7.5995277030017761139e-05 + p * w;
  133. p = -0.00021503011930044477347 + p * w;
  134. p = -0.00013871931833623122026 + p * w;
  135. p = 1.0103004648645343977 + p * w;
  136. p = 4.8499064014085844221 + p * w;
  137. }
  138. return p * x;
  139. }
  140. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  141. auto m = Catch::Benchmark::Detail::mean(first, last);
  142. double variance = std::accumulate( first,
  143. last,
  144. 0.,
  145. [m]( double a, double b ) {
  146. double diff = b - m;
  147. return a + diff * diff;
  148. } ) /
  149. ( last - first );
  150. return std::sqrt( variance );
  151. }
  152. }
  153. namespace Catch {
  154. namespace Benchmark {
  155. namespace Detail {
  156. #if defined( __GNUC__ ) || defined( __clang__ )
  157. # pragma GCC diagnostic push
  158. # pragma GCC diagnostic ignored "-Wfloat-equal"
  159. #endif
  160. bool directCompare( double lhs, double rhs ) { return lhs == rhs; }
  161. #if defined( __GNUC__ ) || defined( __clang__ )
  162. # pragma GCC diagnostic pop
  163. #endif
  164. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  165. auto count = last - first;
  166. double idx = (count - 1) * k / static_cast<double>(q);
  167. int j = static_cast<int>(idx);
  168. double g = idx - j;
  169. std::nth_element(first, first + j, last);
  170. auto xj = first[j];
  171. if ( directCompare( g, 0 ) ) {
  172. return xj;
  173. }
  174. auto xj1 = *std::min_element(first + (j + 1), last);
  175. return xj + g * (xj1 - xj);
  176. }
  177. double erfc_inv(double x) {
  178. return erf_inv(1.0 - x);
  179. }
  180. double normal_quantile(double p) {
  181. static const double ROOT_TWO = std::sqrt(2.0);
  182. double result = 0.0;
  183. assert(p >= 0 && p <= 1);
  184. if (p < 0 || p > 1) {
  185. return result;
  186. }
  187. result = -erfc_inv(2.0 * p);
  188. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  189. result *= /*sd * */ ROOT_TWO;
  190. // result += normal disttribution mean (0)
  191. return result;
  192. }
  193. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  194. double sb = stddev.point;
  195. double mn = mean.point / n;
  196. double mg_min = mn / 2.;
  197. double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
  198. double sg2 = sg * sg;
  199. double sb2 = sb * sb;
  200. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  201. double k = mn - x;
  202. double d = k * k;
  203. double nd = n * d;
  204. double k0 = -n * nd;
  205. double k1 = sb2 - n * sg2 + nd;
  206. double det = k1 * k1 - 4 * sg2 * k0;
  207. return static_cast<int>(-2. * k0 / (k1 + std::sqrt(det)));
  208. };
  209. auto var_out = [n, sb2, sg2](double c) {
  210. double nc = n - c;
  211. return (nc / n) * (sb2 - nc * sg2);
  212. };
  213. return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
  214. }
  215. bootstrap_analysis analyse_samples(double confidence_level, unsigned int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  216. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  217. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  218. static std::random_device entropy;
  219. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  220. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  221. auto mean = &Detail::mean<std::vector<double>::iterator>;
  222. auto stddev = &standard_deviation;
  223. #if defined(CATCH_CONFIG_USE_ASYNC)
  224. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  225. auto seed = entropy();
  226. return std::async(std::launch::async, [=] {
  227. std::mt19937 rng(seed);
  228. auto resampled = resample(rng, n_resamples, first, last, f);
  229. return bootstrap(confidence_level, first, last, resampled, f);
  230. });
  231. };
  232. auto mean_future = Estimate(mean);
  233. auto stddev_future = Estimate(stddev);
  234. auto mean_estimate = mean_future.get();
  235. auto stddev_estimate = stddev_future.get();
  236. #else
  237. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  238. auto seed = entropy();
  239. std::mt19937 rng(seed);
  240. auto resampled = resample(rng, n_resamples, first, last, f);
  241. return bootstrap(confidence_level, first, last, resampled, f);
  242. };
  243. auto mean_estimate = Estimate(mean);
  244. auto stddev_estimate = Estimate(stddev);
  245. #endif // CATCH_USE_ASYNC
  246. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  247. return { mean_estimate, stddev_estimate, outlier_variance };
  248. }
  249. } // namespace Detail
  250. } // namespace Benchmark
  251. } // namespace Catch
  252. #include <cmath>
  253. #include <limits>
  254. namespace {
  255. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  256. // But without the subtraction to allow for INFINITY in comparison
  257. bool marginComparison(double lhs, double rhs, double margin) {
  258. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  259. }
  260. }
  261. namespace Catch {
  262. Approx::Approx ( double value )
  263. : m_epsilon( std::numeric_limits<float>::epsilon()*100. ),
  264. m_margin( 0.0 ),
  265. m_scale( 0.0 ),
  266. m_value( value )
  267. {}
  268. Approx Approx::custom() {
  269. return Approx( 0 );
  270. }
  271. Approx Approx::operator-() const {
  272. auto temp(*this);
  273. temp.m_value = -temp.m_value;
  274. return temp;
  275. }
  276. std::string Approx::toString() const {
  277. ReusableStringStream rss;
  278. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  279. return rss.str();
  280. }
  281. bool Approx::equalityComparisonImpl(const double other) const {
  282. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  283. // Thanks to Richard Harris for his help refining the scaled margin value
  284. return marginComparison(m_value, other, m_margin)
  285. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  286. }
  287. void Approx::setMargin(double newMargin) {
  288. CATCH_ENFORCE(newMargin >= 0,
  289. "Invalid Approx::margin: " << newMargin << '.'
  290. << " Approx::Margin has to be non-negative.");
  291. m_margin = newMargin;
  292. }
  293. void Approx::setEpsilon(double newEpsilon) {
  294. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  295. "Invalid Approx::epsilon: " << newEpsilon << '.'
  296. << " Approx::epsilon has to be in [0, 1]");
  297. m_epsilon = newEpsilon;
  298. }
  299. namespace literals {
  300. Approx operator "" _a(long double val) {
  301. return Approx(val);
  302. }
  303. Approx operator "" _a(unsigned long long val) {
  304. return Approx(val);
  305. }
  306. } // end namespace literals
  307. std::string StringMaker<Catch::Approx>::convert(Catch::Approx const& value) {
  308. return value.toString();
  309. }
  310. } // end namespace Catch
  311. namespace Catch {
  312. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  313. lazyExpression(_lazyExpression),
  314. resultType(_resultType) {}
  315. std::string AssertionResultData::reconstructExpression() const {
  316. if( reconstructedExpression.empty() ) {
  317. if( lazyExpression ) {
  318. ReusableStringStream rss;
  319. rss << lazyExpression;
  320. reconstructedExpression = rss.str();
  321. }
  322. }
  323. return reconstructedExpression;
  324. }
  325. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  326. : m_info( info ),
  327. m_resultData( data )
  328. {}
  329. // Result was a success
  330. bool AssertionResult::succeeded() const {
  331. return Catch::isOk( m_resultData.resultType );
  332. }
  333. // Result was a success, or failure is suppressed
  334. bool AssertionResult::isOk() const {
  335. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  336. }
  337. ResultWas::OfType AssertionResult::getResultType() const {
  338. return m_resultData.resultType;
  339. }
  340. bool AssertionResult::hasExpression() const {
  341. return !m_info.capturedExpression.empty();
  342. }
  343. bool AssertionResult::hasMessage() const {
  344. return !m_resultData.message.empty();
  345. }
  346. std::string AssertionResult::getExpression() const {
  347. // Possibly overallocating by 3 characters should be basically free
  348. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  349. if (isFalseTest(m_info.resultDisposition)) {
  350. expr += "!(";
  351. }
  352. expr += m_info.capturedExpression;
  353. if (isFalseTest(m_info.resultDisposition)) {
  354. expr += ')';
  355. }
  356. return expr;
  357. }
  358. std::string AssertionResult::getExpressionInMacro() const {
  359. std::string expr;
  360. if( m_info.macroName.empty() )
  361. expr = static_cast<std::string>(m_info.capturedExpression);
  362. else {
  363. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  364. expr += m_info.macroName;
  365. expr += "( ";
  366. expr += m_info.capturedExpression;
  367. expr += " )";
  368. }
  369. return expr;
  370. }
  371. bool AssertionResult::hasExpandedExpression() const {
  372. return hasExpression() && getExpandedExpression() != getExpression();
  373. }
  374. std::string AssertionResult::getExpandedExpression() const {
  375. std::string expr = m_resultData.reconstructExpression();
  376. return expr.empty()
  377. ? getExpression()
  378. : expr;
  379. }
  380. StringRef AssertionResult::getMessage() const {
  381. return m_resultData.message;
  382. }
  383. SourceLineInfo AssertionResult::getSourceInfo() const {
  384. return m_info.lineInfo;
  385. }
  386. StringRef AssertionResult::getTestMacroName() const {
  387. return m_info.macroName;
  388. }
  389. } // end namespace Catch
  390. namespace {
  391. bool provideBazelReporterOutput() {
  392. #ifdef CATCH_CONFIG_BAZEL_SUPPORT
  393. return true;
  394. #else
  395. # if defined( _MSC_VER )
  396. // On Windows getenv throws a warning as there is no input validation,
  397. // since the switch is hardcoded, this should not be an issue.
  398. # pragma warning( push )
  399. # pragma warning( disable : 4996 )
  400. # endif
  401. return std::getenv( "BAZEL_TEST" ) != nullptr;
  402. # if defined( _MSC_VER )
  403. # pragma warning( pop )
  404. # endif
  405. #endif
  406. }
  407. }
  408. namespace Catch {
  409. bool operator==( ProcessedReporterSpec const& lhs,
  410. ProcessedReporterSpec const& rhs ) {
  411. return lhs.name == rhs.name &&
  412. lhs.outputFilename == rhs.outputFilename &&
  413. lhs.colourMode == rhs.colourMode &&
  414. lhs.customOptions == rhs.customOptions;
  415. }
  416. Config::Config( ConfigData const& data ):
  417. m_data( data ) {
  418. // We need to trim filter specs to avoid trouble with superfluous
  419. // whitespace (esp. important for bdd macros, as those are manually
  420. // aligned with whitespace).
  421. for (auto& elem : m_data.testsOrTags) {
  422. elem = trim(elem);
  423. }
  424. for (auto& elem : m_data.sectionsToRun) {
  425. elem = trim(elem);
  426. }
  427. TestSpecParser parser(ITagAliasRegistry::get());
  428. if (!m_data.testsOrTags.empty()) {
  429. m_hasTestFilters = true;
  430. for (auto const& testOrTags : m_data.testsOrTags) {
  431. parser.parse(testOrTags);
  432. }
  433. }
  434. m_testSpec = parser.testSpec();
  435. // Insert the default reporter if user hasn't asked for a specfic one
  436. if ( m_data.reporterSpecifications.empty() ) {
  437. m_data.reporterSpecifications.push_back( {
  438. #if defined( CATCH_CONFIG_DEFAULT_REPORTER )
  439. CATCH_CONFIG_DEFAULT_REPORTER,
  440. #else
  441. "console",
  442. #endif
  443. {}, {}, {}
  444. } );
  445. }
  446. if(provideBazelReporterOutput()){
  447. // Register a JUnit reporter for Bazel. Bazel sets an environment
  448. // variable with the path to XML output. If this file is written to
  449. // during test, Bazel will not generate a default XML output.
  450. // This allows the XML output file to contain higher level of detail
  451. // than what is possible otherwise.
  452. # if defined( _MSC_VER )
  453. // On Windows getenv throws a warning as there is no input validation,
  454. // since the key is hardcoded, this should not be an issue.
  455. # pragma warning( push )
  456. # pragma warning( disable : 4996 )
  457. # endif
  458. const auto bazelOutputFilePtr = std::getenv( "XML_OUTPUT_FILE" );
  459. # if defined( _MSC_VER )
  460. # pragma warning( pop )
  461. # endif
  462. if ( bazelOutputFilePtr != nullptr ) {
  463. m_data.reporterSpecifications.push_back(
  464. { "junit", std::string( bazelOutputFilePtr ), {}, {} } );
  465. }
  466. }
  467. // We now fixup the reporter specs to handle default output spec,
  468. // default colour spec, etc
  469. bool defaultOutputUsed = false;
  470. for ( auto const& reporterSpec : m_data.reporterSpecifications ) {
  471. // We do the default-output check separately, while always
  472. // using the default output below to make the code simpler
  473. // and avoid superfluous copies.
  474. if ( reporterSpec.outputFile().none() ) {
  475. CATCH_ENFORCE( !defaultOutputUsed,
  476. "Internal error: cannot use default output for "
  477. "multiple reporters" );
  478. defaultOutputUsed = true;
  479. }
  480. m_processedReporterSpecs.push_back( ProcessedReporterSpec{
  481. reporterSpec.name(),
  482. reporterSpec.outputFile() ? *reporterSpec.outputFile()
  483. : data.defaultOutputFilename,
  484. reporterSpec.colourMode().valueOr( data.defaultColourMode ),
  485. reporterSpec.customOptions() } );
  486. }
  487. }
  488. Config::~Config() = default;
  489. bool Config::listTests() const { return m_data.listTests; }
  490. bool Config::listTags() const { return m_data.listTags; }
  491. bool Config::listReporters() const { return m_data.listReporters; }
  492. bool Config::listListeners() const { return m_data.listListeners; }
  493. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  494. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  495. std::vector<ReporterSpec> const& Config::getReporterSpecs() const {
  496. return m_data.reporterSpecifications;
  497. }
  498. std::vector<ProcessedReporterSpec> const&
  499. Config::getProcessedReporterSpecs() const {
  500. return m_processedReporterSpecs;
  501. }
  502. TestSpec const& Config::testSpec() const { return m_testSpec; }
  503. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  504. bool Config::showHelp() const { return m_data.showHelp; }
  505. // IConfig interface
  506. bool Config::allowThrows() const { return !m_data.noThrow; }
  507. StringRef Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  508. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  509. bool Config::warnAboutMissingAssertions() const {
  510. return !!( m_data.warnings & WarnAbout::NoAssertions );
  511. }
  512. bool Config::warnAboutUnmatchedTestSpecs() const {
  513. return !!( m_data.warnings & WarnAbout::UnmatchedTestSpec );
  514. }
  515. bool Config::zeroTestsCountAsSuccess() const { return m_data.allowZeroTests; }
  516. ShowDurations Config::showDurations() const { return m_data.showDurations; }
  517. double Config::minDuration() const { return m_data.minDuration; }
  518. TestRunOrder Config::runOrder() const { return m_data.runOrder; }
  519. uint32_t Config::rngSeed() const { return m_data.rngSeed; }
  520. unsigned int Config::shardCount() const { return m_data.shardCount; }
  521. unsigned int Config::shardIndex() const { return m_data.shardIndex; }
  522. ColourMode Config::defaultColourMode() const { return m_data.defaultColourMode; }
  523. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  524. int Config::abortAfter() const { return m_data.abortAfter; }
  525. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  526. Verbosity Config::verbosity() const { return m_data.verbosity; }
  527. bool Config::skipBenchmarks() const { return m_data.skipBenchmarks; }
  528. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  529. unsigned int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  530. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  531. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  532. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  533. } // end namespace Catch
  534. #include <cassert>
  535. #include <stack>
  536. namespace Catch {
  537. ////////////////////////////////////////////////////////////////////////////
  538. ScopedMessage::ScopedMessage( MessageBuilder const& builder ):
  539. m_info( builder.m_info ) {
  540. m_info.message = builder.m_stream.str();
  541. getResultCapture().pushScopedMessage( m_info );
  542. }
  543. ScopedMessage::ScopedMessage( ScopedMessage&& old ) noexcept:
  544. m_info( CATCH_MOVE( old.m_info ) ) {
  545. old.m_moved = true;
  546. }
  547. ScopedMessage::~ScopedMessage() {
  548. if ( !uncaught_exceptions() && !m_moved ){
  549. getResultCapture().popScopedMessage(m_info);
  550. }
  551. }
  552. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  553. auto trimmed = [&] (size_t start, size_t end) {
  554. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  555. ++start;
  556. }
  557. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  558. --end;
  559. }
  560. return names.substr(start, end - start + 1);
  561. };
  562. auto skipq = [&] (size_t start, char quote) {
  563. for (auto i = start + 1; i < names.size() ; ++i) {
  564. if (names[i] == quote)
  565. return i;
  566. if (names[i] == '\\')
  567. ++i;
  568. }
  569. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  570. };
  571. size_t start = 0;
  572. std::stack<char> openings;
  573. for (size_t pos = 0; pos < names.size(); ++pos) {
  574. char c = names[pos];
  575. switch (c) {
  576. case '[':
  577. case '{':
  578. case '(':
  579. // It is basically impossible to disambiguate between
  580. // comparison and start of template args in this context
  581. // case '<':
  582. openings.push(c);
  583. break;
  584. case ']':
  585. case '}':
  586. case ')':
  587. // case '>':
  588. openings.pop();
  589. break;
  590. case '"':
  591. case '\'':
  592. pos = skipq(pos, c);
  593. break;
  594. case ',':
  595. if (start != pos && openings.empty()) {
  596. m_messages.emplace_back(macroName, lineInfo, resultType);
  597. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  598. m_messages.back().message += " := ";
  599. start = pos;
  600. }
  601. }
  602. }
  603. assert(openings.empty() && "Mismatched openings");
  604. m_messages.emplace_back(macroName, lineInfo, resultType);
  605. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  606. m_messages.back().message += " := ";
  607. }
  608. Capturer::~Capturer() {
  609. if ( !uncaught_exceptions() ){
  610. assert( m_captured == m_messages.size() );
  611. for( size_t i = 0; i < m_captured; ++i )
  612. m_resultCapture.popScopedMessage( m_messages[i] );
  613. }
  614. }
  615. void Capturer::captureValue( size_t index, std::string const& value ) {
  616. assert( index < m_messages.size() );
  617. m_messages[index].message += value;
  618. m_resultCapture.pushScopedMessage( m_messages[index] );
  619. m_captured++;
  620. }
  621. } // end namespace Catch
  622. namespace Catch {
  623. namespace {
  624. class RegistryHub : public IRegistryHub,
  625. public IMutableRegistryHub,
  626. private Detail::NonCopyable {
  627. public: // IRegistryHub
  628. RegistryHub() = default;
  629. IReporterRegistry const& getReporterRegistry() const override {
  630. return m_reporterRegistry;
  631. }
  632. ITestCaseRegistry const& getTestCaseRegistry() const override {
  633. return m_testCaseRegistry;
  634. }
  635. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  636. return m_exceptionTranslatorRegistry;
  637. }
  638. ITagAliasRegistry const& getTagAliasRegistry() const override {
  639. return m_tagAliasRegistry;
  640. }
  641. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  642. return m_exceptionRegistry;
  643. }
  644. public: // IMutableRegistryHub
  645. void registerReporter( std::string const& name, IReporterFactoryPtr factory ) override {
  646. m_reporterRegistry.registerReporter( name, CATCH_MOVE(factory) );
  647. }
  648. void registerListener( Detail::unique_ptr<EventListenerFactory> factory ) override {
  649. m_reporterRegistry.registerListener( CATCH_MOVE(factory) );
  650. }
  651. void registerTest( Detail::unique_ptr<TestCaseInfo>&& testInfo, Detail::unique_ptr<ITestInvoker>&& invoker ) override {
  652. m_testCaseRegistry.registerTest( CATCH_MOVE(testInfo), CATCH_MOVE(invoker) );
  653. }
  654. void registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) override {
  655. m_exceptionTranslatorRegistry.registerTranslator( CATCH_MOVE(translator) );
  656. }
  657. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  658. m_tagAliasRegistry.add( alias, tag, lineInfo );
  659. }
  660. void registerStartupException() noexcept override {
  661. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  662. m_exceptionRegistry.add(std::current_exception());
  663. #else
  664. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  665. #endif
  666. }
  667. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  668. return m_enumValuesRegistry;
  669. }
  670. private:
  671. TestRegistry m_testCaseRegistry;
  672. ReporterRegistry m_reporterRegistry;
  673. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  674. TagAliasRegistry m_tagAliasRegistry;
  675. StartupExceptionRegistry m_exceptionRegistry;
  676. Detail::EnumValuesRegistry m_enumValuesRegistry;
  677. };
  678. }
  679. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  680. IRegistryHub const& getRegistryHub() {
  681. return RegistryHubSingleton::get();
  682. }
  683. IMutableRegistryHub& getMutableRegistryHub() {
  684. return RegistryHubSingleton::getMutable();
  685. }
  686. void cleanUp() {
  687. cleanupSingletons();
  688. cleanUpContext();
  689. }
  690. std::string translateActiveException() {
  691. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  692. }
  693. } // end namespace Catch
  694. #include <algorithm>
  695. #include <cassert>
  696. #include <iomanip>
  697. #include <set>
  698. namespace Catch {
  699. namespace {
  700. const int MaxExitCode = 255;
  701. IEventListenerPtr createReporter(std::string const& reporterName, ReporterConfig&& config) {
  702. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, CATCH_MOVE(config));
  703. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << '\'');
  704. return reporter;
  705. }
  706. IEventListenerPtr prepareReporters(Config const* config) {
  707. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()
  708. && config->getProcessedReporterSpecs().size() == 1) {
  709. auto const& spec = config->getProcessedReporterSpecs()[0];
  710. return createReporter(
  711. spec.name,
  712. ReporterConfig( config,
  713. makeStream( spec.outputFilename ),
  714. spec.colourMode,
  715. spec.customOptions ) );
  716. }
  717. auto multi = Detail::make_unique<MultiReporter>(config);
  718. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  719. for (auto const& listener : listeners) {
  720. multi->addListener(listener->create(config));
  721. }
  722. std::size_t reporterIdx = 0;
  723. for ( auto const& reporterSpec : config->getProcessedReporterSpecs() ) {
  724. multi->addReporter( createReporter(
  725. reporterSpec.name,
  726. ReporterConfig( config,
  727. makeStream( reporterSpec.outputFilename ),
  728. reporterSpec.colourMode,
  729. reporterSpec.customOptions ) ) );
  730. reporterIdx++;
  731. }
  732. return multi;
  733. }
  734. class TestGroup {
  735. public:
  736. explicit TestGroup(IEventListenerPtr&& reporter, Config const* config):
  737. m_reporter(reporter.get()),
  738. m_config{config},
  739. m_context{config, CATCH_MOVE(reporter)} {
  740. assert( m_config->testSpec().getInvalidSpecs().empty() &&
  741. "Invalid test specs should be handled before running tests" );
  742. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  743. auto const& testSpec = m_config->testSpec();
  744. if ( !testSpec.hasFilters() ) {
  745. for ( auto const& test : allTestCases ) {
  746. if ( !test.getTestCaseInfo().isHidden() ) {
  747. m_tests.emplace( &test );
  748. }
  749. }
  750. } else {
  751. m_matches =
  752. testSpec.matchesByFilter( allTestCases, *m_config );
  753. for ( auto const& match : m_matches ) {
  754. m_tests.insert( match.tests.begin(),
  755. match.tests.end() );
  756. }
  757. }
  758. m_tests = createShard(m_tests, m_config->shardCount(), m_config->shardIndex());
  759. }
  760. Totals execute() {
  761. Totals totals;
  762. for (auto const& testCase : m_tests) {
  763. if (!m_context.aborting())
  764. totals += m_context.runTest(*testCase);
  765. else
  766. m_reporter->skipTest(testCase->getTestCaseInfo());
  767. }
  768. for (auto const& match : m_matches) {
  769. if (match.tests.empty()) {
  770. m_unmatchedTestSpecs = true;
  771. m_reporter->noMatchingTestCases( match.name );
  772. }
  773. }
  774. return totals;
  775. }
  776. bool hadUnmatchedTestSpecs() const {
  777. return m_unmatchedTestSpecs;
  778. }
  779. private:
  780. IEventListener* m_reporter;
  781. Config const* m_config;
  782. RunContext m_context;
  783. std::set<TestCaseHandle const*> m_tests;
  784. TestSpec::Matches m_matches;
  785. bool m_unmatchedTestSpecs = false;
  786. };
  787. void applyFilenamesAsTags() {
  788. for (auto const& testInfo : getRegistryHub().getTestCaseRegistry().getAllInfos()) {
  789. testInfo->addFilenameTag();
  790. }
  791. }
  792. } // anon namespace
  793. Session::Session() {
  794. static bool alreadyInstantiated = false;
  795. if( alreadyInstantiated ) {
  796. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  797. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  798. }
  799. // There cannot be exceptions at startup in no-exception mode.
  800. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  801. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  802. if ( !exceptions.empty() ) {
  803. config();
  804. getCurrentMutableContext().setConfig(m_config.get());
  805. m_startupExceptions = true;
  806. auto errStream = makeStream( "%stderr" );
  807. auto colourImpl = makeColourImpl(
  808. ColourMode::PlatformDefault, errStream.get() );
  809. auto guard = colourImpl->guardColour( Colour::Red );
  810. errStream->stream() << "Errors occurred during startup!" << '\n';
  811. // iterate over all exceptions and notify user
  812. for ( const auto& ex_ptr : exceptions ) {
  813. try {
  814. std::rethrow_exception(ex_ptr);
  815. } catch ( std::exception const& ex ) {
  816. errStream->stream() << TextFlow::Column( ex.what() ).indent(2) << '\n';
  817. }
  818. }
  819. }
  820. #endif
  821. alreadyInstantiated = true;
  822. m_cli = makeCommandLineParser( m_configData );
  823. }
  824. Session::~Session() {
  825. Catch::cleanUp();
  826. }
  827. void Session::showHelp() const {
  828. Catch::cout()
  829. << "\nCatch2 v" << libraryVersion() << '\n'
  830. << m_cli << '\n'
  831. << "For more detailed usage please see the project docs\n\n" << std::flush;
  832. }
  833. void Session::libIdentify() {
  834. Catch::cout()
  835. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  836. << std::left << std::setw(16) << "category: " << "testframework\n"
  837. << std::left << std::setw(16) << "framework: " << "Catch2\n"
  838. << std::left << std::setw(16) << "version: " << libraryVersion() << '\n' << std::flush;
  839. }
  840. int Session::applyCommandLine( int argc, char const * const * argv ) {
  841. if( m_startupExceptions )
  842. return 1;
  843. auto result = m_cli.parse( Clara::Args( argc, argv ) );
  844. if( !result ) {
  845. config();
  846. getCurrentMutableContext().setConfig(m_config.get());
  847. auto errStream = makeStream( "%stderr" );
  848. auto colour = makeColourImpl( ColourMode::PlatformDefault, errStream.get() );
  849. errStream->stream()
  850. << colour->guardColour( Colour::Red )
  851. << "\nError(s) in input:\n"
  852. << TextFlow::Column( result.errorMessage() ).indent( 2 )
  853. << "\n\n";
  854. errStream->stream() << "Run with -? for usage\n\n" << std::flush;
  855. return MaxExitCode;
  856. }
  857. if( m_configData.showHelp )
  858. showHelp();
  859. if( m_configData.libIdentify )
  860. libIdentify();
  861. m_config.reset();
  862. return 0;
  863. }
  864. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  865. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  866. char **utf8Argv = new char *[ argc ];
  867. for ( int i = 0; i < argc; ++i ) {
  868. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  869. utf8Argv[ i ] = new char[ bufSize ];
  870. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  871. }
  872. int returnCode = applyCommandLine( argc, utf8Argv );
  873. for ( int i = 0; i < argc; ++i )
  874. delete [] utf8Argv[ i ];
  875. delete [] utf8Argv;
  876. return returnCode;
  877. }
  878. #endif
  879. void Session::useConfigData( ConfigData const& configData ) {
  880. m_configData = configData;
  881. m_config.reset();
  882. }
  883. int Session::run() {
  884. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  885. Catch::cout() << "...waiting for enter/ return before starting\n" << std::flush;
  886. static_cast<void>(std::getchar());
  887. }
  888. int exitCode = runInternal();
  889. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  890. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << '\n' << std::flush;
  891. static_cast<void>(std::getchar());
  892. }
  893. return exitCode;
  894. }
  895. Clara::Parser const& Session::cli() const {
  896. return m_cli;
  897. }
  898. void Session::cli( Clara::Parser const& newParser ) {
  899. m_cli = newParser;
  900. }
  901. ConfigData& Session::configData() {
  902. return m_configData;
  903. }
  904. Config& Session::config() {
  905. if( !m_config )
  906. m_config = Detail::make_unique<Config>( m_configData );
  907. return *m_config;
  908. }
  909. int Session::runInternal() {
  910. if( m_startupExceptions )
  911. return 1;
  912. if (m_configData.showHelp || m_configData.libIdentify) {
  913. return 0;
  914. }
  915. if ( m_configData.shardIndex >= m_configData.shardCount ) {
  916. Catch::cerr() << "The shard count (" << m_configData.shardCount
  917. << ") must be greater than the shard index ("
  918. << m_configData.shardIndex << ")\n"
  919. << std::flush;
  920. return 1;
  921. }
  922. CATCH_TRY {
  923. config(); // Force config to be constructed
  924. seedRng( *m_config );
  925. if (m_configData.filenamesAsTags) {
  926. applyFilenamesAsTags();
  927. }
  928. // Set up global config instance before we start calling into other functions
  929. getCurrentMutableContext().setConfig(m_config.get());
  930. // Create reporter(s) so we can route listings through them
  931. auto reporter = prepareReporters(m_config.get());
  932. auto const& invalidSpecs = m_config->testSpec().getInvalidSpecs();
  933. if ( !invalidSpecs.empty() ) {
  934. for ( auto const& spec : invalidSpecs ) {
  935. reporter->reportInvalidTestSpec( spec );
  936. }
  937. return 1;
  938. }
  939. // Handle list request
  940. if (list(*reporter, *m_config)) {
  941. return 0;
  942. }
  943. TestGroup tests { CATCH_MOVE(reporter), m_config.get() };
  944. auto const totals = tests.execute();
  945. if ( tests.hadUnmatchedTestSpecs()
  946. && m_config->warnAboutUnmatchedTestSpecs() ) {
  947. return 3;
  948. }
  949. if ( totals.testCases.total() == 0
  950. && !m_config->zeroTestsCountAsSuccess() ) {
  951. return 2;
  952. }
  953. // Note that on unices only the lower 8 bits are usually used, clamping
  954. // the return value to 255 prevents false negative when some multiple
  955. // of 256 tests has failed
  956. return (std::min) (MaxExitCode, static_cast<int>(totals.assertions.failed));
  957. }
  958. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  959. catch( std::exception& ex ) {
  960. Catch::cerr() << ex.what() << '\n' << std::flush;
  961. return MaxExitCode;
  962. }
  963. #endif
  964. }
  965. } // end namespace Catch
  966. namespace Catch {
  967. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  968. CATCH_TRY {
  969. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  970. } CATCH_CATCH_ALL {
  971. // Do not throw when constructing global objects, instead register the exception to be processed later
  972. getMutableRegistryHub().registerStartupException();
  973. }
  974. }
  975. }
  976. #include <cassert>
  977. #include <cctype>
  978. #include <algorithm>
  979. namespace Catch {
  980. namespace {
  981. using TCP_underlying_type = uint8_t;
  982. static_assert(sizeof(TestCaseProperties) == sizeof(TCP_underlying_type),
  983. "The size of the TestCaseProperties is different from the assumed size");
  984. TestCaseProperties operator|(TestCaseProperties lhs, TestCaseProperties rhs) {
  985. return static_cast<TestCaseProperties>(
  986. static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs)
  987. );
  988. }
  989. TestCaseProperties& operator|=(TestCaseProperties& lhs, TestCaseProperties rhs) {
  990. lhs = static_cast<TestCaseProperties>(
  991. static_cast<TCP_underlying_type>(lhs) | static_cast<TCP_underlying_type>(rhs)
  992. );
  993. return lhs;
  994. }
  995. TestCaseProperties operator&(TestCaseProperties lhs, TestCaseProperties rhs) {
  996. return static_cast<TestCaseProperties>(
  997. static_cast<TCP_underlying_type>(lhs) & static_cast<TCP_underlying_type>(rhs)
  998. );
  999. }
  1000. bool applies(TestCaseProperties tcp) {
  1001. static_assert(static_cast<TCP_underlying_type>(TestCaseProperties::None) == 0,
  1002. "TestCaseProperties::None must be equal to 0");
  1003. return tcp != TestCaseProperties::None;
  1004. }
  1005. TestCaseProperties parseSpecialTag( StringRef tag ) {
  1006. if( !tag.empty() && tag[0] == '.' )
  1007. return TestCaseProperties::IsHidden;
  1008. else if( tag == "!throws"_sr )
  1009. return TestCaseProperties::Throws;
  1010. else if( tag == "!shouldfail"_sr )
  1011. return TestCaseProperties::ShouldFail;
  1012. else if( tag == "!mayfail"_sr )
  1013. return TestCaseProperties::MayFail;
  1014. else if( tag == "!nonportable"_sr )
  1015. return TestCaseProperties::NonPortable;
  1016. else if( tag == "!benchmark"_sr )
  1017. return TestCaseProperties::Benchmark | TestCaseProperties::IsHidden;
  1018. else
  1019. return TestCaseProperties::None;
  1020. }
  1021. bool isReservedTag( StringRef tag ) {
  1022. return parseSpecialTag( tag ) == TestCaseProperties::None
  1023. && tag.size() > 0
  1024. && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  1025. }
  1026. void enforceNotReservedTag( StringRef tag, SourceLineInfo const& _lineInfo ) {
  1027. CATCH_ENFORCE( !isReservedTag(tag),
  1028. "Tag name: [" << tag << "] is not allowed.\n"
  1029. << "Tag names starting with non alphanumeric characters are reserved\n"
  1030. << _lineInfo );
  1031. }
  1032. std::string makeDefaultName() {
  1033. static size_t counter = 0;
  1034. return "Anonymous test case " + std::to_string(++counter);
  1035. }
  1036. StringRef extractFilenamePart(StringRef filename) {
  1037. size_t lastDot = filename.size();
  1038. while (lastDot > 0 && filename[lastDot - 1] != '.') {
  1039. --lastDot;
  1040. }
  1041. --lastDot;
  1042. size_t nameStart = lastDot;
  1043. while (nameStart > 0 && filename[nameStart - 1] != '/' && filename[nameStart - 1] != '\\') {
  1044. --nameStart;
  1045. }
  1046. return filename.substr(nameStart, lastDot - nameStart);
  1047. }
  1048. // Returns the upper bound on size of extra tags ([#file]+[.])
  1049. size_t sizeOfExtraTags(StringRef filepath) {
  1050. // [.] is 3, [#] is another 3
  1051. const size_t extras = 3 + 3;
  1052. return extractFilenamePart(filepath).size() + extras;
  1053. }
  1054. } // end unnamed namespace
  1055. bool operator<( Tag const& lhs, Tag const& rhs ) {
  1056. Detail::CaseInsensitiveLess cmp;
  1057. return cmp( lhs.original, rhs.original );
  1058. }
  1059. bool operator==( Tag const& lhs, Tag const& rhs ) {
  1060. Detail::CaseInsensitiveEqualTo cmp;
  1061. return cmp( lhs.original, rhs.original );
  1062. }
  1063. Detail::unique_ptr<TestCaseInfo>
  1064. makeTestCaseInfo(StringRef _className,
  1065. NameAndTags const& nameAndTags,
  1066. SourceLineInfo const& _lineInfo ) {
  1067. return Detail::make_unique<TestCaseInfo>(_className, nameAndTags, _lineInfo);
  1068. }
  1069. TestCaseInfo::TestCaseInfo(StringRef _className,
  1070. NameAndTags const& _nameAndTags,
  1071. SourceLineInfo const& _lineInfo):
  1072. name( _nameAndTags.name.empty() ? makeDefaultName() : _nameAndTags.name ),
  1073. className( _className ),
  1074. lineInfo( _lineInfo )
  1075. {
  1076. StringRef originalTags = _nameAndTags.tags;
  1077. // We need to reserve enough space to store all of the tags
  1078. // (including optional hidden tag and filename tag)
  1079. auto requiredSize = originalTags.size() + sizeOfExtraTags(_lineInfo.file);
  1080. backingTags.reserve(requiredSize);
  1081. // We cannot copy the tags directly, as we need to normalize
  1082. // some tags, so that [.foo] is copied as [.][foo].
  1083. size_t tagStart = 0;
  1084. size_t tagEnd = 0;
  1085. bool inTag = false;
  1086. for (size_t idx = 0; idx < originalTags.size(); ++idx) {
  1087. auto c = originalTags[idx];
  1088. if (c == '[') {
  1089. assert(!inTag);
  1090. inTag = true;
  1091. tagStart = idx;
  1092. }
  1093. if (c == ']') {
  1094. assert(inTag);
  1095. inTag = false;
  1096. tagEnd = idx;
  1097. assert(tagStart < tagEnd);
  1098. // We need to check the tag for special meanings, copy
  1099. // it over to backing storage and actually reference the
  1100. // backing storage in the saved tags
  1101. StringRef tagStr = originalTags.substr(tagStart+1, tagEnd - tagStart - 1);
  1102. CATCH_ENFORCE(!tagStr.empty(), "Empty tags are not allowed");
  1103. enforceNotReservedTag(tagStr, lineInfo);
  1104. properties |= parseSpecialTag(tagStr);
  1105. // When copying a tag to the backing storage, we need to
  1106. // check if it is a merged hide tag, such as [.foo], and
  1107. // if it is, we need to handle it as if it was [foo].
  1108. if (tagStr.size() > 1 && tagStr[0] == '.') {
  1109. tagStr = tagStr.substr(1, tagStr.size() - 1);
  1110. }
  1111. // We skip over dealing with the [.] tag, as we will add
  1112. // it later unconditionally and then sort and unique all
  1113. // the tags.
  1114. internalAppendTag(tagStr);
  1115. }
  1116. (void)inTag; // Silence "set-but-unused" warning in release mode.
  1117. }
  1118. // Add [.] if relevant
  1119. if (isHidden()) {
  1120. internalAppendTag("."_sr);
  1121. }
  1122. // Sort and prepare tags
  1123. std::sort(begin(tags), end(tags));
  1124. tags.erase(std::unique(begin(tags), end(tags)),
  1125. end(tags));
  1126. }
  1127. bool TestCaseInfo::isHidden() const {
  1128. return applies( properties & TestCaseProperties::IsHidden );
  1129. }
  1130. bool TestCaseInfo::throws() const {
  1131. return applies( properties & TestCaseProperties::Throws );
  1132. }
  1133. bool TestCaseInfo::okToFail() const {
  1134. return applies( properties & (TestCaseProperties::ShouldFail | TestCaseProperties::MayFail ) );
  1135. }
  1136. bool TestCaseInfo::expectedToFail() const {
  1137. return applies( properties & (TestCaseProperties::ShouldFail) );
  1138. }
  1139. void TestCaseInfo::addFilenameTag() {
  1140. std::string combined("#");
  1141. combined += extractFilenamePart(lineInfo.file);
  1142. internalAppendTag(combined);
  1143. }
  1144. std::string TestCaseInfo::tagsAsString() const {
  1145. std::string ret;
  1146. // '[' and ']' per tag
  1147. std::size_t full_size = 2 * tags.size();
  1148. for (const auto& tag : tags) {
  1149. full_size += tag.original.size();
  1150. }
  1151. ret.reserve(full_size);
  1152. for (const auto& tag : tags) {
  1153. ret.push_back('[');
  1154. ret += tag.original;
  1155. ret.push_back(']');
  1156. }
  1157. return ret;
  1158. }
  1159. void TestCaseInfo::internalAppendTag(StringRef tagStr) {
  1160. backingTags += '[';
  1161. const auto backingStart = backingTags.size();
  1162. backingTags += tagStr;
  1163. const auto backingEnd = backingTags.size();
  1164. backingTags += ']';
  1165. tags.emplace_back(StringRef(backingTags.c_str() + backingStart, backingEnd - backingStart));
  1166. }
  1167. bool operator<( TestCaseInfo const& lhs, TestCaseInfo const& rhs ) {
  1168. // We want to avoid redoing the string comparisons multiple times,
  1169. // so we store the result of a three-way comparison before using
  1170. // it in the actual comparison logic.
  1171. const auto cmpName = lhs.name.compare( rhs.name );
  1172. if ( cmpName != 0 ) {
  1173. return cmpName < 0;
  1174. }
  1175. const auto cmpClassName = lhs.className.compare( rhs.className );
  1176. if ( cmpClassName != 0 ) {
  1177. return cmpClassName < 0;
  1178. }
  1179. return lhs.tags < rhs.tags;
  1180. }
  1181. TestCaseInfo const& TestCaseHandle::getTestCaseInfo() const {
  1182. return *m_info;
  1183. }
  1184. } // end namespace Catch
  1185. #include <algorithm>
  1186. #include <string>
  1187. #include <vector>
  1188. namespace Catch {
  1189. TestSpec::Pattern::Pattern( std::string const& name )
  1190. : m_name( name )
  1191. {}
  1192. TestSpec::Pattern::~Pattern() = default;
  1193. std::string const& TestSpec::Pattern::name() const {
  1194. return m_name;
  1195. }
  1196. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  1197. : Pattern( filterString )
  1198. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  1199. {}
  1200. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  1201. return m_wildcardPattern.matches( testCase.name );
  1202. }
  1203. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  1204. : Pattern( filterString )
  1205. , m_tag( tag )
  1206. {}
  1207. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  1208. return std::find( begin( testCase.tags ),
  1209. end( testCase.tags ),
  1210. Tag( m_tag ) ) != end( testCase.tags );
  1211. }
  1212. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  1213. bool should_use = !testCase.isHidden();
  1214. for (auto const& pattern : m_required) {
  1215. should_use = true;
  1216. if (!pattern->matches(testCase)) {
  1217. return false;
  1218. }
  1219. }
  1220. for (auto const& pattern : m_forbidden) {
  1221. if (pattern->matches(testCase)) {
  1222. return false;
  1223. }
  1224. }
  1225. return should_use;
  1226. }
  1227. std::string TestSpec::Filter::name() const {
  1228. std::string name;
  1229. for (auto const& p : m_required) {
  1230. name += p->name();
  1231. }
  1232. for (auto const& p : m_forbidden) {
  1233. name += p->name();
  1234. }
  1235. return name;
  1236. }
  1237. bool TestSpec::hasFilters() const {
  1238. return !m_filters.empty();
  1239. }
  1240. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  1241. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  1242. }
  1243. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCaseHandle> const& testCases, IConfig const& config ) const
  1244. {
  1245. Matches matches( m_filters.size() );
  1246. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  1247. std::vector<TestCaseHandle const*> currentMatches;
  1248. for( auto const& test : testCases )
  1249. if( isThrowSafe( test, config ) && filter.matches( test.getTestCaseInfo() ) )
  1250. currentMatches.emplace_back( &test );
  1251. return FilterMatch{ filter.name(), currentMatches };
  1252. } );
  1253. return matches;
  1254. }
  1255. const TestSpec::vectorStrings& TestSpec::getInvalidSpecs() const {
  1256. return m_invalidSpecs;
  1257. }
  1258. }
  1259. #include <chrono>
  1260. namespace Catch {
  1261. namespace {
  1262. static auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  1263. return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
  1264. }
  1265. } // end unnamed namespace
  1266. void Timer::start() {
  1267. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  1268. }
  1269. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  1270. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  1271. }
  1272. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  1273. return getElapsedNanoseconds()/1000;
  1274. }
  1275. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  1276. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  1277. }
  1278. auto Timer::getElapsedSeconds() const -> double {
  1279. return getElapsedMicroseconds()/1000000.0;
  1280. }
  1281. } // namespace Catch
  1282. #include <cmath>
  1283. #include <iomanip>
  1284. namespace Catch {
  1285. namespace Detail {
  1286. namespace {
  1287. const int hexThreshold = 255;
  1288. struct Endianness {
  1289. enum Arch { Big, Little };
  1290. static Arch which() {
  1291. int one = 1;
  1292. // If the lowest byte we read is non-zero, we can assume
  1293. // that little endian format is used.
  1294. auto value = *reinterpret_cast<char*>(&one);
  1295. return value ? Little : Big;
  1296. }
  1297. };
  1298. template<typename T>
  1299. std::string fpToString(T value, int precision) {
  1300. if (Catch::isnan(value)) {
  1301. return "nan";
  1302. }
  1303. ReusableStringStream rss;
  1304. rss << std::setprecision(precision)
  1305. << std::fixed
  1306. << value;
  1307. std::string d = rss.str();
  1308. std::size_t i = d.find_last_not_of('0');
  1309. if (i != std::string::npos && i != d.size() - 1) {
  1310. if (d[i] == '.')
  1311. i++;
  1312. d = d.substr(0, i + 1);
  1313. }
  1314. return d;
  1315. }
  1316. } // end unnamed namespace
  1317. std::string convertIntoString(StringRef string, bool escape_invisibles) {
  1318. std::string ret;
  1319. // This is enough for the "don't escape invisibles" case, and a good
  1320. // lower bound on the "escape invisibles" case.
  1321. ret.reserve(string.size() + 2);
  1322. if (!escape_invisibles) {
  1323. ret += '"';
  1324. ret += string;
  1325. ret += '"';
  1326. return ret;
  1327. }
  1328. ret += '"';
  1329. for (char c : string) {
  1330. switch (c) {
  1331. case '\r':
  1332. ret.append("\\r");
  1333. break;
  1334. case '\n':
  1335. ret.append("\\n");
  1336. break;
  1337. case '\t':
  1338. ret.append("\\t");
  1339. break;
  1340. case '\f':
  1341. ret.append("\\f");
  1342. break;
  1343. default:
  1344. ret.push_back(c);
  1345. break;
  1346. }
  1347. }
  1348. ret += '"';
  1349. return ret;
  1350. }
  1351. std::string convertIntoString(StringRef string) {
  1352. return convertIntoString(string, getCurrentContext().getConfig()->showInvisibles());
  1353. }
  1354. std::string rawMemoryToString( const void *object, std::size_t size ) {
  1355. // Reverse order for little endian architectures
  1356. int i = 0, end = static_cast<int>( size ), inc = 1;
  1357. if( Endianness::which() == Endianness::Little ) {
  1358. i = end-1;
  1359. end = inc = -1;
  1360. }
  1361. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  1362. ReusableStringStream rss;
  1363. rss << "0x" << std::setfill('0') << std::hex;
  1364. for( ; i != end; i += inc )
  1365. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  1366. return rss.str();
  1367. }
  1368. } // end Detail namespace
  1369. //// ======================================================= ////
  1370. //
  1371. // Out-of-line defs for full specialization of StringMaker
  1372. //
  1373. //// ======================================================= ////
  1374. std::string StringMaker<std::string>::convert(const std::string& str) {
  1375. return Detail::convertIntoString( str );
  1376. }
  1377. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1378. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  1379. return Detail::convertIntoString( StringRef( str.data(), str.size() ) );
  1380. }
  1381. #endif
  1382. std::string StringMaker<char const*>::convert(char const* str) {
  1383. if (str) {
  1384. return Detail::convertIntoString( str );
  1385. } else {
  1386. return{ "{null string}" };
  1387. }
  1388. }
  1389. std::string StringMaker<char*>::convert(char* str) {
  1390. if (str) {
  1391. return Detail::convertIntoString( str );
  1392. } else {
  1393. return{ "{null string}" };
  1394. }
  1395. }
  1396. #ifdef CATCH_CONFIG_WCHAR
  1397. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  1398. std::string s;
  1399. s.reserve(wstr.size());
  1400. for (auto c : wstr) {
  1401. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  1402. }
  1403. return ::Catch::Detail::stringify(s);
  1404. }
  1405. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1406. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  1407. return StringMaker<std::wstring>::convert(std::wstring(str));
  1408. }
  1409. # endif
  1410. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  1411. if (str) {
  1412. return ::Catch::Detail::stringify(std::wstring{ str });
  1413. } else {
  1414. return{ "{null string}" };
  1415. }
  1416. }
  1417. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  1418. if (str) {
  1419. return ::Catch::Detail::stringify(std::wstring{ str });
  1420. } else {
  1421. return{ "{null string}" };
  1422. }
  1423. }
  1424. #endif
  1425. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1426. #include <cstddef>
  1427. std::string StringMaker<std::byte>::convert(std::byte value) {
  1428. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  1429. }
  1430. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1431. std::string StringMaker<int>::convert(int value) {
  1432. return ::Catch::Detail::stringify(static_cast<long long>(value));
  1433. }
  1434. std::string StringMaker<long>::convert(long value) {
  1435. return ::Catch::Detail::stringify(static_cast<long long>(value));
  1436. }
  1437. std::string StringMaker<long long>::convert(long long value) {
  1438. ReusableStringStream rss;
  1439. rss << value;
  1440. if (value > Detail::hexThreshold) {
  1441. rss << " (0x" << std::hex << value << ')';
  1442. }
  1443. return rss.str();
  1444. }
  1445. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  1446. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  1447. }
  1448. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  1449. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  1450. }
  1451. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  1452. ReusableStringStream rss;
  1453. rss << value;
  1454. if (value > Detail::hexThreshold) {
  1455. rss << " (0x" << std::hex << value << ')';
  1456. }
  1457. return rss.str();
  1458. }
  1459. std::string StringMaker<signed char>::convert(signed char value) {
  1460. if (value == '\r') {
  1461. return "'\\r'";
  1462. } else if (value == '\f') {
  1463. return "'\\f'";
  1464. } else if (value == '\n') {
  1465. return "'\\n'";
  1466. } else if (value == '\t') {
  1467. return "'\\t'";
  1468. } else if ('\0' <= value && value < ' ') {
  1469. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  1470. } else {
  1471. char chstr[] = "' '";
  1472. chstr[1] = value;
  1473. return chstr;
  1474. }
  1475. }
  1476. std::string StringMaker<char>::convert(char c) {
  1477. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  1478. }
  1479. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  1480. return ::Catch::Detail::stringify(static_cast<char>(c));
  1481. }
  1482. int StringMaker<float>::precision = 5;
  1483. std::string StringMaker<float>::convert(float value) {
  1484. return Detail::fpToString(value, precision) + 'f';
  1485. }
  1486. int StringMaker<double>::precision = 10;
  1487. std::string StringMaker<double>::convert(double value) {
  1488. return Detail::fpToString(value, precision);
  1489. }
  1490. } // end namespace Catch
  1491. namespace Catch {
  1492. Counts Counts::operator - ( Counts const& other ) const {
  1493. Counts diff;
  1494. diff.passed = passed - other.passed;
  1495. diff.failed = failed - other.failed;
  1496. diff.failedButOk = failedButOk - other.failedButOk;
  1497. return diff;
  1498. }
  1499. Counts& Counts::operator += ( Counts const& other ) {
  1500. passed += other.passed;
  1501. failed += other.failed;
  1502. failedButOk += other.failedButOk;
  1503. return *this;
  1504. }
  1505. std::uint64_t Counts::total() const {
  1506. return passed + failed + failedButOk;
  1507. }
  1508. bool Counts::allPassed() const {
  1509. return failed == 0 && failedButOk == 0;
  1510. }
  1511. bool Counts::allOk() const {
  1512. return failed == 0;
  1513. }
  1514. Totals Totals::operator - ( Totals const& other ) const {
  1515. Totals diff;
  1516. diff.assertions = assertions - other.assertions;
  1517. diff.testCases = testCases - other.testCases;
  1518. return diff;
  1519. }
  1520. Totals& Totals::operator += ( Totals const& other ) {
  1521. assertions += other.assertions;
  1522. testCases += other.testCases;
  1523. return *this;
  1524. }
  1525. Totals Totals::delta( Totals const& prevTotals ) const {
  1526. Totals diff = *this - prevTotals;
  1527. if( diff.assertions.failed > 0 )
  1528. ++diff.testCases.failed;
  1529. else if( diff.assertions.failedButOk > 0 )
  1530. ++diff.testCases.failedButOk;
  1531. else
  1532. ++diff.testCases.passed;
  1533. return diff;
  1534. }
  1535. }
  1536. #include <ostream>
  1537. namespace Catch {
  1538. Version::Version
  1539. ( unsigned int _majorVersion,
  1540. unsigned int _minorVersion,
  1541. unsigned int _patchNumber,
  1542. char const * const _branchName,
  1543. unsigned int _buildNumber )
  1544. : majorVersion( _majorVersion ),
  1545. minorVersion( _minorVersion ),
  1546. patchNumber( _patchNumber ),
  1547. branchName( _branchName ),
  1548. buildNumber( _buildNumber )
  1549. {}
  1550. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  1551. os << version.majorVersion << '.'
  1552. << version.minorVersion << '.'
  1553. << version.patchNumber;
  1554. // branchName is never null -> 0th char is \0 if it is empty
  1555. if (version.branchName[0]) {
  1556. os << '-' << version.branchName
  1557. << '.' << version.buildNumber;
  1558. }
  1559. return os;
  1560. }
  1561. Version const& libraryVersion() {
  1562. static Version version( 3, 1, 0, "", 0 );
  1563. return version;
  1564. }
  1565. }
  1566. namespace Catch {
  1567. const char* GeneratorException::what() const noexcept {
  1568. return m_msg;
  1569. }
  1570. } // end namespace Catch
  1571. namespace Catch {
  1572. IGeneratorTracker::~IGeneratorTracker() = default;
  1573. namespace Generators {
  1574. namespace Detail {
  1575. [[noreturn]]
  1576. void throw_generator_exception(char const* msg) {
  1577. Catch::throw_exception(GeneratorException{ msg });
  1578. }
  1579. } // end namespace Detail
  1580. GeneratorUntypedBase::~GeneratorUntypedBase() = default;
  1581. auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  1582. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  1583. }
  1584. } // namespace Generators
  1585. } // namespace Catch
  1586. std::uint32_t Catch::Generators::Detail::getSeed() { return sharedRng()(); }
  1587. namespace Catch {
  1588. IResultCapture::~IResultCapture() = default;
  1589. }
  1590. namespace Catch {
  1591. IConfig::~IConfig() = default;
  1592. }
  1593. namespace Catch {
  1594. IExceptionTranslator::~IExceptionTranslator() = default;
  1595. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  1596. }
  1597. #include <string>
  1598. namespace Catch {
  1599. namespace Generators {
  1600. bool GeneratorUntypedBase::countedNext() {
  1601. auto ret = next();
  1602. if ( ret ) {
  1603. m_stringReprCache.clear();
  1604. ++m_currentElementIndex;
  1605. }
  1606. return ret;
  1607. }
  1608. StringRef GeneratorUntypedBase::currentElementAsString() const {
  1609. if ( m_stringReprCache.empty() ) {
  1610. m_stringReprCache = stringifyImpl();
  1611. }
  1612. return m_stringReprCache;
  1613. }
  1614. } // namespace Generators
  1615. } // namespace Catch
  1616. namespace Catch {
  1617. IRegistryHub::~IRegistryHub() = default;
  1618. IMutableRegistryHub::~IMutableRegistryHub() = default;
  1619. }
  1620. #include <algorithm>
  1621. #include <cassert>
  1622. #include <iomanip>
  1623. namespace Catch {
  1624. ReporterConfig::ReporterConfig(
  1625. IConfig const* _fullConfig,
  1626. Detail::unique_ptr<IStream> _stream,
  1627. ColourMode colourMode,
  1628. std::map<std::string, std::string> customOptions ):
  1629. m_stream( CATCH_MOVE(_stream) ),
  1630. m_fullConfig( _fullConfig ),
  1631. m_colourMode( colourMode ),
  1632. m_customOptions( CATCH_MOVE( customOptions ) ) {}
  1633. Detail::unique_ptr<IStream> ReporterConfig::takeStream() && {
  1634. assert( m_stream );
  1635. return CATCH_MOVE( m_stream );
  1636. }
  1637. IConfig const * ReporterConfig::fullConfig() const { return m_fullConfig; }
  1638. ColourMode ReporterConfig::colourMode() const { return m_colourMode; }
  1639. std::map<std::string, std::string> const&
  1640. ReporterConfig::customOptions() const {
  1641. return m_customOptions;
  1642. }
  1643. ReporterConfig::~ReporterConfig() = default;
  1644. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  1645. std::vector<MessageInfo> const& _infoMessages,
  1646. Totals const& _totals )
  1647. : assertionResult( _assertionResult ),
  1648. infoMessages( _infoMessages ),
  1649. totals( _totals )
  1650. {
  1651. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  1652. if( assertionResult.hasMessage() ) {
  1653. // Copy message into messages list.
  1654. // !TBD This should have been done earlier, somewhere
  1655. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  1656. builder << assertionResult.getMessage();
  1657. builder.m_info.message = builder.m_stream.str();
  1658. infoMessages.push_back( builder.m_info );
  1659. }
  1660. }
  1661. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  1662. Counts const& _assertions,
  1663. double _durationInSeconds,
  1664. bool _missingAssertions )
  1665. : sectionInfo( _sectionInfo ),
  1666. assertions( _assertions ),
  1667. durationInSeconds( _durationInSeconds ),
  1668. missingAssertions( _missingAssertions )
  1669. {}
  1670. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  1671. Totals const& _totals,
  1672. std::string const& _stdOut,
  1673. std::string const& _stdErr,
  1674. bool _aborting )
  1675. : testInfo( &_testInfo ),
  1676. totals( _totals ),
  1677. stdOut( _stdOut ),
  1678. stdErr( _stdErr ),
  1679. aborting( _aborting )
  1680. {}
  1681. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  1682. Totals const& _totals,
  1683. bool _aborting )
  1684. : runInfo( _runInfo ),
  1685. totals( _totals ),
  1686. aborting( _aborting )
  1687. {}
  1688. IEventListener::~IEventListener() = default;
  1689. } // end namespace Catch
  1690. namespace Catch {
  1691. IReporterFactory::~IReporterFactory() = default;
  1692. EventListenerFactory::~EventListenerFactory() = default;
  1693. }
  1694. namespace Catch {
  1695. IReporterRegistry::~IReporterRegistry() = default;
  1696. }
  1697. namespace Catch {
  1698. ITestInvoker::~ITestInvoker() = default;
  1699. ITestCaseRegistry::~ITestCaseRegistry() = default;
  1700. }
  1701. namespace Catch {
  1702. AssertionHandler::AssertionHandler
  1703. ( StringRef macroName,
  1704. SourceLineInfo const& lineInfo,
  1705. StringRef capturedExpression,
  1706. ResultDisposition::Flags resultDisposition )
  1707. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  1708. m_resultCapture( getResultCapture() )
  1709. {}
  1710. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  1711. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  1712. }
  1713. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef message) {
  1714. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  1715. }
  1716. auto AssertionHandler::allowThrows() const -> bool {
  1717. return getCurrentContext().getConfig()->allowThrows();
  1718. }
  1719. void AssertionHandler::complete() {
  1720. setCompleted();
  1721. if( m_reaction.shouldDebugBreak ) {
  1722. // If you find your debugger stopping you here then go one level up on the
  1723. // call-stack for the code that caused it (typically a failed assertion)
  1724. // (To go back to the test and change execution, jump over the throw, next)
  1725. CATCH_BREAK_INTO_DEBUGGER();
  1726. }
  1727. if (m_reaction.shouldThrow) {
  1728. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1729. throw Catch::TestFailureException();
  1730. #else
  1731. CATCH_ERROR( "Test failure requires aborting test!" );
  1732. #endif
  1733. }
  1734. }
  1735. void AssertionHandler::setCompleted() {
  1736. m_completed = true;
  1737. }
  1738. void AssertionHandler::handleUnexpectedInflightException() {
  1739. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  1740. }
  1741. void AssertionHandler::handleExceptionThrownAsExpected() {
  1742. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  1743. }
  1744. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  1745. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  1746. }
  1747. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  1748. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  1749. }
  1750. void AssertionHandler::handleThrowingCallSkipped() {
  1751. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  1752. }
  1753. // This is the overload that takes a string and infers the Equals matcher from it
  1754. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  1755. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  1756. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  1757. }
  1758. } // namespace Catch
  1759. #include <algorithm>
  1760. namespace Catch {
  1761. namespace Detail {
  1762. bool CaseInsensitiveLess::operator()( StringRef lhs,
  1763. StringRef rhs ) const {
  1764. return std::lexicographical_compare(
  1765. lhs.begin(), lhs.end(),
  1766. rhs.begin(), rhs.end(),
  1767. []( char l, char r ) { return toLower( l ) < toLower( r ); } );
  1768. }
  1769. bool
  1770. CaseInsensitiveEqualTo::operator()( StringRef lhs,
  1771. StringRef rhs ) const {
  1772. return std::equal(
  1773. lhs.begin(), lhs.end(),
  1774. rhs.begin(), rhs.end(),
  1775. []( char l, char r ) { return toLower( l ) == toLower( r ); } );
  1776. }
  1777. } // namespace Detail
  1778. } // namespace Catch
  1779. #include <algorithm>
  1780. #include <ostream>
  1781. namespace {
  1782. bool isOptPrefix( char c ) {
  1783. return c == '-'
  1784. #ifdef CATCH_PLATFORM_WINDOWS
  1785. || c == '/'
  1786. #endif
  1787. ;
  1788. }
  1789. std::string normaliseOpt( std::string const& optName ) {
  1790. #ifdef CATCH_PLATFORM_WINDOWS
  1791. if ( optName[0] == '/' )
  1792. return "-" + optName.substr( 1 );
  1793. else
  1794. #endif
  1795. return optName;
  1796. }
  1797. } // namespace
  1798. namespace Catch {
  1799. namespace Clara {
  1800. namespace Detail {
  1801. void TokenStream::loadBuffer() {
  1802. m_tokenBuffer.clear();
  1803. // Skip any empty strings
  1804. while ( it != itEnd && it->empty() ) {
  1805. ++it;
  1806. }
  1807. if ( it != itEnd ) {
  1808. auto const& next = *it;
  1809. if ( isOptPrefix( next[0] ) ) {
  1810. auto delimiterPos = next.find_first_of( " :=" );
  1811. if ( delimiterPos != std::string::npos ) {
  1812. m_tokenBuffer.push_back(
  1813. { TokenType::Option,
  1814. next.substr( 0, delimiterPos ) } );
  1815. m_tokenBuffer.push_back(
  1816. { TokenType::Argument,
  1817. next.substr( delimiterPos + 1 ) } );
  1818. } else {
  1819. if ( next[1] != '-' && next.size() > 2 ) {
  1820. std::string opt = "- ";
  1821. for ( size_t i = 1; i < next.size(); ++i ) {
  1822. opt[1] = next[i];
  1823. m_tokenBuffer.push_back(
  1824. { TokenType::Option, opt } );
  1825. }
  1826. } else {
  1827. m_tokenBuffer.push_back(
  1828. { TokenType::Option, next } );
  1829. }
  1830. }
  1831. } else {
  1832. m_tokenBuffer.push_back(
  1833. { TokenType::Argument, next } );
  1834. }
  1835. }
  1836. }
  1837. TokenStream::TokenStream( Args const& args ):
  1838. TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  1839. TokenStream::TokenStream( Iterator it_, Iterator itEnd_ ):
  1840. it( it_ ), itEnd( itEnd_ ) {
  1841. loadBuffer();
  1842. }
  1843. TokenStream& TokenStream::operator++() {
  1844. if ( m_tokenBuffer.size() >= 2 ) {
  1845. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  1846. } else {
  1847. if ( it != itEnd )
  1848. ++it;
  1849. loadBuffer();
  1850. }
  1851. return *this;
  1852. }
  1853. ParserResult convertInto( std::string const& source,
  1854. std::string& target ) {
  1855. target = source;
  1856. return ParserResult::ok( ParseResultType::Matched );
  1857. }
  1858. ParserResult convertInto( std::string const& source,
  1859. bool& target ) {
  1860. std::string srcLC = toLower( source );
  1861. if ( srcLC == "y" || srcLC == "1" || srcLC == "true" ||
  1862. srcLC == "yes" || srcLC == "on" ) {
  1863. target = true;
  1864. } else if ( srcLC == "n" || srcLC == "0" || srcLC == "false" ||
  1865. srcLC == "no" || srcLC == "off" ) {
  1866. target = false;
  1867. } else {
  1868. return ParserResult::runtimeError(
  1869. "Expected a boolean value but did not recognise: '" +
  1870. source + '\'' );
  1871. }
  1872. return ParserResult::ok( ParseResultType::Matched );
  1873. }
  1874. size_t ParserBase::cardinality() const { return 1; }
  1875. InternalParseResult ParserBase::parse( Args const& args ) const {
  1876. return parse( args.exeName(), TokenStream( args ) );
  1877. }
  1878. ParseState::ParseState( ParseResultType type,
  1879. TokenStream const& remainingTokens ):
  1880. m_type( type ), m_remainingTokens( remainingTokens ) {}
  1881. ParserResult BoundFlagRef::setFlag( bool flag ) {
  1882. m_ref = flag;
  1883. return ParserResult::ok( ParseResultType::Matched );
  1884. }
  1885. ResultBase::~ResultBase() = default;
  1886. bool BoundRef::isContainer() const { return false; }
  1887. bool BoundRef::isFlag() const { return false; }
  1888. bool BoundFlagRefBase::isFlag() const { return true; }
  1889. } // namespace Detail
  1890. Detail::InternalParseResult Arg::parse(std::string const&,
  1891. Detail::TokenStream const& tokens) const {
  1892. auto validationResult = validate();
  1893. if (!validationResult)
  1894. return Detail::InternalParseResult(validationResult);
  1895. auto remainingTokens = tokens;
  1896. auto const& token = *remainingTokens;
  1897. if (token.type != Detail::TokenType::Argument)
  1898. return Detail::InternalParseResult::ok(Detail::ParseState(
  1899. ParseResultType::NoMatch, remainingTokens));
  1900. assert(!m_ref->isFlag());
  1901. auto valueRef =
  1902. static_cast<Detail::BoundValueRefBase*>(m_ref.get());
  1903. auto result = valueRef->setValue(remainingTokens->token);
  1904. if (!result)
  1905. return Detail::InternalParseResult(result);
  1906. else
  1907. return Detail::InternalParseResult::ok(Detail::ParseState(
  1908. ParseResultType::Matched, ++remainingTokens));
  1909. }
  1910. Opt::Opt(bool& ref) :
  1911. ParserRefImpl(std::make_shared<Detail::BoundFlagRef>(ref)) {}
  1912. std::vector<Detail::HelpColumns> Opt::getHelpColumns() const {
  1913. std::ostringstream oss;
  1914. bool first = true;
  1915. for (auto const& opt : m_optNames) {
  1916. if (first)
  1917. first = false;
  1918. else
  1919. oss << ", ";
  1920. oss << opt;
  1921. }
  1922. if (!m_hint.empty())
  1923. oss << " <" << m_hint << '>';
  1924. return { { oss.str(), m_description } };
  1925. }
  1926. bool Opt::isMatch(std::string const& optToken) const {
  1927. auto normalisedToken = normaliseOpt(optToken);
  1928. for (auto const& name : m_optNames) {
  1929. if (normaliseOpt(name) == normalisedToken)
  1930. return true;
  1931. }
  1932. return false;
  1933. }
  1934. Detail::InternalParseResult Opt::parse(std::string const&,
  1935. Detail::TokenStream const& tokens) const {
  1936. auto validationResult = validate();
  1937. if (!validationResult)
  1938. return Detail::InternalParseResult(validationResult);
  1939. auto remainingTokens = tokens;
  1940. if (remainingTokens &&
  1941. remainingTokens->type == Detail::TokenType::Option) {
  1942. auto const& token = *remainingTokens;
  1943. if (isMatch(token.token)) {
  1944. if (m_ref->isFlag()) {
  1945. auto flagRef =
  1946. static_cast<Detail::BoundFlagRefBase*>(
  1947. m_ref.get());
  1948. auto result = flagRef->setFlag(true);
  1949. if (!result)
  1950. return Detail::InternalParseResult(result);
  1951. if (result.value() ==
  1952. ParseResultType::ShortCircuitAll)
  1953. return Detail::InternalParseResult::ok(Detail::ParseState(
  1954. result.value(), remainingTokens));
  1955. } else {
  1956. auto valueRef =
  1957. static_cast<Detail::BoundValueRefBase*>(
  1958. m_ref.get());
  1959. ++remainingTokens;
  1960. if (!remainingTokens)
  1961. return Detail::InternalParseResult::runtimeError(
  1962. "Expected argument following " +
  1963. token.token);
  1964. auto const& argToken = *remainingTokens;
  1965. if (argToken.type != Detail::TokenType::Argument)
  1966. return Detail::InternalParseResult::runtimeError(
  1967. "Expected argument following " +
  1968. token.token);
  1969. const auto result = valueRef->setValue(argToken.token);
  1970. if (!result)
  1971. return Detail::InternalParseResult(result);
  1972. if (result.value() ==
  1973. ParseResultType::ShortCircuitAll)
  1974. return Detail::InternalParseResult::ok(Detail::ParseState(
  1975. result.value(), remainingTokens));
  1976. }
  1977. return Detail::InternalParseResult::ok(Detail::ParseState(
  1978. ParseResultType::Matched, ++remainingTokens));
  1979. }
  1980. }
  1981. return Detail::InternalParseResult::ok(
  1982. Detail::ParseState(ParseResultType::NoMatch, remainingTokens));
  1983. }
  1984. Detail::Result Opt::validate() const {
  1985. if (m_optNames.empty())
  1986. return Detail::Result::logicError("No options supplied to Opt");
  1987. for (auto const& name : m_optNames) {
  1988. if (name.empty())
  1989. return Detail::Result::logicError(
  1990. "Option name cannot be empty");
  1991. #ifdef CATCH_PLATFORM_WINDOWS
  1992. if (name[0] != '-' && name[0] != '/')
  1993. return Detail::Result::logicError(
  1994. "Option name must begin with '-' or '/'");
  1995. #else
  1996. if (name[0] != '-')
  1997. return Detail::Result::logicError(
  1998. "Option name must begin with '-'");
  1999. #endif
  2000. }
  2001. return ParserRefImpl::validate();
  2002. }
  2003. ExeName::ExeName() :
  2004. m_name(std::make_shared<std::string>("<executable>")) {}
  2005. ExeName::ExeName(std::string& ref) : ExeName() {
  2006. m_ref = std::make_shared<Detail::BoundValueRef<std::string>>(ref);
  2007. }
  2008. Detail::InternalParseResult
  2009. ExeName::parse(std::string const&,
  2010. Detail::TokenStream const& tokens) const {
  2011. return Detail::InternalParseResult::ok(
  2012. Detail::ParseState(ParseResultType::NoMatch, tokens));
  2013. }
  2014. ParserResult ExeName::set(std::string const& newName) {
  2015. auto lastSlash = newName.find_last_of("\\/");
  2016. auto filename = (lastSlash == std::string::npos)
  2017. ? newName
  2018. : newName.substr(lastSlash + 1);
  2019. *m_name = filename;
  2020. if (m_ref)
  2021. return m_ref->setValue(filename);
  2022. else
  2023. return ParserResult::ok(ParseResultType::Matched);
  2024. }
  2025. Parser& Parser::operator|=( Parser const& other ) {
  2026. m_options.insert( m_options.end(),
  2027. other.m_options.begin(),
  2028. other.m_options.end() );
  2029. m_args.insert(
  2030. m_args.end(), other.m_args.begin(), other.m_args.end() );
  2031. return *this;
  2032. }
  2033. std::vector<Detail::HelpColumns> Parser::getHelpColumns() const {
  2034. std::vector<Detail::HelpColumns> cols;
  2035. for ( auto const& o : m_options ) {
  2036. auto childCols = o.getHelpColumns();
  2037. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  2038. }
  2039. return cols;
  2040. }
  2041. void Parser::writeToStream( std::ostream& os ) const {
  2042. if ( !m_exeName.name().empty() ) {
  2043. os << "usage:\n"
  2044. << " " << m_exeName.name() << ' ';
  2045. bool required = true, first = true;
  2046. for ( auto const& arg : m_args ) {
  2047. if ( first )
  2048. first = false;
  2049. else
  2050. os << ' ';
  2051. if ( arg.isOptional() && required ) {
  2052. os << '[';
  2053. required = false;
  2054. }
  2055. os << '<' << arg.hint() << '>';
  2056. if ( arg.cardinality() == 0 )
  2057. os << " ... ";
  2058. }
  2059. if ( !required )
  2060. os << ']';
  2061. if ( !m_options.empty() )
  2062. os << " options";
  2063. os << "\n\nwhere options are:\n";
  2064. }
  2065. auto rows = getHelpColumns();
  2066. size_t consoleWidth = CATCH_CONFIG_CONSOLE_WIDTH;
  2067. size_t optWidth = 0;
  2068. for ( auto const& cols : rows )
  2069. optWidth = ( std::max )( optWidth, cols.left.size() + 2 );
  2070. optWidth = ( std::min )( optWidth, consoleWidth / 2 );
  2071. for ( auto const& cols : rows ) {
  2072. auto row = TextFlow::Column( cols.left )
  2073. .width( optWidth )
  2074. .indent( 2 ) +
  2075. TextFlow::Spacer( 4 ) +
  2076. TextFlow::Column( cols.right )
  2077. .width( consoleWidth - 7 - optWidth );
  2078. os << row << '\n';
  2079. }
  2080. }
  2081. Detail::Result Parser::validate() const {
  2082. for ( auto const& opt : m_options ) {
  2083. auto result = opt.validate();
  2084. if ( !result )
  2085. return result;
  2086. }
  2087. for ( auto const& arg : m_args ) {
  2088. auto result = arg.validate();
  2089. if ( !result )
  2090. return result;
  2091. }
  2092. return Detail::Result::ok();
  2093. }
  2094. Detail::InternalParseResult
  2095. Parser::parse( std::string const& exeName,
  2096. Detail::TokenStream const& tokens ) const {
  2097. struct ParserInfo {
  2098. ParserBase const* parser = nullptr;
  2099. size_t count = 0;
  2100. };
  2101. std::vector<ParserInfo> parseInfos;
  2102. parseInfos.reserve( m_options.size() + m_args.size() );
  2103. for ( auto const& opt : m_options ) {
  2104. parseInfos.push_back( { &opt, 0 } );
  2105. }
  2106. for ( auto const& arg : m_args ) {
  2107. parseInfos.push_back( { &arg, 0 } );
  2108. }
  2109. m_exeName.set( exeName );
  2110. auto result = Detail::InternalParseResult::ok(
  2111. Detail::ParseState( ParseResultType::NoMatch, tokens ) );
  2112. while ( result.value().remainingTokens() ) {
  2113. bool tokenParsed = false;
  2114. for ( auto& parseInfo : parseInfos ) {
  2115. if ( parseInfo.parser->cardinality() == 0 ||
  2116. parseInfo.count < parseInfo.parser->cardinality() ) {
  2117. result = parseInfo.parser->parse(
  2118. exeName, result.value().remainingTokens() );
  2119. if ( !result )
  2120. return result;
  2121. if ( result.value().type() !=
  2122. ParseResultType::NoMatch ) {
  2123. tokenParsed = true;
  2124. ++parseInfo.count;
  2125. break;
  2126. }
  2127. }
  2128. }
  2129. if ( result.value().type() == ParseResultType::ShortCircuitAll )
  2130. return result;
  2131. if ( !tokenParsed )
  2132. return Detail::InternalParseResult::runtimeError(
  2133. "Unrecognised token: " +
  2134. result.value().remainingTokens()->token );
  2135. }
  2136. // !TBD Check missing required options
  2137. return result;
  2138. }
  2139. Args::Args(int argc, char const* const* argv) :
  2140. m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
  2141. Args::Args(std::initializer_list<std::string> args) :
  2142. m_exeName(*args.begin()),
  2143. m_args(args.begin() + 1, args.end()) {}
  2144. Help::Help( bool& showHelpFlag ):
  2145. Opt( [&]( bool flag ) {
  2146. showHelpFlag = flag;
  2147. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  2148. } ) {
  2149. static_cast<Opt&> ( *this )(
  2150. "display usage information" )["-?"]["-h"]["--help"]
  2151. .optional();
  2152. }
  2153. } // namespace Clara
  2154. } // namespace Catch
  2155. #include <fstream>
  2156. #include <string>
  2157. namespace Catch {
  2158. Clara::Parser makeCommandLineParser( ConfigData& config ) {
  2159. using namespace Clara;
  2160. auto const setWarning = [&]( std::string const& warning ) {
  2161. if ( warning == "NoAssertions" ) {
  2162. config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::NoAssertions);
  2163. return ParserResult::ok( ParseResultType::Matched );
  2164. } else if ( warning == "UnmatchedTestSpec" ) {
  2165. config.warnings = static_cast<WarnAbout::What>(config.warnings | WarnAbout::UnmatchedTestSpec);
  2166. return ParserResult::ok( ParseResultType::Matched );
  2167. }
  2168. return ParserResult ::runtimeError(
  2169. "Unrecognised warning option: '" + warning + '\'' );
  2170. };
  2171. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  2172. std::ifstream f( filename.c_str() );
  2173. if( !f.is_open() )
  2174. return ParserResult::runtimeError( "Unable to load input file: '" + filename + '\'' );
  2175. std::string line;
  2176. while( std::getline( f, line ) ) {
  2177. line = trim(line);
  2178. if( !line.empty() && !startsWith( line, '#' ) ) {
  2179. if( !startsWith( line, '"' ) )
  2180. line = '"' + line + '"';
  2181. config.testsOrTags.push_back( line );
  2182. config.testsOrTags.emplace_back( "," );
  2183. }
  2184. }
  2185. //Remove comma in the end
  2186. if(!config.testsOrTags.empty())
  2187. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  2188. return ParserResult::ok( ParseResultType::Matched );
  2189. };
  2190. auto const setTestOrder = [&]( std::string const& order ) {
  2191. if( startsWith( "declared", order ) )
  2192. config.runOrder = TestRunOrder::Declared;
  2193. else if( startsWith( "lexical", order ) )
  2194. config.runOrder = TestRunOrder::LexicographicallySorted;
  2195. else if( startsWith( "random", order ) )
  2196. config.runOrder = TestRunOrder::Randomized;
  2197. else
  2198. return ParserResult::runtimeError( "Unrecognised ordering: '" + order + '\'' );
  2199. return ParserResult::ok( ParseResultType::Matched );
  2200. };
  2201. auto const setRngSeed = [&]( std::string const& seed ) {
  2202. if( seed == "time" ) {
  2203. config.rngSeed = generateRandomSeed(GenerateFrom::Time);
  2204. return ParserResult::ok(ParseResultType::Matched);
  2205. } else if (seed == "random-device") {
  2206. config.rngSeed = generateRandomSeed(GenerateFrom::RandomDevice);
  2207. return ParserResult::ok(ParseResultType::Matched);
  2208. }
  2209. CATCH_TRY {
  2210. std::size_t parsedTo = 0;
  2211. unsigned long parsedSeed = std::stoul(seed, &parsedTo, 0);
  2212. if (parsedTo != seed.size()) {
  2213. return ParserResult::runtimeError("Could not parse '" + seed + "' as seed");
  2214. }
  2215. // TODO: Ideally we could parse unsigned int directly,
  2216. // but the stdlib doesn't provide helper for that
  2217. // type. After this is refactored to use fixed size
  2218. // type, we should check the parsed value is in range
  2219. // of the underlying type.
  2220. config.rngSeed = static_cast<unsigned int>(parsedSeed);
  2221. return ParserResult::ok(ParseResultType::Matched);
  2222. } CATCH_CATCH_ANON(std::exception const&) {
  2223. return ParserResult::runtimeError("Could not parse '" + seed + "' as seed");
  2224. }
  2225. };
  2226. auto const setDefaultColourMode = [&]( std::string const& colourMode ) {
  2227. Optional<ColourMode> maybeMode = Catch::Detail::stringToColourMode(toLower( colourMode ));
  2228. if ( !maybeMode ) {
  2229. return ParserResult::runtimeError(
  2230. "colour mode must be one of: default, ansi, win32, "
  2231. "or none. '" +
  2232. colourMode + "' is not recognised" );
  2233. }
  2234. auto mode = *maybeMode;
  2235. if ( !isColourImplAvailable( mode ) ) {
  2236. return ParserResult::runtimeError(
  2237. "colour mode '" + colourMode +
  2238. "' is not supported in this binary" );
  2239. }
  2240. config.defaultColourMode = mode;
  2241. return ParserResult::ok( ParseResultType::Matched );
  2242. };
  2243. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  2244. auto keypressLc = toLower( keypress );
  2245. if (keypressLc == "never")
  2246. config.waitForKeypress = WaitForKeypress::Never;
  2247. else if( keypressLc == "start" )
  2248. config.waitForKeypress = WaitForKeypress::BeforeStart;
  2249. else if( keypressLc == "exit" )
  2250. config.waitForKeypress = WaitForKeypress::BeforeExit;
  2251. else if( keypressLc == "both" )
  2252. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  2253. else
  2254. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  2255. return ParserResult::ok( ParseResultType::Matched );
  2256. };
  2257. auto const setVerbosity = [&]( std::string const& verbosity ) {
  2258. auto lcVerbosity = toLower( verbosity );
  2259. if( lcVerbosity == "quiet" )
  2260. config.verbosity = Verbosity::Quiet;
  2261. else if( lcVerbosity == "normal" )
  2262. config.verbosity = Verbosity::Normal;
  2263. else if( lcVerbosity == "high" )
  2264. config.verbosity = Verbosity::High;
  2265. else
  2266. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + '\'' );
  2267. return ParserResult::ok( ParseResultType::Matched );
  2268. };
  2269. auto const setReporter = [&]( std::string const& userReporterSpec ) {
  2270. if ( userReporterSpec.empty() ) {
  2271. return ParserResult::runtimeError( "Received empty reporter spec." );
  2272. }
  2273. Optional<ReporterSpec> parsed =
  2274. parseReporterSpec( userReporterSpec );
  2275. if ( !parsed ) {
  2276. return ParserResult::runtimeError(
  2277. "Could not parse reporter spec '" + userReporterSpec +
  2278. "'" );
  2279. }
  2280. auto const& reporterSpec = *parsed;
  2281. IReporterRegistry::FactoryMap const& factories =
  2282. getRegistryHub().getReporterRegistry().getFactories();
  2283. auto result = factories.find( reporterSpec.name() );
  2284. if ( result == factories.end() ) {
  2285. return ParserResult::runtimeError(
  2286. "Unrecognized reporter, '" + reporterSpec.name() +
  2287. "'. Check available with --list-reporters" );
  2288. }
  2289. const bool hadOutputFile = reporterSpec.outputFile().some();
  2290. config.reporterSpecifications.push_back( CATCH_MOVE( *parsed ) );
  2291. // It would be enough to check this only once at the very end, but
  2292. // there is not a place where we could call this check, so do it
  2293. // every time it could fail. For valid inputs, this is still called
  2294. // at most once.
  2295. if (!hadOutputFile) {
  2296. int n_reporters_without_file = 0;
  2297. for (auto const& spec : config.reporterSpecifications) {
  2298. if (spec.outputFile().none()) {
  2299. n_reporters_without_file++;
  2300. }
  2301. }
  2302. if (n_reporters_without_file > 1) {
  2303. return ParserResult::runtimeError( "Only one reporter may have unspecified output file." );
  2304. }
  2305. }
  2306. return ParserResult::ok( ParseResultType::Matched );
  2307. };
  2308. auto const setShardCount = [&]( std::string const& shardCount ) {
  2309. CATCH_TRY{
  2310. std::size_t parsedTo = 0;
  2311. int64_t parsedCount = std::stoll(shardCount, &parsedTo, 0);
  2312. if (parsedTo != shardCount.size()) {
  2313. return ParserResult::runtimeError("Could not parse '" + shardCount + "' as shard count");
  2314. }
  2315. if (parsedCount <= 0) {
  2316. return ParserResult::runtimeError("Shard count must be a positive number");
  2317. }
  2318. config.shardCount = static_cast<unsigned int>(parsedCount);
  2319. return ParserResult::ok(ParseResultType::Matched);
  2320. } CATCH_CATCH_ANON(std::exception const&) {
  2321. return ParserResult::runtimeError("Could not parse '" + shardCount + "' as shard count");
  2322. }
  2323. };
  2324. auto const setShardIndex = [&](std::string const& shardIndex) {
  2325. CATCH_TRY{
  2326. std::size_t parsedTo = 0;
  2327. int64_t parsedIndex = std::stoll(shardIndex, &parsedTo, 0);
  2328. if (parsedTo != shardIndex.size()) {
  2329. return ParserResult::runtimeError("Could not parse '" + shardIndex + "' as shard index");
  2330. }
  2331. if (parsedIndex < 0) {
  2332. return ParserResult::runtimeError("Shard index must be a non-negative number");
  2333. }
  2334. config.shardIndex = static_cast<unsigned int>(parsedIndex);
  2335. return ParserResult::ok(ParseResultType::Matched);
  2336. } CATCH_CATCH_ANON(std::exception const&) {
  2337. return ParserResult::runtimeError("Could not parse '" + shardIndex + "' as shard index");
  2338. }
  2339. };
  2340. auto cli
  2341. = ExeName( config.processName )
  2342. | Help( config.showHelp )
  2343. | Opt( config.showSuccessfulTests )
  2344. ["-s"]["--success"]
  2345. ( "include successful tests in output" )
  2346. | Opt( config.shouldDebugBreak )
  2347. ["-b"]["--break"]
  2348. ( "break into debugger on failure" )
  2349. | Opt( config.noThrow )
  2350. ["-e"]["--nothrow"]
  2351. ( "skip exception tests" )
  2352. | Opt( config.showInvisibles )
  2353. ["-i"]["--invisibles"]
  2354. ( "show invisibles (tabs, newlines)" )
  2355. | Opt( config.defaultOutputFilename, "filename" )
  2356. ["-o"]["--out"]
  2357. ( "default output filename" )
  2358. | Opt( accept_many, setReporter, "name[::key=value]*" )
  2359. ["-r"]["--reporter"]
  2360. ( "reporter to use (defaults to console)" )
  2361. | Opt( config.name, "name" )
  2362. ["-n"]["--name"]
  2363. ( "suite name" )
  2364. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  2365. ["-a"]["--abort"]
  2366. ( "abort at first failure" )
  2367. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  2368. ["-x"]["--abortx"]
  2369. ( "abort after x failures" )
  2370. | Opt( accept_many, setWarning, "warning name" )
  2371. ["-w"]["--warn"]
  2372. ( "enable warnings" )
  2373. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  2374. ["-d"]["--durations"]
  2375. ( "show test durations" )
  2376. | Opt( config.minDuration, "seconds" )
  2377. ["-D"]["--min-duration"]
  2378. ( "show test durations for tests taking at least the given number of seconds" )
  2379. | Opt( loadTestNamesFromFile, "filename" )
  2380. ["-f"]["--input-file"]
  2381. ( "load test names to run from a file" )
  2382. | Opt( config.filenamesAsTags )
  2383. ["-#"]["--filenames-as-tags"]
  2384. ( "adds a tag for the filename" )
  2385. | Opt( config.sectionsToRun, "section name" )
  2386. ["-c"]["--section"]
  2387. ( "specify section to run" )
  2388. | Opt( setVerbosity, "quiet|normal|high" )
  2389. ["-v"]["--verbosity"]
  2390. ( "set output verbosity" )
  2391. | Opt( config.listTests )
  2392. ["--list-tests"]
  2393. ( "list all/matching test cases" )
  2394. | Opt( config.listTags )
  2395. ["--list-tags"]
  2396. ( "list all/matching tags" )
  2397. | Opt( config.listReporters )
  2398. ["--list-reporters"]
  2399. ( "list all available reporters" )
  2400. | Opt( config.listListeners )
  2401. ["--list-listeners"]
  2402. ( "list all listeners" )
  2403. | Opt( setTestOrder, "decl|lex|rand" )
  2404. ["--order"]
  2405. ( "test case order (defaults to decl)" )
  2406. | Opt( setRngSeed, "'time'|'random-device'|number" )
  2407. ["--rng-seed"]
  2408. ( "set a specific seed for random numbers" )
  2409. | Opt( setDefaultColourMode, "ansi|win32|none|default" )
  2410. ["--colour-mode"]
  2411. ( "what color mode should be used as default" )
  2412. | Opt( config.libIdentify )
  2413. ["--libidentify"]
  2414. ( "report name and version according to libidentify standard" )
  2415. | Opt( setWaitForKeypress, "never|start|exit|both" )
  2416. ["--wait-for-keypress"]
  2417. ( "waits for a keypress before exiting" )
  2418. | Opt( config.skipBenchmarks)
  2419. ["--skip-benchmarks"]
  2420. ( "disable running benchmarks")
  2421. | Opt( config.benchmarkSamples, "samples" )
  2422. ["--benchmark-samples"]
  2423. ( "number of samples to collect (default: 100)" )
  2424. | Opt( config.benchmarkResamples, "resamples" )
  2425. ["--benchmark-resamples"]
  2426. ( "number of resamples for the bootstrap (default: 100000)" )
  2427. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  2428. ["--benchmark-confidence-interval"]
  2429. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  2430. | Opt( config.benchmarkNoAnalysis )
  2431. ["--benchmark-no-analysis"]
  2432. ( "perform only measurements; do not perform any analysis" )
  2433. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  2434. ["--benchmark-warmup-time"]
  2435. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  2436. | Opt( setShardCount, "shard count" )
  2437. ["--shard-count"]
  2438. ( "split the tests to execute into this many groups" )
  2439. | Opt( setShardIndex, "shard index" )
  2440. ["--shard-index"]
  2441. ( "index of the group of tests to execute (see --shard-count)" ) |
  2442. Opt( config.allowZeroTests )
  2443. ["--allow-running-no-tests"]
  2444. ( "Treat 'No tests run' as a success" )
  2445. | Arg( config.testsOrTags, "test name|pattern|tags" )
  2446. ( "which test or tests to use" );
  2447. return cli;
  2448. }
  2449. } // end namespace Catch
  2450. #if defined(__clang__)
  2451. # pragma clang diagnostic push
  2452. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  2453. #endif
  2454. #include <cassert>
  2455. #include <ostream>
  2456. #include <utility>
  2457. namespace Catch {
  2458. ColourImpl::~ColourImpl() = default;
  2459. ColourImpl::ColourGuard ColourImpl::guardColour( Colour::Code colourCode ) {
  2460. return ColourGuard(colourCode, this );
  2461. }
  2462. void ColourImpl::ColourGuard::engageImpl( std::ostream& stream ) {
  2463. assert( &stream == &m_colourImpl->m_stream->stream() &&
  2464. "Engaging colour guard for different stream than used by the "
  2465. "parent colour implementation" );
  2466. static_cast<void>( stream );
  2467. m_engaged = true;
  2468. m_colourImpl->use( m_code );
  2469. }
  2470. ColourImpl::ColourGuard::ColourGuard( Colour::Code code,
  2471. ColourImpl const* colour ):
  2472. m_colourImpl( colour ), m_code( code ) {
  2473. }
  2474. ColourImpl::ColourGuard::ColourGuard( ColourGuard&& rhs ) noexcept:
  2475. m_colourImpl( rhs.m_colourImpl ),
  2476. m_code( rhs.m_code ),
  2477. m_engaged( rhs.m_engaged ) {
  2478. rhs.m_engaged = false;
  2479. }
  2480. ColourImpl::ColourGuard&
  2481. ColourImpl::ColourGuard::operator=( ColourGuard&& rhs ) noexcept {
  2482. using std::swap;
  2483. swap( m_colourImpl, rhs.m_colourImpl );
  2484. swap( m_code, rhs.m_code );
  2485. swap( m_engaged, rhs.m_engaged );
  2486. return *this;
  2487. }
  2488. ColourImpl::ColourGuard::~ColourGuard() {
  2489. if ( m_engaged ) {
  2490. m_colourImpl->use( Colour::None );
  2491. }
  2492. }
  2493. ColourImpl::ColourGuard&
  2494. ColourImpl::ColourGuard::engage( std::ostream& stream ) & {
  2495. engageImpl( stream );
  2496. return *this;
  2497. }
  2498. ColourImpl::ColourGuard&&
  2499. ColourImpl::ColourGuard::engage( std::ostream& stream ) && {
  2500. engageImpl( stream );
  2501. return CATCH_MOVE(*this);
  2502. }
  2503. namespace {
  2504. //! A do-nothing implementation of colour, used as fallback for unknown
  2505. //! platforms, and when the user asks to deactivate all colours.
  2506. class NoColourImpl : public ColourImpl {
  2507. public:
  2508. NoColourImpl( IStream* stream ): ColourImpl( stream ) {}
  2509. private:
  2510. void use( Colour::Code ) const override {}
  2511. };
  2512. } // namespace
  2513. } // namespace Catch
  2514. #if defined ( CATCH_CONFIG_COLOUR_WIN32 ) /////////////////////////////////////////
  2515. namespace Catch {
  2516. namespace {
  2517. class Win32ColourImpl : public ColourImpl {
  2518. public:
  2519. Win32ColourImpl(IStream* stream):
  2520. ColourImpl(stream) {
  2521. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  2522. GetConsoleScreenBufferInfo( GetStdHandle( STD_OUTPUT_HANDLE ),
  2523. &csbiInfo );
  2524. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  2525. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  2526. }
  2527. static bool useImplementationForStream(IStream const& stream) {
  2528. // Win32 text colour APIs can only be used on console streams
  2529. // We cannot check that the output hasn't been redirected,
  2530. // so we just check that the original stream is console stream.
  2531. return stream.isConsole();
  2532. }
  2533. private:
  2534. void use( Colour::Code _colourCode ) const override {
  2535. switch( _colourCode ) {
  2536. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  2537. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  2538. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  2539. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  2540. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  2541. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  2542. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  2543. case Colour::Grey: return setTextAttribute( 0 );
  2544. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  2545. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  2546. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  2547. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  2548. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  2549. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  2550. default:
  2551. CATCH_ERROR( "Unknown colour requested" );
  2552. }
  2553. }
  2554. void setTextAttribute( WORD _textAttribute ) const {
  2555. SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),
  2556. _textAttribute |
  2557. originalBackgroundAttributes );
  2558. }
  2559. WORD originalForegroundAttributes;
  2560. WORD originalBackgroundAttributes;
  2561. };
  2562. } // end anon namespace
  2563. } // end namespace Catch
  2564. #endif // Windows/ ANSI/ None
  2565. #if defined( CATCH_PLATFORM_LINUX ) || defined( CATCH_PLATFORM_MAC )
  2566. # define CATCH_INTERNAL_HAS_ISATTY
  2567. # include <unistd.h>
  2568. #endif
  2569. namespace Catch {
  2570. namespace {
  2571. class ANSIColourImpl : public ColourImpl {
  2572. public:
  2573. ANSIColourImpl( IStream* stream ): ColourImpl( stream ) {}
  2574. static bool useImplementationForStream(IStream const& stream) {
  2575. // This is kinda messy due to trying to support a bunch of
  2576. // different platforms at once.
  2577. // The basic idea is that if we are asked to do autodetection (as
  2578. // opposed to being told to use posixy colours outright), then we
  2579. // only want to use the colours if we are writing to console.
  2580. // However, console might be redirected, so we make an attempt at
  2581. // checking for that on platforms where we know how to do that.
  2582. bool useColour = stream.isConsole();
  2583. #if defined( CATCH_INTERNAL_HAS_ISATTY ) && \
  2584. !( defined( __DJGPP__ ) && defined( __STRICT_ANSI__ ) )
  2585. ErrnoGuard _; // for isatty
  2586. useColour = useColour && isatty( STDOUT_FILENO );
  2587. # endif
  2588. # if defined( CATCH_PLATFORM_MAC ) || defined( CATCH_PLATFORM_IPHONE )
  2589. useColour = useColour && !isDebuggerActive();
  2590. # endif
  2591. return useColour;
  2592. }
  2593. private:
  2594. void use( Colour::Code _colourCode ) const override {
  2595. auto setColour = [&out =
  2596. m_stream->stream()]( char const* escapeCode ) {
  2597. // The escape sequence must be flushed to console, otherwise
  2598. // if stdin and stderr are intermixed, we'd get accidentally
  2599. // coloured output.
  2600. out << '\033' << escapeCode << std::flush;
  2601. };
  2602. switch( _colourCode ) {
  2603. case Colour::None:
  2604. case Colour::White: return setColour( "[0m" );
  2605. case Colour::Red: return setColour( "[0;31m" );
  2606. case Colour::Green: return setColour( "[0;32m" );
  2607. case Colour::Blue: return setColour( "[0;34m" );
  2608. case Colour::Cyan: return setColour( "[0;36m" );
  2609. case Colour::Yellow: return setColour( "[0;33m" );
  2610. case Colour::Grey: return setColour( "[1;30m" );
  2611. case Colour::LightGrey: return setColour( "[0;37m" );
  2612. case Colour::BrightRed: return setColour( "[1;31m" );
  2613. case Colour::BrightGreen: return setColour( "[1;32m" );
  2614. case Colour::BrightWhite: return setColour( "[1;37m" );
  2615. case Colour::BrightYellow: return setColour( "[1;33m" );
  2616. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  2617. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  2618. }
  2619. }
  2620. };
  2621. } // end anon namespace
  2622. } // end namespace Catch
  2623. namespace Catch {
  2624. Detail::unique_ptr<ColourImpl> makeColourImpl( ColourMode implSelection,
  2625. IStream* stream ) {
  2626. #if defined( CATCH_CONFIG_COLOUR_WIN32 )
  2627. if ( implSelection == ColourMode::Win32 ) {
  2628. return Detail::make_unique<Win32ColourImpl>( stream );
  2629. }
  2630. #endif
  2631. if ( implSelection == ColourMode::ANSI ) {
  2632. return Detail::make_unique<ANSIColourImpl>( stream );
  2633. }
  2634. if ( implSelection == ColourMode::None ) {
  2635. return Detail::make_unique<NoColourImpl>( stream );
  2636. }
  2637. if ( implSelection == ColourMode::PlatformDefault) {
  2638. #if defined( CATCH_CONFIG_COLOUR_WIN32 )
  2639. if ( Win32ColourImpl::useImplementationForStream( *stream ) ) {
  2640. return Detail::make_unique<Win32ColourImpl>( stream );
  2641. }
  2642. #endif
  2643. if ( ANSIColourImpl::useImplementationForStream( *stream ) ) {
  2644. return Detail::make_unique<ANSIColourImpl>( stream );
  2645. }
  2646. return Detail::make_unique<NoColourImpl>( stream );
  2647. }
  2648. CATCH_ERROR( "Could not create colour impl for selection " << static_cast<int>(implSelection) );
  2649. }
  2650. bool isColourImplAvailable( ColourMode colourSelection ) {
  2651. switch ( colourSelection ) {
  2652. #if defined( CATCH_CONFIG_COLOUR_WIN32 )
  2653. case ColourMode::Win32:
  2654. #endif
  2655. case ColourMode::ANSI:
  2656. case ColourMode::None:
  2657. case ColourMode::PlatformDefault:
  2658. return true;
  2659. default:
  2660. return false;
  2661. }
  2662. }
  2663. } // end namespace Catch
  2664. #if defined(__clang__)
  2665. # pragma clang diagnostic pop
  2666. #endif
  2667. namespace Catch {
  2668. class Context : public IMutableContext, private Detail::NonCopyable {
  2669. public: // IContext
  2670. IResultCapture* getResultCapture() override {
  2671. return m_resultCapture;
  2672. }
  2673. IConfig const* getConfig() const override {
  2674. return m_config;
  2675. }
  2676. ~Context() override;
  2677. public: // IMutableContext
  2678. void setResultCapture( IResultCapture* resultCapture ) override {
  2679. m_resultCapture = resultCapture;
  2680. }
  2681. void setConfig( IConfig const* config ) override {
  2682. m_config = config;
  2683. }
  2684. friend IMutableContext& getCurrentMutableContext();
  2685. private:
  2686. IConfig const* m_config = nullptr;
  2687. IResultCapture* m_resultCapture = nullptr;
  2688. };
  2689. IMutableContext *IMutableContext::currentContext = nullptr;
  2690. void IMutableContext::createContext()
  2691. {
  2692. currentContext = new Context();
  2693. }
  2694. void cleanUpContext() {
  2695. delete IMutableContext::currentContext;
  2696. IMutableContext::currentContext = nullptr;
  2697. }
  2698. IContext::~IContext() = default;
  2699. IMutableContext::~IMutableContext() = default;
  2700. Context::~Context() = default;
  2701. SimplePcg32& sharedRng() {
  2702. static SimplePcg32 s_rng;
  2703. return s_rng;
  2704. }
  2705. }
  2706. #include <ostream>
  2707. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  2708. #include <android/log.h>
  2709. namespace Catch {
  2710. void writeToDebugConsole( std::string const& text ) {
  2711. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  2712. }
  2713. }
  2714. #elif defined(CATCH_PLATFORM_WINDOWS)
  2715. namespace Catch {
  2716. void writeToDebugConsole( std::string const& text ) {
  2717. ::OutputDebugStringA( text.c_str() );
  2718. }
  2719. }
  2720. #else
  2721. namespace Catch {
  2722. void writeToDebugConsole( std::string const& text ) {
  2723. // !TBD: Need a version for Mac/ XCode and other IDEs
  2724. Catch::cout() << text;
  2725. }
  2726. }
  2727. #endif // Platform
  2728. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  2729. # include <cassert>
  2730. # include <sys/types.h>
  2731. # include <unistd.h>
  2732. # include <cstddef>
  2733. # include <ostream>
  2734. #ifdef __apple_build_version__
  2735. // These headers will only compile with AppleClang (XCode)
  2736. // For other compilers (Clang, GCC, ... ) we need to exclude them
  2737. # include <sys/sysctl.h>
  2738. #endif
  2739. namespace Catch {
  2740. #ifdef __apple_build_version__
  2741. // The following function is taken directly from the following technical note:
  2742. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  2743. // Returns true if the current process is being debugged (either
  2744. // running under the debugger or has a debugger attached post facto).
  2745. bool isDebuggerActive(){
  2746. int mib[4];
  2747. struct kinfo_proc info;
  2748. std::size_t size;
  2749. // Initialize the flags so that, if sysctl fails for some bizarre
  2750. // reason, we get a predictable result.
  2751. info.kp_proc.p_flag = 0;
  2752. // Initialize mib, which tells sysctl the info we want, in this case
  2753. // we're looking for information about a specific process ID.
  2754. mib[0] = CTL_KERN;
  2755. mib[1] = KERN_PROC;
  2756. mib[2] = KERN_PROC_PID;
  2757. mib[3] = getpid();
  2758. // Call sysctl.
  2759. size = sizeof(info);
  2760. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  2761. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n\n" << std::flush;
  2762. return false;
  2763. }
  2764. // We're being debugged if the P_TRACED flag is set.
  2765. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  2766. }
  2767. #else
  2768. bool isDebuggerActive() {
  2769. // We need to find another way to determine this for non-appleclang compilers on macOS
  2770. return false;
  2771. }
  2772. #endif
  2773. } // namespace Catch
  2774. #elif defined(CATCH_PLATFORM_LINUX)
  2775. #include <fstream>
  2776. #include <string>
  2777. namespace Catch{
  2778. // The standard POSIX way of detecting a debugger is to attempt to
  2779. // ptrace() the process, but this needs to be done from a child and not
  2780. // this process itself to still allow attaching to this process later
  2781. // if wanted, so is rather heavy. Under Linux we have the PID of the
  2782. // "debugger" (which doesn't need to be gdb, of course, it could also
  2783. // be strace, for example) in /proc/$PID/status, so just get it from
  2784. // there instead.
  2785. bool isDebuggerActive(){
  2786. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  2787. // This way our users can properly assert over errno values
  2788. ErrnoGuard guard;
  2789. std::ifstream in("/proc/self/status");
  2790. for( std::string line; std::getline(in, line); ) {
  2791. static const int PREFIX_LEN = 11;
  2792. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  2793. // We're traced if the PID is not 0 and no other PID starts
  2794. // with 0 digit, so it's enough to check for just a single
  2795. // character.
  2796. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  2797. }
  2798. }
  2799. return false;
  2800. }
  2801. } // namespace Catch
  2802. #elif defined(_MSC_VER)
  2803. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  2804. namespace Catch {
  2805. bool isDebuggerActive() {
  2806. return IsDebuggerPresent() != 0;
  2807. }
  2808. }
  2809. #elif defined(__MINGW32__)
  2810. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  2811. namespace Catch {
  2812. bool isDebuggerActive() {
  2813. return IsDebuggerPresent() != 0;
  2814. }
  2815. }
  2816. #else
  2817. namespace Catch {
  2818. bool isDebuggerActive() { return false; }
  2819. }
  2820. #endif // Platform
  2821. namespace Catch {
  2822. ITransientExpression::~ITransientExpression() = default;
  2823. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  2824. if( lhs.size() + rhs.size() < 40 &&
  2825. lhs.find('\n') == std::string::npos &&
  2826. rhs.find('\n') == std::string::npos )
  2827. os << lhs << ' ' << op << ' ' << rhs;
  2828. else
  2829. os << lhs << '\n' << op << '\n' << rhs;
  2830. }
  2831. }
  2832. #include <stdexcept>
  2833. namespace Catch {
  2834. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  2835. [[noreturn]]
  2836. void throw_exception(std::exception const& e) {
  2837. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  2838. << "The message was: " << e.what() << '\n';
  2839. std::terminate();
  2840. }
  2841. #endif
  2842. [[noreturn]]
  2843. void throw_logic_error(std::string const& msg) {
  2844. throw_exception(std::logic_error(msg));
  2845. }
  2846. [[noreturn]]
  2847. void throw_domain_error(std::string const& msg) {
  2848. throw_exception(std::domain_error(msg));
  2849. }
  2850. [[noreturn]]
  2851. void throw_runtime_error(std::string const& msg) {
  2852. throw_exception(std::runtime_error(msg));
  2853. }
  2854. } // namespace Catch;
  2855. #include <cassert>
  2856. namespace Catch {
  2857. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() = default;
  2858. namespace Detail {
  2859. namespace {
  2860. // Extracts the actual name part of an enum instance
  2861. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  2862. StringRef extractInstanceName(StringRef enumInstance) {
  2863. // Find last occurrence of ":"
  2864. size_t name_start = enumInstance.size();
  2865. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  2866. --name_start;
  2867. }
  2868. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  2869. }
  2870. }
  2871. std::vector<StringRef> parseEnums( StringRef enums ) {
  2872. auto enumValues = splitStringRef( enums, ',' );
  2873. std::vector<StringRef> parsed;
  2874. parsed.reserve( enumValues.size() );
  2875. for( auto const& enumValue : enumValues ) {
  2876. parsed.push_back(trim(extractInstanceName(enumValue)));
  2877. }
  2878. return parsed;
  2879. }
  2880. EnumInfo::~EnumInfo() {}
  2881. StringRef EnumInfo::lookup( int value ) const {
  2882. for( auto const& valueToName : m_values ) {
  2883. if( valueToName.first == value )
  2884. return valueToName.second;
  2885. }
  2886. return "{** unexpected enum value **}"_sr;
  2887. }
  2888. Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  2889. auto enumInfo = Catch::Detail::make_unique<EnumInfo>();
  2890. enumInfo->m_name = enumName;
  2891. enumInfo->m_values.reserve( values.size() );
  2892. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  2893. assert( valueNames.size() == values.size() );
  2894. std::size_t i = 0;
  2895. for( auto value : values )
  2896. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  2897. return enumInfo;
  2898. }
  2899. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  2900. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  2901. return *m_enumInfos.back();
  2902. }
  2903. } // Detail
  2904. } // Catch
  2905. #include <cerrno>
  2906. namespace Catch {
  2907. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  2908. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  2909. }
  2910. namespace Catch {
  2911. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  2912. }
  2913. void ExceptionTranslatorRegistry::registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) {
  2914. m_translators.push_back( CATCH_MOVE( translator ) );
  2915. }
  2916. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2917. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  2918. // Compiling a mixed mode project with MSVC means that CLR
  2919. // exceptions will be caught in (...) as well. However, these do
  2920. // do not fill-in std::current_exception and thus lead to crash
  2921. // when attempting rethrow.
  2922. // /EHa switch also causes structured exceptions to be caught
  2923. // here, but they fill-in current_exception properly, so
  2924. // at worst the output should be a little weird, instead of
  2925. // causing a crash.
  2926. if ( std::current_exception() == nullptr ) {
  2927. return "Non C++ exception. Possibly a CLR exception.";
  2928. }
  2929. // First we try user-registered translators. If none of them can
  2930. // handle the exception, it will be rethrown handled by our defaults.
  2931. try {
  2932. return tryTranslators();
  2933. }
  2934. // To avoid having to handle TFE explicitly everywhere, we just
  2935. // rethrow it so that it goes back up the caller.
  2936. catch( TestFailureException& ) {
  2937. std::rethrow_exception(std::current_exception());
  2938. }
  2939. catch( std::exception const& ex ) {
  2940. return ex.what();
  2941. }
  2942. catch( std::string const& msg ) {
  2943. return msg;
  2944. }
  2945. catch( const char* msg ) {
  2946. return msg;
  2947. }
  2948. catch(...) {
  2949. return "Unknown exception";
  2950. }
  2951. }
  2952. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  2953. if (m_translators.empty()) {
  2954. std::rethrow_exception(std::current_exception());
  2955. } else {
  2956. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  2957. }
  2958. }
  2959. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2960. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  2961. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  2962. }
  2963. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  2964. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  2965. }
  2966. #endif
  2967. }
  2968. /** \file
  2969. * This file provides platform specific implementations of FatalConditionHandler
  2970. *
  2971. * This means that there is a lot of conditional compilation, and platform
  2972. * specific code. Currently, Catch2 supports a dummy handler (if no
  2973. * handler is desired), and 2 platform specific handlers:
  2974. * * Windows' SEH
  2975. * * POSIX signals
  2976. *
  2977. * Consequently, various pieces of code below are compiled if either of
  2978. * the platform specific handlers is enabled, or if none of them are
  2979. * enabled. It is assumed that both cannot be enabled at the same time,
  2980. * and doing so should cause a compilation error.
  2981. *
  2982. * If another platform specific handler is added, the compile guards
  2983. * below will need to be updated taking these assumptions into account.
  2984. */
  2985. #include <algorithm>
  2986. #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
  2987. namespace Catch {
  2988. // If neither SEH nor signal handling is required, the handler impls
  2989. // do not have to do anything, and can be empty.
  2990. void FatalConditionHandler::engage_platform() {}
  2991. void FatalConditionHandler::disengage_platform() noexcept {}
  2992. FatalConditionHandler::FatalConditionHandler() = default;
  2993. FatalConditionHandler::~FatalConditionHandler() = default;
  2994. } // end namespace Catch
  2995. #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
  2996. #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
  2997. #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
  2998. #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
  2999. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  3000. namespace {
  3001. //! Signals fatal error message to the run context
  3002. void reportFatal( char const * const message ) {
  3003. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  3004. }
  3005. //! Minimal size Catch2 needs for its own fatal error handling.
  3006. //! Picked empirically, so it might not be sufficient on all
  3007. //! platforms, and for all configurations.
  3008. constexpr std::size_t minStackSizeForErrors = 32 * 1024;
  3009. } // end unnamed namespace
  3010. #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
  3011. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  3012. namespace Catch {
  3013. struct SignalDefs { DWORD id; const char* name; };
  3014. // There is no 1-1 mapping between signals and windows exceptions.
  3015. // Windows can easily distinguish between SO and SigSegV,
  3016. // but SigInt, SigTerm, etc are handled differently.
  3017. static SignalDefs signalDefs[] = {
  3018. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  3019. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  3020. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  3021. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  3022. };
  3023. static LONG CALLBACK topLevelExceptionFilter(PEXCEPTION_POINTERS ExceptionInfo) {
  3024. for (auto const& def : signalDefs) {
  3025. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  3026. reportFatal(def.name);
  3027. }
  3028. }
  3029. // If its not an exception we care about, pass it along.
  3030. // This stops us from eating debugger breaks etc.
  3031. return EXCEPTION_CONTINUE_SEARCH;
  3032. }
  3033. // Since we do not support multiple instantiations, we put these
  3034. // into global variables and rely on cleaning them up in outlined
  3035. // constructors/destructors
  3036. static LPTOP_LEVEL_EXCEPTION_FILTER previousTopLevelExceptionFilter = nullptr;
  3037. // For MSVC, we reserve part of the stack memory for handling
  3038. // memory overflow structured exception.
  3039. FatalConditionHandler::FatalConditionHandler() {
  3040. ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
  3041. if (!SetThreadStackGuarantee(&guaranteeSize)) {
  3042. // We do not want to fully error out, because needing
  3043. // the stack reserve should be rare enough anyway.
  3044. Catch::cerr()
  3045. << "Failed to reserve piece of stack."
  3046. << " Stack overflows will not be reported successfully.";
  3047. }
  3048. }
  3049. // We do not attempt to unset the stack guarantee, because
  3050. // Windows does not support lowering the stack size guarantee.
  3051. FatalConditionHandler::~FatalConditionHandler() = default;
  3052. void FatalConditionHandler::engage_platform() {
  3053. // Register as a the top level exception filter.
  3054. previousTopLevelExceptionFilter = SetUnhandledExceptionFilter(topLevelExceptionFilter);
  3055. }
  3056. void FatalConditionHandler::disengage_platform() noexcept {
  3057. if (SetUnhandledExceptionFilter(previousTopLevelExceptionFilter) != topLevelExceptionFilter) {
  3058. Catch::cerr()
  3059. << "Unexpected SEH unhandled exception filter on disengage."
  3060. << " The filter was restored, but might be rolled back unexpectedly.";
  3061. }
  3062. previousTopLevelExceptionFilter = nullptr;
  3063. }
  3064. } // end namespace Catch
  3065. #endif // CATCH_CONFIG_WINDOWS_SEH
  3066. #if defined( CATCH_CONFIG_POSIX_SIGNALS )
  3067. #include <signal.h>
  3068. namespace Catch {
  3069. struct SignalDefs {
  3070. int id;
  3071. const char* name;
  3072. };
  3073. static SignalDefs signalDefs[] = {
  3074. { SIGINT, "SIGINT - Terminal interrupt signal" },
  3075. { SIGILL, "SIGILL - Illegal instruction signal" },
  3076. { SIGFPE, "SIGFPE - Floating point error signal" },
  3077. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  3078. { SIGTERM, "SIGTERM - Termination request signal" },
  3079. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  3080. };
  3081. // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
  3082. // which is zero initialization, but not explicit. We want to avoid
  3083. // that.
  3084. #if defined(__GNUC__)
  3085. # pragma GCC diagnostic push
  3086. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  3087. #endif
  3088. static char* altStackMem = nullptr;
  3089. static std::size_t altStackSize = 0;
  3090. static stack_t oldSigStack{};
  3091. static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
  3092. static void restorePreviousSignalHandlers() noexcept {
  3093. // We set signal handlers back to the previous ones. Hopefully
  3094. // nobody overwrote them in the meantime, and doesn't expect
  3095. // their signal handlers to live past ours given that they
  3096. // installed them after ours..
  3097. for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
  3098. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  3099. }
  3100. // Return the old stack
  3101. sigaltstack(&oldSigStack, nullptr);
  3102. }
  3103. static void handleSignal( int sig ) {
  3104. char const * name = "<unknown signal>";
  3105. for (auto const& def : signalDefs) {
  3106. if (sig == def.id) {
  3107. name = def.name;
  3108. break;
  3109. }
  3110. }
  3111. // We need to restore previous signal handlers and let them do
  3112. // their thing, so that the users can have the debugger break
  3113. // when a signal is raised, and so on.
  3114. restorePreviousSignalHandlers();
  3115. reportFatal( name );
  3116. raise( sig );
  3117. }
  3118. FatalConditionHandler::FatalConditionHandler() {
  3119. assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
  3120. if (altStackSize == 0) {
  3121. altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
  3122. }
  3123. altStackMem = new char[altStackSize]();
  3124. }
  3125. FatalConditionHandler::~FatalConditionHandler() {
  3126. delete[] altStackMem;
  3127. // We signal that another instance can be constructed by zeroing
  3128. // out the pointer.
  3129. altStackMem = nullptr;
  3130. }
  3131. void FatalConditionHandler::engage_platform() {
  3132. stack_t sigStack;
  3133. sigStack.ss_sp = altStackMem;
  3134. sigStack.ss_size = altStackSize;
  3135. sigStack.ss_flags = 0;
  3136. sigaltstack(&sigStack, &oldSigStack);
  3137. struct sigaction sa = { };
  3138. sa.sa_handler = handleSignal;
  3139. sa.sa_flags = SA_ONSTACK;
  3140. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  3141. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  3142. }
  3143. }
  3144. #if defined(__GNUC__)
  3145. # pragma GCC diagnostic pop
  3146. #endif
  3147. void FatalConditionHandler::disengage_platform() noexcept {
  3148. restorePreviousSignalHandlers();
  3149. }
  3150. } // end namespace Catch
  3151. #endif // CATCH_CONFIG_POSIX_SIGNALS
  3152. #include <cstring>
  3153. namespace Catch {
  3154. namespace Detail {
  3155. uint32_t convertToBits(float f) {
  3156. static_assert(sizeof(float) == sizeof(uint32_t), "Important ULP matcher assumption violated");
  3157. uint32_t i;
  3158. std::memcpy(&i, &f, sizeof(f));
  3159. return i;
  3160. }
  3161. uint64_t convertToBits(double d) {
  3162. static_assert(sizeof(double) == sizeof(uint64_t), "Important ULP matcher assumption violated");
  3163. uint64_t i;
  3164. std::memcpy(&i, &d, sizeof(d));
  3165. return i;
  3166. }
  3167. } // end namespace Detail
  3168. } // end namespace Catch
  3169. #include <cstdio>
  3170. #include <fstream>
  3171. #include <sstream>
  3172. #include <vector>
  3173. namespace Catch {
  3174. Catch::IStream::~IStream() = default;
  3175. namespace Detail {
  3176. namespace {
  3177. template<typename WriterF, std::size_t bufferSize=256>
  3178. class StreamBufImpl : public std::streambuf {
  3179. char data[bufferSize];
  3180. WriterF m_writer;
  3181. public:
  3182. StreamBufImpl() {
  3183. setp( data, data + sizeof(data) );
  3184. }
  3185. ~StreamBufImpl() noexcept override {
  3186. StreamBufImpl::sync();
  3187. }
  3188. private:
  3189. int overflow( int c ) override {
  3190. sync();
  3191. if( c != EOF ) {
  3192. if( pbase() == epptr() )
  3193. m_writer( std::string( 1, static_cast<char>( c ) ) );
  3194. else
  3195. sputc( static_cast<char>( c ) );
  3196. }
  3197. return 0;
  3198. }
  3199. int sync() override {
  3200. if( pbase() != pptr() ) {
  3201. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  3202. setp( pbase(), epptr() );
  3203. }
  3204. return 0;
  3205. }
  3206. };
  3207. ///////////////////////////////////////////////////////////////////////////
  3208. struct OutputDebugWriter {
  3209. void operator()( std::string const& str ) {
  3210. if ( !str.empty() ) {
  3211. writeToDebugConsole( str );
  3212. }
  3213. }
  3214. };
  3215. ///////////////////////////////////////////////////////////////////////////
  3216. class FileStream : public IStream {
  3217. std::ofstream m_ofs;
  3218. public:
  3219. FileStream( std::string const& filename ) {
  3220. m_ofs.open( filename.c_str() );
  3221. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << '\'' );
  3222. }
  3223. ~FileStream() override = default;
  3224. public: // IStream
  3225. std::ostream& stream() override {
  3226. return m_ofs;
  3227. }
  3228. };
  3229. ///////////////////////////////////////////////////////////////////////////
  3230. class CoutStream : public IStream {
  3231. std::ostream m_os;
  3232. public:
  3233. // Store the streambuf from cout up-front because
  3234. // cout may get redirected when running tests
  3235. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  3236. ~CoutStream() override = default;
  3237. public: // IStream
  3238. std::ostream& stream() override { return m_os; }
  3239. bool isConsole() const override { return true; }
  3240. };
  3241. class CerrStream : public IStream {
  3242. std::ostream m_os;
  3243. public:
  3244. // Store the streambuf from cerr up-front because
  3245. // cout may get redirected when running tests
  3246. CerrStream(): m_os( Catch::cerr().rdbuf() ) {}
  3247. ~CerrStream() override = default;
  3248. public: // IStream
  3249. std::ostream& stream() override { return m_os; }
  3250. bool isConsole() const override { return true; }
  3251. };
  3252. ///////////////////////////////////////////////////////////////////////////
  3253. class DebugOutStream : public IStream {
  3254. Detail::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  3255. std::ostream m_os;
  3256. public:
  3257. DebugOutStream()
  3258. : m_streamBuf( Detail::make_unique<StreamBufImpl<OutputDebugWriter>>() ),
  3259. m_os( m_streamBuf.get() )
  3260. {}
  3261. ~DebugOutStream() override = default;
  3262. public: // IStream
  3263. std::ostream& stream() override { return m_os; }
  3264. };
  3265. } // unnamed namespace
  3266. } // namespace Detail
  3267. ///////////////////////////////////////////////////////////////////////////
  3268. auto makeStream( std::string const& filename ) -> Detail::unique_ptr<IStream> {
  3269. if ( filename.empty() || filename == "-" ) {
  3270. return Detail::make_unique<Detail::CoutStream>();
  3271. }
  3272. if( filename[0] == '%' ) {
  3273. if ( filename == "%debug" ) {
  3274. return Detail::make_unique<Detail::DebugOutStream>();
  3275. } else if ( filename == "%stderr" ) {
  3276. return Detail::make_unique<Detail::CerrStream>();
  3277. } else if ( filename == "%stdout" ) {
  3278. return Detail::make_unique<Detail::CoutStream>();
  3279. } else {
  3280. CATCH_ERROR( "Unrecognised stream: '" << filename << '\'' );
  3281. }
  3282. }
  3283. return Detail::make_unique<Detail::FileStream>( filename );
  3284. }
  3285. }
  3286. namespace Catch {
  3287. auto operator << (std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& {
  3288. if (lazyExpr.m_isNegated)
  3289. os << '!';
  3290. if (lazyExpr) {
  3291. if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
  3292. os << '(' << *lazyExpr.m_transientExpression << ')';
  3293. else
  3294. os << *lazyExpr.m_transientExpression;
  3295. } else {
  3296. os << "{** error - unchecked empty expression requested **}";
  3297. }
  3298. return os;
  3299. }
  3300. } // namespace Catch
  3301. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  3302. #include <crtdbg.h>
  3303. namespace Catch {
  3304. LeakDetector::LeakDetector() {
  3305. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  3306. flag |= _CRTDBG_LEAK_CHECK_DF;
  3307. flag |= _CRTDBG_ALLOC_MEM_DF;
  3308. _CrtSetDbgFlag(flag);
  3309. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  3310. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  3311. // Change this to leaking allocation's number to break there
  3312. _CrtSetBreakAlloc(-1);
  3313. }
  3314. }
  3315. #else // ^^ Windows crt debug heap enabled // Windows crt debug heap disabled vv
  3316. Catch::LeakDetector::LeakDetector() {}
  3317. #endif // CATCH_CONFIG_WINDOWS_CRTDBG
  3318. Catch::LeakDetector::~LeakDetector() {
  3319. Catch::cleanUp();
  3320. }
  3321. namespace Catch {
  3322. namespace {
  3323. void listTests(IEventListener& reporter, IConfig const& config) {
  3324. auto const& testSpec = config.testSpec();
  3325. auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
  3326. reporter.listTests(matchedTestCases);
  3327. }
  3328. void listTags(IEventListener& reporter, IConfig const& config) {
  3329. auto const& testSpec = config.testSpec();
  3330. std::vector<TestCaseHandle> matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
  3331. std::map<StringRef, TagInfo, Detail::CaseInsensitiveLess> tagCounts;
  3332. for (auto const& testCase : matchedTestCases) {
  3333. for (auto const& tagName : testCase.getTestCaseInfo().tags) {
  3334. auto it = tagCounts.find(tagName.original);
  3335. if (it == tagCounts.end())
  3336. it = tagCounts.insert(std::make_pair(tagName.original, TagInfo())).first;
  3337. it->second.add(tagName.original);
  3338. }
  3339. }
  3340. std::vector<TagInfo> infos; infos.reserve(tagCounts.size());
  3341. for (auto& tagc : tagCounts) {
  3342. infos.push_back(CATCH_MOVE(tagc.second));
  3343. }
  3344. reporter.listTags(infos);
  3345. }
  3346. void listReporters(IEventListener& reporter) {
  3347. std::vector<ReporterDescription> descriptions;
  3348. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  3349. descriptions.reserve(factories.size());
  3350. for (auto const& fac : factories) {
  3351. descriptions.push_back({ fac.first, fac.second->getDescription() });
  3352. }
  3353. reporter.listReporters(descriptions);
  3354. }
  3355. void listListeners(IEventListener& reporter) {
  3356. std::vector<ListenerDescription> descriptions;
  3357. auto const& factories =
  3358. getRegistryHub().getReporterRegistry().getListeners();
  3359. descriptions.reserve( factories.size() );
  3360. for ( auto const& fac : factories ) {
  3361. descriptions.push_back( { fac->getName(), fac->getDescription() } );
  3362. }
  3363. reporter.listListeners( descriptions );
  3364. }
  3365. } // end anonymous namespace
  3366. void TagInfo::add( StringRef spelling ) {
  3367. ++count;
  3368. spellings.insert( spelling );
  3369. }
  3370. std::string TagInfo::all() const {
  3371. // 2 per tag for brackets '[' and ']'
  3372. size_t size = spellings.size() * 2;
  3373. for (auto const& spelling : spellings) {
  3374. size += spelling.size();
  3375. }
  3376. std::string out; out.reserve(size);
  3377. for (auto const& spelling : spellings) {
  3378. out += '[';
  3379. out += spelling;
  3380. out += ']';
  3381. }
  3382. return out;
  3383. }
  3384. bool list( IEventListener& reporter, Config const& config ) {
  3385. bool listed = false;
  3386. if (config.listTests()) {
  3387. listed = true;
  3388. listTests(reporter, config);
  3389. }
  3390. if (config.listTags()) {
  3391. listed = true;
  3392. listTags(reporter, config);
  3393. }
  3394. if (config.listReporters()) {
  3395. listed = true;
  3396. listReporters(reporter);
  3397. }
  3398. if ( config.listListeners() ) {
  3399. listed = true;
  3400. listListeners( reporter );
  3401. }
  3402. return listed;
  3403. }
  3404. } // end namespace Catch
  3405. namespace Catch {
  3406. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  3407. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3408. static LeakDetector leakDetector;
  3409. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  3410. }
  3411. // Allow users of amalgamated .cpp file to remove our main and provide their own.
  3412. #if !defined(CATCH_AMALGAMATED_CUSTOM_MAIN)
  3413. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  3414. // Standard C/C++ Win32 Unicode wmain entry point
  3415. extern "C" int __cdecl wmain (int argc, wchar_t * argv[], wchar_t * []) {
  3416. #else
  3417. // Standard C/C++ main entry point
  3418. int main (int argc, char * argv[]) {
  3419. #endif
  3420. // We want to force the linker not to discard the global variable
  3421. // and its constructor, as it (optionally) registers leak detector
  3422. (void)&Catch::leakDetector;
  3423. return Catch::Session().run( argc, argv );
  3424. }
  3425. #endif // !defined(CATCH_AMALGAMATED_CUSTOM_MAIN
  3426. namespace Catch {
  3427. MessageInfo::MessageInfo( StringRef _macroName,
  3428. SourceLineInfo const& _lineInfo,
  3429. ResultWas::OfType _type )
  3430. : macroName( _macroName ),
  3431. lineInfo( _lineInfo ),
  3432. type( _type ),
  3433. sequence( ++globalCount )
  3434. {}
  3435. // This may need protecting if threading support is added
  3436. unsigned int MessageInfo::globalCount = 0;
  3437. } // end namespace Catch
  3438. #include <cstdio>
  3439. #include <cstring>
  3440. #include <sstream>
  3441. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  3442. #if defined(_MSC_VER)
  3443. #include <io.h> //_dup and _dup2
  3444. #define dup _dup
  3445. #define dup2 _dup2
  3446. #define fileno _fileno
  3447. #else
  3448. #include <unistd.h> // dup and dup2
  3449. #endif
  3450. #endif
  3451. namespace Catch {
  3452. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  3453. : m_originalStream( originalStream ),
  3454. m_redirectionStream( redirectionStream ),
  3455. m_prevBuf( m_originalStream.rdbuf() )
  3456. {
  3457. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  3458. }
  3459. RedirectedStream::~RedirectedStream() {
  3460. m_originalStream.rdbuf( m_prevBuf );
  3461. }
  3462. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  3463. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  3464. RedirectedStdErr::RedirectedStdErr()
  3465. : m_cerr( Catch::cerr(), m_rss.get() ),
  3466. m_clog( Catch::clog(), m_rss.get() )
  3467. {}
  3468. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  3469. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  3470. : m_redirectedCout(redirectedCout),
  3471. m_redirectedCerr(redirectedCerr)
  3472. {}
  3473. RedirectedStreams::~RedirectedStreams() {
  3474. m_redirectedCout += m_redirectedStdOut.str();
  3475. m_redirectedCerr += m_redirectedStdErr.str();
  3476. }
  3477. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  3478. #if defined(_MSC_VER)
  3479. TempFile::TempFile() {
  3480. if (tmpnam_s(m_buffer)) {
  3481. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  3482. }
  3483. if (fopen_s(&m_file, m_buffer, "w+")) {
  3484. char buffer[100];
  3485. if (strerror_s(buffer, errno)) {
  3486. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  3487. }
  3488. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  3489. }
  3490. }
  3491. #else
  3492. TempFile::TempFile() {
  3493. m_file = std::tmpfile();
  3494. if (!m_file) {
  3495. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  3496. }
  3497. }
  3498. #endif
  3499. TempFile::~TempFile() {
  3500. // TBD: What to do about errors here?
  3501. std::fclose(m_file);
  3502. // We manually create the file on Windows only, on Linux
  3503. // it will be autodeleted
  3504. #if defined(_MSC_VER)
  3505. std::remove(m_buffer);
  3506. #endif
  3507. }
  3508. FILE* TempFile::getFile() {
  3509. return m_file;
  3510. }
  3511. std::string TempFile::getContents() {
  3512. std::stringstream sstr;
  3513. char buffer[100] = {};
  3514. std::rewind(m_file);
  3515. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  3516. sstr << buffer;
  3517. }
  3518. return sstr.str();
  3519. }
  3520. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  3521. m_originalStdout(dup(1)),
  3522. m_originalStderr(dup(2)),
  3523. m_stdoutDest(stdout_dest),
  3524. m_stderrDest(stderr_dest) {
  3525. dup2(fileno(m_stdoutFile.getFile()), 1);
  3526. dup2(fileno(m_stderrFile.getFile()), 2);
  3527. }
  3528. OutputRedirect::~OutputRedirect() {
  3529. Catch::cout() << std::flush;
  3530. fflush(stdout);
  3531. // Since we support overriding these streams, we flush cerr
  3532. // even though std::cerr is unbuffered
  3533. Catch::cerr() << std::flush;
  3534. Catch::clog() << std::flush;
  3535. fflush(stderr);
  3536. dup2(m_originalStdout, 1);
  3537. dup2(m_originalStderr, 2);
  3538. m_stdoutDest += m_stdoutFile.getContents();
  3539. m_stderrDest += m_stderrFile.getContents();
  3540. }
  3541. #endif // CATCH_CONFIG_NEW_CAPTURE
  3542. } // namespace Catch
  3543. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  3544. #if defined(_MSC_VER)
  3545. #undef dup
  3546. #undef dup2
  3547. #undef fileno
  3548. #endif
  3549. #endif
  3550. #include <cmath>
  3551. namespace Catch {
  3552. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  3553. bool isnan(float f) {
  3554. return std::isnan(f);
  3555. }
  3556. bool isnan(double d) {
  3557. return std::isnan(d);
  3558. }
  3559. #else
  3560. // For now we only use this for embarcadero
  3561. bool isnan(float f) {
  3562. return std::_isnan(f);
  3563. }
  3564. bool isnan(double d) {
  3565. return std::_isnan(d);
  3566. }
  3567. #endif
  3568. } // end namespace Catch
  3569. namespace Catch {
  3570. namespace {
  3571. #if defined(_MSC_VER)
  3572. #pragma warning(push)
  3573. #pragma warning(disable:4146) // we negate uint32 during the rotate
  3574. #endif
  3575. // Safe rotr implementation thanks to John Regehr
  3576. uint32_t rotate_right(uint32_t val, uint32_t count) {
  3577. const uint32_t mask = 31;
  3578. count &= mask;
  3579. return (val >> count) | (val << (-count & mask));
  3580. }
  3581. #if defined(_MSC_VER)
  3582. #pragma warning(pop)
  3583. #endif
  3584. }
  3585. SimplePcg32::SimplePcg32(result_type seed_) {
  3586. seed(seed_);
  3587. }
  3588. void SimplePcg32::seed(result_type seed_) {
  3589. m_state = 0;
  3590. (*this)();
  3591. m_state += seed_;
  3592. (*this)();
  3593. }
  3594. void SimplePcg32::discard(uint64_t skip) {
  3595. // We could implement this to run in O(log n) steps, but this
  3596. // should suffice for our use case.
  3597. for (uint64_t s = 0; s < skip; ++s) {
  3598. static_cast<void>((*this)());
  3599. }
  3600. }
  3601. SimplePcg32::result_type SimplePcg32::operator()() {
  3602. // prepare the output value
  3603. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  3604. const auto output = rotate_right(xorshifted, m_state >> 59u);
  3605. // advance state
  3606. m_state = m_state * 6364136223846793005ULL + s_inc;
  3607. return output;
  3608. }
  3609. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  3610. return lhs.m_state == rhs.m_state;
  3611. }
  3612. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  3613. return lhs.m_state != rhs.m_state;
  3614. }
  3615. }
  3616. #include <ctime>
  3617. #include <random>
  3618. namespace Catch {
  3619. std::uint32_t generateRandomSeed( GenerateFrom from ) {
  3620. switch ( from ) {
  3621. case GenerateFrom::Time:
  3622. return static_cast<std::uint32_t>( std::time( nullptr ) );
  3623. case GenerateFrom::Default:
  3624. case GenerateFrom::RandomDevice:
  3625. // In theory, a platform could have random_device that returns just
  3626. // 16 bits. That is still some randomness, so we don't care too much
  3627. return static_cast<std::uint32_t>( std::random_device{}() );
  3628. default:
  3629. CATCH_ERROR("Unknown generation method");
  3630. }
  3631. }
  3632. } // end namespace Catch
  3633. namespace Catch {
  3634. ReporterRegistry::ReporterRegistry() {
  3635. // Because it is impossible to move out of initializer list,
  3636. // we have to add the elements manually
  3637. m_factories["Automake"] = Detail::make_unique<ReporterFactory<AutomakeReporter>>();
  3638. m_factories["compact"] = Detail::make_unique<ReporterFactory<CompactReporter>>();
  3639. m_factories["console"] = Detail::make_unique<ReporterFactory<ConsoleReporter>>();
  3640. m_factories["JUnit"] = Detail::make_unique<ReporterFactory<JunitReporter>>();
  3641. m_factories["SonarQube"] = Detail::make_unique<ReporterFactory<SonarQubeReporter>>();
  3642. m_factories["TAP"] = Detail::make_unique<ReporterFactory<TAPReporter>>();
  3643. m_factories["TeamCity"] = Detail::make_unique<ReporterFactory<TeamCityReporter>>();
  3644. m_factories["XML"] = Detail::make_unique<ReporterFactory<XmlReporter>>();
  3645. }
  3646. ReporterRegistry::~ReporterRegistry() = default;
  3647. IEventListenerPtr ReporterRegistry::create( std::string const& name, ReporterConfig&& config ) const {
  3648. auto it = m_factories.find( name );
  3649. if( it == m_factories.end() )
  3650. return nullptr;
  3651. return it->second->create( CATCH_MOVE(config) );
  3652. }
  3653. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr factory ) {
  3654. CATCH_ENFORCE( name.find( "::" ) == name.npos,
  3655. "'::' is not allowed in reporter name: '" + name + '\'' );
  3656. auto ret = m_factories.emplace(name, CATCH_MOVE(factory));
  3657. CATCH_ENFORCE( ret.second, "reporter using '" + name + "' as name was already registered" );
  3658. }
  3659. void ReporterRegistry::registerListener(
  3660. Detail::unique_ptr<EventListenerFactory> factory ) {
  3661. m_listeners.push_back( CATCH_MOVE(factory) );
  3662. }
  3663. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  3664. return m_factories;
  3665. }
  3666. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  3667. return m_listeners;
  3668. }
  3669. }
  3670. #include <algorithm>
  3671. namespace Catch {
  3672. namespace {
  3673. struct kvPair {
  3674. StringRef key, value;
  3675. };
  3676. kvPair splitKVPair(StringRef kvString) {
  3677. auto splitPos = static_cast<size_t>( std::distance(
  3678. kvString.begin(),
  3679. std::find( kvString.begin(), kvString.end(), '=' ) ) );
  3680. return { kvString.substr( 0, splitPos ),
  3681. kvString.substr( splitPos + 1, kvString.size() ) };
  3682. }
  3683. }
  3684. namespace Detail {
  3685. std::vector<std::string> splitReporterSpec( StringRef reporterSpec ) {
  3686. static constexpr auto separator = "::";
  3687. static constexpr size_t separatorSize = 2;
  3688. size_t separatorPos = 0;
  3689. auto findNextSeparator = [&reporterSpec]( size_t startPos ) {
  3690. static_assert(
  3691. separatorSize == 2,
  3692. "The code below currently assumes 2 char separator" );
  3693. auto currentPos = startPos;
  3694. do {
  3695. while ( currentPos < reporterSpec.size() &&
  3696. reporterSpec[currentPos] != separator[0] ) {
  3697. ++currentPos;
  3698. }
  3699. if ( currentPos + 1 < reporterSpec.size() &&
  3700. reporterSpec[currentPos + 1] == separator[1] ) {
  3701. return currentPos;
  3702. }
  3703. ++currentPos;
  3704. } while ( currentPos < reporterSpec.size() );
  3705. return static_cast<size_t>( -1 );
  3706. };
  3707. std::vector<std::string> parts;
  3708. while ( separatorPos < reporterSpec.size() ) {
  3709. const auto nextSeparator = findNextSeparator( separatorPos );
  3710. parts.push_back( static_cast<std::string>( reporterSpec.substr(
  3711. separatorPos, nextSeparator - separatorPos ) ) );
  3712. if ( nextSeparator == static_cast<size_t>( -1 ) ) {
  3713. break;
  3714. }
  3715. separatorPos = nextSeparator + separatorSize;
  3716. }
  3717. // Handle a separator at the end.
  3718. // This is not a valid spec, but we want to do validation in a
  3719. // centralized place
  3720. if ( separatorPos == reporterSpec.size() ) {
  3721. parts.emplace_back();
  3722. }
  3723. return parts;
  3724. }
  3725. Optional<ColourMode> stringToColourMode( StringRef colourMode ) {
  3726. if ( colourMode == "default" ) {
  3727. return ColourMode::PlatformDefault;
  3728. } else if ( colourMode == "ansi" ) {
  3729. return ColourMode::ANSI;
  3730. } else if ( colourMode == "win32" ) {
  3731. return ColourMode::Win32;
  3732. } else if ( colourMode == "none" ) {
  3733. return ColourMode::None;
  3734. } else {
  3735. return {};
  3736. }
  3737. }
  3738. } // namespace Detail
  3739. bool operator==( ReporterSpec const& lhs, ReporterSpec const& rhs ) {
  3740. return lhs.m_name == rhs.m_name &&
  3741. lhs.m_outputFileName == rhs.m_outputFileName &&
  3742. lhs.m_colourMode == rhs.m_colourMode &&
  3743. lhs.m_customOptions == rhs.m_customOptions;
  3744. }
  3745. Optional<ReporterSpec> parseReporterSpec( StringRef reporterSpec ) {
  3746. auto parts = Detail::splitReporterSpec( reporterSpec );
  3747. assert( parts.size() > 0 && "Split should never return empty vector" );
  3748. std::map<std::string, std::string> kvPairs;
  3749. Optional<std::string> outputFileName;
  3750. Optional<ColourMode> colourMode;
  3751. // First part is always reporter name, so we skip it
  3752. for ( size_t i = 1; i < parts.size(); ++i ) {
  3753. auto kv = splitKVPair( parts[i] );
  3754. auto key = kv.key, value = kv.value;
  3755. if ( key.empty() || value.empty() ) {
  3756. return {};
  3757. } else if ( key[0] == 'X' ) {
  3758. // This is a reporter-specific option, we don't check these
  3759. // apart from basic sanity checks
  3760. if ( key.size() == 1 ) {
  3761. return {};
  3762. }
  3763. auto ret = kvPairs.emplace( std::string(kv.key), std::string(kv.value) );
  3764. if ( !ret.second ) {
  3765. // Duplicated key. We might want to handle this differently,
  3766. // e.g. by overwriting the existing value?
  3767. return {};
  3768. }
  3769. } else if ( key == "out" ) {
  3770. // Duplicated key
  3771. if ( outputFileName ) {
  3772. return {};
  3773. }
  3774. outputFileName = static_cast<std::string>( value );
  3775. } else if ( key == "colour-mode" ) {
  3776. // Duplicated key
  3777. if ( colourMode ) {
  3778. return {};
  3779. }
  3780. colourMode = Detail::stringToColourMode( value );
  3781. // Parsing failed
  3782. if ( !colourMode ) {
  3783. return {};
  3784. }
  3785. } else {
  3786. // Unrecognized option
  3787. return {};
  3788. }
  3789. }
  3790. return ReporterSpec{ CATCH_MOVE( parts[0] ),
  3791. CATCH_MOVE( outputFileName ),
  3792. CATCH_MOVE( colourMode ),
  3793. CATCH_MOVE( kvPairs ) };
  3794. }
  3795. ReporterSpec::ReporterSpec(
  3796. std::string name,
  3797. Optional<std::string> outputFileName,
  3798. Optional<ColourMode> colourMode,
  3799. std::map<std::string, std::string> customOptions ):
  3800. m_name( CATCH_MOVE( name ) ),
  3801. m_outputFileName( CATCH_MOVE( outputFileName ) ),
  3802. m_colourMode( CATCH_MOVE( colourMode ) ),
  3803. m_customOptions( CATCH_MOVE( customOptions ) ) {}
  3804. } // namespace Catch
  3805. namespace Catch {
  3806. bool isOk( ResultWas::OfType resultType ) {
  3807. return ( resultType & ResultWas::FailureBit ) == 0;
  3808. }
  3809. bool isJustInfo( int flags ) {
  3810. return flags == ResultWas::Info;
  3811. }
  3812. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  3813. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  3814. }
  3815. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  3816. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  3817. } // end namespace Catch
  3818. #include <cstdio>
  3819. #include <sstream>
  3820. #include <vector>
  3821. namespace Catch {
  3822. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  3823. struct StringStreams {
  3824. std::vector<Detail::unique_ptr<std::ostringstream>> m_streams;
  3825. std::vector<std::size_t> m_unused;
  3826. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  3827. auto add() -> std::size_t {
  3828. if( m_unused.empty() ) {
  3829. m_streams.push_back( Detail::make_unique<std::ostringstream>() );
  3830. return m_streams.size()-1;
  3831. }
  3832. else {
  3833. auto index = m_unused.back();
  3834. m_unused.pop_back();
  3835. return index;
  3836. }
  3837. }
  3838. void release( std::size_t index ) {
  3839. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  3840. m_unused.push_back(index);
  3841. }
  3842. };
  3843. ReusableStringStream::ReusableStringStream()
  3844. : m_index( Singleton<StringStreams>::getMutable().add() ),
  3845. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  3846. {}
  3847. ReusableStringStream::~ReusableStringStream() {
  3848. static_cast<std::ostringstream*>( m_oss )->str("");
  3849. m_oss->clear();
  3850. Singleton<StringStreams>::getMutable().release( m_index );
  3851. }
  3852. std::string ReusableStringStream::str() const {
  3853. return static_cast<std::ostringstream*>( m_oss )->str();
  3854. }
  3855. void ReusableStringStream::str( std::string const& str ) {
  3856. static_cast<std::ostringstream*>( m_oss )->str( str );
  3857. }
  3858. }
  3859. #include <cassert>
  3860. #include <algorithm>
  3861. namespace Catch {
  3862. namespace Generators {
  3863. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  3864. GeneratorBasePtr m_generator;
  3865. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  3866. : TrackerBase( nameAndLocation, ctx, parent )
  3867. {}
  3868. ~GeneratorTracker() override;
  3869. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  3870. GeneratorTracker* tracker;
  3871. ITracker& currentTracker = ctx.currentTracker();
  3872. // Under specific circumstances, the generator we want
  3873. // to acquire is also the current tracker. If this is
  3874. // the case, we have to avoid looking through current
  3875. // tracker's children, and instead return the current
  3876. // tracker.
  3877. // A case where this check is important is e.g.
  3878. // for (int i = 0; i < 5; ++i) {
  3879. // int n = GENERATE(1, 2);
  3880. // }
  3881. //
  3882. // without it, the code above creates 5 nested generators.
  3883. if ( currentTracker.nameAndLocation() == nameAndLocation ) {
  3884. auto thisTracker =
  3885. currentTracker.parent()->findChild( nameAndLocation );
  3886. assert( thisTracker );
  3887. assert( thisTracker->isGeneratorTracker() );
  3888. tracker = static_cast<GeneratorTracker*>( thisTracker );
  3889. } else if ( ITracker* childTracker =
  3890. currentTracker.findChild( nameAndLocation ) ) {
  3891. assert( childTracker );
  3892. assert( childTracker->isGeneratorTracker() );
  3893. tracker = static_cast<GeneratorTracker*>( childTracker );
  3894. } else {
  3895. auto newTracker =
  3896. Catch::Detail::make_unique<GeneratorTracker>(
  3897. nameAndLocation, ctx, &currentTracker );
  3898. tracker = newTracker.get();
  3899. currentTracker.addChild( CATCH_MOVE(newTracker) );
  3900. }
  3901. if( !tracker->isComplete() ) {
  3902. tracker->open();
  3903. }
  3904. return *tracker;
  3905. }
  3906. // TrackerBase interface
  3907. bool isGeneratorTracker() const override { return true; }
  3908. auto hasGenerator() const -> bool override {
  3909. return !!m_generator;
  3910. }
  3911. void close() override {
  3912. TrackerBase::close();
  3913. // If a generator has a child (it is followed by a section)
  3914. // and none of its children have started, then we must wait
  3915. // until later to start consuming its values.
  3916. // This catches cases where `GENERATE` is placed between two
  3917. // `SECTION`s.
  3918. // **The check for m_children.empty cannot be removed**.
  3919. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  3920. const bool should_wait_for_child = [&]() {
  3921. // No children -> nobody to wait for
  3922. if ( m_children.empty() ) {
  3923. return false;
  3924. }
  3925. // If at least one child started executing, don't wait
  3926. if ( std::find_if(
  3927. m_children.begin(),
  3928. m_children.end(),
  3929. []( TestCaseTracking::ITrackerPtr const& tracker ) {
  3930. return tracker->hasStarted();
  3931. } ) != m_children.end() ) {
  3932. return false;
  3933. }
  3934. // No children have started. We need to check if they _can_
  3935. // start, and thus we should wait for them, or they cannot
  3936. // start (due to filters), and we shouldn't wait for them
  3937. ITracker* parent = m_parent;
  3938. // This is safe: there is always at least one section
  3939. // tracker in a test case tracking tree
  3940. while ( !parent->isSectionTracker() ) {
  3941. parent = parent->parent();
  3942. }
  3943. assert( parent &&
  3944. "Missing root (test case) level section" );
  3945. auto const& parentSection =
  3946. static_cast<SectionTracker const&>( *parent );
  3947. auto const& filters = parentSection.getFilters();
  3948. // No filters -> no restrictions on running sections
  3949. if ( filters.empty() ) {
  3950. return true;
  3951. }
  3952. for ( auto const& child : m_children ) {
  3953. if ( child->isSectionTracker() &&
  3954. std::find(
  3955. filters.begin(),
  3956. filters.end(),
  3957. static_cast<SectionTracker const&>( *child )
  3958. .trimmedName() ) != filters.end() ) {
  3959. return true;
  3960. }
  3961. }
  3962. return false;
  3963. }();
  3964. // This check is a bit tricky, because m_generator->next()
  3965. // has a side-effect, where it consumes generator's current
  3966. // value, but we do not want to invoke the side-effect if
  3967. // this generator is still waiting for any child to start.
  3968. if ( should_wait_for_child ||
  3969. ( m_runState == CompletedSuccessfully &&
  3970. m_generator->countedNext() ) ) {
  3971. m_children.clear();
  3972. m_runState = Executing;
  3973. }
  3974. }
  3975. // IGeneratorTracker interface
  3976. auto getGenerator() const -> GeneratorBasePtr const& override {
  3977. return m_generator;
  3978. }
  3979. void setGenerator( GeneratorBasePtr&& generator ) override {
  3980. m_generator = CATCH_MOVE( generator );
  3981. }
  3982. };
  3983. GeneratorTracker::~GeneratorTracker() = default;
  3984. }
  3985. RunContext::RunContext(IConfig const* _config, IEventListenerPtr&& reporter)
  3986. : m_runInfo(_config->name()),
  3987. m_context(getCurrentMutableContext()),
  3988. m_config(_config),
  3989. m_reporter(CATCH_MOVE(reporter)),
  3990. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  3991. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  3992. {
  3993. m_context.setResultCapture(this);
  3994. m_reporter->testRunStarting(m_runInfo);
  3995. }
  3996. RunContext::~RunContext() {
  3997. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  3998. }
  3999. Totals RunContext::runTest(TestCaseHandle const& testCase) {
  4000. const Totals prevTotals = m_totals;
  4001. std::string redirectedCout;
  4002. std::string redirectedCerr;
  4003. auto const& testInfo = testCase.getTestCaseInfo();
  4004. m_reporter->testCaseStarting(testInfo);
  4005. m_activeTestCase = &testCase;
  4006. ITracker& rootTracker = m_trackerContext.startRun();
  4007. assert(rootTracker.isSectionTracker());
  4008. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  4009. // We intentionally only seed the internal RNG once per test case,
  4010. // before it is first invoked. The reason for that is a complex
  4011. // interplay of generator/section implementation details and the
  4012. // Random*Generator types.
  4013. //
  4014. // The issue boils down to us needing to seed the Random*Generators
  4015. // with different seed each, so that they return different sequences
  4016. // of random numbers. We do this by giving them a number from the
  4017. // shared RNG instance as their seed.
  4018. //
  4019. // However, this runs into an issue if the reseeding happens each
  4020. // time the test case is entered (as opposed to first time only),
  4021. // because multiple generators could get the same seed, e.g. in
  4022. // ```cpp
  4023. // TEST_CASE() {
  4024. // auto i = GENERATE(take(10, random(0, 100));
  4025. // SECTION("A") {
  4026. // auto j = GENERATE(take(10, random(0, 100));
  4027. // }
  4028. // SECTION("B") {
  4029. // auto k = GENERATE(take(10, random(0, 100));
  4030. // }
  4031. // }
  4032. // ```
  4033. // `i` and `j` would properly return values from different sequences,
  4034. // but `i` and `k` would return the same sequence, because their seed
  4035. // would be the same.
  4036. // (The reason their seeds would be the same is that the generator
  4037. // for k would be initialized when the test case is entered the second
  4038. // time, after the shared RNG instance was reset to the same value
  4039. // it had when the generator for i was initialized.)
  4040. seedRng( *m_config );
  4041. uint64_t testRuns = 0;
  4042. do {
  4043. m_trackerContext.startCycle();
  4044. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  4045. m_reporter->testCasePartialStarting(testInfo, testRuns);
  4046. const auto beforeRunTotals = m_totals;
  4047. std::string oneRunCout, oneRunCerr;
  4048. runCurrentTest(oneRunCout, oneRunCerr);
  4049. redirectedCout += oneRunCout;
  4050. redirectedCerr += oneRunCerr;
  4051. const auto singleRunTotals = m_totals.delta(beforeRunTotals);
  4052. auto statsForOneRun = TestCaseStats(testInfo, singleRunTotals, oneRunCout, oneRunCerr, aborting());
  4053. m_reporter->testCasePartialEnded(statsForOneRun, testRuns);
  4054. ++testRuns;
  4055. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  4056. Totals deltaTotals = m_totals.delta(prevTotals);
  4057. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  4058. deltaTotals.assertions.failed++;
  4059. deltaTotals.testCases.passed--;
  4060. deltaTotals.testCases.failed++;
  4061. }
  4062. m_totals.testCases += deltaTotals.testCases;
  4063. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  4064. deltaTotals,
  4065. redirectedCout,
  4066. redirectedCerr,
  4067. aborting()));
  4068. m_activeTestCase = nullptr;
  4069. m_testCaseTracker = nullptr;
  4070. return deltaTotals;
  4071. }
  4072. void RunContext::assertionEnded(AssertionResult const & result) {
  4073. if (result.getResultType() == ResultWas::Ok) {
  4074. m_totals.assertions.passed++;
  4075. m_lastAssertionPassed = true;
  4076. } else if (!result.succeeded()) {
  4077. m_lastAssertionPassed = false;
  4078. if (result.isOk()) {
  4079. }
  4080. else if( m_activeTestCase->getTestCaseInfo().okToFail() )
  4081. m_totals.assertions.failedButOk++;
  4082. else
  4083. m_totals.assertions.failed++;
  4084. }
  4085. else {
  4086. m_lastAssertionPassed = true;
  4087. }
  4088. m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals));
  4089. if (result.getResultType() != ResultWas::Warning)
  4090. m_messageScopes.clear();
  4091. // Reset working state
  4092. resetAssertionInfo();
  4093. m_lastResult = result;
  4094. }
  4095. void RunContext::resetAssertionInfo() {
  4096. m_lastAssertionInfo.macroName = StringRef();
  4097. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  4098. }
  4099. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  4100. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  4101. if (!sectionTracker.isOpen())
  4102. return false;
  4103. m_activeSections.push_back(&sectionTracker);
  4104. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  4105. m_reporter->sectionStarting(sectionInfo);
  4106. assertions = m_totals.assertions;
  4107. return true;
  4108. }
  4109. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  4110. using namespace Generators;
  4111. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  4112. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  4113. m_lastAssertionInfo.lineInfo = lineInfo;
  4114. return tracker;
  4115. }
  4116. bool RunContext::testForMissingAssertions(Counts& assertions) {
  4117. if (assertions.total() != 0)
  4118. return false;
  4119. if (!m_config->warnAboutMissingAssertions())
  4120. return false;
  4121. if (m_trackerContext.currentTracker().hasChildren())
  4122. return false;
  4123. m_totals.assertions.failed++;
  4124. assertions.failed++;
  4125. return true;
  4126. }
  4127. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  4128. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  4129. bool missingAssertions = testForMissingAssertions(assertions);
  4130. if (!m_activeSections.empty()) {
  4131. m_activeSections.back()->close();
  4132. m_activeSections.pop_back();
  4133. }
  4134. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  4135. m_messages.clear();
  4136. m_messageScopes.clear();
  4137. }
  4138. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  4139. if (m_unfinishedSections.empty())
  4140. m_activeSections.back()->fail();
  4141. else
  4142. m_activeSections.back()->close();
  4143. m_activeSections.pop_back();
  4144. m_unfinishedSections.push_back(endInfo);
  4145. }
  4146. void RunContext::benchmarkPreparing( StringRef name ) {
  4147. m_reporter->benchmarkPreparing(name);
  4148. }
  4149. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  4150. m_reporter->benchmarkStarting( info );
  4151. }
  4152. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  4153. m_reporter->benchmarkEnded( stats );
  4154. }
  4155. void RunContext::benchmarkFailed( StringRef error ) {
  4156. m_reporter->benchmarkFailed( error );
  4157. }
  4158. void RunContext::pushScopedMessage(MessageInfo const & message) {
  4159. m_messages.push_back(message);
  4160. }
  4161. void RunContext::popScopedMessage(MessageInfo const & message) {
  4162. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  4163. }
  4164. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  4165. m_messageScopes.emplace_back( builder );
  4166. }
  4167. std::string RunContext::getCurrentTestName() const {
  4168. return m_activeTestCase
  4169. ? m_activeTestCase->getTestCaseInfo().name
  4170. : std::string();
  4171. }
  4172. const AssertionResult * RunContext::getLastResult() const {
  4173. return &(*m_lastResult);
  4174. }
  4175. void RunContext::exceptionEarlyReported() {
  4176. m_shouldReportUnexpected = false;
  4177. }
  4178. void RunContext::handleFatalErrorCondition( StringRef message ) {
  4179. // First notify reporter that bad things happened
  4180. m_reporter->fatalErrorEncountered(message);
  4181. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  4182. // Instead, fake a result data.
  4183. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  4184. tempResult.message = static_cast<std::string>(message);
  4185. AssertionResult result(m_lastAssertionInfo, tempResult);
  4186. assertionEnded(result);
  4187. handleUnfinishedSections();
  4188. // Recreate section for test case (as we will lose the one that was in scope)
  4189. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  4190. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  4191. Counts assertions;
  4192. assertions.failed = 1;
  4193. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  4194. m_reporter->sectionEnded(testCaseSectionStats);
  4195. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  4196. Totals deltaTotals;
  4197. deltaTotals.testCases.failed = 1;
  4198. deltaTotals.assertions.failed = 1;
  4199. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  4200. deltaTotals,
  4201. std::string(),
  4202. std::string(),
  4203. false));
  4204. m_totals.testCases.failed++;
  4205. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  4206. }
  4207. bool RunContext::lastAssertionPassed() {
  4208. return m_lastAssertionPassed;
  4209. }
  4210. void RunContext::assertionPassed() {
  4211. m_lastAssertionPassed = true;
  4212. ++m_totals.assertions.passed;
  4213. resetAssertionInfo();
  4214. m_messageScopes.clear();
  4215. }
  4216. bool RunContext::aborting() const {
  4217. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  4218. }
  4219. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  4220. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  4221. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  4222. m_reporter->sectionStarting(testCaseSection);
  4223. Counts prevAssertions = m_totals.assertions;
  4224. double duration = 0;
  4225. m_shouldReportUnexpected = true;
  4226. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  4227. Timer timer;
  4228. CATCH_TRY {
  4229. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  4230. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  4231. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  4232. timer.start();
  4233. invokeActiveTestCase();
  4234. #else
  4235. OutputRedirect r(redirectedCout, redirectedCerr);
  4236. timer.start();
  4237. invokeActiveTestCase();
  4238. #endif
  4239. } else {
  4240. timer.start();
  4241. invokeActiveTestCase();
  4242. }
  4243. duration = timer.getElapsedSeconds();
  4244. } CATCH_CATCH_ANON (TestFailureException&) {
  4245. // This just means the test was aborted due to failure
  4246. } CATCH_CATCH_ALL {
  4247. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  4248. // are reported without translation at the point of origin.
  4249. if( m_shouldReportUnexpected ) {
  4250. AssertionReaction dummyReaction;
  4251. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  4252. }
  4253. }
  4254. Counts assertions = m_totals.assertions - prevAssertions;
  4255. bool missingAssertions = testForMissingAssertions(assertions);
  4256. m_testCaseTracker->close();
  4257. handleUnfinishedSections();
  4258. m_messages.clear();
  4259. m_messageScopes.clear();
  4260. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  4261. m_reporter->sectionEnded(testCaseSectionStats);
  4262. }
  4263. void RunContext::invokeActiveTestCase() {
  4264. // We need to engage a handler for signals/structured exceptions
  4265. // before running the tests themselves, or the binary can crash
  4266. // without failed test being reported.
  4267. FatalConditionHandlerGuard _(&m_fatalConditionhandler);
  4268. // We keep having issue where some compilers warn about an unused
  4269. // variable, even though the type has non-trivial constructor and
  4270. // destructor. This is annoying and ugly, but it makes them stfu.
  4271. (void)_;
  4272. m_activeTestCase->invoke();
  4273. }
  4274. void RunContext::handleUnfinishedSections() {
  4275. // If sections ended prematurely due to an exception we stored their
  4276. // infos here so we can tear them down outside the unwind process.
  4277. for (auto it = m_unfinishedSections.rbegin(),
  4278. itEnd = m_unfinishedSections.rend();
  4279. it != itEnd;
  4280. ++it)
  4281. sectionEnded(*it);
  4282. m_unfinishedSections.clear();
  4283. }
  4284. void RunContext::handleExpr(
  4285. AssertionInfo const& info,
  4286. ITransientExpression const& expr,
  4287. AssertionReaction& reaction
  4288. ) {
  4289. m_reporter->assertionStarting( info );
  4290. bool negated = isFalseTest( info.resultDisposition );
  4291. bool result = expr.getResult() != negated;
  4292. if( result ) {
  4293. if (!m_includeSuccessfulResults) {
  4294. assertionPassed();
  4295. }
  4296. else {
  4297. reportExpr(info, ResultWas::Ok, &expr, negated);
  4298. }
  4299. }
  4300. else {
  4301. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  4302. populateReaction( reaction );
  4303. }
  4304. }
  4305. void RunContext::reportExpr(
  4306. AssertionInfo const &info,
  4307. ResultWas::OfType resultType,
  4308. ITransientExpression const *expr,
  4309. bool negated ) {
  4310. m_lastAssertionInfo = info;
  4311. AssertionResultData data( resultType, LazyExpression( negated ) );
  4312. AssertionResult assertionResult{ info, data };
  4313. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  4314. assertionEnded( assertionResult );
  4315. }
  4316. void RunContext::handleMessage(
  4317. AssertionInfo const& info,
  4318. ResultWas::OfType resultType,
  4319. StringRef message,
  4320. AssertionReaction& reaction
  4321. ) {
  4322. m_reporter->assertionStarting( info );
  4323. m_lastAssertionInfo = info;
  4324. AssertionResultData data( resultType, LazyExpression( false ) );
  4325. data.message = static_cast<std::string>(message);
  4326. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  4327. assertionEnded( assertionResult );
  4328. if( !assertionResult.isOk() )
  4329. populateReaction( reaction );
  4330. }
  4331. void RunContext::handleUnexpectedExceptionNotThrown(
  4332. AssertionInfo const& info,
  4333. AssertionReaction& reaction
  4334. ) {
  4335. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  4336. }
  4337. void RunContext::handleUnexpectedInflightException(
  4338. AssertionInfo const& info,
  4339. std::string const& message,
  4340. AssertionReaction& reaction
  4341. ) {
  4342. m_lastAssertionInfo = info;
  4343. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  4344. data.message = message;
  4345. AssertionResult assertionResult{ info, data };
  4346. assertionEnded( assertionResult );
  4347. populateReaction( reaction );
  4348. }
  4349. void RunContext::populateReaction( AssertionReaction& reaction ) {
  4350. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  4351. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  4352. }
  4353. void RunContext::handleIncomplete(
  4354. AssertionInfo const& info
  4355. ) {
  4356. m_lastAssertionInfo = info;
  4357. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  4358. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  4359. AssertionResult assertionResult{ info, data };
  4360. assertionEnded( assertionResult );
  4361. }
  4362. void RunContext::handleNonExpr(
  4363. AssertionInfo const &info,
  4364. ResultWas::OfType resultType,
  4365. AssertionReaction &reaction
  4366. ) {
  4367. m_lastAssertionInfo = info;
  4368. AssertionResultData data( resultType, LazyExpression( false ) );
  4369. AssertionResult assertionResult{ info, data };
  4370. assertionEnded( assertionResult );
  4371. if( !assertionResult.isOk() )
  4372. populateReaction( reaction );
  4373. }
  4374. IResultCapture& getResultCapture() {
  4375. if (auto* capture = getCurrentContext().getResultCapture())
  4376. return *capture;
  4377. else
  4378. CATCH_INTERNAL_ERROR("No result capture instance");
  4379. }
  4380. void seedRng(IConfig const& config) {
  4381. sharedRng().seed(config.rngSeed());
  4382. }
  4383. unsigned int rngSeed() {
  4384. return getCurrentContext().getConfig()->rngSeed();
  4385. }
  4386. }
  4387. namespace Catch {
  4388. Section::Section( SectionInfo&& info ):
  4389. m_info( CATCH_MOVE( info ) ),
  4390. m_sectionIncluded(
  4391. getResultCapture().sectionStarted( m_info, m_assertions ) ) {
  4392. // Non-"included" sections will not use the timing information
  4393. // anyway, so don't bother with the potential syscall.
  4394. if (m_sectionIncluded) {
  4395. m_timer.start();
  4396. }
  4397. }
  4398. Section::~Section() {
  4399. if( m_sectionIncluded ) {
  4400. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  4401. if( uncaught_exceptions() )
  4402. getResultCapture().sectionEndedEarly( endInfo );
  4403. else
  4404. getResultCapture().sectionEnded( endInfo );
  4405. }
  4406. }
  4407. // This indicates whether the section should be executed or not
  4408. Section::operator bool() const {
  4409. return m_sectionIncluded;
  4410. }
  4411. } // end namespace Catch
  4412. #include <vector>
  4413. namespace Catch {
  4414. namespace {
  4415. static auto getSingletons() -> std::vector<ISingleton*>*& {
  4416. static std::vector<ISingleton*>* g_singletons = nullptr;
  4417. if( !g_singletons )
  4418. g_singletons = new std::vector<ISingleton*>();
  4419. return g_singletons;
  4420. }
  4421. }
  4422. ISingleton::~ISingleton() = default;
  4423. void addSingleton(ISingleton* singleton ) {
  4424. getSingletons()->push_back( singleton );
  4425. }
  4426. void cleanupSingletons() {
  4427. auto& singletons = getSingletons();
  4428. for( auto singleton : *singletons )
  4429. delete singleton;
  4430. delete singletons;
  4431. singletons = nullptr;
  4432. }
  4433. } // namespace Catch
  4434. #include <cstring>
  4435. #include <ostream>
  4436. namespace Catch {
  4437. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  4438. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  4439. }
  4440. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  4441. // We can assume that the same file will usually have the same pointer.
  4442. // Thus, if the pointers are the same, there is no point in calling the strcmp
  4443. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  4444. }
  4445. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  4446. #ifndef __GNUG__
  4447. os << info.file << '(' << info.line << ')';
  4448. #else
  4449. os << info.file << ':' << info.line;
  4450. #endif
  4451. return os;
  4452. }
  4453. } // end namespace Catch
  4454. namespace Catch {
  4455. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4456. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  4457. CATCH_TRY {
  4458. m_exceptions.push_back(exception);
  4459. } CATCH_CATCH_ALL {
  4460. // If we run out of memory during start-up there's really not a lot more we can do about it
  4461. std::terminate();
  4462. }
  4463. }
  4464. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  4465. return m_exceptions;
  4466. }
  4467. #endif
  4468. } // end namespace Catch
  4469. #include <iostream>
  4470. namespace Catch {
  4471. // If you #define this you must implement these functions
  4472. #if !defined( CATCH_CONFIG_NOSTDOUT )
  4473. std::ostream& cout() { return std::cout; }
  4474. std::ostream& cerr() { return std::cerr; }
  4475. std::ostream& clog() { return std::clog; }
  4476. #endif
  4477. } // namespace Catch
  4478. #include <algorithm>
  4479. #include <ostream>
  4480. #include <cstring>
  4481. #include <cctype>
  4482. #include <vector>
  4483. namespace Catch {
  4484. bool startsWith( std::string const& s, std::string const& prefix ) {
  4485. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  4486. }
  4487. bool startsWith( StringRef s, char prefix ) {
  4488. return !s.empty() && s[0] == prefix;
  4489. }
  4490. bool endsWith( std::string const& s, std::string const& suffix ) {
  4491. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  4492. }
  4493. bool endsWith( std::string const& s, char suffix ) {
  4494. return !s.empty() && s[s.size()-1] == suffix;
  4495. }
  4496. bool contains( std::string const& s, std::string const& infix ) {
  4497. return s.find( infix ) != std::string::npos;
  4498. }
  4499. void toLowerInPlace( std::string& s ) {
  4500. std::transform( s.begin(), s.end(), s.begin(), []( char c ) {
  4501. return toLower( c );
  4502. } );
  4503. }
  4504. std::string toLower( std::string const& s ) {
  4505. std::string lc = s;
  4506. toLowerInPlace( lc );
  4507. return lc;
  4508. }
  4509. char toLower(char c) {
  4510. return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
  4511. }
  4512. std::string trim( std::string const& str ) {
  4513. static char const* whitespaceChars = "\n\r\t ";
  4514. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  4515. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  4516. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  4517. }
  4518. StringRef trim(StringRef ref) {
  4519. const auto is_ws = [](char c) {
  4520. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  4521. };
  4522. size_t real_begin = 0;
  4523. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  4524. size_t real_end = ref.size();
  4525. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  4526. return ref.substr(real_begin, real_end - real_begin);
  4527. }
  4528. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  4529. bool replaced = false;
  4530. std::size_t i = str.find( replaceThis );
  4531. while( i != std::string::npos ) {
  4532. replaced = true;
  4533. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  4534. if( i < str.size()-withThis.size() )
  4535. i = str.find( replaceThis, i+withThis.size() );
  4536. else
  4537. i = std::string::npos;
  4538. }
  4539. return replaced;
  4540. }
  4541. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  4542. std::vector<StringRef> subStrings;
  4543. std::size_t start = 0;
  4544. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  4545. if( str[pos] == delimiter ) {
  4546. if( pos - start > 1 )
  4547. subStrings.push_back( str.substr( start, pos-start ) );
  4548. start = pos+1;
  4549. }
  4550. }
  4551. if( start < str.size() )
  4552. subStrings.push_back( str.substr( start, str.size()-start ) );
  4553. return subStrings;
  4554. }
  4555. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  4556. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  4557. if( pluraliser.m_count != 1 )
  4558. os << 's';
  4559. return os;
  4560. }
  4561. }
  4562. #include <algorithm>
  4563. #include <ostream>
  4564. #include <cstring>
  4565. #include <cstdint>
  4566. namespace Catch {
  4567. StringRef::StringRef( char const* rawChars ) noexcept
  4568. : StringRef( rawChars, std::strlen(rawChars) )
  4569. {}
  4570. auto StringRef::operator == ( StringRef other ) const noexcept -> bool {
  4571. return m_size == other.m_size
  4572. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  4573. }
  4574. bool StringRef::operator<(StringRef rhs) const noexcept {
  4575. if (m_size < rhs.m_size) {
  4576. return strncmp(m_start, rhs.m_start, m_size) <= 0;
  4577. }
  4578. return strncmp(m_start, rhs.m_start, rhs.m_size) < 0;
  4579. }
  4580. int StringRef::compare( StringRef rhs ) const {
  4581. auto cmpResult =
  4582. strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) );
  4583. // This means that strncmp found a difference before the strings
  4584. // ended, and we can return it directly
  4585. if ( cmpResult != 0 ) {
  4586. return cmpResult;
  4587. }
  4588. // If strings are equal up to length, then their comparison results on
  4589. // their size
  4590. if ( m_size < rhs.m_size ) {
  4591. return -1;
  4592. } else if ( m_size > rhs.m_size ) {
  4593. return 1;
  4594. } else {
  4595. return 0;
  4596. }
  4597. }
  4598. auto operator << ( std::ostream& os, StringRef str ) -> std::ostream& {
  4599. return os.write(str.data(), static_cast<std::streamsize>(str.size()));
  4600. }
  4601. std::string operator+(StringRef lhs, StringRef rhs) {
  4602. std::string ret;
  4603. ret.reserve(lhs.size() + rhs.size());
  4604. ret += lhs;
  4605. ret += rhs;
  4606. return ret;
  4607. }
  4608. auto operator+=( std::string& lhs, StringRef rhs ) -> std::string& {
  4609. lhs.append(rhs.data(), rhs.size());
  4610. return lhs;
  4611. }
  4612. } // namespace Catch
  4613. namespace Catch {
  4614. TagAliasRegistry::~TagAliasRegistry() {}
  4615. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  4616. auto it = m_registry.find( alias );
  4617. if( it != m_registry.end() )
  4618. return &(it->second);
  4619. else
  4620. return nullptr;
  4621. }
  4622. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  4623. std::string expandedTestSpec = unexpandedTestSpec;
  4624. for( auto const& registryKvp : m_registry ) {
  4625. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  4626. if( pos != std::string::npos ) {
  4627. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  4628. registryKvp.second.tag +
  4629. expandedTestSpec.substr( pos + registryKvp.first.size() );
  4630. }
  4631. }
  4632. return expandedTestSpec;
  4633. }
  4634. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  4635. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  4636. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  4637. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  4638. "error: tag alias, '" << alias << "' already registered.\n"
  4639. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  4640. << "\tRedefined at: " << lineInfo );
  4641. }
  4642. ITagAliasRegistry::~ITagAliasRegistry() = default;
  4643. ITagAliasRegistry const& ITagAliasRegistry::get() {
  4644. return getRegistryHub().getTagAliasRegistry();
  4645. }
  4646. } // end namespace Catch
  4647. namespace Catch {
  4648. TestCaseInfoHasher::TestCaseInfoHasher( hash_t seed ): m_seed( seed ) {}
  4649. uint32_t TestCaseInfoHasher::operator()( TestCaseInfo const& t ) const {
  4650. // FNV-1a hash algorithm that is designed for uniqueness:
  4651. const hash_t prime = 1099511628211u;
  4652. hash_t hash = 14695981039346656037u;
  4653. for ( const char c : t.name ) {
  4654. hash ^= c;
  4655. hash *= prime;
  4656. }
  4657. for ( const char c : t.className ) {
  4658. hash ^= c;
  4659. hash *= prime;
  4660. }
  4661. for ( const Tag& tag : t.tags ) {
  4662. for ( const char c : tag.original ) {
  4663. hash ^= c;
  4664. hash *= prime;
  4665. }
  4666. }
  4667. hash ^= m_seed;
  4668. hash *= prime;
  4669. const uint32_t low{ static_cast<uint32_t>( hash ) };
  4670. const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
  4671. return low * high;
  4672. }
  4673. } // namespace Catch
  4674. #include <algorithm>
  4675. #include <set>
  4676. namespace Catch {
  4677. std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases ) {
  4678. switch (config.runOrder()) {
  4679. case TestRunOrder::Declared:
  4680. return unsortedTestCases;
  4681. case TestRunOrder::LexicographicallySorted: {
  4682. std::vector<TestCaseHandle> sorted = unsortedTestCases;
  4683. std::sort(
  4684. sorted.begin(),
  4685. sorted.end(),
  4686. []( TestCaseHandle const& lhs, TestCaseHandle const& rhs ) {
  4687. return lhs.getTestCaseInfo() < rhs.getTestCaseInfo();
  4688. }
  4689. );
  4690. return sorted;
  4691. }
  4692. case TestRunOrder::Randomized: {
  4693. seedRng(config);
  4694. using TestWithHash = std::pair<TestCaseInfoHasher::hash_t, TestCaseHandle>;
  4695. TestCaseInfoHasher h{ config.rngSeed() };
  4696. std::vector<TestWithHash> indexed_tests;
  4697. indexed_tests.reserve(unsortedTestCases.size());
  4698. for (auto const& handle : unsortedTestCases) {
  4699. indexed_tests.emplace_back(h(handle.getTestCaseInfo()), handle);
  4700. }
  4701. std::sort( indexed_tests.begin(),
  4702. indexed_tests.end(),
  4703. []( TestWithHash const& lhs, TestWithHash const& rhs ) {
  4704. if ( lhs.first == rhs.first ) {
  4705. return lhs.second.getTestCaseInfo() <
  4706. rhs.second.getTestCaseInfo();
  4707. }
  4708. return lhs.first < rhs.first;
  4709. } );
  4710. std::vector<TestCaseHandle> randomized;
  4711. randomized.reserve(indexed_tests.size());
  4712. for (auto const& indexed : indexed_tests) {
  4713. randomized.push_back(indexed.second);
  4714. }
  4715. return randomized;
  4716. }
  4717. }
  4718. CATCH_INTERNAL_ERROR("Unknown test order value!");
  4719. }
  4720. bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config ) {
  4721. return !testCase.getTestCaseInfo().throws() || config.allowThrows();
  4722. }
  4723. bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  4724. return testSpec.matches( testCase.getTestCaseInfo() ) && isThrowSafe( testCase, config );
  4725. }
  4726. void
  4727. enforceNoDuplicateTestCases( std::vector<TestCaseHandle> const& tests ) {
  4728. auto testInfoCmp = []( TestCaseInfo const* lhs,
  4729. TestCaseInfo const* rhs ) {
  4730. return *lhs < *rhs;
  4731. };
  4732. std::set<TestCaseInfo const*, decltype(testInfoCmp)> seenTests(testInfoCmp);
  4733. for ( auto const& test : tests ) {
  4734. const auto infoPtr = &test.getTestCaseInfo();
  4735. const auto prev = seenTests.insert( infoPtr );
  4736. CATCH_ENFORCE(
  4737. prev.second,
  4738. "error: test case \"" << infoPtr->name << "\", with tags \""
  4739. << infoPtr->tagsAsString() << "\" already defined.\n"
  4740. << "\tFirst seen at " << ( *prev.first )->lineInfo << "\n"
  4741. << "\tRedefined at " << infoPtr->lineInfo );
  4742. }
  4743. }
  4744. std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  4745. std::vector<TestCaseHandle> filtered;
  4746. filtered.reserve( testCases.size() );
  4747. for (auto const& testCase : testCases) {
  4748. if ((!testSpec.hasFilters() && !testCase.getTestCaseInfo().isHidden()) ||
  4749. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  4750. filtered.push_back(testCase);
  4751. }
  4752. }
  4753. return createShard(filtered, config.shardCount(), config.shardIndex());
  4754. }
  4755. std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config ) {
  4756. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  4757. }
  4758. void TestRegistry::registerTest(Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker) {
  4759. m_handles.emplace_back(testInfo.get(), testInvoker.get());
  4760. m_viewed_test_infos.push_back(testInfo.get());
  4761. m_owned_test_infos.push_back(CATCH_MOVE(testInfo));
  4762. m_invokers.push_back(CATCH_MOVE(testInvoker));
  4763. }
  4764. std::vector<TestCaseInfo*> const& TestRegistry::getAllInfos() const {
  4765. return m_viewed_test_infos;
  4766. }
  4767. std::vector<TestCaseHandle> const& TestRegistry::getAllTests() const {
  4768. return m_handles;
  4769. }
  4770. std::vector<TestCaseHandle> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  4771. if( m_sortedFunctions.empty() )
  4772. enforceNoDuplicateTestCases( m_handles );
  4773. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  4774. m_sortedFunctions = sortTests( config, m_handles );
  4775. m_currentSortOrder = config.runOrder();
  4776. }
  4777. return m_sortedFunctions;
  4778. }
  4779. ///////////////////////////////////////////////////////////////////////////
  4780. void TestInvokerAsFunction::invoke() const {
  4781. m_testAsFunction();
  4782. }
  4783. } // end namespace Catch
  4784. #include <algorithm>
  4785. #include <cassert>
  4786. #if defined(__clang__)
  4787. # pragma clang diagnostic push
  4788. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  4789. #endif
  4790. namespace Catch {
  4791. namespace TestCaseTracking {
  4792. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  4793. : name( _name ),
  4794. location( _location )
  4795. {}
  4796. ITracker::~ITracker() = default;
  4797. void ITracker::markAsNeedingAnotherRun() {
  4798. m_runState = NeedsAnotherRun;
  4799. }
  4800. void ITracker::addChild( ITrackerPtr&& child ) {
  4801. m_children.push_back( CATCH_MOVE(child) );
  4802. }
  4803. ITracker* ITracker::findChild( NameAndLocation const& nameAndLocation ) {
  4804. auto it = std::find_if(
  4805. m_children.begin(),
  4806. m_children.end(),
  4807. [&nameAndLocation]( ITrackerPtr const& tracker ) {
  4808. return tracker->nameAndLocation().location ==
  4809. nameAndLocation.location &&
  4810. tracker->nameAndLocation().name == nameAndLocation.name;
  4811. } );
  4812. return ( it != m_children.end() ) ? it->get() : nullptr;
  4813. }
  4814. bool ITracker::isSectionTracker() const { return false; }
  4815. bool ITracker::isGeneratorTracker() const { return false; }
  4816. bool ITracker::isSuccessfullyCompleted() const {
  4817. return m_runState == CompletedSuccessfully;
  4818. }
  4819. bool ITracker::isOpen() const {
  4820. return m_runState != NotStarted && !isComplete();
  4821. }
  4822. bool ITracker::hasStarted() const { return m_runState != NotStarted; }
  4823. void ITracker::openChild() {
  4824. if (m_runState != ExecutingChildren) {
  4825. m_runState = ExecutingChildren;
  4826. if (m_parent) {
  4827. m_parent->openChild();
  4828. }
  4829. }
  4830. }
  4831. ITracker& TrackerContext::startRun() {
  4832. using namespace std::string_literals;
  4833. m_rootTracker = Catch::Detail::make_unique<SectionTracker>(
  4834. NameAndLocation( "{root}"s, CATCH_INTERNAL_LINEINFO ),
  4835. *this,
  4836. nullptr );
  4837. m_currentTracker = nullptr;
  4838. m_runState = Executing;
  4839. return *m_rootTracker;
  4840. }
  4841. void TrackerContext::endRun() {
  4842. m_rootTracker.reset();
  4843. m_currentTracker = nullptr;
  4844. m_runState = NotStarted;
  4845. }
  4846. void TrackerContext::startCycle() {
  4847. m_currentTracker = m_rootTracker.get();
  4848. m_runState = Executing;
  4849. }
  4850. void TrackerContext::completeCycle() {
  4851. m_runState = CompletedCycle;
  4852. }
  4853. bool TrackerContext::completedCycle() const {
  4854. return m_runState == CompletedCycle;
  4855. }
  4856. ITracker& TrackerContext::currentTracker() {
  4857. return *m_currentTracker;
  4858. }
  4859. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  4860. m_currentTracker = tracker;
  4861. }
  4862. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  4863. ITracker(nameAndLocation, parent),
  4864. m_ctx( ctx )
  4865. {}
  4866. bool TrackerBase::isComplete() const {
  4867. return m_runState == CompletedSuccessfully || m_runState == Failed;
  4868. }
  4869. void TrackerBase::open() {
  4870. m_runState = Executing;
  4871. moveToThis();
  4872. if( m_parent )
  4873. m_parent->openChild();
  4874. }
  4875. void TrackerBase::close() {
  4876. // Close any still open children (e.g. generators)
  4877. while( &m_ctx.currentTracker() != this )
  4878. m_ctx.currentTracker().close();
  4879. switch( m_runState ) {
  4880. case NeedsAnotherRun:
  4881. break;
  4882. case Executing:
  4883. m_runState = CompletedSuccessfully;
  4884. break;
  4885. case ExecutingChildren:
  4886. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  4887. m_runState = CompletedSuccessfully;
  4888. break;
  4889. case NotStarted:
  4890. case CompletedSuccessfully:
  4891. case Failed:
  4892. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  4893. default:
  4894. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  4895. }
  4896. moveToParent();
  4897. m_ctx.completeCycle();
  4898. }
  4899. void TrackerBase::fail() {
  4900. m_runState = Failed;
  4901. if( m_parent )
  4902. m_parent->markAsNeedingAnotherRun();
  4903. moveToParent();
  4904. m_ctx.completeCycle();
  4905. }
  4906. void TrackerBase::moveToParent() {
  4907. assert( m_parent );
  4908. m_ctx.setCurrentTracker( m_parent );
  4909. }
  4910. void TrackerBase::moveToThis() {
  4911. m_ctx.setCurrentTracker( this );
  4912. }
  4913. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  4914. : TrackerBase( nameAndLocation, ctx, parent ),
  4915. m_trimmed_name(trim(nameAndLocation.name))
  4916. {
  4917. if( parent ) {
  4918. while( !parent->isSectionTracker() )
  4919. parent = parent->parent();
  4920. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  4921. addNextFilters( parentSection.m_filters );
  4922. }
  4923. }
  4924. bool SectionTracker::isComplete() const {
  4925. bool complete = true;
  4926. if (m_filters.empty()
  4927. || m_filters[0].empty()
  4928. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  4929. complete = TrackerBase::isComplete();
  4930. }
  4931. return complete;
  4932. }
  4933. bool SectionTracker::isSectionTracker() const { return true; }
  4934. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  4935. SectionTracker* section;
  4936. ITracker& currentTracker = ctx.currentTracker();
  4937. if ( ITracker* childTracker =
  4938. currentTracker.findChild( nameAndLocation ) ) {
  4939. assert( childTracker );
  4940. assert( childTracker->isSectionTracker() );
  4941. section = static_cast<SectionTracker*>( childTracker );
  4942. } else {
  4943. auto newSection = Catch::Detail::make_unique<SectionTracker>(
  4944. nameAndLocation, ctx, &currentTracker );
  4945. section = newSection.get();
  4946. currentTracker.addChild( CATCH_MOVE( newSection ) );
  4947. }
  4948. if( !ctx.completedCycle() )
  4949. section->tryOpen();
  4950. return *section;
  4951. }
  4952. void SectionTracker::tryOpen() {
  4953. if( !isComplete() )
  4954. open();
  4955. }
  4956. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  4957. if( !filters.empty() ) {
  4958. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  4959. m_filters.emplace_back(StringRef{}); // Root - should never be consulted
  4960. m_filters.emplace_back(StringRef{}); // Test Case - not a section filter
  4961. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  4962. }
  4963. }
  4964. void SectionTracker::addNextFilters( std::vector<StringRef> const& filters ) {
  4965. if( filters.size() > 1 )
  4966. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  4967. }
  4968. std::vector<StringRef> const& SectionTracker::getFilters() const {
  4969. return m_filters;
  4970. }
  4971. StringRef SectionTracker::trimmedName() const {
  4972. return m_trimmed_name;
  4973. }
  4974. } // namespace TestCaseTracking
  4975. } // namespace Catch
  4976. #if defined(__clang__)
  4977. # pragma clang diagnostic pop
  4978. #endif
  4979. #include <algorithm>
  4980. #include <iterator>
  4981. namespace Catch {
  4982. namespace {
  4983. StringRef extractClassName( StringRef classOrMethodName ) {
  4984. if ( !startsWith( classOrMethodName, '&' ) ) {
  4985. return classOrMethodName;
  4986. }
  4987. // Remove the leading '&' to avoid having to special case it later
  4988. const auto methodName =
  4989. classOrMethodName.substr( 1, classOrMethodName.size() );
  4990. auto reverseStart = std::make_reverse_iterator( methodName.end() );
  4991. auto reverseEnd = std::make_reverse_iterator( methodName.begin() );
  4992. // We make a simplifying assumption that ":" is only present
  4993. // in the input as part of "::" from C++ typenames (this is
  4994. // relatively safe assumption because the input is generated
  4995. // as stringification of type through preprocessor).
  4996. auto lastColons = std::find( reverseStart, reverseEnd, ':' ) + 1;
  4997. auto secondLastColons =
  4998. std::find( lastColons + 1, reverseEnd, ':' );
  4999. auto const startIdx = reverseEnd - secondLastColons;
  5000. auto const classNameSize = secondLastColons - lastColons - 1;
  5001. return methodName.substr(
  5002. static_cast<std::size_t>( startIdx ),
  5003. static_cast<std::size_t>( classNameSize ) );
  5004. }
  5005. } // namespace
  5006. Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() ) {
  5007. return Detail::make_unique<TestInvokerAsFunction>( testAsFunction );
  5008. }
  5009. AutoReg::AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  5010. CATCH_TRY {
  5011. getMutableRegistryHub()
  5012. .registerTest(
  5013. makeTestCaseInfo(
  5014. extractClassName( classOrMethod ),
  5015. nameAndTags,
  5016. lineInfo),
  5017. CATCH_MOVE(invoker)
  5018. );
  5019. } CATCH_CATCH_ALL {
  5020. // Do not throw when constructing global objects, instead register the exception to be processed later
  5021. getMutableRegistryHub().registerStartupException();
  5022. }
  5023. }
  5024. }
  5025. namespace Catch {
  5026. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  5027. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  5028. m_mode = None;
  5029. m_exclusion = false;
  5030. m_arg = m_tagAliases->expandAliases( arg );
  5031. m_escapeChars.clear();
  5032. m_substring.reserve(m_arg.size());
  5033. m_patternName.reserve(m_arg.size());
  5034. m_realPatternPos = 0;
  5035. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  5036. //if visitChar fails
  5037. if( !visitChar( m_arg[m_pos] ) ){
  5038. m_testSpec.m_invalidSpecs.push_back(arg);
  5039. break;
  5040. }
  5041. endMode();
  5042. return *this;
  5043. }
  5044. TestSpec TestSpecParser::testSpec() {
  5045. addFilter();
  5046. return CATCH_MOVE(m_testSpec);
  5047. }
  5048. bool TestSpecParser::visitChar( char c ) {
  5049. if( (m_mode != EscapedName) && (c == '\\') ) {
  5050. escape();
  5051. addCharToPattern(c);
  5052. return true;
  5053. }else if((m_mode != EscapedName) && (c == ',') ) {
  5054. return separate();
  5055. }
  5056. switch( m_mode ) {
  5057. case None:
  5058. if( processNoneChar( c ) )
  5059. return true;
  5060. break;
  5061. case Name:
  5062. processNameChar( c );
  5063. break;
  5064. case EscapedName:
  5065. endMode();
  5066. addCharToPattern(c);
  5067. return true;
  5068. default:
  5069. case Tag:
  5070. case QuotedName:
  5071. if( processOtherChar( c ) )
  5072. return true;
  5073. break;
  5074. }
  5075. m_substring += c;
  5076. if( !isControlChar( c ) ) {
  5077. m_patternName += c;
  5078. m_realPatternPos++;
  5079. }
  5080. return true;
  5081. }
  5082. // Two of the processing methods return true to signal the caller to return
  5083. // without adding the given character to the current pattern strings
  5084. bool TestSpecParser::processNoneChar( char c ) {
  5085. switch( c ) {
  5086. case ' ':
  5087. return true;
  5088. case '~':
  5089. m_exclusion = true;
  5090. return false;
  5091. case '[':
  5092. startNewMode( Tag );
  5093. return false;
  5094. case '"':
  5095. startNewMode( QuotedName );
  5096. return false;
  5097. default:
  5098. startNewMode( Name );
  5099. return false;
  5100. }
  5101. }
  5102. void TestSpecParser::processNameChar( char c ) {
  5103. if( c == '[' ) {
  5104. if( m_substring == "exclude:" )
  5105. m_exclusion = true;
  5106. else
  5107. endMode();
  5108. startNewMode( Tag );
  5109. }
  5110. }
  5111. bool TestSpecParser::processOtherChar( char c ) {
  5112. if( !isControlChar( c ) )
  5113. return false;
  5114. m_substring += c;
  5115. endMode();
  5116. return true;
  5117. }
  5118. void TestSpecParser::startNewMode( Mode mode ) {
  5119. m_mode = mode;
  5120. }
  5121. void TestSpecParser::endMode() {
  5122. switch( m_mode ) {
  5123. case Name:
  5124. case QuotedName:
  5125. return addNamePattern();
  5126. case Tag:
  5127. return addTagPattern();
  5128. case EscapedName:
  5129. revertBackToLastMode();
  5130. return;
  5131. case None:
  5132. default:
  5133. return startNewMode( None );
  5134. }
  5135. }
  5136. void TestSpecParser::escape() {
  5137. saveLastMode();
  5138. m_mode = EscapedName;
  5139. m_escapeChars.push_back(m_realPatternPos);
  5140. }
  5141. bool TestSpecParser::isControlChar( char c ) const {
  5142. switch( m_mode ) {
  5143. default:
  5144. return false;
  5145. case None:
  5146. return c == '~';
  5147. case Name:
  5148. return c == '[';
  5149. case EscapedName:
  5150. return true;
  5151. case QuotedName:
  5152. return c == '"';
  5153. case Tag:
  5154. return c == '[' || c == ']';
  5155. }
  5156. }
  5157. void TestSpecParser::addFilter() {
  5158. if( !m_currentFilter.m_required.empty() || !m_currentFilter.m_forbidden.empty() ) {
  5159. m_testSpec.m_filters.push_back( CATCH_MOVE(m_currentFilter) );
  5160. m_currentFilter = TestSpec::Filter();
  5161. }
  5162. }
  5163. void TestSpecParser::saveLastMode() {
  5164. lastMode = m_mode;
  5165. }
  5166. void TestSpecParser::revertBackToLastMode() {
  5167. m_mode = lastMode;
  5168. }
  5169. bool TestSpecParser::separate() {
  5170. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  5171. //invalid argument, signal failure to previous scope.
  5172. m_mode = None;
  5173. m_pos = m_arg.size();
  5174. m_substring.clear();
  5175. m_patternName.clear();
  5176. m_realPatternPos = 0;
  5177. return false;
  5178. }
  5179. endMode();
  5180. addFilter();
  5181. return true; //success
  5182. }
  5183. std::string TestSpecParser::preprocessPattern() {
  5184. std::string token = m_patternName;
  5185. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  5186. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  5187. m_escapeChars.clear();
  5188. if (startsWith(token, "exclude:")) {
  5189. m_exclusion = true;
  5190. token = token.substr(8);
  5191. }
  5192. m_patternName.clear();
  5193. m_realPatternPos = 0;
  5194. return token;
  5195. }
  5196. void TestSpecParser::addNamePattern() {
  5197. auto token = preprocessPattern();
  5198. if (!token.empty()) {
  5199. if (m_exclusion) {
  5200. m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring));
  5201. } else {
  5202. m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::NamePattern>(token, m_substring));
  5203. }
  5204. }
  5205. m_substring.clear();
  5206. m_exclusion = false;
  5207. m_mode = None;
  5208. }
  5209. void TestSpecParser::addTagPattern() {
  5210. auto token = preprocessPattern();
  5211. if (!token.empty()) {
  5212. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  5213. // we have to create a separate hide tag and shorten the real one
  5214. if (token.size() > 1 && token[0] == '.') {
  5215. token.erase(token.begin());
  5216. if (m_exclusion) {
  5217. m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring));
  5218. m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
  5219. } else {
  5220. m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(".", m_substring));
  5221. m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
  5222. }
  5223. }
  5224. if (m_exclusion) {
  5225. m_currentFilter.m_forbidden.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
  5226. } else {
  5227. m_currentFilter.m_required.emplace_back(Detail::make_unique<TestSpec::TagPattern>(token, m_substring));
  5228. }
  5229. }
  5230. m_substring.clear();
  5231. m_exclusion = false;
  5232. m_mode = None;
  5233. }
  5234. TestSpec parseTestSpec( std::string const& arg ) {
  5235. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  5236. }
  5237. } // namespace Catch
  5238. #include <algorithm>
  5239. #include <cstring>
  5240. #include <ostream>
  5241. namespace {
  5242. bool isWhitespace( char c ) {
  5243. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  5244. }
  5245. bool isBreakableBefore( char c ) {
  5246. static const char chars[] = "[({<|";
  5247. return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr;
  5248. }
  5249. bool isBreakableAfter( char c ) {
  5250. static const char chars[] = "])}>.,:;*+-=&/\\";
  5251. return std::memchr( chars, c, sizeof( chars ) - 1 ) != nullptr;
  5252. }
  5253. bool isBoundary( std::string const& line, size_t at ) {
  5254. assert( at > 0 );
  5255. assert( at <= line.size() );
  5256. return at == line.size() ||
  5257. ( isWhitespace( line[at] ) && !isWhitespace( line[at - 1] ) ) ||
  5258. isBreakableBefore( line[at] ) ||
  5259. isBreakableAfter( line[at - 1] );
  5260. }
  5261. } // namespace
  5262. namespace Catch {
  5263. namespace TextFlow {
  5264. void Column::const_iterator::calcLength() {
  5265. m_addHyphen = false;
  5266. m_parsedTo = m_lineStart;
  5267. std::string const& current_line = m_column.m_string;
  5268. if ( current_line[m_lineStart] == '\n' ) {
  5269. ++m_parsedTo;
  5270. }
  5271. const auto maxLineLength = m_column.m_width - indentSize();
  5272. const auto maxParseTo = std::min(current_line.size(), m_lineStart + maxLineLength);
  5273. while ( m_parsedTo < maxParseTo &&
  5274. current_line[m_parsedTo] != '\n' ) {
  5275. ++m_parsedTo;
  5276. }
  5277. // If we encountered a newline before the column is filled,
  5278. // then we linebreak at the newline and consider this line
  5279. // finished.
  5280. if ( m_parsedTo < m_lineStart + maxLineLength ) {
  5281. m_lineLength = m_parsedTo - m_lineStart;
  5282. } else {
  5283. // Look for a natural linebreak boundary in the column
  5284. // (We look from the end, so that the first found boundary is
  5285. // the right one)
  5286. size_t newLineLength = maxLineLength;
  5287. while ( newLineLength > 0 && !isBoundary( current_line, m_lineStart + newLineLength ) ) {
  5288. --newLineLength;
  5289. }
  5290. while ( newLineLength > 0 &&
  5291. isWhitespace( current_line[m_lineStart + newLineLength - 1] ) ) {
  5292. --newLineLength;
  5293. }
  5294. // If we found one, then that is where we linebreak
  5295. if ( newLineLength > 0 ) {
  5296. m_lineLength = newLineLength;
  5297. } else {
  5298. // Otherwise we have to split text with a hyphen
  5299. m_addHyphen = true;
  5300. m_lineLength = maxLineLength - 1;
  5301. }
  5302. }
  5303. }
  5304. size_t Column::const_iterator::indentSize() const {
  5305. auto initial =
  5306. m_lineStart == 0 ? m_column.m_initialIndent : std::string::npos;
  5307. return initial == std::string::npos ? m_column.m_indent : initial;
  5308. }
  5309. std::string
  5310. Column::const_iterator::addIndentAndSuffix( size_t position,
  5311. size_t length ) const {
  5312. std::string ret;
  5313. const auto desired_indent = indentSize();
  5314. ret.reserve( desired_indent + length + m_addHyphen );
  5315. ret.append( desired_indent, ' ' );
  5316. ret.append( m_column.m_string, position, length );
  5317. if ( m_addHyphen ) {
  5318. ret.push_back( '-' );
  5319. }
  5320. return ret;
  5321. }
  5322. Column::const_iterator::const_iterator( Column const& column ): m_column( column ) {
  5323. assert( m_column.m_width > m_column.m_indent );
  5324. assert( m_column.m_initialIndent == std::string::npos ||
  5325. m_column.m_width > m_column.m_initialIndent );
  5326. calcLength();
  5327. if ( m_lineLength == 0 ) {
  5328. m_lineStart = m_column.m_string.size();
  5329. }
  5330. }
  5331. std::string Column::const_iterator::operator*() const {
  5332. assert( m_lineStart <= m_parsedTo );
  5333. return addIndentAndSuffix( m_lineStart, m_lineLength );
  5334. }
  5335. Column::const_iterator& Column::const_iterator::operator++() {
  5336. m_lineStart += m_lineLength;
  5337. std::string const& current_line = m_column.m_string;
  5338. if ( m_lineStart < current_line.size() && current_line[m_lineStart] == '\n' ) {
  5339. m_lineStart += 1;
  5340. } else {
  5341. while ( m_lineStart < current_line.size() &&
  5342. isWhitespace( current_line[m_lineStart] ) ) {
  5343. ++m_lineStart;
  5344. }
  5345. }
  5346. if ( m_lineStart != current_line.size() ) {
  5347. calcLength();
  5348. }
  5349. return *this;
  5350. }
  5351. Column::const_iterator Column::const_iterator::operator++( int ) {
  5352. const_iterator prev( *this );
  5353. operator++();
  5354. return prev;
  5355. }
  5356. std::ostream& operator<<( std::ostream& os, Column const& col ) {
  5357. bool first = true;
  5358. for ( auto line : col ) {
  5359. if ( first ) {
  5360. first = false;
  5361. } else {
  5362. os << '\n';
  5363. }
  5364. os << line;
  5365. }
  5366. return os;
  5367. }
  5368. Column Spacer( size_t spaceWidth ) {
  5369. Column ret{ "" };
  5370. ret.width( spaceWidth );
  5371. return ret;
  5372. }
  5373. Columns::iterator::iterator( Columns const& columns, EndTag ):
  5374. m_columns( columns.m_columns ), m_activeIterators( 0 ) {
  5375. m_iterators.reserve( m_columns.size() );
  5376. for ( auto const& col : m_columns ) {
  5377. m_iterators.push_back( col.end() );
  5378. }
  5379. }
  5380. Columns::iterator::iterator( Columns const& columns ):
  5381. m_columns( columns.m_columns ),
  5382. m_activeIterators( m_columns.size() ) {
  5383. m_iterators.reserve( m_columns.size() );
  5384. for ( auto const& col : m_columns ) {
  5385. m_iterators.push_back( col.begin() );
  5386. }
  5387. }
  5388. std::string Columns::iterator::operator*() const {
  5389. std::string row, padding;
  5390. for ( size_t i = 0; i < m_columns.size(); ++i ) {
  5391. const auto width = m_columns[i].width();
  5392. if ( m_iterators[i] != m_columns[i].end() ) {
  5393. std::string col = *m_iterators[i];
  5394. row += padding;
  5395. row += col;
  5396. padding.clear();
  5397. if ( col.size() < width ) {
  5398. padding.append( width - col.size(), ' ' );
  5399. }
  5400. } else {
  5401. padding.append( width, ' ' );
  5402. }
  5403. }
  5404. return row;
  5405. }
  5406. Columns::iterator& Columns::iterator::operator++() {
  5407. for ( size_t i = 0; i < m_columns.size(); ++i ) {
  5408. if ( m_iterators[i] != m_columns[i].end() ) {
  5409. ++m_iterators[i];
  5410. }
  5411. }
  5412. return *this;
  5413. }
  5414. Columns::iterator Columns::iterator::operator++( int ) {
  5415. iterator prev( *this );
  5416. operator++();
  5417. return prev;
  5418. }
  5419. std::ostream& operator<<( std::ostream& os, Columns const& cols ) {
  5420. bool first = true;
  5421. for ( auto line : cols ) {
  5422. if ( first ) {
  5423. first = false;
  5424. } else {
  5425. os << '\n';
  5426. }
  5427. os << line;
  5428. }
  5429. return os;
  5430. }
  5431. Columns Column::operator+( Column const& other ) {
  5432. Columns cols;
  5433. cols += *this;
  5434. cols += other;
  5435. return cols;
  5436. }
  5437. Columns& Columns::operator+=( Column const& col ) {
  5438. m_columns.push_back( col );
  5439. return *this;
  5440. }
  5441. Columns Columns::operator+( Column const& col ) {
  5442. Columns combined = *this;
  5443. combined += col;
  5444. return combined;
  5445. }
  5446. } // namespace TextFlow
  5447. } // namespace Catch
  5448. #include <exception>
  5449. namespace Catch {
  5450. bool uncaught_exceptions() {
  5451. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  5452. return false;
  5453. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  5454. return std::uncaught_exceptions() > 0;
  5455. #else
  5456. return std::uncaught_exception();
  5457. #endif
  5458. }
  5459. } // end namespace Catch
  5460. namespace Catch {
  5461. WildcardPattern::WildcardPattern( std::string const& pattern,
  5462. CaseSensitive caseSensitivity )
  5463. : m_caseSensitivity( caseSensitivity ),
  5464. m_pattern( normaliseString( pattern ) )
  5465. {
  5466. if( startsWith( m_pattern, '*' ) ) {
  5467. m_pattern = m_pattern.substr( 1 );
  5468. m_wildcard = WildcardAtStart;
  5469. }
  5470. if( endsWith( m_pattern, '*' ) ) {
  5471. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  5472. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  5473. }
  5474. }
  5475. bool WildcardPattern::matches( std::string const& str ) const {
  5476. switch( m_wildcard ) {
  5477. case NoWildcard:
  5478. return m_pattern == normaliseString( str );
  5479. case WildcardAtStart:
  5480. return endsWith( normaliseString( str ), m_pattern );
  5481. case WildcardAtEnd:
  5482. return startsWith( normaliseString( str ), m_pattern );
  5483. case WildcardAtBothEnds:
  5484. return contains( normaliseString( str ), m_pattern );
  5485. default:
  5486. CATCH_INTERNAL_ERROR( "Unknown enum" );
  5487. }
  5488. }
  5489. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  5490. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  5491. }
  5492. }
  5493. // Note: swapping these two includes around causes MSVC to error out
  5494. // while in /permissive- mode. No, I don't know why.
  5495. // Tested on VS 2019, 18.{3, 4}.x
  5496. #include <iomanip>
  5497. #include <type_traits>
  5498. namespace Catch {
  5499. namespace {
  5500. size_t trailingBytes(unsigned char c) {
  5501. if ((c & 0xE0) == 0xC0) {
  5502. return 2;
  5503. }
  5504. if ((c & 0xF0) == 0xE0) {
  5505. return 3;
  5506. }
  5507. if ((c & 0xF8) == 0xF0) {
  5508. return 4;
  5509. }
  5510. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  5511. }
  5512. uint32_t headerValue(unsigned char c) {
  5513. if ((c & 0xE0) == 0xC0) {
  5514. return c & 0x1F;
  5515. }
  5516. if ((c & 0xF0) == 0xE0) {
  5517. return c & 0x0F;
  5518. }
  5519. if ((c & 0xF8) == 0xF0) {
  5520. return c & 0x07;
  5521. }
  5522. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  5523. }
  5524. void hexEscapeChar(std::ostream& os, unsigned char c) {
  5525. std::ios_base::fmtflags f(os.flags());
  5526. os << "\\x"
  5527. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  5528. << static_cast<int>(c);
  5529. os.flags(f);
  5530. }
  5531. bool shouldNewline(XmlFormatting fmt) {
  5532. return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Newline));
  5533. }
  5534. bool shouldIndent(XmlFormatting fmt) {
  5535. return !!(static_cast<std::underlying_type_t<XmlFormatting>>(fmt & XmlFormatting::Indent));
  5536. }
  5537. } // anonymous namespace
  5538. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  5539. return static_cast<XmlFormatting>(
  5540. static_cast<std::underlying_type_t<XmlFormatting>>(lhs) |
  5541. static_cast<std::underlying_type_t<XmlFormatting>>(rhs)
  5542. );
  5543. }
  5544. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  5545. return static_cast<XmlFormatting>(
  5546. static_cast<std::underlying_type_t<XmlFormatting>>(lhs) &
  5547. static_cast<std::underlying_type_t<XmlFormatting>>(rhs)
  5548. );
  5549. }
  5550. XmlEncode::XmlEncode( StringRef str, ForWhat forWhat )
  5551. : m_str( str ),
  5552. m_forWhat( forWhat )
  5553. {}
  5554. void XmlEncode::encodeTo( std::ostream& os ) const {
  5555. // Apostrophe escaping not necessary if we always use " to write attributes
  5556. // (see: http://www.w3.org/TR/xml/#syntax)
  5557. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  5558. unsigned char c = static_cast<unsigned char>(m_str[idx]);
  5559. switch (c) {
  5560. case '<': os << "&lt;"; break;
  5561. case '&': os << "&amp;"; break;
  5562. case '>':
  5563. // See: http://www.w3.org/TR/xml/#syntax
  5564. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  5565. os << "&gt;";
  5566. else
  5567. os << c;
  5568. break;
  5569. case '\"':
  5570. if (m_forWhat == ForAttributes)
  5571. os << "&quot;";
  5572. else
  5573. os << c;
  5574. break;
  5575. default:
  5576. // Check for control characters and invalid utf-8
  5577. // Escape control characters in standard ascii
  5578. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  5579. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  5580. hexEscapeChar(os, c);
  5581. break;
  5582. }
  5583. // Plain ASCII: Write it to stream
  5584. if (c < 0x7F) {
  5585. os << c;
  5586. break;
  5587. }
  5588. // UTF-8 territory
  5589. // Check if the encoding is valid and if it is not, hex escape bytes.
  5590. // Important: We do not check the exact decoded values for validity, only the encoding format
  5591. // First check that this bytes is a valid lead byte:
  5592. // This means that it is not encoded as 1111 1XXX
  5593. // Or as 10XX XXXX
  5594. if (c < 0xC0 ||
  5595. c >= 0xF8) {
  5596. hexEscapeChar(os, c);
  5597. break;
  5598. }
  5599. auto encBytes = trailingBytes(c);
  5600. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  5601. if (idx + encBytes - 1 >= m_str.size()) {
  5602. hexEscapeChar(os, c);
  5603. break;
  5604. }
  5605. // The header is valid, check data
  5606. // The next encBytes bytes must together be a valid utf-8
  5607. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  5608. bool valid = true;
  5609. uint32_t value = headerValue(c);
  5610. for (std::size_t n = 1; n < encBytes; ++n) {
  5611. unsigned char nc = static_cast<unsigned char>(m_str[idx + n]);
  5612. valid &= ((nc & 0xC0) == 0x80);
  5613. value = (value << 6) | (nc & 0x3F);
  5614. }
  5615. if (
  5616. // Wrong bit pattern of following bytes
  5617. (!valid) ||
  5618. // Overlong encodings
  5619. (value < 0x80) ||
  5620. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  5621. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  5622. // Encoded value out of range
  5623. (value >= 0x110000)
  5624. ) {
  5625. hexEscapeChar(os, c);
  5626. break;
  5627. }
  5628. // If we got here, this is in fact a valid(ish) utf-8 sequence
  5629. for (std::size_t n = 0; n < encBytes; ++n) {
  5630. os << m_str[idx + n];
  5631. }
  5632. idx += encBytes - 1;
  5633. break;
  5634. }
  5635. }
  5636. }
  5637. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  5638. xmlEncode.encodeTo( os );
  5639. return os;
  5640. }
  5641. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  5642. : m_writer( writer ),
  5643. m_fmt(fmt)
  5644. {}
  5645. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  5646. : m_writer( other.m_writer ),
  5647. m_fmt(other.m_fmt)
  5648. {
  5649. other.m_writer = nullptr;
  5650. other.m_fmt = XmlFormatting::None;
  5651. }
  5652. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  5653. if ( m_writer ) {
  5654. m_writer->endElement();
  5655. }
  5656. m_writer = other.m_writer;
  5657. other.m_writer = nullptr;
  5658. m_fmt = other.m_fmt;
  5659. other.m_fmt = XmlFormatting::None;
  5660. return *this;
  5661. }
  5662. XmlWriter::ScopedElement::~ScopedElement() {
  5663. if (m_writer) {
  5664. m_writer->endElement(m_fmt);
  5665. }
  5666. }
  5667. XmlWriter::ScopedElement&
  5668. XmlWriter::ScopedElement::writeText( StringRef text, XmlFormatting fmt ) {
  5669. m_writer->writeText( text, fmt );
  5670. return *this;
  5671. }
  5672. XmlWriter::ScopedElement&
  5673. XmlWriter::ScopedElement::writeAttribute( StringRef name,
  5674. StringRef attribute ) {
  5675. m_writer->writeAttribute( name, attribute );
  5676. return *this;
  5677. }
  5678. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  5679. {
  5680. writeDeclaration();
  5681. }
  5682. XmlWriter::~XmlWriter() {
  5683. while (!m_tags.empty()) {
  5684. endElement();
  5685. }
  5686. newlineIfNecessary();
  5687. }
  5688. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  5689. ensureTagClosed();
  5690. newlineIfNecessary();
  5691. if (shouldIndent(fmt)) {
  5692. m_os << m_indent;
  5693. m_indent += " ";
  5694. }
  5695. m_os << '<' << name;
  5696. m_tags.push_back( name );
  5697. m_tagIsOpen = true;
  5698. applyFormatting(fmt);
  5699. return *this;
  5700. }
  5701. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  5702. ScopedElement scoped( this, fmt );
  5703. startElement( name, fmt );
  5704. return scoped;
  5705. }
  5706. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  5707. m_indent = m_indent.substr(0, m_indent.size() - 2);
  5708. if( m_tagIsOpen ) {
  5709. m_os << "/>";
  5710. m_tagIsOpen = false;
  5711. } else {
  5712. newlineIfNecessary();
  5713. if (shouldIndent(fmt)) {
  5714. m_os << m_indent;
  5715. }
  5716. m_os << "</" << m_tags.back() << '>';
  5717. }
  5718. m_os << std::flush;
  5719. applyFormatting(fmt);
  5720. m_tags.pop_back();
  5721. return *this;
  5722. }
  5723. XmlWriter& XmlWriter::writeAttribute( StringRef name,
  5724. StringRef attribute ) {
  5725. if( !name.empty() && !attribute.empty() )
  5726. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  5727. return *this;
  5728. }
  5729. XmlWriter& XmlWriter::writeAttribute( StringRef name, bool attribute ) {
  5730. writeAttribute(name, (attribute ? "true"_sr : "false"_sr));
  5731. return *this;
  5732. }
  5733. XmlWriter& XmlWriter::writeAttribute( StringRef name,
  5734. char const* attribute ) {
  5735. writeAttribute( name, StringRef( attribute ) );
  5736. return *this;
  5737. }
  5738. XmlWriter& XmlWriter::writeText( StringRef text, XmlFormatting fmt ) {
  5739. CATCH_ENFORCE(!m_tags.empty(), "Cannot write text as top level element");
  5740. if( !text.empty() ){
  5741. bool tagWasOpen = m_tagIsOpen;
  5742. ensureTagClosed();
  5743. if (tagWasOpen && shouldIndent(fmt)) {
  5744. m_os << m_indent;
  5745. }
  5746. m_os << XmlEncode( text, XmlEncode::ForTextNodes );
  5747. applyFormatting(fmt);
  5748. }
  5749. return *this;
  5750. }
  5751. XmlWriter& XmlWriter::writeComment( StringRef text, XmlFormatting fmt ) {
  5752. ensureTagClosed();
  5753. if (shouldIndent(fmt)) {
  5754. m_os << m_indent;
  5755. }
  5756. m_os << "<!-- " << text << " -->";
  5757. applyFormatting(fmt);
  5758. return *this;
  5759. }
  5760. void XmlWriter::writeStylesheetRef( StringRef url ) {
  5761. m_os << R"(<?xml-stylesheet type="text/xsl" href=")" << url << R"("?>)" << '\n';
  5762. }
  5763. void XmlWriter::ensureTagClosed() {
  5764. if( m_tagIsOpen ) {
  5765. m_os << '>' << std::flush;
  5766. newlineIfNecessary();
  5767. m_tagIsOpen = false;
  5768. }
  5769. }
  5770. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  5771. m_needsNewline = shouldNewline(fmt);
  5772. }
  5773. void XmlWriter::writeDeclaration() {
  5774. m_os << R"(<?xml version="1.0" encoding="UTF-8"?>)" << '\n';
  5775. }
  5776. void XmlWriter::newlineIfNecessary() {
  5777. if( m_needsNewline ) {
  5778. m_os << '\n' << std::flush;
  5779. m_needsNewline = false;
  5780. }
  5781. }
  5782. }
  5783. namespace Catch {
  5784. namespace Matchers {
  5785. std::string MatcherUntypedBase::toString() const {
  5786. if (m_cachedToString.empty()) {
  5787. m_cachedToString = describe();
  5788. }
  5789. return m_cachedToString;
  5790. }
  5791. MatcherUntypedBase::~MatcherUntypedBase() = default;
  5792. } // namespace Matchers
  5793. } // namespace Catch
  5794. namespace Catch {
  5795. namespace Matchers {
  5796. std::string IsEmptyMatcher::describe() const {
  5797. return "is empty";
  5798. }
  5799. std::string HasSizeMatcher::describe() const {
  5800. ReusableStringStream sstr;
  5801. sstr << "has size == " << m_target_size;
  5802. return sstr.str();
  5803. }
  5804. IsEmptyMatcher IsEmpty() {
  5805. return {};
  5806. }
  5807. HasSizeMatcher SizeIs(std::size_t sz) {
  5808. return HasSizeMatcher{ sz };
  5809. }
  5810. } // end namespace Matchers
  5811. } // end namespace Catch
  5812. namespace Catch {
  5813. namespace Matchers {
  5814. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  5815. return ex.what() == m_message;
  5816. }
  5817. std::string ExceptionMessageMatcher::describe() const {
  5818. return "exception message matches \"" + m_message + '"';
  5819. }
  5820. ExceptionMessageMatcher Message(std::string const& message) {
  5821. return ExceptionMessageMatcher(message);
  5822. }
  5823. } // namespace Matchers
  5824. } // namespace Catch
  5825. #include <algorithm>
  5826. #include <cmath>
  5827. #include <cstdlib>
  5828. #include <cstdint>
  5829. #include <sstream>
  5830. #include <iomanip>
  5831. #include <limits>
  5832. namespace Catch {
  5833. namespace {
  5834. template <typename FP>
  5835. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  5836. // Comparison with NaN should always be false.
  5837. // This way we can rule it out before getting into the ugly details
  5838. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  5839. return false;
  5840. }
  5841. // This should also handle positive and negative zeros, infinities
  5842. const auto ulpDist = ulpDistance(lhs, rhs);
  5843. return ulpDist <= maxUlpDiff;
  5844. }
  5845. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  5846. float nextafter(float x, float y) {
  5847. return ::nextafterf(x, y);
  5848. }
  5849. double nextafter(double x, double y) {
  5850. return ::nextafter(x, y);
  5851. }
  5852. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  5853. template <typename FP>
  5854. FP step(FP start, FP direction, uint64_t steps) {
  5855. for (uint64_t i = 0; i < steps; ++i) {
  5856. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  5857. start = Catch::nextafter(start, direction);
  5858. #else
  5859. start = std::nextafter(start, direction);
  5860. #endif
  5861. }
  5862. return start;
  5863. }
  5864. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  5865. // But without the subtraction to allow for INFINITY in comparison
  5866. bool marginComparison(double lhs, double rhs, double margin) {
  5867. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  5868. }
  5869. template <typename FloatingPoint>
  5870. void write(std::ostream& out, FloatingPoint num) {
  5871. out << std::scientific
  5872. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  5873. << num;
  5874. }
  5875. } // end anonymous namespace
  5876. namespace Matchers {
  5877. namespace Detail {
  5878. enum class FloatingPointKind : uint8_t {
  5879. Float,
  5880. Double
  5881. };
  5882. } // end namespace Detail
  5883. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  5884. :m_target{ target }, m_margin{ margin } {
  5885. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  5886. << " Margin has to be non-negative.");
  5887. }
  5888. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  5889. // But without the subtraction to allow for INFINITY in comparison
  5890. bool WithinAbsMatcher::match(double const& matchee) const {
  5891. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  5892. }
  5893. std::string WithinAbsMatcher::describe() const {
  5894. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  5895. }
  5896. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, Detail::FloatingPointKind baseType)
  5897. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  5898. CATCH_ENFORCE(m_type == Detail::FloatingPointKind::Double
  5899. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  5900. "Provided ULP is impossibly large for a float comparison.");
  5901. CATCH_ENFORCE( std::numeric_limits<double>::is_iec559,
  5902. "WithinUlp matcher only supports platforms with "
  5903. "IEEE-754 compatible floating point representation" );
  5904. }
  5905. #if defined(__clang__)
  5906. #pragma clang diagnostic push
  5907. // Clang <3.5 reports on the default branch in the switch below
  5908. #pragma clang diagnostic ignored "-Wunreachable-code"
  5909. #endif
  5910. bool WithinUlpsMatcher::match(double const& matchee) const {
  5911. switch (m_type) {
  5912. case Detail::FloatingPointKind::Float:
  5913. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  5914. case Detail::FloatingPointKind::Double:
  5915. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  5916. default:
  5917. CATCH_INTERNAL_ERROR( "Unknown Detail::FloatingPointKind value" );
  5918. }
  5919. }
  5920. #if defined(__clang__)
  5921. #pragma clang diagnostic pop
  5922. #endif
  5923. std::string WithinUlpsMatcher::describe() const {
  5924. std::stringstream ret;
  5925. ret << "is within " << m_ulps << " ULPs of ";
  5926. if (m_type == Detail::FloatingPointKind::Float) {
  5927. write(ret, static_cast<float>(m_target));
  5928. ret << 'f';
  5929. } else {
  5930. write(ret, m_target);
  5931. }
  5932. ret << " ([";
  5933. if (m_type == Detail::FloatingPointKind::Double) {
  5934. write( ret,
  5935. step( m_target,
  5936. -std::numeric_limits<double>::infinity(),
  5937. m_ulps ) );
  5938. ret << ", ";
  5939. write( ret,
  5940. step( m_target,
  5941. std::numeric_limits<double>::infinity(),
  5942. m_ulps ) );
  5943. } else {
  5944. // We have to cast INFINITY to float because of MinGW, see #1782
  5945. write( ret,
  5946. step( static_cast<float>( m_target ),
  5947. -std::numeric_limits<float>::infinity(),
  5948. m_ulps ) );
  5949. ret << ", ";
  5950. write( ret,
  5951. step( static_cast<float>( m_target ),
  5952. std::numeric_limits<float>::infinity(),
  5953. m_ulps ) );
  5954. }
  5955. ret << "])";
  5956. return ret.str();
  5957. }
  5958. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  5959. m_target(target),
  5960. m_epsilon(epsilon){
  5961. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  5962. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  5963. }
  5964. bool WithinRelMatcher::match(double const& matchee) const {
  5965. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  5966. return marginComparison(matchee, m_target,
  5967. std::isinf(relMargin)? 0 : relMargin);
  5968. }
  5969. std::string WithinRelMatcher::describe() const {
  5970. Catch::ReusableStringStream sstr;
  5971. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  5972. return sstr.str();
  5973. }
  5974. WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  5975. return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Double);
  5976. }
  5977. WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  5978. return WithinUlpsMatcher(target, maxUlpDiff, Detail::FloatingPointKind::Float);
  5979. }
  5980. WithinAbsMatcher WithinAbs(double target, double margin) {
  5981. return WithinAbsMatcher(target, margin);
  5982. }
  5983. WithinRelMatcher WithinRel(double target, double eps) {
  5984. return WithinRelMatcher(target, eps);
  5985. }
  5986. WithinRelMatcher WithinRel(double target) {
  5987. return WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  5988. }
  5989. WithinRelMatcher WithinRel(float target, float eps) {
  5990. return WithinRelMatcher(target, eps);
  5991. }
  5992. WithinRelMatcher WithinRel(float target) {
  5993. return WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  5994. }
  5995. } // namespace Matchers
  5996. } // namespace Catch
  5997. std::string Catch::Matchers::Detail::finalizeDescription(const std::string& desc) {
  5998. if (desc.empty()) {
  5999. return "matches undescribed predicate";
  6000. } else {
  6001. return "matches predicate: \"" + desc + '"';
  6002. }
  6003. }
  6004. namespace Catch {
  6005. namespace Matchers {
  6006. std::string AllTrueMatcher::describe() const { return "contains only true"; }
  6007. AllTrueMatcher AllTrue() { return AllTrueMatcher{}; }
  6008. std::string NoneTrueMatcher::describe() const { return "contains no true"; }
  6009. NoneTrueMatcher NoneTrue() { return NoneTrueMatcher{}; }
  6010. std::string AnyTrueMatcher::describe() const { return "contains at least one true"; }
  6011. AnyTrueMatcher AnyTrue() { return AnyTrueMatcher{}; }
  6012. } // namespace Matchers
  6013. } // namespace Catch
  6014. #include <regex>
  6015. namespace Catch {
  6016. namespace Matchers {
  6017. CasedString::CasedString( std::string const& str, CaseSensitive caseSensitivity )
  6018. : m_caseSensitivity( caseSensitivity ),
  6019. m_str( adjustString( str ) )
  6020. {}
  6021. std::string CasedString::adjustString( std::string const& str ) const {
  6022. return m_caseSensitivity == CaseSensitive::No
  6023. ? toLower( str )
  6024. : str;
  6025. }
  6026. StringRef CasedString::caseSensitivitySuffix() const {
  6027. return m_caseSensitivity == CaseSensitive::Yes
  6028. ? StringRef()
  6029. : " (case insensitive)"_sr;
  6030. }
  6031. StringMatcherBase::StringMatcherBase( StringRef operation, CasedString const& comparator )
  6032. : m_comparator( comparator ),
  6033. m_operation( operation ) {
  6034. }
  6035. std::string StringMatcherBase::describe() const {
  6036. std::string description;
  6037. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6038. m_comparator.caseSensitivitySuffix().size());
  6039. description += m_operation;
  6040. description += ": \"";
  6041. description += m_comparator.m_str;
  6042. description += '"';
  6043. description += m_comparator.caseSensitivitySuffix();
  6044. return description;
  6045. }
  6046. StringEqualsMatcher::StringEqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals"_sr, comparator ) {}
  6047. bool StringEqualsMatcher::match( std::string const& source ) const {
  6048. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6049. }
  6050. StringContainsMatcher::StringContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains"_sr, comparator ) {}
  6051. bool StringContainsMatcher::match( std::string const& source ) const {
  6052. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6053. }
  6054. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with"_sr, comparator ) {}
  6055. bool StartsWithMatcher::match( std::string const& source ) const {
  6056. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6057. }
  6058. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with"_sr, comparator ) {}
  6059. bool EndsWithMatcher::match( std::string const& source ) const {
  6060. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6061. }
  6062. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive caseSensitivity): m_regex(CATCH_MOVE(regex)), m_caseSensitivity(caseSensitivity) {}
  6063. bool RegexMatcher::match(std::string const& matchee) const {
  6064. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6065. if (m_caseSensitivity == CaseSensitive::No) {
  6066. flags |= std::regex::icase;
  6067. }
  6068. auto reg = std::regex(m_regex, flags);
  6069. return std::regex_match(matchee, reg);
  6070. }
  6071. std::string RegexMatcher::describe() const {
  6072. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Yes)? " case sensitively" : " case insensitively");
  6073. }
  6074. StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity ) {
  6075. return StringEqualsMatcher( CasedString( str, caseSensitivity) );
  6076. }
  6077. StringContainsMatcher ContainsSubstring( std::string const& str, CaseSensitive caseSensitivity ) {
  6078. return StringContainsMatcher( CasedString( str, caseSensitivity) );
  6079. }
  6080. EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity ) {
  6081. return EndsWithMatcher( CasedString( str, caseSensitivity) );
  6082. }
  6083. StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity ) {
  6084. return StartsWithMatcher( CasedString( str, caseSensitivity) );
  6085. }
  6086. RegexMatcher Matches(std::string const& regex, CaseSensitive caseSensitivity) {
  6087. return RegexMatcher(regex, caseSensitivity);
  6088. }
  6089. } // namespace Matchers
  6090. } // namespace Catch
  6091. namespace Catch {
  6092. namespace Matchers {
  6093. MatcherGenericBase::~MatcherGenericBase() = default;
  6094. namespace Detail {
  6095. std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end) {
  6096. std::string description;
  6097. std::size_t combined_size = 4;
  6098. for ( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) {
  6099. combined_size += desc->size();
  6100. }
  6101. combined_size += static_cast<size_t>(descriptions_end - descriptions_begin - 1) * combine.size();
  6102. description.reserve(combined_size);
  6103. description += "( ";
  6104. bool first = true;
  6105. for( auto desc = descriptions_begin; desc != descriptions_end; ++desc ) {
  6106. if( first )
  6107. first = false;
  6108. else
  6109. description += combine;
  6110. description += *desc;
  6111. }
  6112. description += " )";
  6113. return description;
  6114. }
  6115. } // namespace Detail
  6116. } // namespace Matchers
  6117. } // namespace Catch
  6118. namespace Catch {
  6119. // This is the general overload that takes a any string matcher
  6120. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6121. // the Equals matcher (so the header does not mention matchers)
  6122. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  6123. std::string exceptionMessage = Catch::translateActiveException();
  6124. MatchExpr<std::string, StringMatcher const&> expr( CATCH_MOVE(exceptionMessage), matcher, matcherString );
  6125. handler.handleExpr( expr );
  6126. }
  6127. } // namespace Catch
  6128. #include <ostream>
  6129. namespace Catch {
  6130. AutomakeReporter::~AutomakeReporter() {}
  6131. void AutomakeReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  6132. // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR.
  6133. m_stream << ":test-result: ";
  6134. if (_testCaseStats.totals.assertions.allPassed()) {
  6135. m_stream << "PASS";
  6136. } else if (_testCaseStats.totals.assertions.allOk()) {
  6137. m_stream << "XFAIL";
  6138. } else {
  6139. m_stream << "FAIL";
  6140. }
  6141. m_stream << ' ' << _testCaseStats.testInfo->name << '\n';
  6142. StreamingReporterBase::testCaseEnded(_testCaseStats);
  6143. }
  6144. void AutomakeReporter::skipTest(TestCaseInfo const& testInfo) {
  6145. m_stream << ":test-result: SKIP " << testInfo.name << '\n';
  6146. }
  6147. } // end namespace Catch
  6148. namespace Catch {
  6149. ReporterBase::ReporterBase( ReporterConfig&& config ):
  6150. IEventListener( config.fullConfig() ),
  6151. m_wrapped_stream( CATCH_MOVE(config).takeStream() ),
  6152. m_stream( m_wrapped_stream->stream() ),
  6153. m_colour( makeColourImpl( config.colourMode(), m_wrapped_stream.get() ) ),
  6154. m_customOptions( config.customOptions() )
  6155. {}
  6156. ReporterBase::~ReporterBase() = default;
  6157. void ReporterBase::listReporters(
  6158. std::vector<ReporterDescription> const& descriptions ) {
  6159. defaultListReporters(m_stream, descriptions, m_config->verbosity());
  6160. }
  6161. void ReporterBase::listListeners(
  6162. std::vector<ListenerDescription> const& descriptions ) {
  6163. defaultListListeners( m_stream, descriptions );
  6164. }
  6165. void ReporterBase::listTests(std::vector<TestCaseHandle> const& tests) {
  6166. defaultListTests(m_stream,
  6167. m_colour.get(),
  6168. tests,
  6169. m_config->hasTestFilters(),
  6170. m_config->verbosity());
  6171. }
  6172. void ReporterBase::listTags(std::vector<TagInfo> const& tags) {
  6173. defaultListTags( m_stream, tags, m_config->hasTestFilters() );
  6174. }
  6175. } // namespace Catch
  6176. #include <ostream>
  6177. namespace {
  6178. constexpr Catch::StringRef bothOrAll( std::uint64_t count ) {
  6179. switch (count) {
  6180. case 1:
  6181. return Catch::StringRef{};
  6182. case 2:
  6183. return "both "_catch_sr;
  6184. default:
  6185. return "all "_catch_sr;
  6186. }
  6187. }
  6188. } // anon namespace
  6189. namespace Catch {
  6190. namespace {
  6191. // Colour::LightGrey
  6192. static constexpr Colour::Code compactDimColour = Colour::FileName;
  6193. #ifdef CATCH_PLATFORM_MAC
  6194. static constexpr Catch::StringRef compactFailedString = "FAILED"_sr;
  6195. static constexpr Catch::StringRef compactPassedString = "PASSED"_sr;
  6196. #else
  6197. static constexpr Catch::StringRef compactFailedString = "failed"_sr;
  6198. static constexpr Catch::StringRef compactPassedString = "passed"_sr;
  6199. #endif
  6200. // Colour, message variants:
  6201. // - white: No tests ran.
  6202. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  6203. // - white: Passed [both/all] N test cases (no assertions).
  6204. // - red: Failed N tests cases, failed M assertions.
  6205. // - green: Passed [both/all] N tests cases with M assertions.
  6206. void printTotals(std::ostream& out, const Totals& totals, ColourImpl* colourImpl) {
  6207. if (totals.testCases.total() == 0) {
  6208. out << "No tests ran.";
  6209. } else if (totals.testCases.failed == totals.testCases.total()) {
  6210. auto guard = colourImpl->guardColour( Colour::ResultError ).engage( out );
  6211. const StringRef qualify_assertions_failed =
  6212. totals.assertions.failed == totals.assertions.total() ?
  6213. bothOrAll(totals.assertions.failed) : StringRef{};
  6214. out <<
  6215. "Failed " << bothOrAll(totals.testCases.failed)
  6216. << pluralise(totals.testCases.failed, "test case"_sr) << ", "
  6217. "failed " << qualify_assertions_failed <<
  6218. pluralise(totals.assertions.failed, "assertion"_sr) << '.';
  6219. } else if (totals.assertions.total() == 0) {
  6220. out <<
  6221. "Passed " << bothOrAll(totals.testCases.total())
  6222. << pluralise(totals.testCases.total(), "test case"_sr)
  6223. << " (no assertions).";
  6224. } else if (totals.assertions.failed) {
  6225. out << colourImpl->guardColour( Colour::ResultError ) <<
  6226. "Failed " << pluralise(totals.testCases.failed, "test case"_sr) << ", "
  6227. "failed " << pluralise(totals.assertions.failed, "assertion"_sr) << '.';
  6228. } else {
  6229. out << colourImpl->guardColour( Colour::ResultSuccess ) <<
  6230. "Passed " << bothOrAll(totals.testCases.passed)
  6231. << pluralise(totals.testCases.passed, "test case"_sr) <<
  6232. " with " << pluralise(totals.assertions.passed, "assertion"_sr) << '.';
  6233. }
  6234. }
  6235. // Implementation of CompactReporter formatting
  6236. class AssertionPrinter {
  6237. public:
  6238. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  6239. AssertionPrinter(AssertionPrinter const&) = delete;
  6240. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages, ColourImpl* colourImpl_)
  6241. : stream(_stream)
  6242. , result(_stats.assertionResult)
  6243. , messages(_stats.infoMessages)
  6244. , itMessage(_stats.infoMessages.begin())
  6245. , printInfoMessages(_printInfoMessages)
  6246. , colourImpl(colourImpl_)
  6247. {}
  6248. void print() {
  6249. printSourceInfo();
  6250. itMessage = messages.begin();
  6251. switch (result.getResultType()) {
  6252. case ResultWas::Ok:
  6253. printResultType(Colour::ResultSuccess, compactPassedString);
  6254. printOriginalExpression();
  6255. printReconstructedExpression();
  6256. if (!result.hasExpression())
  6257. printRemainingMessages(Colour::None);
  6258. else
  6259. printRemainingMessages();
  6260. break;
  6261. case ResultWas::ExpressionFailed:
  6262. if (result.isOk())
  6263. printResultType(Colour::ResultSuccess, compactFailedString + " - but was ok"_sr);
  6264. else
  6265. printResultType(Colour::Error, compactFailedString);
  6266. printOriginalExpression();
  6267. printReconstructedExpression();
  6268. printRemainingMessages();
  6269. break;
  6270. case ResultWas::ThrewException:
  6271. printResultType(Colour::Error, compactFailedString);
  6272. printIssue("unexpected exception with message:");
  6273. printMessage();
  6274. printExpressionWas();
  6275. printRemainingMessages();
  6276. break;
  6277. case ResultWas::FatalErrorCondition:
  6278. printResultType(Colour::Error, compactFailedString);
  6279. printIssue("fatal error condition with message:");
  6280. printMessage();
  6281. printExpressionWas();
  6282. printRemainingMessages();
  6283. break;
  6284. case ResultWas::DidntThrowException:
  6285. printResultType(Colour::Error, compactFailedString);
  6286. printIssue("expected exception, got none");
  6287. printExpressionWas();
  6288. printRemainingMessages();
  6289. break;
  6290. case ResultWas::Info:
  6291. printResultType(Colour::None, "info"_sr);
  6292. printMessage();
  6293. printRemainingMessages();
  6294. break;
  6295. case ResultWas::Warning:
  6296. printResultType(Colour::None, "warning"_sr);
  6297. printMessage();
  6298. printRemainingMessages();
  6299. break;
  6300. case ResultWas::ExplicitFailure:
  6301. printResultType(Colour::Error, compactFailedString);
  6302. printIssue("explicitly");
  6303. printRemainingMessages(Colour::None);
  6304. break;
  6305. // These cases are here to prevent compiler warnings
  6306. case ResultWas::Unknown:
  6307. case ResultWas::FailureBit:
  6308. case ResultWas::Exception:
  6309. printResultType(Colour::Error, "** internal error **");
  6310. break;
  6311. }
  6312. }
  6313. private:
  6314. void printSourceInfo() const {
  6315. stream << colourImpl->guardColour( Colour::FileName )
  6316. << result.getSourceInfo() << ':';
  6317. }
  6318. void printResultType(Colour::Code colour, StringRef passOrFail) const {
  6319. if (!passOrFail.empty()) {
  6320. stream << colourImpl->guardColour(colour) << ' ' << passOrFail;
  6321. stream << ':';
  6322. }
  6323. }
  6324. void printIssue(char const* issue) const {
  6325. stream << ' ' << issue;
  6326. }
  6327. void printExpressionWas() {
  6328. if (result.hasExpression()) {
  6329. stream << ';';
  6330. {
  6331. stream << colourImpl->guardColour(compactDimColour) << " expression was:";
  6332. }
  6333. printOriginalExpression();
  6334. }
  6335. }
  6336. void printOriginalExpression() const {
  6337. if (result.hasExpression()) {
  6338. stream << ' ' << result.getExpression();
  6339. }
  6340. }
  6341. void printReconstructedExpression() const {
  6342. if (result.hasExpandedExpression()) {
  6343. stream << colourImpl->guardColour(compactDimColour) << " for: ";
  6344. stream << result.getExpandedExpression();
  6345. }
  6346. }
  6347. void printMessage() {
  6348. if (itMessage != messages.end()) {
  6349. stream << " '" << itMessage->message << '\'';
  6350. ++itMessage;
  6351. }
  6352. }
  6353. void printRemainingMessages(Colour::Code colour = compactDimColour) {
  6354. if (itMessage == messages.end())
  6355. return;
  6356. const auto itEnd = messages.cend();
  6357. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  6358. stream << colourImpl->guardColour( colour ) << " with "
  6359. << pluralise( N, "message"_sr ) << ':';
  6360. while (itMessage != itEnd) {
  6361. // If this assertion is a warning ignore any INFO messages
  6362. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  6363. printMessage();
  6364. if (itMessage != itEnd) {
  6365. stream << colourImpl->guardColour(compactDimColour) << " and";
  6366. }
  6367. continue;
  6368. }
  6369. ++itMessage;
  6370. }
  6371. }
  6372. private:
  6373. std::ostream& stream;
  6374. AssertionResult const& result;
  6375. std::vector<MessageInfo> messages;
  6376. std::vector<MessageInfo>::const_iterator itMessage;
  6377. bool printInfoMessages;
  6378. ColourImpl* colourImpl;
  6379. };
  6380. } // anon namespace
  6381. std::string CompactReporter::getDescription() {
  6382. return "Reports test results on a single line, suitable for IDEs";
  6383. }
  6384. void CompactReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
  6385. m_stream << "No test cases matched '" << unmatchedSpec << "'\n";
  6386. }
  6387. void CompactReporter::testRunStarting( TestRunInfo const& ) {
  6388. if ( m_config->testSpec().hasFilters() ) {
  6389. m_stream << m_colour->guardColour( Colour::BrightYellow )
  6390. << "Filters: "
  6391. << serializeFilters( m_config->getTestsOrTags() )
  6392. << '\n';
  6393. }
  6394. m_stream << "RNG seed: " << m_config->rngSeed() << '\n';
  6395. }
  6396. void CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  6397. AssertionResult const& result = _assertionStats.assertionResult;
  6398. bool printInfoMessages = true;
  6399. // Drop out if result was successful and we're not printing those
  6400. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  6401. if( result.getResultType() != ResultWas::Warning )
  6402. return;
  6403. printInfoMessages = false;
  6404. }
  6405. AssertionPrinter printer( m_stream, _assertionStats, printInfoMessages, m_colour.get() );
  6406. printer.print();
  6407. m_stream << '\n' << std::flush;
  6408. }
  6409. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  6410. double dur = _sectionStats.durationInSeconds;
  6411. if ( shouldShowDuration( *m_config, dur ) ) {
  6412. m_stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush;
  6413. }
  6414. }
  6415. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  6416. printTotals( m_stream, _testRunStats.totals, m_colour.get() );
  6417. m_stream << "\n\n" << std::flush;
  6418. StreamingReporterBase::testRunEnded( _testRunStats );
  6419. }
  6420. CompactReporter::~CompactReporter() {}
  6421. } // end namespace Catch
  6422. #include <cstdio>
  6423. #if defined(_MSC_VER)
  6424. #pragma warning(push)
  6425. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  6426. // Note that 4062 (not all labels are handled and default is missing) is enabled
  6427. #endif
  6428. #if defined(__clang__)
  6429. # pragma clang diagnostic push
  6430. // For simplicity, benchmarking-only helpers are always enabled
  6431. # pragma clang diagnostic ignored "-Wunused-function"
  6432. #endif
  6433. namespace Catch {
  6434. namespace {
  6435. // Formatter impl for ConsoleReporter
  6436. class ConsoleAssertionPrinter {
  6437. public:
  6438. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  6439. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  6440. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, ColourImpl* colourImpl_, bool _printInfoMessages)
  6441. : stream(_stream),
  6442. stats(_stats),
  6443. result(_stats.assertionResult),
  6444. colour(Colour::None),
  6445. message(result.getMessage()),
  6446. messages(_stats.infoMessages),
  6447. colourImpl(colourImpl_),
  6448. printInfoMessages(_printInfoMessages) {
  6449. switch (result.getResultType()) {
  6450. case ResultWas::Ok:
  6451. colour = Colour::Success;
  6452. passOrFail = "PASSED"_sr;
  6453. //if( result.hasMessage() )
  6454. if (_stats.infoMessages.size() == 1)
  6455. messageLabel = "with message";
  6456. if (_stats.infoMessages.size() > 1)
  6457. messageLabel = "with messages";
  6458. break;
  6459. case ResultWas::ExpressionFailed:
  6460. if (result.isOk()) {
  6461. colour = Colour::Success;
  6462. passOrFail = "FAILED - but was ok"_sr;
  6463. } else {
  6464. colour = Colour::Error;
  6465. passOrFail = "FAILED"_sr;
  6466. }
  6467. if (_stats.infoMessages.size() == 1)
  6468. messageLabel = "with message";
  6469. if (_stats.infoMessages.size() > 1)
  6470. messageLabel = "with messages";
  6471. break;
  6472. case ResultWas::ThrewException:
  6473. colour = Colour::Error;
  6474. passOrFail = "FAILED"_sr;
  6475. messageLabel = "due to unexpected exception with ";
  6476. if (_stats.infoMessages.size() == 1)
  6477. messageLabel += "message";
  6478. if (_stats.infoMessages.size() > 1)
  6479. messageLabel += "messages";
  6480. break;
  6481. case ResultWas::FatalErrorCondition:
  6482. colour = Colour::Error;
  6483. passOrFail = "FAILED"_sr;
  6484. messageLabel = "due to a fatal error condition";
  6485. break;
  6486. case ResultWas::DidntThrowException:
  6487. colour = Colour::Error;
  6488. passOrFail = "FAILED"_sr;
  6489. messageLabel = "because no exception was thrown where one was expected";
  6490. break;
  6491. case ResultWas::Info:
  6492. messageLabel = "info";
  6493. break;
  6494. case ResultWas::Warning:
  6495. messageLabel = "warning";
  6496. break;
  6497. case ResultWas::ExplicitFailure:
  6498. passOrFail = "FAILED"_sr;
  6499. colour = Colour::Error;
  6500. if (_stats.infoMessages.size() == 1)
  6501. messageLabel = "explicitly with message";
  6502. if (_stats.infoMessages.size() > 1)
  6503. messageLabel = "explicitly with messages";
  6504. break;
  6505. // These cases are here to prevent compiler warnings
  6506. case ResultWas::Unknown:
  6507. case ResultWas::FailureBit:
  6508. case ResultWas::Exception:
  6509. passOrFail = "** internal error **"_sr;
  6510. colour = Colour::Error;
  6511. break;
  6512. }
  6513. }
  6514. void print() const {
  6515. printSourceInfo();
  6516. if (stats.totals.assertions.total() > 0) {
  6517. printResultType();
  6518. printOriginalExpression();
  6519. printReconstructedExpression();
  6520. } else {
  6521. stream << '\n';
  6522. }
  6523. printMessage();
  6524. }
  6525. private:
  6526. void printResultType() const {
  6527. if (!passOrFail.empty()) {
  6528. stream << colourImpl->guardColour(colour) << passOrFail << ":\n";
  6529. }
  6530. }
  6531. void printOriginalExpression() const {
  6532. if (result.hasExpression()) {
  6533. stream << colourImpl->guardColour( Colour::OriginalExpression )
  6534. << " " << result.getExpressionInMacro() << '\n';
  6535. }
  6536. }
  6537. void printReconstructedExpression() const {
  6538. if (result.hasExpandedExpression()) {
  6539. stream << "with expansion:\n";
  6540. stream << colourImpl->guardColour( Colour::ReconstructedExpression )
  6541. << TextFlow::Column( result.getExpandedExpression() )
  6542. .indent( 2 )
  6543. << '\n';
  6544. }
  6545. }
  6546. void printMessage() const {
  6547. if (!messageLabel.empty())
  6548. stream << messageLabel << ':' << '\n';
  6549. for (auto const& msg : messages) {
  6550. // If this assertion is a warning ignore any INFO messages
  6551. if (printInfoMessages || msg.type != ResultWas::Info)
  6552. stream << TextFlow::Column(msg.message).indent(2) << '\n';
  6553. }
  6554. }
  6555. void printSourceInfo() const {
  6556. stream << colourImpl->guardColour( Colour::FileName )
  6557. << result.getSourceInfo() << ": ";
  6558. }
  6559. std::ostream& stream;
  6560. AssertionStats const& stats;
  6561. AssertionResult const& result;
  6562. Colour::Code colour;
  6563. StringRef passOrFail;
  6564. std::string messageLabel;
  6565. std::string message;
  6566. std::vector<MessageInfo> messages;
  6567. ColourImpl* colourImpl;
  6568. bool printInfoMessages;
  6569. };
  6570. std::size_t makeRatio( std::uint64_t number, std::uint64_t total ) {
  6571. const auto ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  6572. return (ratio == 0 && number > 0) ? 1 : static_cast<std::size_t>(ratio);
  6573. }
  6574. std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
  6575. if (i > j && i > k)
  6576. return i;
  6577. else if (j > k)
  6578. return j;
  6579. else
  6580. return k;
  6581. }
  6582. enum class Justification { Left, Right };
  6583. struct ColumnInfo {
  6584. std::string name;
  6585. std::size_t width;
  6586. Justification justification;
  6587. };
  6588. struct ColumnBreak {};
  6589. struct RowBreak {};
  6590. class Duration {
  6591. enum class Unit {
  6592. Auto,
  6593. Nanoseconds,
  6594. Microseconds,
  6595. Milliseconds,
  6596. Seconds,
  6597. Minutes
  6598. };
  6599. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  6600. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  6601. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  6602. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  6603. double m_inNanoseconds;
  6604. Unit m_units;
  6605. public:
  6606. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  6607. : m_inNanoseconds(inNanoseconds),
  6608. m_units(units) {
  6609. if (m_units == Unit::Auto) {
  6610. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  6611. m_units = Unit::Nanoseconds;
  6612. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  6613. m_units = Unit::Microseconds;
  6614. else if (m_inNanoseconds < s_nanosecondsInASecond)
  6615. m_units = Unit::Milliseconds;
  6616. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  6617. m_units = Unit::Seconds;
  6618. else
  6619. m_units = Unit::Minutes;
  6620. }
  6621. }
  6622. auto value() const -> double {
  6623. switch (m_units) {
  6624. case Unit::Microseconds:
  6625. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  6626. case Unit::Milliseconds:
  6627. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  6628. case Unit::Seconds:
  6629. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  6630. case Unit::Minutes:
  6631. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  6632. default:
  6633. return m_inNanoseconds;
  6634. }
  6635. }
  6636. StringRef unitsAsString() const {
  6637. switch (m_units) {
  6638. case Unit::Nanoseconds:
  6639. return "ns"_sr;
  6640. case Unit::Microseconds:
  6641. return "us"_sr;
  6642. case Unit::Milliseconds:
  6643. return "ms"_sr;
  6644. case Unit::Seconds:
  6645. return "s"_sr;
  6646. case Unit::Minutes:
  6647. return "m"_sr;
  6648. default:
  6649. return "** internal error **"_sr;
  6650. }
  6651. }
  6652. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  6653. return os << duration.value() << ' ' << duration.unitsAsString();
  6654. }
  6655. };
  6656. } // end anon namespace
  6657. class TablePrinter {
  6658. std::ostream& m_os;
  6659. std::vector<ColumnInfo> m_columnInfos;
  6660. ReusableStringStream m_oss;
  6661. int m_currentColumn = -1;
  6662. bool m_isOpen = false;
  6663. public:
  6664. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  6665. : m_os( os ),
  6666. m_columnInfos( CATCH_MOVE( columnInfos ) ) {}
  6667. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  6668. return m_columnInfos;
  6669. }
  6670. void open() {
  6671. if (!m_isOpen) {
  6672. m_isOpen = true;
  6673. *this << RowBreak();
  6674. TextFlow::Columns headerCols;
  6675. auto spacer = TextFlow::Spacer(2);
  6676. for (auto const& info : m_columnInfos) {
  6677. assert(info.width > 2);
  6678. headerCols += TextFlow::Column(info.name).width(info.width - 2);
  6679. headerCols += spacer;
  6680. }
  6681. m_os << headerCols << '\n';
  6682. m_os << lineOfChars('-') << '\n';
  6683. }
  6684. }
  6685. void close() {
  6686. if (m_isOpen) {
  6687. *this << RowBreak();
  6688. m_os << '\n' << std::flush;
  6689. m_isOpen = false;
  6690. }
  6691. }
  6692. template<typename T>
  6693. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  6694. tp.m_oss << value;
  6695. return tp;
  6696. }
  6697. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  6698. auto colStr = tp.m_oss.str();
  6699. const auto strSize = colStr.size();
  6700. tp.m_oss.str("");
  6701. tp.open();
  6702. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  6703. tp.m_currentColumn = -1;
  6704. tp.m_os << '\n';
  6705. }
  6706. tp.m_currentColumn++;
  6707. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  6708. auto padding = (strSize + 1 < colInfo.width)
  6709. ? std::string(colInfo.width - (strSize + 1), ' ')
  6710. : std::string();
  6711. if (colInfo.justification == Justification::Left)
  6712. tp.m_os << colStr << padding << ' ';
  6713. else
  6714. tp.m_os << padding << colStr << ' ';
  6715. return tp;
  6716. }
  6717. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  6718. if (tp.m_currentColumn > 0) {
  6719. tp.m_os << '\n';
  6720. tp.m_currentColumn = -1;
  6721. }
  6722. return tp;
  6723. }
  6724. };
  6725. ConsoleReporter::ConsoleReporter(ReporterConfig&& config):
  6726. StreamingReporterBase( CATCH_MOVE( config ) ),
  6727. m_tablePrinter(Detail::make_unique<TablePrinter>(m_stream,
  6728. [&config]() -> std::vector<ColumnInfo> {
  6729. if (config.fullConfig()->benchmarkNoAnalysis())
  6730. {
  6731. return{
  6732. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left },
  6733. { " samples", 14, Justification::Right },
  6734. { " iterations", 14, Justification::Right },
  6735. { " mean", 14, Justification::Right }
  6736. };
  6737. }
  6738. else
  6739. {
  6740. return{
  6741. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, Justification::Left },
  6742. { "samples mean std dev", 14, Justification::Right },
  6743. { "iterations low mean low std dev", 14, Justification::Right },
  6744. { "estimated high mean high std dev", 14, Justification::Right }
  6745. };
  6746. }
  6747. }())) {}
  6748. ConsoleReporter::~ConsoleReporter() = default;
  6749. std::string ConsoleReporter::getDescription() {
  6750. return "Reports test results as plain lines of text";
  6751. }
  6752. void ConsoleReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
  6753. m_stream << "No test cases matched '" << unmatchedSpec << "'\n";
  6754. }
  6755. void ConsoleReporter::reportInvalidTestSpec( StringRef arg ) {
  6756. m_stream << "Invalid Filter: " << arg << '\n';
  6757. }
  6758. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  6759. void ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  6760. AssertionResult const& result = _assertionStats.assertionResult;
  6761. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  6762. // Drop out if result was successful but we're not printing them.
  6763. if (!includeResults && result.getResultType() != ResultWas::Warning)
  6764. return;
  6765. lazyPrint();
  6766. ConsoleAssertionPrinter printer(m_stream, _assertionStats, m_colour.get(), includeResults);
  6767. printer.print();
  6768. m_stream << '\n' << std::flush;
  6769. }
  6770. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  6771. m_tablePrinter->close();
  6772. m_headerPrinted = false;
  6773. StreamingReporterBase::sectionStarting(_sectionInfo);
  6774. }
  6775. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  6776. m_tablePrinter->close();
  6777. if (_sectionStats.missingAssertions) {
  6778. lazyPrint();
  6779. auto guard =
  6780. m_colour->guardColour( Colour::ResultError ).engage( m_stream );
  6781. if (m_sectionStack.size() > 1)
  6782. m_stream << "\nNo assertions in section";
  6783. else
  6784. m_stream << "\nNo assertions in test case";
  6785. m_stream << " '" << _sectionStats.sectionInfo.name << "'\n\n" << std::flush;
  6786. }
  6787. double dur = _sectionStats.durationInSeconds;
  6788. if (shouldShowDuration(*m_config, dur)) {
  6789. m_stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << '\n' << std::flush;
  6790. }
  6791. if (m_headerPrinted) {
  6792. m_headerPrinted = false;
  6793. }
  6794. StreamingReporterBase::sectionEnded(_sectionStats);
  6795. }
  6796. void ConsoleReporter::benchmarkPreparing( StringRef name ) {
  6797. lazyPrintWithoutClosingBenchmarkTable();
  6798. auto nameCol = TextFlow::Column( static_cast<std::string>( name ) )
  6799. .width( m_tablePrinter->columnInfos()[0].width - 2 );
  6800. bool firstLine = true;
  6801. for (auto line : nameCol) {
  6802. if (!firstLine)
  6803. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  6804. else
  6805. firstLine = false;
  6806. (*m_tablePrinter) << line << ColumnBreak();
  6807. }
  6808. }
  6809. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  6810. (*m_tablePrinter) << info.samples << ColumnBreak()
  6811. << info.iterations << ColumnBreak();
  6812. if (!m_config->benchmarkNoAnalysis())
  6813. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  6814. }
  6815. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  6816. if (m_config->benchmarkNoAnalysis())
  6817. {
  6818. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  6819. }
  6820. else
  6821. {
  6822. (*m_tablePrinter) << ColumnBreak()
  6823. << Duration(stats.mean.point.count()) << ColumnBreak()
  6824. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  6825. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  6826. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  6827. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  6828. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  6829. }
  6830. }
  6831. void ConsoleReporter::benchmarkFailed( StringRef error ) {
  6832. auto guard = m_colour->guardColour( Colour::Red ).engage( m_stream );
  6833. (*m_tablePrinter)
  6834. << "Benchmark failed (" << error << ')'
  6835. << ColumnBreak() << RowBreak();
  6836. }
  6837. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  6838. m_tablePrinter->close();
  6839. StreamingReporterBase::testCaseEnded(_testCaseStats);
  6840. m_headerPrinted = false;
  6841. }
  6842. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  6843. printTotalsDivider(_testRunStats.totals);
  6844. printTotals(_testRunStats.totals);
  6845. m_stream << '\n' << std::flush;
  6846. StreamingReporterBase::testRunEnded(_testRunStats);
  6847. }
  6848. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  6849. StreamingReporterBase::testRunStarting(_testInfo);
  6850. if ( m_config->testSpec().hasFilters() ) {
  6851. m_stream << m_colour->guardColour( Colour::BrightYellow ) << "Filters: "
  6852. << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  6853. }
  6854. m_stream << "Randomness seeded to: " << m_config->rngSeed() << '\n';
  6855. }
  6856. void ConsoleReporter::lazyPrint() {
  6857. m_tablePrinter->close();
  6858. lazyPrintWithoutClosingBenchmarkTable();
  6859. }
  6860. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  6861. if ( !m_testRunInfoPrinted ) {
  6862. lazyPrintRunInfo();
  6863. }
  6864. if (!m_headerPrinted) {
  6865. printTestCaseAndSectionHeader();
  6866. m_headerPrinted = true;
  6867. }
  6868. }
  6869. void ConsoleReporter::lazyPrintRunInfo() {
  6870. m_stream << '\n'
  6871. << lineOfChars( '~' ) << '\n'
  6872. << m_colour->guardColour( Colour::SecondaryText )
  6873. << currentTestRunInfo.name << " is a Catch2 v" << libraryVersion()
  6874. << " host application.\n"
  6875. << "Run with -? for options\n\n";
  6876. m_testRunInfoPrinted = true;
  6877. }
  6878. void ConsoleReporter::printTestCaseAndSectionHeader() {
  6879. assert(!m_sectionStack.empty());
  6880. printOpenHeader(currentTestCaseInfo->name);
  6881. if (m_sectionStack.size() > 1) {
  6882. auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream );
  6883. auto
  6884. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  6885. itEnd = m_sectionStack.end();
  6886. for (; it != itEnd; ++it)
  6887. printHeaderString(it->name, 2);
  6888. }
  6889. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  6890. m_stream << lineOfChars( '-' ) << '\n'
  6891. << m_colour->guardColour( Colour::FileName ) << lineInfo << '\n'
  6892. << lineOfChars( '.' ) << "\n\n"
  6893. << std::flush;
  6894. }
  6895. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  6896. printOpenHeader(_name);
  6897. m_stream << lineOfChars('.') << '\n';
  6898. }
  6899. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  6900. m_stream << lineOfChars('-') << '\n';
  6901. {
  6902. auto guard = m_colour->guardColour( Colour::Headers ).engage( m_stream );
  6903. printHeaderString(_name);
  6904. }
  6905. }
  6906. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  6907. // We want to get a bit fancy with line breaking here, so that subsequent
  6908. // lines start after ":" if one is present, e.g.
  6909. // ```
  6910. // blablabla: Fancy
  6911. // linebreaking
  6912. // ```
  6913. // but we also want to avoid problems with overly long indentation causing
  6914. // the text to take up too many lines, e.g.
  6915. // ```
  6916. // blablabla: F
  6917. // a
  6918. // n
  6919. // c
  6920. // y
  6921. // .
  6922. // .
  6923. // .
  6924. // ```
  6925. // So we limit the prefix indentation check to first quarter of the possible
  6926. // width
  6927. std::size_t idx = _string.find( ": " );
  6928. if ( idx != std::string::npos && idx < CATCH_CONFIG_CONSOLE_WIDTH / 4 ) {
  6929. idx += 2;
  6930. } else {
  6931. idx = 0;
  6932. }
  6933. m_stream << TextFlow::Column( _string )
  6934. .indent( indent + idx )
  6935. .initialIndent( indent )
  6936. << '\n';
  6937. }
  6938. struct SummaryColumn {
  6939. SummaryColumn( std::string _label, Colour::Code _colour )
  6940. : label( CATCH_MOVE( _label ) ),
  6941. colour( _colour ) {}
  6942. SummaryColumn addRow( std::uint64_t count ) {
  6943. ReusableStringStream rss;
  6944. rss << count;
  6945. std::string row = rss.str();
  6946. for (auto& oldRow : rows) {
  6947. while (oldRow.size() < row.size())
  6948. oldRow = ' ' + oldRow;
  6949. while (oldRow.size() > row.size())
  6950. row = ' ' + row;
  6951. }
  6952. rows.push_back(row);
  6953. return *this;
  6954. }
  6955. std::string label;
  6956. Colour::Code colour;
  6957. std::vector<std::string> rows;
  6958. };
  6959. void ConsoleReporter::printTotals( Totals const& totals ) {
  6960. if (totals.testCases.total() == 0) {
  6961. m_stream << m_colour->guardColour( Colour::Warning )
  6962. << "No tests ran\n";
  6963. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  6964. m_stream << m_colour->guardColour( Colour::ResultSuccess )
  6965. << "All tests passed";
  6966. m_stream << " ("
  6967. << pluralise(totals.assertions.passed, "assertion"_sr) << " in "
  6968. << pluralise(totals.testCases.passed, "test case"_sr) << ')'
  6969. << '\n';
  6970. } else {
  6971. std::vector<SummaryColumn> columns;
  6972. columns.push_back(SummaryColumn("", Colour::None)
  6973. .addRow(totals.testCases.total())
  6974. .addRow(totals.assertions.total()));
  6975. columns.push_back(SummaryColumn("passed", Colour::Success)
  6976. .addRow(totals.testCases.passed)
  6977. .addRow(totals.assertions.passed));
  6978. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  6979. .addRow(totals.testCases.failed)
  6980. .addRow(totals.assertions.failed));
  6981. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  6982. .addRow(totals.testCases.failedButOk)
  6983. .addRow(totals.assertions.failedButOk));
  6984. printSummaryRow("test cases"_sr, columns, 0);
  6985. printSummaryRow("assertions"_sr, columns, 1);
  6986. }
  6987. }
  6988. void ConsoleReporter::printSummaryRow(StringRef label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  6989. for (auto col : cols) {
  6990. std::string const& value = col.rows[row];
  6991. if (col.label.empty()) {
  6992. m_stream << label << ": ";
  6993. if ( value != "0" ) {
  6994. m_stream << value;
  6995. } else {
  6996. m_stream << m_colour->guardColour( Colour::Warning )
  6997. << "- none -";
  6998. }
  6999. } else if (value != "0") {
  7000. m_stream << m_colour->guardColour( Colour::LightGrey ) << " | "
  7001. << m_colour->guardColour( col.colour ) << value << ' '
  7002. << col.label;
  7003. }
  7004. }
  7005. m_stream << '\n';
  7006. }
  7007. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  7008. if (totals.testCases.total() > 0) {
  7009. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  7010. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  7011. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  7012. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  7013. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  7014. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  7015. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  7016. m_stream << m_colour->guardColour( Colour::Error )
  7017. << std::string( failedRatio, '=' )
  7018. << m_colour->guardColour( Colour::ResultExpectedFailure )
  7019. << std::string( failedButOkRatio, '=' );
  7020. if ( totals.testCases.allPassed() ) {
  7021. m_stream << m_colour->guardColour( Colour::ResultSuccess )
  7022. << std::string( passedRatio, '=' );
  7023. } else {
  7024. m_stream << m_colour->guardColour( Colour::Success )
  7025. << std::string( passedRatio, '=' );
  7026. }
  7027. } else {
  7028. m_stream << m_colour->guardColour( Colour::Warning )
  7029. << std::string( CATCH_CONFIG_CONSOLE_WIDTH - 1, '=' );
  7030. }
  7031. m_stream << '\n';
  7032. }
  7033. void ConsoleReporter::printSummaryDivider() {
  7034. m_stream << lineOfChars('-') << '\n';
  7035. }
  7036. } // end namespace Catch
  7037. #if defined(_MSC_VER)
  7038. #pragma warning(pop)
  7039. #endif
  7040. #if defined(__clang__)
  7041. # pragma clang diagnostic pop
  7042. #endif
  7043. #include <algorithm>
  7044. #include <cassert>
  7045. namespace Catch {
  7046. namespace {
  7047. struct BySectionInfo {
  7048. BySectionInfo( SectionInfo const& other ): m_other( other ) {}
  7049. BySectionInfo( BySectionInfo const& other ):
  7050. m_other( other.m_other ) {}
  7051. bool operator()(
  7052. Detail::unique_ptr<CumulativeReporterBase::SectionNode> const&
  7053. node ) const {
  7054. return (
  7055. ( node->stats.sectionInfo.name == m_other.name ) &&
  7056. ( node->stats.sectionInfo.lineInfo == m_other.lineInfo ) );
  7057. }
  7058. void operator=( BySectionInfo const& ) = delete;
  7059. private:
  7060. SectionInfo const& m_other;
  7061. };
  7062. } // namespace
  7063. namespace Detail {
  7064. AssertionOrBenchmarkResult::AssertionOrBenchmarkResult(
  7065. AssertionStats const& assertion ):
  7066. m_assertion( assertion ) {}
  7067. AssertionOrBenchmarkResult::AssertionOrBenchmarkResult(
  7068. BenchmarkStats<> const& benchmark ):
  7069. m_benchmark( benchmark ) {}
  7070. bool AssertionOrBenchmarkResult::isAssertion() const {
  7071. return m_assertion.some();
  7072. }
  7073. bool AssertionOrBenchmarkResult::isBenchmark() const {
  7074. return m_benchmark.some();
  7075. }
  7076. AssertionStats const& AssertionOrBenchmarkResult::asAssertion() const {
  7077. assert(m_assertion.some());
  7078. return *m_assertion;
  7079. }
  7080. BenchmarkStats<> const& AssertionOrBenchmarkResult::asBenchmark() const {
  7081. assert(m_benchmark.some());
  7082. return *m_benchmark;
  7083. }
  7084. }
  7085. CumulativeReporterBase::~CumulativeReporterBase() = default;
  7086. void CumulativeReporterBase::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  7087. m_sectionStack.back()->assertionsAndBenchmarks.emplace_back(benchmarkStats);
  7088. }
  7089. void
  7090. CumulativeReporterBase::sectionStarting( SectionInfo const& sectionInfo ) {
  7091. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  7092. SectionNode* node;
  7093. if ( m_sectionStack.empty() ) {
  7094. if ( !m_rootSection ) {
  7095. m_rootSection =
  7096. Detail::make_unique<SectionNode>( incompleteStats );
  7097. }
  7098. node = m_rootSection.get();
  7099. } else {
  7100. SectionNode& parentNode = *m_sectionStack.back();
  7101. auto it = std::find_if( parentNode.childSections.begin(),
  7102. parentNode.childSections.end(),
  7103. BySectionInfo( sectionInfo ) );
  7104. if ( it == parentNode.childSections.end() ) {
  7105. auto newNode =
  7106. Detail::make_unique<SectionNode>( incompleteStats );
  7107. node = newNode.get();
  7108. parentNode.childSections.push_back( CATCH_MOVE( newNode ) );
  7109. } else {
  7110. node = it->get();
  7111. }
  7112. }
  7113. m_deepestSection = node;
  7114. m_sectionStack.push_back( node );
  7115. }
  7116. void CumulativeReporterBase::assertionEnded(
  7117. AssertionStats const& assertionStats ) {
  7118. assert( !m_sectionStack.empty() );
  7119. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  7120. // which getExpandedExpression() calls to build the expression string.
  7121. // Our section stack copy of the assertionResult will likely outlive the
  7122. // temporary, so it must be expanded or discarded now to avoid calling
  7123. // a destroyed object later.
  7124. if ( m_shouldStoreFailedAssertions &&
  7125. !assertionStats.assertionResult.isOk() ) {
  7126. static_cast<void>(
  7127. assertionStats.assertionResult.getExpandedExpression() );
  7128. }
  7129. if ( m_shouldStoreSuccesfulAssertions &&
  7130. assertionStats.assertionResult.isOk() ) {
  7131. static_cast<void>(
  7132. assertionStats.assertionResult.getExpandedExpression() );
  7133. }
  7134. SectionNode& sectionNode = *m_sectionStack.back();
  7135. sectionNode.assertionsAndBenchmarks.emplace_back( assertionStats );
  7136. }
  7137. void CumulativeReporterBase::sectionEnded( SectionStats const& sectionStats ) {
  7138. assert( !m_sectionStack.empty() );
  7139. SectionNode& node = *m_sectionStack.back();
  7140. node.stats = sectionStats;
  7141. m_sectionStack.pop_back();
  7142. }
  7143. void CumulativeReporterBase::testCaseEnded(
  7144. TestCaseStats const& testCaseStats ) {
  7145. auto node = Detail::make_unique<TestCaseNode>( testCaseStats );
  7146. assert( m_sectionStack.size() == 0 );
  7147. node->children.push_back( CATCH_MOVE(m_rootSection) );
  7148. m_testCases.push_back( CATCH_MOVE(node) );
  7149. assert( m_deepestSection );
  7150. m_deepestSection->stdOut = testCaseStats.stdOut;
  7151. m_deepestSection->stdErr = testCaseStats.stdErr;
  7152. }
  7153. void CumulativeReporterBase::testRunEnded( TestRunStats const& testRunStats ) {
  7154. assert(!m_testRun && "CumulativeReporterBase assumes there can only be one test run");
  7155. m_testRun = Detail::make_unique<TestRunNode>( testRunStats );
  7156. m_testRun->children.swap( m_testCases );
  7157. testRunEndedCumulative();
  7158. }
  7159. bool CumulativeReporterBase::SectionNode::hasAnyAssertions() const {
  7160. return std::any_of(
  7161. assertionsAndBenchmarks.begin(),
  7162. assertionsAndBenchmarks.end(),
  7163. []( Detail::AssertionOrBenchmarkResult const& res ) {
  7164. return res.isAssertion();
  7165. } );
  7166. }
  7167. } // end namespace Catch
  7168. namespace Catch {
  7169. void EventListenerBase::fatalErrorEncountered( StringRef ) {}
  7170. void EventListenerBase::benchmarkPreparing( StringRef ) {}
  7171. void EventListenerBase::benchmarkStarting( BenchmarkInfo const& ) {}
  7172. void EventListenerBase::benchmarkEnded( BenchmarkStats<> const& ) {}
  7173. void EventListenerBase::benchmarkFailed( StringRef ) {}
  7174. void EventListenerBase::assertionStarting( AssertionInfo const& ) {}
  7175. void EventListenerBase::assertionEnded( AssertionStats const& ) {}
  7176. void EventListenerBase::listReporters(
  7177. std::vector<ReporterDescription> const& ) {}
  7178. void EventListenerBase::listListeners(
  7179. std::vector<ListenerDescription> const& ) {}
  7180. void EventListenerBase::listTests( std::vector<TestCaseHandle> const& ) {}
  7181. void EventListenerBase::listTags( std::vector<TagInfo> const& ) {}
  7182. void EventListenerBase::noMatchingTestCases( StringRef ) {}
  7183. void EventListenerBase::reportInvalidTestSpec( StringRef ) {}
  7184. void EventListenerBase::testRunStarting( TestRunInfo const& ) {}
  7185. void EventListenerBase::testCaseStarting( TestCaseInfo const& ) {}
  7186. void EventListenerBase::testCasePartialStarting(TestCaseInfo const&, uint64_t) {}
  7187. void EventListenerBase::sectionStarting( SectionInfo const& ) {}
  7188. void EventListenerBase::sectionEnded( SectionStats const& ) {}
  7189. void EventListenerBase::testCasePartialEnded(TestCaseStats const&, uint64_t) {}
  7190. void EventListenerBase::testCaseEnded( TestCaseStats const& ) {}
  7191. void EventListenerBase::testRunEnded( TestRunStats const& ) {}
  7192. void EventListenerBase::skipTest( TestCaseInfo const& ) {}
  7193. } // namespace Catch
  7194. #include <algorithm>
  7195. #include <cfloat>
  7196. #include <cstdio>
  7197. #include <ostream>
  7198. #include <iomanip>
  7199. namespace Catch {
  7200. namespace {
  7201. void listTestNamesOnly(std::ostream& out,
  7202. std::vector<TestCaseHandle> const& tests) {
  7203. for (auto const& test : tests) {
  7204. auto const& testCaseInfo = test.getTestCaseInfo();
  7205. if (startsWith(testCaseInfo.name, '#')) {
  7206. out << '"' << testCaseInfo.name << '"';
  7207. } else {
  7208. out << testCaseInfo.name;
  7209. }
  7210. out << '\n';
  7211. }
  7212. out << std::flush;
  7213. }
  7214. } // end unnamed namespace
  7215. // Because formatting using c++ streams is stateful, drop down to C is
  7216. // required Alternatively we could use stringstream, but its performance
  7217. // is... not good.
  7218. std::string getFormattedDuration( double duration ) {
  7219. // Max exponent + 1 is required to represent the whole part
  7220. // + 1 for decimal point
  7221. // + 3 for the 3 decimal places
  7222. // + 1 for null terminator
  7223. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  7224. char buffer[maxDoubleSize];
  7225. // Save previous errno, to prevent sprintf from overwriting it
  7226. ErrnoGuard guard;
  7227. #ifdef _MSC_VER
  7228. size_t printedLength = static_cast<size_t>(
  7229. sprintf_s( buffer, "%.3f", duration ) );
  7230. #else
  7231. size_t printedLength = static_cast<size_t>(
  7232. std::snprintf( buffer, maxDoubleSize, "%.3f", duration ) );
  7233. #endif
  7234. return std::string( buffer, printedLength );
  7235. }
  7236. bool shouldShowDuration( IConfig const& config, double duration ) {
  7237. if ( config.showDurations() == ShowDurations::Always ) {
  7238. return true;
  7239. }
  7240. if ( config.showDurations() == ShowDurations::Never ) {
  7241. return false;
  7242. }
  7243. const double min = config.minDuration();
  7244. return min >= 0 && duration >= min;
  7245. }
  7246. std::string serializeFilters( std::vector<std::string> const& filters ) {
  7247. // We add a ' ' separator between each filter
  7248. size_t serialized_size = filters.size() - 1;
  7249. for (auto const& filter : filters) {
  7250. serialized_size += filter.size();
  7251. }
  7252. std::string serialized;
  7253. serialized.reserve(serialized_size);
  7254. bool first = true;
  7255. for (auto const& filter : filters) {
  7256. if (!first) {
  7257. serialized.push_back(' ');
  7258. }
  7259. first = false;
  7260. serialized.append(filter);
  7261. }
  7262. return serialized;
  7263. }
  7264. std::ostream& operator<<( std::ostream& out, lineOfChars value ) {
  7265. for ( size_t idx = 0; idx < CATCH_CONFIG_CONSOLE_WIDTH - 1; ++idx ) {
  7266. out.put( value.c );
  7267. }
  7268. return out;
  7269. }
  7270. void
  7271. defaultListReporters( std::ostream& out,
  7272. std::vector<ReporterDescription> const& descriptions,
  7273. Verbosity verbosity ) {
  7274. out << "Available reporters:\n";
  7275. const auto maxNameLen =
  7276. std::max_element( descriptions.begin(),
  7277. descriptions.end(),
  7278. []( ReporterDescription const& lhs,
  7279. ReporterDescription const& rhs ) {
  7280. return lhs.name.size() < rhs.name.size();
  7281. } )
  7282. ->name.size();
  7283. for ( auto const& desc : descriptions ) {
  7284. if ( verbosity == Verbosity::Quiet ) {
  7285. out << TextFlow::Column( desc.name )
  7286. .indent( 2 )
  7287. .width( 5 + maxNameLen )
  7288. << '\n';
  7289. } else {
  7290. out << TextFlow::Column( desc.name + ':' )
  7291. .indent( 2 )
  7292. .width( 5 + maxNameLen ) +
  7293. TextFlow::Column( desc.description )
  7294. .initialIndent( 0 )
  7295. .indent( 2 )
  7296. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 )
  7297. << '\n';
  7298. }
  7299. }
  7300. out << '\n' << std::flush;
  7301. }
  7302. void defaultListListeners( std::ostream& out,
  7303. std::vector<ListenerDescription> const& descriptions ) {
  7304. out << "Registered listeners:\n";
  7305. if(descriptions.empty()) {
  7306. return;
  7307. }
  7308. const auto maxNameLen =
  7309. std::max_element( descriptions.begin(),
  7310. descriptions.end(),
  7311. []( ListenerDescription const& lhs,
  7312. ListenerDescription const& rhs ) {
  7313. return lhs.name.size() < rhs.name.size();
  7314. } )
  7315. ->name.size();
  7316. for ( auto const& desc : descriptions ) {
  7317. out << TextFlow::Column( static_cast<std::string>( desc.name ) +
  7318. ':' )
  7319. .indent( 2 )
  7320. .width( maxNameLen + 5 ) +
  7321. TextFlow::Column( desc.description )
  7322. .initialIndent( 0 )
  7323. .indent( 2 )
  7324. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 )
  7325. << '\n';
  7326. }
  7327. out << '\n' << std::flush;
  7328. }
  7329. void defaultListTags( std::ostream& out,
  7330. std::vector<TagInfo> const& tags,
  7331. bool isFiltered ) {
  7332. if ( isFiltered ) {
  7333. out << "Tags for matching test cases:\n";
  7334. } else {
  7335. out << "All available tags:\n";
  7336. }
  7337. for ( auto const& tagCount : tags ) {
  7338. ReusableStringStream rss;
  7339. rss << " " << std::setw( 2 ) << tagCount.count << " ";
  7340. auto str = rss.str();
  7341. auto wrapper = TextFlow::Column( tagCount.all() )
  7342. .initialIndent( 0 )
  7343. .indent( str.size() )
  7344. .width( CATCH_CONFIG_CONSOLE_WIDTH - 10 );
  7345. out << str << wrapper << '\n';
  7346. }
  7347. out << pluralise(tags.size(), "tag"_sr) << "\n\n" << std::flush;
  7348. }
  7349. void defaultListTests(std::ostream& out, ColourImpl* streamColour, std::vector<TestCaseHandle> const& tests, bool isFiltered, Verbosity verbosity) {
  7350. // We special case this to provide the equivalent of old
  7351. // `--list-test-names-only`, which could then be used by the
  7352. // `--input-file` option.
  7353. if (verbosity == Verbosity::Quiet) {
  7354. listTestNamesOnly(out, tests);
  7355. return;
  7356. }
  7357. if (isFiltered) {
  7358. out << "Matching test cases:\n";
  7359. } else {
  7360. out << "All available test cases:\n";
  7361. }
  7362. for (auto const& test : tests) {
  7363. auto const& testCaseInfo = test.getTestCaseInfo();
  7364. Colour::Code colour = testCaseInfo.isHidden()
  7365. ? Colour::SecondaryText
  7366. : Colour::None;
  7367. auto colourGuard = streamColour->guardColour( colour ).engage( out );
  7368. out << TextFlow::Column(testCaseInfo.name).indent(2) << '\n';
  7369. if (verbosity >= Verbosity::High) {
  7370. out << TextFlow::Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4) << '\n';
  7371. }
  7372. if (!testCaseInfo.tags.empty() &&
  7373. verbosity > Verbosity::Quiet) {
  7374. out << TextFlow::Column(testCaseInfo.tagsAsString()).indent(6) << '\n';
  7375. }
  7376. }
  7377. if (isFiltered) {
  7378. out << pluralise(tests.size(), "matching test case"_sr);
  7379. } else {
  7380. out << pluralise(tests.size(), "test case"_sr);
  7381. }
  7382. out << "\n\n" << std::flush;
  7383. }
  7384. } // namespace Catch
  7385. #include <cassert>
  7386. #include <ctime>
  7387. #include <algorithm>
  7388. #include <iomanip>
  7389. namespace Catch {
  7390. namespace {
  7391. std::string getCurrentTimestamp() {
  7392. time_t rawtime;
  7393. std::time(&rawtime);
  7394. std::tm timeInfo = {};
  7395. #if defined (_MSC_VER) || defined (__MINGW32__)
  7396. gmtime_s(&timeInfo, &rawtime);
  7397. #else
  7398. gmtime_r(&rawtime, &timeInfo);
  7399. #endif
  7400. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  7401. char timeStamp[timeStampSize];
  7402. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  7403. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  7404. return std::string(timeStamp, timeStampSize - 1);
  7405. }
  7406. std::string fileNameTag(std::vector<Tag> const& tags) {
  7407. auto it = std::find_if(begin(tags),
  7408. end(tags),
  7409. [] (Tag const& tag) {
  7410. return tag.original.size() > 0
  7411. && tag.original[0] == '#'; });
  7412. if (it != tags.end()) {
  7413. return static_cast<std::string>(
  7414. it->original.substr(1, it->original.size() - 1)
  7415. );
  7416. }
  7417. return std::string();
  7418. }
  7419. // Formats the duration in seconds to 3 decimal places.
  7420. // This is done because some genius defined Maven Surefire schema
  7421. // in a way that only accepts 3 decimal places, and tools like
  7422. // Jenkins use that schema for validation JUnit reporter output.
  7423. std::string formatDuration( double seconds ) {
  7424. ReusableStringStream rss;
  7425. rss << std::fixed << std::setprecision( 3 ) << seconds;
  7426. return rss.str();
  7427. }
  7428. static void normalizeNamespaceMarkers(std::string& str) {
  7429. std::size_t pos = str.find( "::" );
  7430. while ( pos != str.npos ) {
  7431. str.replace( pos, 2, "." );
  7432. pos += 1;
  7433. pos = str.find( "::", pos );
  7434. }
  7435. }
  7436. } // anonymous namespace
  7437. JunitReporter::JunitReporter( ReporterConfig&& _config )
  7438. : CumulativeReporterBase( CATCH_MOVE(_config) ),
  7439. xml( m_stream )
  7440. {
  7441. m_preferences.shouldRedirectStdOut = true;
  7442. m_preferences.shouldReportAllAssertions = true;
  7443. m_shouldStoreSuccesfulAssertions = false;
  7444. }
  7445. std::string JunitReporter::getDescription() {
  7446. return "Reports test results in an XML format that looks like Ant's junitreport target";
  7447. }
  7448. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  7449. CumulativeReporterBase::testRunStarting( runInfo );
  7450. xml.startElement( "testsuites" );
  7451. suiteTimer.start();
  7452. stdOutForSuite.clear();
  7453. stdErrForSuite.clear();
  7454. unexpectedExceptions = 0;
  7455. }
  7456. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  7457. m_okToFail = testCaseInfo.okToFail();
  7458. }
  7459. void JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  7460. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  7461. unexpectedExceptions++;
  7462. CumulativeReporterBase::assertionEnded( assertionStats );
  7463. }
  7464. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  7465. stdOutForSuite += testCaseStats.stdOut;
  7466. stdErrForSuite += testCaseStats.stdErr;
  7467. CumulativeReporterBase::testCaseEnded( testCaseStats );
  7468. }
  7469. void JunitReporter::testRunEndedCumulative() {
  7470. const auto suiteTime = suiteTimer.getElapsedSeconds();
  7471. writeRun( *m_testRun, suiteTime );
  7472. xml.endElement();
  7473. }
  7474. void JunitReporter::writeRun( TestRunNode const& testRunNode, double suiteTime ) {
  7475. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  7476. TestRunStats const& stats = testRunNode.value;
  7477. xml.writeAttribute( "name"_sr, stats.runInfo.name );
  7478. xml.writeAttribute( "errors"_sr, unexpectedExceptions );
  7479. xml.writeAttribute( "failures"_sr, stats.totals.assertions.failed-unexpectedExceptions );
  7480. xml.writeAttribute( "tests"_sr, stats.totals.assertions.total() );
  7481. xml.writeAttribute( "hostname"_sr, "tbd"_sr ); // !TBD
  7482. if( m_config->showDurations() == ShowDurations::Never )
  7483. xml.writeAttribute( "time"_sr, ""_sr );
  7484. else
  7485. xml.writeAttribute( "time"_sr, formatDuration( suiteTime ) );
  7486. xml.writeAttribute( "timestamp"_sr, getCurrentTimestamp() );
  7487. // Write properties
  7488. {
  7489. auto properties = xml.scopedElement("properties");
  7490. xml.scopedElement("property")
  7491. .writeAttribute("name"_sr, "random-seed"_sr)
  7492. .writeAttribute("value"_sr, m_config->rngSeed());
  7493. if (m_config->hasTestFilters()) {
  7494. xml.scopedElement("property")
  7495. .writeAttribute("name"_sr, "filters"_sr)
  7496. .writeAttribute("value"_sr, serializeFilters(m_config->getTestsOrTags()));
  7497. }
  7498. }
  7499. // Write test cases
  7500. for( auto const& child : testRunNode.children )
  7501. writeTestCase( *child );
  7502. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  7503. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  7504. }
  7505. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  7506. TestCaseStats const& stats = testCaseNode.value;
  7507. // All test cases have exactly one section - which represents the
  7508. // test case itself. That section may have 0-n nested sections
  7509. assert( testCaseNode.children.size() == 1 );
  7510. SectionNode const& rootSection = *testCaseNode.children.front();
  7511. std::string className =
  7512. static_cast<std::string>( stats.testInfo->className );
  7513. if( className.empty() ) {
  7514. className = fileNameTag(stats.testInfo->tags);
  7515. if ( className.empty() ) {
  7516. className = "global";
  7517. }
  7518. }
  7519. if ( !m_config->name().empty() )
  7520. className = static_cast<std::string>(m_config->name()) + '.' + className;
  7521. normalizeNamespaceMarkers(className);
  7522. writeSection( className, "", rootSection, stats.testInfo->okToFail() );
  7523. }
  7524. void JunitReporter::writeSection( std::string const& className,
  7525. std::string const& rootName,
  7526. SectionNode const& sectionNode,
  7527. bool testOkToFail) {
  7528. std::string name = trim( sectionNode.stats.sectionInfo.name );
  7529. if( !rootName.empty() )
  7530. name = rootName + '/' + name;
  7531. if( sectionNode.hasAnyAssertions()
  7532. || !sectionNode.stdOut.empty()
  7533. || !sectionNode.stdErr.empty() ) {
  7534. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  7535. if( className.empty() ) {
  7536. xml.writeAttribute( "classname"_sr, name );
  7537. xml.writeAttribute( "name"_sr, "root"_sr );
  7538. }
  7539. else {
  7540. xml.writeAttribute( "classname"_sr, className );
  7541. xml.writeAttribute( "name"_sr, name );
  7542. }
  7543. xml.writeAttribute( "time"_sr, formatDuration( sectionNode.stats.durationInSeconds ) );
  7544. // This is not ideal, but it should be enough to mimic gtest's
  7545. // junit output.
  7546. // Ideally the JUnit reporter would also handle `skipTest`
  7547. // events and write those out appropriately.
  7548. xml.writeAttribute( "status"_sr, "run"_sr );
  7549. if (sectionNode.stats.assertions.failedButOk) {
  7550. xml.scopedElement("skipped")
  7551. .writeAttribute("message", "TEST_CASE tagged with !mayfail");
  7552. }
  7553. writeAssertions( sectionNode );
  7554. if( !sectionNode.stdOut.empty() )
  7555. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  7556. if( !sectionNode.stdErr.empty() )
  7557. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  7558. }
  7559. for( auto const& childNode : sectionNode.childSections )
  7560. if( className.empty() )
  7561. writeSection( name, "", *childNode, testOkToFail );
  7562. else
  7563. writeSection( className, name, *childNode, testOkToFail );
  7564. }
  7565. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  7566. for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) {
  7567. if (assertionOrBenchmark.isAssertion()) {
  7568. writeAssertion(assertionOrBenchmark.asAssertion());
  7569. }
  7570. }
  7571. }
  7572. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  7573. AssertionResult const& result = stats.assertionResult;
  7574. if( !result.isOk() ) {
  7575. std::string elementName;
  7576. switch( result.getResultType() ) {
  7577. case ResultWas::ThrewException:
  7578. case ResultWas::FatalErrorCondition:
  7579. elementName = "error";
  7580. break;
  7581. case ResultWas::ExplicitFailure:
  7582. case ResultWas::ExpressionFailed:
  7583. case ResultWas::DidntThrowException:
  7584. elementName = "failure";
  7585. break;
  7586. // We should never see these here:
  7587. case ResultWas::Info:
  7588. case ResultWas::Warning:
  7589. case ResultWas::Ok:
  7590. case ResultWas::Unknown:
  7591. case ResultWas::FailureBit:
  7592. case ResultWas::Exception:
  7593. elementName = "internalError";
  7594. break;
  7595. }
  7596. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  7597. xml.writeAttribute( "message"_sr, result.getExpression() );
  7598. xml.writeAttribute( "type"_sr, result.getTestMacroName() );
  7599. ReusableStringStream rss;
  7600. if (stats.totals.assertions.total() > 0) {
  7601. rss << "FAILED" << ":\n";
  7602. if (result.hasExpression()) {
  7603. rss << " ";
  7604. rss << result.getExpressionInMacro();
  7605. rss << '\n';
  7606. }
  7607. if (result.hasExpandedExpression()) {
  7608. rss << "with expansion:\n";
  7609. rss << TextFlow::Column(result.getExpandedExpression()).indent(2) << '\n';
  7610. }
  7611. } else {
  7612. rss << '\n';
  7613. }
  7614. if( !result.getMessage().empty() )
  7615. rss << result.getMessage() << '\n';
  7616. for( auto const& msg : stats.infoMessages )
  7617. if( msg.type == ResultWas::Info )
  7618. rss << msg.message << '\n';
  7619. rss << "at " << result.getSourceInfo();
  7620. xml.writeText( rss.str(), XmlFormatting::Newline );
  7621. }
  7622. }
  7623. } // end namespace Catch
  7624. #include <ostream>
  7625. namespace Catch {
  7626. void MultiReporter::updatePreferences(IEventListener const& reporterish) {
  7627. m_preferences.shouldRedirectStdOut |=
  7628. reporterish.getPreferences().shouldRedirectStdOut;
  7629. m_preferences.shouldReportAllAssertions |=
  7630. reporterish.getPreferences().shouldReportAllAssertions;
  7631. }
  7632. void MultiReporter::addListener( IEventListenerPtr&& listener ) {
  7633. updatePreferences(*listener);
  7634. m_reporterLikes.insert(m_reporterLikes.begin() + m_insertedListeners, CATCH_MOVE(listener) );
  7635. ++m_insertedListeners;
  7636. }
  7637. void MultiReporter::addReporter( IEventListenerPtr&& reporter ) {
  7638. updatePreferences(*reporter);
  7639. // We will need to output the captured stdout if there are reporters
  7640. // that do not want it captured.
  7641. // We do not consider listeners, because it is generally assumed that
  7642. // listeners are output-transparent, even though they can ask for stdout
  7643. // capture to do something with it.
  7644. m_haveNoncapturingReporters |= !reporter->getPreferences().shouldRedirectStdOut;
  7645. // Reporters can always be placed to the back without breaking the
  7646. // reporting order
  7647. m_reporterLikes.push_back( CATCH_MOVE( reporter ) );
  7648. }
  7649. void MultiReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
  7650. for ( auto& reporterish : m_reporterLikes ) {
  7651. reporterish->noMatchingTestCases( unmatchedSpec );
  7652. }
  7653. }
  7654. void MultiReporter::fatalErrorEncountered( StringRef error ) {
  7655. for ( auto& reporterish : m_reporterLikes ) {
  7656. reporterish->fatalErrorEncountered( error );
  7657. }
  7658. }
  7659. void MultiReporter::reportInvalidTestSpec( StringRef arg ) {
  7660. for ( auto& reporterish : m_reporterLikes ) {
  7661. reporterish->reportInvalidTestSpec( arg );
  7662. }
  7663. }
  7664. void MultiReporter::benchmarkPreparing( StringRef name ) {
  7665. for (auto& reporterish : m_reporterLikes) {
  7666. reporterish->benchmarkPreparing(name);
  7667. }
  7668. }
  7669. void MultiReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  7670. for ( auto& reporterish : m_reporterLikes ) {
  7671. reporterish->benchmarkStarting( benchmarkInfo );
  7672. }
  7673. }
  7674. void MultiReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  7675. for ( auto& reporterish : m_reporterLikes ) {
  7676. reporterish->benchmarkEnded( benchmarkStats );
  7677. }
  7678. }
  7679. void MultiReporter::benchmarkFailed( StringRef error ) {
  7680. for (auto& reporterish : m_reporterLikes) {
  7681. reporterish->benchmarkFailed(error);
  7682. }
  7683. }
  7684. void MultiReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  7685. for ( auto& reporterish : m_reporterLikes ) {
  7686. reporterish->testRunStarting( testRunInfo );
  7687. }
  7688. }
  7689. void MultiReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  7690. for ( auto& reporterish : m_reporterLikes ) {
  7691. reporterish->testCaseStarting( testInfo );
  7692. }
  7693. }
  7694. void
  7695. MultiReporter::testCasePartialStarting( TestCaseInfo const& testInfo,
  7696. uint64_t partNumber ) {
  7697. for ( auto& reporterish : m_reporterLikes ) {
  7698. reporterish->testCasePartialStarting( testInfo, partNumber );
  7699. }
  7700. }
  7701. void MultiReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  7702. for ( auto& reporterish : m_reporterLikes ) {
  7703. reporterish->sectionStarting( sectionInfo );
  7704. }
  7705. }
  7706. void MultiReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  7707. for ( auto& reporterish : m_reporterLikes ) {
  7708. reporterish->assertionStarting( assertionInfo );
  7709. }
  7710. }
  7711. // The return value indicates if the messages buffer should be cleared:
  7712. void MultiReporter::assertionEnded( AssertionStats const& assertionStats ) {
  7713. const bool reportByDefault =
  7714. assertionStats.assertionResult.getResultType() != ResultWas::Ok ||
  7715. m_config->includeSuccessfulResults();
  7716. for ( auto & reporterish : m_reporterLikes ) {
  7717. if ( reportByDefault ||
  7718. reporterish->getPreferences().shouldReportAllAssertions ) {
  7719. reporterish->assertionEnded( assertionStats );
  7720. }
  7721. }
  7722. }
  7723. void MultiReporter::sectionEnded( SectionStats const& sectionStats ) {
  7724. for ( auto& reporterish : m_reporterLikes ) {
  7725. reporterish->sectionEnded( sectionStats );
  7726. }
  7727. }
  7728. void MultiReporter::testCasePartialEnded( TestCaseStats const& testStats,
  7729. uint64_t partNumber ) {
  7730. if ( m_preferences.shouldRedirectStdOut &&
  7731. m_haveNoncapturingReporters ) {
  7732. if ( !testStats.stdOut.empty() ) {
  7733. Catch::cout() << testStats.stdOut << std::flush;
  7734. }
  7735. if ( !testStats.stdErr.empty() ) {
  7736. Catch::cerr() << testStats.stdErr << std::flush;
  7737. }
  7738. }
  7739. for ( auto& reporterish : m_reporterLikes ) {
  7740. reporterish->testCasePartialEnded( testStats, partNumber );
  7741. }
  7742. }
  7743. void MultiReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  7744. for ( auto& reporterish : m_reporterLikes ) {
  7745. reporterish->testCaseEnded( testCaseStats );
  7746. }
  7747. }
  7748. void MultiReporter::testRunEnded( TestRunStats const& testRunStats ) {
  7749. for ( auto& reporterish : m_reporterLikes ) {
  7750. reporterish->testRunEnded( testRunStats );
  7751. }
  7752. }
  7753. void MultiReporter::skipTest( TestCaseInfo const& testInfo ) {
  7754. for ( auto& reporterish : m_reporterLikes ) {
  7755. reporterish->skipTest( testInfo );
  7756. }
  7757. }
  7758. void MultiReporter::listReporters(std::vector<ReporterDescription> const& descriptions) {
  7759. for (auto& reporterish : m_reporterLikes) {
  7760. reporterish->listReporters(descriptions);
  7761. }
  7762. }
  7763. void MultiReporter::listListeners(
  7764. std::vector<ListenerDescription> const& descriptions ) {
  7765. for ( auto& reporterish : m_reporterLikes ) {
  7766. reporterish->listListeners( descriptions );
  7767. }
  7768. }
  7769. void MultiReporter::listTests(std::vector<TestCaseHandle> const& tests) {
  7770. for (auto& reporterish : m_reporterLikes) {
  7771. reporterish->listTests(tests);
  7772. }
  7773. }
  7774. void MultiReporter::listTags(std::vector<TagInfo> const& tags) {
  7775. for (auto& reporterish : m_reporterLikes) {
  7776. reporterish->listTags(tags);
  7777. }
  7778. }
  7779. } // end namespace Catch
  7780. namespace Catch {
  7781. namespace Detail {
  7782. void registerReporterImpl( std::string const& name,
  7783. IReporterFactoryPtr reporterPtr ) {
  7784. CATCH_TRY {
  7785. getMutableRegistryHub().registerReporter(
  7786. name, CATCH_MOVE( reporterPtr ) );
  7787. }
  7788. CATCH_CATCH_ALL {
  7789. // Do not throw when constructing global objects, instead
  7790. // register the exception to be processed later
  7791. getMutableRegistryHub().registerStartupException();
  7792. }
  7793. }
  7794. } // namespace Detail
  7795. } // namespace Catch
  7796. #include <map>
  7797. namespace Catch {
  7798. namespace {
  7799. std::string createRngSeedString(uint32_t seed) {
  7800. ReusableStringStream sstr;
  7801. sstr << "rng-seed=" << seed;
  7802. return sstr.str();
  7803. }
  7804. }
  7805. void SonarQubeReporter::testRunStarting(TestRunInfo const& testRunInfo) {
  7806. CumulativeReporterBase::testRunStarting(testRunInfo);
  7807. xml.writeComment( createRngSeedString( m_config->rngSeed() ) );
  7808. xml.startElement("testExecutions");
  7809. xml.writeAttribute("version"_sr, '1');
  7810. }
  7811. void SonarQubeReporter::writeRun( TestRunNode const& runNode ) {
  7812. std::map<std::string, std::vector<TestCaseNode const*>> testsPerFile;
  7813. for ( auto const& child : runNode.children ) {
  7814. testsPerFile[child->value.testInfo->lineInfo.file].push_back(
  7815. child.get() );
  7816. }
  7817. for ( auto const& kv : testsPerFile ) {
  7818. writeTestFile( kv.first, kv.second );
  7819. }
  7820. }
  7821. void SonarQubeReporter::writeTestFile(std::string const& filename, std::vector<TestCaseNode const*> const& testCaseNodes) {
  7822. XmlWriter::ScopedElement e = xml.scopedElement("file");
  7823. xml.writeAttribute("path"_sr, filename);
  7824. for (auto const& child : testCaseNodes)
  7825. writeTestCase(*child);
  7826. }
  7827. void SonarQubeReporter::writeTestCase(TestCaseNode const& testCaseNode) {
  7828. // All test cases have exactly one section - which represents the
  7829. // test case itself. That section may have 0-n nested sections
  7830. assert(testCaseNode.children.size() == 1);
  7831. SectionNode const& rootSection = *testCaseNode.children.front();
  7832. writeSection("", rootSection, testCaseNode.value.testInfo->okToFail());
  7833. }
  7834. void SonarQubeReporter::writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) {
  7835. std::string name = trim(sectionNode.stats.sectionInfo.name);
  7836. if (!rootName.empty())
  7837. name = rootName + '/' + name;
  7838. if ( sectionNode.hasAnyAssertions()
  7839. || !sectionNode.stdOut.empty()
  7840. || !sectionNode.stdErr.empty() ) {
  7841. XmlWriter::ScopedElement e = xml.scopedElement("testCase");
  7842. xml.writeAttribute("name"_sr, name);
  7843. xml.writeAttribute("duration"_sr, static_cast<long>(sectionNode.stats.durationInSeconds * 1000));
  7844. writeAssertions(sectionNode, okToFail);
  7845. }
  7846. for (auto const& childNode : sectionNode.childSections)
  7847. writeSection(name, *childNode, okToFail);
  7848. }
  7849. void SonarQubeReporter::writeAssertions(SectionNode const& sectionNode, bool okToFail) {
  7850. for (auto const& assertionOrBenchmark : sectionNode.assertionsAndBenchmarks) {
  7851. if (assertionOrBenchmark.isAssertion()) {
  7852. writeAssertion(assertionOrBenchmark.asAssertion(), okToFail);
  7853. }
  7854. }
  7855. }
  7856. void SonarQubeReporter::writeAssertion(AssertionStats const& stats, bool okToFail) {
  7857. AssertionResult const& result = stats.assertionResult;
  7858. if (!result.isOk()) {
  7859. std::string elementName;
  7860. if (okToFail) {
  7861. elementName = "skipped";
  7862. } else {
  7863. switch (result.getResultType()) {
  7864. case ResultWas::ThrewException:
  7865. case ResultWas::FatalErrorCondition:
  7866. elementName = "error";
  7867. break;
  7868. case ResultWas::ExplicitFailure:
  7869. elementName = "failure";
  7870. break;
  7871. case ResultWas::ExpressionFailed:
  7872. elementName = "failure";
  7873. break;
  7874. case ResultWas::DidntThrowException:
  7875. elementName = "failure";
  7876. break;
  7877. // We should never see these here:
  7878. case ResultWas::Info:
  7879. case ResultWas::Warning:
  7880. case ResultWas::Ok:
  7881. case ResultWas::Unknown:
  7882. case ResultWas::FailureBit:
  7883. case ResultWas::Exception:
  7884. elementName = "internalError";
  7885. break;
  7886. }
  7887. }
  7888. XmlWriter::ScopedElement e = xml.scopedElement(elementName);
  7889. ReusableStringStream messageRss;
  7890. messageRss << result.getTestMacroName() << '(' << result.getExpression() << ')';
  7891. xml.writeAttribute("message"_sr, messageRss.str());
  7892. ReusableStringStream textRss;
  7893. if (stats.totals.assertions.total() > 0) {
  7894. textRss << "FAILED:\n";
  7895. if (result.hasExpression()) {
  7896. textRss << '\t' << result.getExpressionInMacro() << '\n';
  7897. }
  7898. if (result.hasExpandedExpression()) {
  7899. textRss << "with expansion:\n\t" << result.getExpandedExpression() << '\n';
  7900. }
  7901. }
  7902. if (!result.getMessage().empty())
  7903. textRss << result.getMessage() << '\n';
  7904. for (auto const& msg : stats.infoMessages)
  7905. if (msg.type == ResultWas::Info)
  7906. textRss << msg.message << '\n';
  7907. textRss << "at " << result.getSourceInfo();
  7908. xml.writeText(textRss.str(), XmlFormatting::Newline);
  7909. }
  7910. }
  7911. } // end namespace Catch
  7912. namespace Catch {
  7913. StreamingReporterBase::~StreamingReporterBase() = default;
  7914. void
  7915. StreamingReporterBase::testRunStarting( TestRunInfo const& _testRunInfo ) {
  7916. currentTestRunInfo = _testRunInfo;
  7917. }
  7918. void StreamingReporterBase::testRunEnded( TestRunStats const& ) {
  7919. currentTestCaseInfo = nullptr;
  7920. }
  7921. } // end namespace Catch
  7922. #include <algorithm>
  7923. #include <iterator>
  7924. #include <ostream>
  7925. namespace Catch {
  7926. namespace {
  7927. // Yes, this has to be outside the class and namespaced by naming.
  7928. // Making older compiler happy is hard.
  7929. static constexpr StringRef tapFailedString = "not ok"_sr;
  7930. static constexpr StringRef tapPassedString = "ok"_sr;
  7931. static constexpr Colour::Code tapDimColour = Colour::FileName;
  7932. class TapAssertionPrinter {
  7933. public:
  7934. TapAssertionPrinter& operator= (TapAssertionPrinter const&) = delete;
  7935. TapAssertionPrinter(TapAssertionPrinter const&) = delete;
  7936. TapAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter, ColourImpl* colour_)
  7937. : stream(_stream)
  7938. , result(_stats.assertionResult)
  7939. , messages(_stats.infoMessages)
  7940. , itMessage(_stats.infoMessages.begin())
  7941. , printInfoMessages(true)
  7942. , counter(_counter)
  7943. , colourImpl( colour_ ) {}
  7944. void print() {
  7945. itMessage = messages.begin();
  7946. switch (result.getResultType()) {
  7947. case ResultWas::Ok:
  7948. printResultType(tapPassedString);
  7949. printOriginalExpression();
  7950. printReconstructedExpression();
  7951. if (!result.hasExpression())
  7952. printRemainingMessages(Colour::None);
  7953. else
  7954. printRemainingMessages();
  7955. break;
  7956. case ResultWas::ExpressionFailed:
  7957. if (result.isOk()) {
  7958. printResultType(tapPassedString);
  7959. } else {
  7960. printResultType(tapFailedString);
  7961. }
  7962. printOriginalExpression();
  7963. printReconstructedExpression();
  7964. if (result.isOk()) {
  7965. printIssue(" # TODO");
  7966. }
  7967. printRemainingMessages();
  7968. break;
  7969. case ResultWas::ThrewException:
  7970. printResultType(tapFailedString);
  7971. printIssue("unexpected exception with message:"_sr);
  7972. printMessage();
  7973. printExpressionWas();
  7974. printRemainingMessages();
  7975. break;
  7976. case ResultWas::FatalErrorCondition:
  7977. printResultType(tapFailedString);
  7978. printIssue("fatal error condition with message:"_sr);
  7979. printMessage();
  7980. printExpressionWas();
  7981. printRemainingMessages();
  7982. break;
  7983. case ResultWas::DidntThrowException:
  7984. printResultType(tapFailedString);
  7985. printIssue("expected exception, got none"_sr);
  7986. printExpressionWas();
  7987. printRemainingMessages();
  7988. break;
  7989. case ResultWas::Info:
  7990. printResultType("info"_sr);
  7991. printMessage();
  7992. printRemainingMessages();
  7993. break;
  7994. case ResultWas::Warning:
  7995. printResultType("warning"_sr);
  7996. printMessage();
  7997. printRemainingMessages();
  7998. break;
  7999. case ResultWas::ExplicitFailure:
  8000. printResultType(tapFailedString);
  8001. printIssue("explicitly"_sr);
  8002. printRemainingMessages(Colour::None);
  8003. break;
  8004. // These cases are here to prevent compiler warnings
  8005. case ResultWas::Unknown:
  8006. case ResultWas::FailureBit:
  8007. case ResultWas::Exception:
  8008. printResultType("** internal error **"_sr);
  8009. break;
  8010. }
  8011. }
  8012. private:
  8013. void printResultType(StringRef passOrFail) const {
  8014. if (!passOrFail.empty()) {
  8015. stream << passOrFail << ' ' << counter << " -";
  8016. }
  8017. }
  8018. void printIssue(StringRef issue) const {
  8019. stream << ' ' << issue;
  8020. }
  8021. void printExpressionWas() {
  8022. if (result.hasExpression()) {
  8023. stream << ';';
  8024. stream << colourImpl->guardColour( tapDimColour )
  8025. << " expression was:";
  8026. printOriginalExpression();
  8027. }
  8028. }
  8029. void printOriginalExpression() const {
  8030. if (result.hasExpression()) {
  8031. stream << ' ' << result.getExpression();
  8032. }
  8033. }
  8034. void printReconstructedExpression() const {
  8035. if (result.hasExpandedExpression()) {
  8036. stream << colourImpl->guardColour( tapDimColour ) << " for: ";
  8037. std::string expr = result.getExpandedExpression();
  8038. std::replace(expr.begin(), expr.end(), '\n', ' ');
  8039. stream << expr;
  8040. }
  8041. }
  8042. void printMessage() {
  8043. if (itMessage != messages.end()) {
  8044. stream << " '" << itMessage->message << '\'';
  8045. ++itMessage;
  8046. }
  8047. }
  8048. void printRemainingMessages(Colour::Code colour = tapDimColour) {
  8049. if (itMessage == messages.end()) {
  8050. return;
  8051. }
  8052. // using messages.end() directly (or auto) yields compilation error:
  8053. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  8054. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  8055. stream << colourImpl->guardColour( colour ) << " with "
  8056. << pluralise( N, "message"_sr ) << ':';
  8057. for (; itMessage != itEnd; ) {
  8058. // If this assertion is a warning ignore any INFO messages
  8059. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  8060. stream << " '" << itMessage->message << '\'';
  8061. if (++itMessage != itEnd) {
  8062. stream << colourImpl->guardColour(tapDimColour) << " and";
  8063. }
  8064. }
  8065. }
  8066. }
  8067. private:
  8068. std::ostream& stream;
  8069. AssertionResult const& result;
  8070. std::vector<MessageInfo> messages;
  8071. std::vector<MessageInfo>::const_iterator itMessage;
  8072. bool printInfoMessages;
  8073. std::size_t counter;
  8074. ColourImpl* colourImpl;
  8075. };
  8076. } // End anonymous namespace
  8077. void TAPReporter::testRunStarting( TestRunInfo const& ) {
  8078. m_stream << "# rng-seed: " << m_config->rngSeed() << '\n';
  8079. }
  8080. void TAPReporter::noMatchingTestCases( StringRef unmatchedSpec ) {
  8081. m_stream << "# No test cases matched '" << unmatchedSpec << "'\n";
  8082. }
  8083. void TAPReporter::assertionEnded(AssertionStats const& _assertionStats) {
  8084. ++counter;
  8085. m_stream << "# " << currentTestCaseInfo->name << '\n';
  8086. TapAssertionPrinter printer(m_stream, _assertionStats, counter, m_colour.get());
  8087. printer.print();
  8088. m_stream << '\n' << std::flush;
  8089. }
  8090. void TAPReporter::testRunEnded(TestRunStats const& _testRunStats) {
  8091. m_stream << "1.." << _testRunStats.totals.assertions.total();
  8092. if (_testRunStats.totals.testCases.total() == 0) {
  8093. m_stream << " # Skipped: No tests ran.";
  8094. }
  8095. m_stream << "\n\n" << std::flush;
  8096. StreamingReporterBase::testRunEnded(_testRunStats);
  8097. }
  8098. } // end namespace Catch
  8099. #include <cassert>
  8100. #include <ostream>
  8101. namespace Catch {
  8102. namespace {
  8103. // if string has a : in first line will set indent to follow it on
  8104. // subsequent lines
  8105. void printHeaderString(std::ostream& os, std::string const& _string, std::size_t indent = 0) {
  8106. std::size_t i = _string.find(": ");
  8107. if (i != std::string::npos)
  8108. i += 2;
  8109. else
  8110. i = 0;
  8111. os << TextFlow::Column(_string)
  8112. .indent(indent + i)
  8113. .initialIndent(indent) << '\n';
  8114. }
  8115. std::string escape(StringRef str) {
  8116. std::string escaped = static_cast<std::string>(str);
  8117. replaceInPlace(escaped, "|", "||");
  8118. replaceInPlace(escaped, "'", "|'");
  8119. replaceInPlace(escaped, "\n", "|n");
  8120. replaceInPlace(escaped, "\r", "|r");
  8121. replaceInPlace(escaped, "[", "|[");
  8122. replaceInPlace(escaped, "]", "|]");
  8123. return escaped;
  8124. }
  8125. } // end anonymous namespace
  8126. TeamCityReporter::~TeamCityReporter() {}
  8127. void TeamCityReporter::testRunStarting( TestRunInfo const& runInfo ) {
  8128. m_stream << "##teamcity[testSuiteStarted name='" << escape( runInfo.name )
  8129. << "']\n";
  8130. }
  8131. void TeamCityReporter::testRunEnded( TestRunStats const& runStats ) {
  8132. m_stream << "##teamcity[testSuiteFinished name='"
  8133. << escape( runStats.runInfo.name ) << "']\n";
  8134. }
  8135. void TeamCityReporter::assertionEnded(AssertionStats const& assertionStats) {
  8136. AssertionResult const& result = assertionStats.assertionResult;
  8137. if (!result.isOk()) {
  8138. ReusableStringStream msg;
  8139. if (!m_headerPrintedForThisSection)
  8140. printSectionHeader(msg.get());
  8141. m_headerPrintedForThisSection = true;
  8142. msg << result.getSourceInfo() << '\n';
  8143. switch (result.getResultType()) {
  8144. case ResultWas::ExpressionFailed:
  8145. msg << "expression failed";
  8146. break;
  8147. case ResultWas::ThrewException:
  8148. msg << "unexpected exception";
  8149. break;
  8150. case ResultWas::FatalErrorCondition:
  8151. msg << "fatal error condition";
  8152. break;
  8153. case ResultWas::DidntThrowException:
  8154. msg << "no exception was thrown where one was expected";
  8155. break;
  8156. case ResultWas::ExplicitFailure:
  8157. msg << "explicit failure";
  8158. break;
  8159. // We shouldn't get here because of the isOk() test
  8160. case ResultWas::Ok:
  8161. case ResultWas::Info:
  8162. case ResultWas::Warning:
  8163. CATCH_ERROR("Internal error in TeamCity reporter");
  8164. // These cases are here to prevent compiler warnings
  8165. case ResultWas::Unknown:
  8166. case ResultWas::FailureBit:
  8167. case ResultWas::Exception:
  8168. CATCH_ERROR("Not implemented");
  8169. }
  8170. if (assertionStats.infoMessages.size() == 1)
  8171. msg << " with message:";
  8172. if (assertionStats.infoMessages.size() > 1)
  8173. msg << " with messages:";
  8174. for (auto const& messageInfo : assertionStats.infoMessages)
  8175. msg << "\n \"" << messageInfo.message << '"';
  8176. if (result.hasExpression()) {
  8177. msg <<
  8178. "\n " << result.getExpressionInMacro() << "\n"
  8179. "with expansion:\n"
  8180. " " << result.getExpandedExpression() << '\n';
  8181. }
  8182. if (currentTestCaseInfo->okToFail()) {
  8183. msg << "- failure ignore as test marked as 'ok to fail'\n";
  8184. m_stream << "##teamcity[testIgnored"
  8185. << " name='" << escape(currentTestCaseInfo->name) << '\''
  8186. << " message='" << escape(msg.str()) << '\''
  8187. << "]\n";
  8188. } else {
  8189. m_stream << "##teamcity[testFailed"
  8190. << " name='" << escape(currentTestCaseInfo->name) << '\''
  8191. << " message='" << escape(msg.str()) << '\''
  8192. << "]\n";
  8193. }
  8194. }
  8195. m_stream.flush();
  8196. }
  8197. void TeamCityReporter::testCaseStarting(TestCaseInfo const& testInfo) {
  8198. m_testTimer.start();
  8199. StreamingReporterBase::testCaseStarting(testInfo);
  8200. m_stream << "##teamcity[testStarted name='"
  8201. << escape(testInfo.name) << "']\n";
  8202. m_stream.flush();
  8203. }
  8204. void TeamCityReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
  8205. StreamingReporterBase::testCaseEnded(testCaseStats);
  8206. auto const& testCaseInfo = *testCaseStats.testInfo;
  8207. if (!testCaseStats.stdOut.empty())
  8208. m_stream << "##teamcity[testStdOut name='"
  8209. << escape(testCaseInfo.name)
  8210. << "' out='" << escape(testCaseStats.stdOut) << "']\n";
  8211. if (!testCaseStats.stdErr.empty())
  8212. m_stream << "##teamcity[testStdErr name='"
  8213. << escape(testCaseInfo.name)
  8214. << "' out='" << escape(testCaseStats.stdErr) << "']\n";
  8215. m_stream << "##teamcity[testFinished name='"
  8216. << escape(testCaseInfo.name) << "' duration='"
  8217. << m_testTimer.getElapsedMilliseconds() << "']\n";
  8218. m_stream.flush();
  8219. }
  8220. void TeamCityReporter::printSectionHeader(std::ostream& os) {
  8221. assert(!m_sectionStack.empty());
  8222. if (m_sectionStack.size() > 1) {
  8223. os << lineOfChars('-') << '\n';
  8224. std::vector<SectionInfo>::const_iterator
  8225. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  8226. itEnd = m_sectionStack.end();
  8227. for (; it != itEnd; ++it)
  8228. printHeaderString(os, it->name);
  8229. os << lineOfChars('-') << '\n';
  8230. }
  8231. SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
  8232. os << lineInfo << '\n';
  8233. os << lineOfChars('.') << "\n\n";
  8234. }
  8235. } // end namespace Catch
  8236. #if defined(_MSC_VER)
  8237. #pragma warning(push)
  8238. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  8239. // Note that 4062 (not all labels are handled
  8240. // and default is missing) is enabled
  8241. #endif
  8242. namespace Catch {
  8243. XmlReporter::XmlReporter( ReporterConfig&& _config )
  8244. : StreamingReporterBase( CATCH_MOVE(_config) ),
  8245. m_xml(m_stream)
  8246. {
  8247. m_preferences.shouldRedirectStdOut = true;
  8248. m_preferences.shouldReportAllAssertions = true;
  8249. }
  8250. XmlReporter::~XmlReporter() = default;
  8251. std::string XmlReporter::getDescription() {
  8252. return "Reports test results as an XML document";
  8253. }
  8254. std::string XmlReporter::getStylesheetRef() const {
  8255. return std::string();
  8256. }
  8257. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  8258. m_xml
  8259. .writeAttribute( "filename"_sr, sourceInfo.file )
  8260. .writeAttribute( "line"_sr, sourceInfo.line );
  8261. }
  8262. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  8263. StreamingReporterBase::testRunStarting( testInfo );
  8264. std::string stylesheetRef = getStylesheetRef();
  8265. if( !stylesheetRef.empty() )
  8266. m_xml.writeStylesheetRef( stylesheetRef );
  8267. m_xml.startElement("Catch2TestRun")
  8268. .writeAttribute("name"_sr, m_config->name())
  8269. .writeAttribute("rng-seed"_sr, m_config->rngSeed())
  8270. .writeAttribute("catch2-version"_sr, libraryVersion());
  8271. if (m_config->testSpec().hasFilters())
  8272. m_xml.writeAttribute( "filters"_sr, serializeFilters( m_config->getTestsOrTags() ) );
  8273. }
  8274. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  8275. StreamingReporterBase::testCaseStarting(testInfo);
  8276. m_xml.startElement( "TestCase" )
  8277. .writeAttribute( "name"_sr, trim( testInfo.name ) )
  8278. .writeAttribute( "tags"_sr, testInfo.tagsAsString() );
  8279. writeSourceInfo( testInfo.lineInfo );
  8280. if ( m_config->showDurations() == ShowDurations::Always )
  8281. m_testCaseTimer.start();
  8282. m_xml.ensureTagClosed();
  8283. }
  8284. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  8285. StreamingReporterBase::sectionStarting( sectionInfo );
  8286. if( m_sectionDepth++ > 0 ) {
  8287. m_xml.startElement( "Section" )
  8288. .writeAttribute( "name"_sr, trim( sectionInfo.name ) );
  8289. writeSourceInfo( sectionInfo.lineInfo );
  8290. m_xml.ensureTagClosed();
  8291. }
  8292. }
  8293. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  8294. void XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  8295. AssertionResult const& result = assertionStats.assertionResult;
  8296. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  8297. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  8298. // Print any info messages in <Info> tags.
  8299. for( auto const& msg : assertionStats.infoMessages ) {
  8300. if( msg.type == ResultWas::Info && includeResults ) {
  8301. m_xml.scopedElement( "Info" )
  8302. .writeText( msg.message );
  8303. } else if ( msg.type == ResultWas::Warning ) {
  8304. m_xml.scopedElement( "Warning" )
  8305. .writeText( msg.message );
  8306. }
  8307. }
  8308. }
  8309. // Drop out if result was successful but we're not printing them.
  8310. if( !includeResults && result.getResultType() != ResultWas::Warning )
  8311. return;
  8312. // Print the expression if there is one.
  8313. if( result.hasExpression() ) {
  8314. m_xml.startElement( "Expression" )
  8315. .writeAttribute( "success"_sr, result.succeeded() )
  8316. .writeAttribute( "type"_sr, result.getTestMacroName() );
  8317. writeSourceInfo( result.getSourceInfo() );
  8318. m_xml.scopedElement( "Original" )
  8319. .writeText( result.getExpression() );
  8320. m_xml.scopedElement( "Expanded" )
  8321. .writeText( result.getExpandedExpression() );
  8322. }
  8323. // And... Print a result applicable to each result type.
  8324. switch( result.getResultType() ) {
  8325. case ResultWas::ThrewException:
  8326. m_xml.startElement( "Exception" );
  8327. writeSourceInfo( result.getSourceInfo() );
  8328. m_xml.writeText( result.getMessage() );
  8329. m_xml.endElement();
  8330. break;
  8331. case ResultWas::FatalErrorCondition:
  8332. m_xml.startElement( "FatalErrorCondition" );
  8333. writeSourceInfo( result.getSourceInfo() );
  8334. m_xml.writeText( result.getMessage() );
  8335. m_xml.endElement();
  8336. break;
  8337. case ResultWas::Info:
  8338. m_xml.scopedElement( "Info" )
  8339. .writeText( result.getMessage() );
  8340. break;
  8341. case ResultWas::Warning:
  8342. // Warning will already have been written
  8343. break;
  8344. case ResultWas::ExplicitFailure:
  8345. m_xml.startElement( "Failure" );
  8346. writeSourceInfo( result.getSourceInfo() );
  8347. m_xml.writeText( result.getMessage() );
  8348. m_xml.endElement();
  8349. break;
  8350. default:
  8351. break;
  8352. }
  8353. if( result.hasExpression() )
  8354. m_xml.endElement();
  8355. }
  8356. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  8357. StreamingReporterBase::sectionEnded( sectionStats );
  8358. if( --m_sectionDepth > 0 ) {
  8359. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  8360. e.writeAttribute( "successes"_sr, sectionStats.assertions.passed );
  8361. e.writeAttribute( "failures"_sr, sectionStats.assertions.failed );
  8362. e.writeAttribute( "expectedFailures"_sr, sectionStats.assertions.failedButOk );
  8363. if ( m_config->showDurations() == ShowDurations::Always )
  8364. e.writeAttribute( "durationInSeconds"_sr, sectionStats.durationInSeconds );
  8365. m_xml.endElement();
  8366. }
  8367. }
  8368. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  8369. StreamingReporterBase::testCaseEnded( testCaseStats );
  8370. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  8371. e.writeAttribute( "success"_sr, testCaseStats.totals.assertions.allOk() );
  8372. if ( m_config->showDurations() == ShowDurations::Always )
  8373. e.writeAttribute( "durationInSeconds"_sr, m_testCaseTimer.getElapsedSeconds() );
  8374. if( !testCaseStats.stdOut.empty() )
  8375. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  8376. if( !testCaseStats.stdErr.empty() )
  8377. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  8378. m_xml.endElement();
  8379. }
  8380. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  8381. StreamingReporterBase::testRunEnded( testRunStats );
  8382. m_xml.scopedElement( "OverallResults" )
  8383. .writeAttribute( "successes"_sr, testRunStats.totals.assertions.passed )
  8384. .writeAttribute( "failures"_sr, testRunStats.totals.assertions.failed )
  8385. .writeAttribute( "expectedFailures"_sr, testRunStats.totals.assertions.failedButOk );
  8386. m_xml.scopedElement( "OverallResultsCases")
  8387. .writeAttribute( "successes"_sr, testRunStats.totals.testCases.passed )
  8388. .writeAttribute( "failures"_sr, testRunStats.totals.testCases.failed )
  8389. .writeAttribute( "expectedFailures"_sr, testRunStats.totals.testCases.failedButOk );
  8390. m_xml.endElement();
  8391. }
  8392. void XmlReporter::benchmarkPreparing( StringRef name ) {
  8393. m_xml.startElement("BenchmarkResults")
  8394. .writeAttribute("name"_sr, name);
  8395. }
  8396. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  8397. m_xml.writeAttribute("samples"_sr, info.samples)
  8398. .writeAttribute("resamples"_sr, info.resamples)
  8399. .writeAttribute("iterations"_sr, info.iterations)
  8400. .writeAttribute("clockResolution"_sr, info.clockResolution)
  8401. .writeAttribute("estimatedDuration"_sr, info.estimatedDuration)
  8402. .writeComment("All values in nano seconds"_sr);
  8403. }
  8404. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  8405. m_xml.startElement("mean")
  8406. .writeAttribute("value"_sr, benchmarkStats.mean.point.count())
  8407. .writeAttribute("lowerBound"_sr, benchmarkStats.mean.lower_bound.count())
  8408. .writeAttribute("upperBound"_sr, benchmarkStats.mean.upper_bound.count())
  8409. .writeAttribute("ci"_sr, benchmarkStats.mean.confidence_interval);
  8410. m_xml.endElement();
  8411. m_xml.startElement("standardDeviation")
  8412. .writeAttribute("value"_sr, benchmarkStats.standardDeviation.point.count())
  8413. .writeAttribute("lowerBound"_sr, benchmarkStats.standardDeviation.lower_bound.count())
  8414. .writeAttribute("upperBound"_sr, benchmarkStats.standardDeviation.upper_bound.count())
  8415. .writeAttribute("ci"_sr, benchmarkStats.standardDeviation.confidence_interval);
  8416. m_xml.endElement();
  8417. m_xml.startElement("outliers")
  8418. .writeAttribute("variance"_sr, benchmarkStats.outlierVariance)
  8419. .writeAttribute("lowMild"_sr, benchmarkStats.outliers.low_mild)
  8420. .writeAttribute("lowSevere"_sr, benchmarkStats.outliers.low_severe)
  8421. .writeAttribute("highMild"_sr, benchmarkStats.outliers.high_mild)
  8422. .writeAttribute("highSevere"_sr, benchmarkStats.outliers.high_severe);
  8423. m_xml.endElement();
  8424. m_xml.endElement();
  8425. }
  8426. void XmlReporter::benchmarkFailed(StringRef error) {
  8427. m_xml.scopedElement("failed").
  8428. writeAttribute("message"_sr, error);
  8429. m_xml.endElement();
  8430. }
  8431. void XmlReporter::listReporters(std::vector<ReporterDescription> const& descriptions) {
  8432. auto outerTag = m_xml.scopedElement("AvailableReporters");
  8433. for (auto const& reporter : descriptions) {
  8434. auto inner = m_xml.scopedElement("Reporter");
  8435. m_xml.startElement("Name", XmlFormatting::Indent)
  8436. .writeText(reporter.name, XmlFormatting::None)
  8437. .endElement(XmlFormatting::Newline);
  8438. m_xml.startElement("Description", XmlFormatting::Indent)
  8439. .writeText(reporter.description, XmlFormatting::None)
  8440. .endElement(XmlFormatting::Newline);
  8441. }
  8442. }
  8443. void XmlReporter::listListeners(std::vector<ListenerDescription> const& descriptions) {
  8444. auto outerTag = m_xml.scopedElement( "RegisteredListeners" );
  8445. for ( auto const& listener : descriptions ) {
  8446. auto inner = m_xml.scopedElement( "Listener" );
  8447. m_xml.startElement( "Name", XmlFormatting::Indent )
  8448. .writeText( listener.name, XmlFormatting::None )
  8449. .endElement( XmlFormatting::Newline );
  8450. m_xml.startElement( "Description", XmlFormatting::Indent )
  8451. .writeText( listener.description, XmlFormatting::None )
  8452. .endElement( XmlFormatting::Newline );
  8453. }
  8454. }
  8455. void XmlReporter::listTests(std::vector<TestCaseHandle> const& tests) {
  8456. auto outerTag = m_xml.scopedElement("MatchingTests");
  8457. for (auto const& test : tests) {
  8458. auto innerTag = m_xml.scopedElement("TestCase");
  8459. auto const& testInfo = test.getTestCaseInfo();
  8460. m_xml.startElement("Name", XmlFormatting::Indent)
  8461. .writeText(testInfo.name, XmlFormatting::None)
  8462. .endElement(XmlFormatting::Newline);
  8463. m_xml.startElement("ClassName", XmlFormatting::Indent)
  8464. .writeText(testInfo.className, XmlFormatting::None)
  8465. .endElement(XmlFormatting::Newline);
  8466. m_xml.startElement("Tags", XmlFormatting::Indent)
  8467. .writeText(testInfo.tagsAsString(), XmlFormatting::None)
  8468. .endElement(XmlFormatting::Newline);
  8469. auto sourceTag = m_xml.scopedElement("SourceInfo");
  8470. m_xml.startElement("File", XmlFormatting::Indent)
  8471. .writeText(testInfo.lineInfo.file, XmlFormatting::None)
  8472. .endElement(XmlFormatting::Newline);
  8473. m_xml.startElement("Line", XmlFormatting::Indent)
  8474. .writeText(std::to_string(testInfo.lineInfo.line), XmlFormatting::None)
  8475. .endElement(XmlFormatting::Newline);
  8476. }
  8477. }
  8478. void XmlReporter::listTags(std::vector<TagInfo> const& tags) {
  8479. auto outerTag = m_xml.scopedElement("TagsFromMatchingTests");
  8480. for (auto const& tag : tags) {
  8481. auto innerTag = m_xml.scopedElement("Tag");
  8482. m_xml.startElement("Count", XmlFormatting::Indent)
  8483. .writeText(std::to_string(tag.count), XmlFormatting::None)
  8484. .endElement(XmlFormatting::Newline);
  8485. auto aliasTag = m_xml.scopedElement("Aliases");
  8486. for (auto const& alias : tag.spellings) {
  8487. m_xml.startElement("Alias", XmlFormatting::Indent)
  8488. .writeText(alias, XmlFormatting::None)
  8489. .endElement(XmlFormatting::Newline);
  8490. }
  8491. }
  8492. }
  8493. } // end namespace Catch
  8494. #if defined(_MSC_VER)
  8495. #pragma warning(pop)
  8496. #endif