gtest_unittest.cc 258 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775
  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Tests for Google Test itself. This verifies that the basic constructs of
  31. // Google Test work.
  32. #include "gtest/gtest.h"
  33. // Verifies that the command line flag variables can be accessed in
  34. // code once "gtest.h" has been #included.
  35. // Do not move it after other gtest #includes.
  36. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
  37. bool dummy =
  38. GTEST_FLAG_GET(also_run_disabled_tests) ||
  39. GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
  40. GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
  41. GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
  42. GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
  43. GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
  44. GTEST_FLAG_GET(repeat) > 0 ||
  45. GTEST_FLAG_GET(recreate_environments_when_repeating) ||
  46. GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
  47. GTEST_FLAG_GET(stack_trace_depth) > 0 ||
  48. GTEST_FLAG_GET(stream_result_to) != "unknown" ||
  49. GTEST_FLAG_GET(throw_on_failure);
  50. EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
  51. }
  52. #include <limits.h> // For INT_MAX.
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <time.h>
  56. #include <cstdint>
  57. #include <map>
  58. #include <memory>
  59. #include <ostream>
  60. #include <set>
  61. #include <stdexcept>
  62. #include <string>
  63. #include <type_traits>
  64. #include <unordered_set>
  65. #include <utility>
  66. #include <vector>
  67. #include "gtest/gtest-spi.h"
  68. #include "src/gtest-internal-inl.h"
  69. struct ConvertibleGlobalType {
  70. // The inner enable_if is to ensure invoking is_constructible doesn't fail.
  71. // The outer enable_if is to ensure the overload resolution doesn't encounter
  72. // an ambiguity.
  73. template <
  74. class T,
  75. std::enable_if_t<
  76. false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0>
  77. operator T() const; // NOLINT(google-explicit-constructor)
  78. };
  79. void operator<<(ConvertibleGlobalType&, int);
  80. static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>()
  81. << 1)(*)()) > 0,
  82. "error in operator<< overload resolution");
  83. namespace testing {
  84. namespace internal {
  85. #if GTEST_CAN_STREAM_RESULTS_
  86. class StreamingListenerTest : public Test {
  87. public:
  88. class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
  89. public:
  90. // Sends a string to the socket.
  91. void Send(const std::string& message) override { output_ += message; }
  92. std::string output_;
  93. };
  94. StreamingListenerTest()
  95. : fake_sock_writer_(new FakeSocketWriter),
  96. streamer_(fake_sock_writer_),
  97. test_info_obj_("FooTest", "Bar", nullptr, nullptr,
  98. CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
  99. protected:
  100. std::string* output() { return &(fake_sock_writer_->output_); }
  101. FakeSocketWriter* const fake_sock_writer_;
  102. StreamingListener streamer_;
  103. UnitTest unit_test_;
  104. TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
  105. };
  106. TEST_F(StreamingListenerTest, OnTestProgramEnd) {
  107. *output() = "";
  108. streamer_.OnTestProgramEnd(unit_test_);
  109. EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
  110. }
  111. TEST_F(StreamingListenerTest, OnTestIterationEnd) {
  112. *output() = "";
  113. streamer_.OnTestIterationEnd(unit_test_, 42);
  114. EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
  115. }
  116. TEST_F(StreamingListenerTest, OnTestSuiteStart) {
  117. *output() = "";
  118. streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr));
  119. EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
  120. }
  121. TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
  122. *output() = "";
  123. streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr));
  124. EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
  125. }
  126. TEST_F(StreamingListenerTest, OnTestStart) {
  127. *output() = "";
  128. streamer_.OnTestStart(test_info_obj_);
  129. EXPECT_EQ("event=TestStart&name=Bar\n", *output());
  130. }
  131. TEST_F(StreamingListenerTest, OnTestEnd) {
  132. *output() = "";
  133. streamer_.OnTestEnd(test_info_obj_);
  134. EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
  135. }
  136. TEST_F(StreamingListenerTest, OnTestPartResult) {
  137. *output() = "";
  138. streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,
  139. "foo.cc", 42, "failed=\n&%"));
  140. // Meta characters in the failure message should be properly escaped.
  141. EXPECT_EQ(
  142. "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
  143. *output());
  144. }
  145. #endif // GTEST_CAN_STREAM_RESULTS_
  146. // Provides access to otherwise private parts of the TestEventListeners class
  147. // that are needed to test it.
  148. class TestEventListenersAccessor {
  149. public:
  150. static TestEventListener* GetRepeater(TestEventListeners* listeners) {
  151. return listeners->repeater();
  152. }
  153. static void SetDefaultResultPrinter(TestEventListeners* listeners,
  154. TestEventListener* listener) {
  155. listeners->SetDefaultResultPrinter(listener);
  156. }
  157. static void SetDefaultXmlGenerator(TestEventListeners* listeners,
  158. TestEventListener* listener) {
  159. listeners->SetDefaultXmlGenerator(listener);
  160. }
  161. static bool EventForwardingEnabled(const TestEventListeners& listeners) {
  162. return listeners.EventForwardingEnabled();
  163. }
  164. static void SuppressEventForwarding(TestEventListeners* listeners) {
  165. listeners->SuppressEventForwarding(true);
  166. }
  167. };
  168. class UnitTestRecordPropertyTestHelper : public Test {
  169. protected:
  170. UnitTestRecordPropertyTestHelper() {}
  171. // Forwards to UnitTest::RecordProperty() to bypass access controls.
  172. void UnitTestRecordProperty(const char* key, const std::string& value) {
  173. unit_test_.RecordProperty(key, value);
  174. }
  175. UnitTest unit_test_;
  176. };
  177. } // namespace internal
  178. } // namespace testing
  179. using testing::AssertionFailure;
  180. using testing::AssertionResult;
  181. using testing::AssertionSuccess;
  182. using testing::DoubleLE;
  183. using testing::EmptyTestEventListener;
  184. using testing::Environment;
  185. using testing::FloatLE;
  186. using testing::IsNotSubstring;
  187. using testing::IsSubstring;
  188. using testing::kMaxStackTraceDepth;
  189. using testing::Message;
  190. using testing::ScopedFakeTestPartResultReporter;
  191. using testing::StaticAssertTypeEq;
  192. using testing::Test;
  193. using testing::TestEventListeners;
  194. using testing::TestInfo;
  195. using testing::TestPartResult;
  196. using testing::TestPartResultArray;
  197. using testing::TestProperty;
  198. using testing::TestResult;
  199. using testing::TimeInMillis;
  200. using testing::UnitTest;
  201. using testing::internal::AlwaysFalse;
  202. using testing::internal::AlwaysTrue;
  203. using testing::internal::AppendUserMessage;
  204. using testing::internal::ArrayAwareFind;
  205. using testing::internal::ArrayEq;
  206. using testing::internal::CodePointToUtf8;
  207. using testing::internal::CopyArray;
  208. using testing::internal::CountIf;
  209. using testing::internal::EqFailure;
  210. using testing::internal::FloatingPoint;
  211. using testing::internal::ForEach;
  212. using testing::internal::FormatEpochTimeInMillisAsIso8601;
  213. using testing::internal::FormatTimeInMillisAsSeconds;
  214. using testing::internal::GetElementOr;
  215. using testing::internal::GetNextRandomSeed;
  216. using testing::internal::GetRandomSeedFromFlag;
  217. using testing::internal::GetTestTypeId;
  218. using testing::internal::GetTimeInMillis;
  219. using testing::internal::GetTypeId;
  220. using testing::internal::GetUnitTestImpl;
  221. using testing::internal::GTestFlagSaver;
  222. using testing::internal::HasDebugStringAndShortDebugString;
  223. using testing::internal::Int32FromEnvOrDie;
  224. using testing::internal::IsContainer;
  225. using testing::internal::IsContainerTest;
  226. using testing::internal::IsNotContainer;
  227. using testing::internal::kMaxRandomSeed;
  228. using testing::internal::kTestTypeIdInGoogleTest;
  229. using testing::internal::NativeArray;
  230. using testing::internal::ParseFlag;
  231. using testing::internal::RelationToSourceCopy;
  232. using testing::internal::RelationToSourceReference;
  233. using testing::internal::ShouldRunTestOnShard;
  234. using testing::internal::ShouldShard;
  235. using testing::internal::ShouldUseColor;
  236. using testing::internal::Shuffle;
  237. using testing::internal::ShuffleRange;
  238. using testing::internal::SkipPrefix;
  239. using testing::internal::StreamableToString;
  240. using testing::internal::String;
  241. using testing::internal::TestEventListenersAccessor;
  242. using testing::internal::TestResultAccessor;
  243. using testing::internal::WideStringToUtf8;
  244. using testing::internal::edit_distance::CalculateOptimalEdits;
  245. using testing::internal::edit_distance::CreateUnifiedDiff;
  246. using testing::internal::edit_distance::EditType;
  247. #if GTEST_HAS_STREAM_REDIRECTION
  248. using testing::internal::CaptureStdout;
  249. using testing::internal::GetCapturedStdout;
  250. #endif
  251. #ifdef GTEST_IS_THREADSAFE
  252. using testing::internal::ThreadWithParam;
  253. #endif
  254. class TestingVector : public std::vector<int> {};
  255. ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {
  256. os << "{ ";
  257. for (size_t i = 0; i < vector.size(); i++) {
  258. os << vector[i] << " ";
  259. }
  260. os << "}";
  261. return os;
  262. }
  263. // This line tests that we can define tests in an unnamed namespace.
  264. namespace {
  265. TEST(GetRandomSeedFromFlagTest, HandlesZero) {
  266. const int seed = GetRandomSeedFromFlag(0);
  267. EXPECT_LE(1, seed);
  268. EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
  269. }
  270. TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
  271. EXPECT_EQ(1, GetRandomSeedFromFlag(1));
  272. EXPECT_EQ(2, GetRandomSeedFromFlag(2));
  273. EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
  274. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  275. GetRandomSeedFromFlag(kMaxRandomSeed));
  276. }
  277. TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
  278. const int seed1 = GetRandomSeedFromFlag(-1);
  279. EXPECT_LE(1, seed1);
  280. EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
  281. const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
  282. EXPECT_LE(1, seed2);
  283. EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
  284. }
  285. TEST(GetNextRandomSeedTest, WorksForValidInput) {
  286. EXPECT_EQ(2, GetNextRandomSeed(1));
  287. EXPECT_EQ(3, GetNextRandomSeed(2));
  288. EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
  289. GetNextRandomSeed(kMaxRandomSeed - 1));
  290. EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
  291. // We deliberately don't test GetNextRandomSeed() with invalid
  292. // inputs, as that requires death tests, which are expensive. This
  293. // is fine as GetNextRandomSeed() is internal and has a
  294. // straightforward definition.
  295. }
  296. static void ClearCurrentTestPartResults() {
  297. TestResultAccessor::ClearTestPartResults(
  298. GetUnitTestImpl()->current_test_result());
  299. }
  300. // Tests GetTypeId.
  301. TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
  302. EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
  303. EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
  304. }
  305. class SubClassOfTest : public Test {};
  306. class AnotherSubClassOfTest : public Test {};
  307. TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
  308. EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
  309. EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
  310. EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
  311. EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
  312. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
  313. EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
  314. }
  315. // Verifies that GetTestTypeId() returns the same value, no matter it
  316. // is called from inside Google Test or outside of it.
  317. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
  318. EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
  319. }
  320. // Tests CanonicalizeForStdLibVersioning.
  321. using ::testing::internal::CanonicalizeForStdLibVersioning;
  322. TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
  323. EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
  324. EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
  325. EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
  326. EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
  327. EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
  328. EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
  329. }
  330. TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
  331. EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
  332. EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
  333. EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
  334. EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
  335. EXPECT_EQ("std::bind",
  336. CanonicalizeForStdLibVersioning("std::__google::bind"));
  337. EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
  338. }
  339. // Tests FormatTimeInMillisAsSeconds().
  340. TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
  341. EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0));
  342. }
  343. TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
  344. EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
  345. EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
  346. EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
  347. EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
  348. EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000));
  349. EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000));
  350. EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000));
  351. EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456));
  352. EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890));
  353. }
  354. TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
  355. EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
  356. EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
  357. EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
  358. EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
  359. EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000));
  360. EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000));
  361. EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000));
  362. EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456));
  363. EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890));
  364. }
  365. // TODO: b/287046337 - In emscripten, local time zone modification is not
  366. // supported.
  367. #if !defined(__EMSCRIPTEN__)
  368. // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
  369. // for particular dates below was verified in Python using
  370. // datetime.datetime.fromutctimestamp(<timestamp>/1000).
  371. // FormatEpochTimeInMillisAsIso8601 depends on the local timezone, so we
  372. // have to set up a particular timezone to obtain predictable results.
  373. class FormatEpochTimeInMillisAsIso8601Test : public Test {
  374. public:
  375. // On Cygwin, GCC doesn't allow unqualified integer literals to exceed
  376. // 32 bits, even when 64-bit integer types are available. We have to
  377. // force the constants to have a 64-bit type here.
  378. static const TimeInMillis kMillisPerSec = 1000;
  379. private:
  380. void SetUp() override {
  381. saved_tz_.reset();
  382. GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv: deprecated */)
  383. if (const char* tz = getenv("TZ")) {
  384. saved_tz_ = std::make_unique<std::string>(tz);
  385. }
  386. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  387. // Set the local time zone for FormatEpochTimeInMillisAsIso8601 to be
  388. // a fixed time zone for reproducibility purposes.
  389. SetTimeZone("UTC+00");
  390. }
  391. void TearDown() override {
  392. SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr);
  393. saved_tz_.reset();
  394. }
  395. static void SetTimeZone(const char* time_zone) {
  396. // tzset() distinguishes between the TZ variable being present and empty
  397. // and not being present, so we have to consider the case of time_zone
  398. // being NULL.
  399. #if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)
  400. // ...Unless it's MSVC, whose standard library's _putenv doesn't
  401. // distinguish between an empty and a missing variable.
  402. const std::string env_var =
  403. std::string("TZ=") + (time_zone ? time_zone : "");
  404. _putenv(env_var.c_str());
  405. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
  406. tzset();
  407. GTEST_DISABLE_MSC_WARNINGS_POP_()
  408. #else
  409. #if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21
  410. // Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
  411. // See https://github.com/android/ndk/issues/1604.
  412. setenv("TZ", "UTC", 1);
  413. tzset();
  414. #endif
  415. if (time_zone) {
  416. setenv(("TZ"), time_zone, 1);
  417. } else {
  418. unsetenv("TZ");
  419. }
  420. tzset();
  421. #endif
  422. }
  423. std::unique_ptr<std::string> saved_tz_; // Empty and null are different here
  424. };
  425. const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
  426. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
  427. EXPECT_EQ("2011-10-31T18:52:42.000",
  428. FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
  429. }
  430. TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
  431. EXPECT_EQ("2011-10-31T18:52:42.234",
  432. FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
  433. }
  434. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
  435. EXPECT_EQ("2011-09-03T05:07:02.000",
  436. FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
  437. }
  438. TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
  439. EXPECT_EQ("2011-09-28T17:08:22.000",
  440. FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
  441. }
  442. TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
  443. EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
  444. }
  445. #endif // __EMSCRIPTEN__
  446. #ifdef __BORLANDC__
  447. // Silences warnings: "Condition is always true", "Unreachable code"
  448. #pragma option push -w-ccc -w-rch
  449. #endif
  450. // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
  451. // when the RHS is a pointer type.
  452. TEST(NullLiteralTest, LHSAllowsNullLiterals) {
  453. EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
  454. ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
  455. EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
  456. ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
  457. EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
  458. ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
  459. const int* const p = nullptr;
  460. EXPECT_EQ(0, p); // NOLINT
  461. ASSERT_EQ(0, p); // NOLINT
  462. EXPECT_EQ(NULL, p); // NOLINT
  463. ASSERT_EQ(NULL, p); // NOLINT
  464. EXPECT_EQ(nullptr, p);
  465. ASSERT_EQ(nullptr, p);
  466. }
  467. struct ConvertToAll {
  468. template <typename T>
  469. operator T() const { // NOLINT
  470. return T();
  471. }
  472. };
  473. struct ConvertToPointer {
  474. template <class T>
  475. operator T*() const { // NOLINT
  476. return nullptr;
  477. }
  478. };
  479. struct ConvertToAllButNoPointers {
  480. template <typename T,
  481. typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
  482. operator T() const { // NOLINT
  483. return T();
  484. }
  485. };
  486. struct MyType {};
  487. inline bool operator==(MyType const&, MyType const&) { return true; }
  488. TEST(NullLiteralTest, ImplicitConversion) {
  489. EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
  490. #if !defined(__GNUC__) || defined(__clang__)
  491. // Disabled due to GCC bug gcc.gnu.org/PR89580
  492. EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
  493. #endif
  494. EXPECT_EQ(ConvertToAll{}, MyType{});
  495. EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
  496. }
  497. #ifdef __clang__
  498. #pragma clang diagnostic push
  499. #if __has_warning("-Wzero-as-null-pointer-constant")
  500. #pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
  501. #endif
  502. #endif
  503. TEST(NullLiteralTest, NoConversionNoWarning) {
  504. // Test that gtests detection and handling of null pointer constants
  505. // doesn't trigger a warning when '0' isn't actually used as null.
  506. EXPECT_EQ(0, 0);
  507. ASSERT_EQ(0, 0);
  508. }
  509. #ifdef __clang__
  510. #pragma clang diagnostic pop
  511. #endif
  512. #ifdef __BORLANDC__
  513. // Restores warnings after previous "#pragma option push" suppressed them.
  514. #pragma option pop
  515. #endif
  516. //
  517. // Tests CodePointToUtf8().
  518. // Tests that the NUL character L'\0' is encoded correctly.
  519. TEST(CodePointToUtf8Test, CanEncodeNul) {
  520. EXPECT_EQ("", CodePointToUtf8(L'\0'));
  521. }
  522. // Tests that ASCII characters are encoded correctly.
  523. TEST(CodePointToUtf8Test, CanEncodeAscii) {
  524. EXPECT_EQ("a", CodePointToUtf8(L'a'));
  525. EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
  526. EXPECT_EQ("&", CodePointToUtf8(L'&'));
  527. EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
  528. }
  529. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  530. // as 110xxxxx 10xxxxxx.
  531. TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
  532. // 000 1101 0011 => 110-00011 10-010011
  533. EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
  534. // 101 0111 0110 => 110-10101 10-110110
  535. // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
  536. // in wide strings and wide chars. In order to accommodate them, we have to
  537. // introduce such character constants as integers.
  538. EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576)));
  539. }
  540. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  541. // as 1110xxxx 10xxxxxx 10xxxxxx.
  542. TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
  543. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  544. EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
  545. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  546. EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
  547. }
  548. #if !GTEST_WIDE_STRING_USES_UTF16_
  549. // Tests in this group require a wchar_t to hold > 16 bits, and thus
  550. // are skipped on Windows, and Cygwin, where a wchar_t is
  551. // 16-bit wide. This code may not compile on those systems.
  552. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  553. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
  554. TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
  555. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  556. EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
  557. // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
  558. EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
  559. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  560. EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
  561. }
  562. // Tests that encoding an invalid code-point generates the expected result.
  563. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
  564. EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
  565. }
  566. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  567. // Tests WideStringToUtf8().
  568. // Tests that the NUL character L'\0' is encoded correctly.
  569. TEST(WideStringToUtf8Test, CanEncodeNul) {
  570. EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
  571. EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
  572. }
  573. // Tests that ASCII strings are encoded correctly.
  574. TEST(WideStringToUtf8Test, CanEncodeAscii) {
  575. EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
  576. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
  577. EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
  578. EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
  579. }
  580. // Tests that Unicode code-points that have 8 to 11 bits are encoded
  581. // as 110xxxxx 10xxxxxx.
  582. TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
  583. // 000 1101 0011 => 110-00011 10-010011
  584. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
  585. EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
  586. // 101 0111 0110 => 110-10101 10-110110
  587. const wchar_t s[] = {0x576, '\0'};
  588. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
  589. EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
  590. }
  591. // Tests that Unicode code-points that have 12 to 16 bits are encoded
  592. // as 1110xxxx 10xxxxxx 10xxxxxx.
  593. TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
  594. // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
  595. const wchar_t s1[] = {0x8D3, '\0'};
  596. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
  597. EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
  598. // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
  599. const wchar_t s2[] = {0xC74D, '\0'};
  600. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
  601. EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
  602. }
  603. // Tests that the conversion stops when the function encounters \0 character.
  604. TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
  605. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
  606. }
  607. // Tests that the conversion stops when the function reaches the limit
  608. // specified by the 'length' parameter.
  609. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
  610. EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
  611. }
  612. #if !GTEST_WIDE_STRING_USES_UTF16_
  613. // Tests that Unicode code-points that have 17 to 21 bits are encoded
  614. // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
  615. // on the systems using UTF-16 encoding.
  616. TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
  617. // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
  618. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
  619. EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
  620. // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
  621. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
  622. EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
  623. }
  624. // Tests that encoding an invalid code-point generates the expected result.
  625. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
  626. EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
  627. WideStringToUtf8(L"\xABCDFF", -1).c_str());
  628. }
  629. #else // !GTEST_WIDE_STRING_USES_UTF16_
  630. // Tests that surrogate pairs are encoded correctly on the systems using
  631. // UTF-16 encoding in the wide strings.
  632. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
  633. const wchar_t s[] = {0xD801, 0xDC00, '\0'};
  634. EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
  635. }
  636. // Tests that encoding an invalid UTF-16 surrogate pair
  637. // generates the expected result.
  638. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
  639. // Leading surrogate is at the end of the string.
  640. const wchar_t s1[] = {0xD800, '\0'};
  641. EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
  642. // Leading surrogate is not followed by the trailing surrogate.
  643. const wchar_t s2[] = {0xD800, 'M', '\0'};
  644. EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
  645. // Trailing surrogate appearas without a leading surrogate.
  646. const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'};
  647. EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
  648. }
  649. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  650. // Tests that codepoint concatenation works correctly.
  651. #if !GTEST_WIDE_STRING_USES_UTF16_
  652. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  653. const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
  654. EXPECT_STREQ(
  655. "\xF4\x88\x98\xB4"
  656. "\xEC\x9D\x8D"
  657. "\n"
  658. "\xD5\xB6"
  659. "\xE0\xA3\x93"
  660. "\xF4\x88\x98\xB4",
  661. WideStringToUtf8(s, -1).c_str());
  662. }
  663. #else
  664. TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
  665. const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'};
  666. EXPECT_STREQ(
  667. "\xEC\x9D\x8D"
  668. "\n"
  669. "\xD5\xB6"
  670. "\xE0\xA3\x93",
  671. WideStringToUtf8(s, -1).c_str());
  672. }
  673. #endif // !GTEST_WIDE_STRING_USES_UTF16_
  674. // Tests the Random class.
  675. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
  676. testing::internal::Random random(42);
  677. EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),
  678. "Cannot generate a number in the range \\[0, 0\\)");
  679. EXPECT_DEATH_IF_SUPPORTED(
  680. random.Generate(testing::internal::Random::kMaxRange + 1),
  681. "Generation of a number in \\[0, 2147483649\\) was requested, "
  682. "but this can only generate numbers in \\[0, 2147483648\\)");
  683. }
  684. TEST(RandomTest, GeneratesNumbersWithinRange) {
  685. constexpr uint32_t kRange = 10000;
  686. testing::internal::Random random(12345);
  687. for (int i = 0; i < 10; i++) {
  688. EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
  689. }
  690. testing::internal::Random random2(testing::internal::Random::kMaxRange);
  691. for (int i = 0; i < 10; i++) {
  692. EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
  693. }
  694. }
  695. TEST(RandomTest, RepeatsWhenReseeded) {
  696. constexpr int kSeed = 123;
  697. constexpr int kArraySize = 10;
  698. constexpr uint32_t kRange = 10000;
  699. uint32_t values[kArraySize];
  700. testing::internal::Random random(kSeed);
  701. for (int i = 0; i < kArraySize; i++) {
  702. values[i] = random.Generate(kRange);
  703. }
  704. random.Reseed(kSeed);
  705. for (int i = 0; i < kArraySize; i++) {
  706. EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
  707. }
  708. }
  709. // Tests STL container utilities.
  710. // Tests CountIf().
  711. static bool IsPositive(int n) { return n > 0; }
  712. TEST(ContainerUtilityTest, CountIf) {
  713. std::vector<int> v;
  714. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
  715. v.push_back(-1);
  716. v.push_back(0);
  717. EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
  718. v.push_back(2);
  719. v.push_back(-10);
  720. v.push_back(10);
  721. EXPECT_EQ(2, CountIf(v, IsPositive));
  722. }
  723. // Tests ForEach().
  724. static int g_sum = 0;
  725. static void Accumulate(int n) { g_sum += n; }
  726. TEST(ContainerUtilityTest, ForEach) {
  727. std::vector<int> v;
  728. g_sum = 0;
  729. ForEach(v, Accumulate);
  730. EXPECT_EQ(0, g_sum); // Works for an empty container;
  731. g_sum = 0;
  732. v.push_back(1);
  733. ForEach(v, Accumulate);
  734. EXPECT_EQ(1, g_sum); // Works for a container with one element.
  735. g_sum = 0;
  736. v.push_back(20);
  737. v.push_back(300);
  738. ForEach(v, Accumulate);
  739. EXPECT_EQ(321, g_sum);
  740. }
  741. // Tests GetElementOr().
  742. TEST(ContainerUtilityTest, GetElementOr) {
  743. std::vector<char> a;
  744. EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
  745. a.push_back('a');
  746. a.push_back('b');
  747. EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
  748. EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
  749. EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
  750. EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
  751. }
  752. TEST(ContainerUtilityDeathTest, ShuffleRange) {
  753. std::vector<int> a;
  754. a.push_back(0);
  755. a.push_back(1);
  756. a.push_back(2);
  757. testing::internal::Random random(1);
  758. EXPECT_DEATH_IF_SUPPORTED(
  759. ShuffleRange(&random, -1, 1, &a),
  760. "Invalid shuffle range start -1: must be in range \\[0, 3\\]");
  761. EXPECT_DEATH_IF_SUPPORTED(
  762. ShuffleRange(&random, 4, 4, &a),
  763. "Invalid shuffle range start 4: must be in range \\[0, 3\\]");
  764. EXPECT_DEATH_IF_SUPPORTED(
  765. ShuffleRange(&random, 3, 2, &a),
  766. "Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
  767. EXPECT_DEATH_IF_SUPPORTED(
  768. ShuffleRange(&random, 3, 4, &a),
  769. "Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
  770. }
  771. class VectorShuffleTest : public Test {
  772. protected:
  773. static const size_t kVectorSize = 20;
  774. VectorShuffleTest() : random_(1) {
  775. for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
  776. vector_.push_back(i);
  777. }
  778. }
  779. static bool VectorIsCorrupt(const TestingVector& vector) {
  780. if (kVectorSize != vector.size()) {
  781. return true;
  782. }
  783. bool found_in_vector[kVectorSize] = {false};
  784. for (size_t i = 0; i < vector.size(); i++) {
  785. const int e = vector[i];
  786. if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
  787. return true;
  788. }
  789. found_in_vector[e] = true;
  790. }
  791. // Vector size is correct, elements' range is correct, no
  792. // duplicate elements. Therefore no corruption has occurred.
  793. return false;
  794. }
  795. static bool VectorIsNotCorrupt(const TestingVector& vector) {
  796. return !VectorIsCorrupt(vector);
  797. }
  798. static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
  799. for (int i = begin; i < end; i++) {
  800. if (i != vector[static_cast<size_t>(i)]) {
  801. return true;
  802. }
  803. }
  804. return false;
  805. }
  806. static bool RangeIsUnshuffled(const TestingVector& vector, int begin,
  807. int end) {
  808. return !RangeIsShuffled(vector, begin, end);
  809. }
  810. static bool VectorIsShuffled(const TestingVector& vector) {
  811. return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
  812. }
  813. static bool VectorIsUnshuffled(const TestingVector& vector) {
  814. return !VectorIsShuffled(vector);
  815. }
  816. testing::internal::Random random_;
  817. TestingVector vector_;
  818. }; // class VectorShuffleTest
  819. const size_t VectorShuffleTest::kVectorSize;
  820. TEST_F(VectorShuffleTest, HandlesEmptyRange) {
  821. // Tests an empty range at the beginning...
  822. ShuffleRange(&random_, 0, 0, &vector_);
  823. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  824. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  825. // ...in the middle...
  826. ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);
  827. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  828. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  829. // ...at the end...
  830. ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
  831. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  832. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  833. // ...and past the end.
  834. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
  835. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  836. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  837. }
  838. TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
  839. // Tests a size one range at the beginning...
  840. ShuffleRange(&random_, 0, 1, &vector_);
  841. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  842. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  843. // ...in the middle...
  844. ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
  845. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  846. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  847. // ...and at the end.
  848. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
  849. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  850. ASSERT_PRED1(VectorIsUnshuffled, vector_);
  851. }
  852. // Because we use our own random number generator and a fixed seed,
  853. // we can guarantee that the following "random" tests will succeed.
  854. TEST_F(VectorShuffleTest, ShufflesEntireVector) {
  855. Shuffle(&random_, &vector_);
  856. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  857. EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
  858. // Tests the first and last elements in particular to ensure that
  859. // there are no off-by-one problems in our shuffle algorithm.
  860. EXPECT_NE(0, vector_[0]);
  861. EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
  862. }
  863. TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
  864. const int kRangeSize = kVectorSize / 2;
  865. ShuffleRange(&random_, 0, kRangeSize, &vector_);
  866. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  867. EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
  868. EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
  869. static_cast<int>(kVectorSize));
  870. }
  871. TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
  872. const int kRangeSize = kVectorSize / 2;
  873. ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
  874. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  875. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  876. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
  877. static_cast<int>(kVectorSize));
  878. }
  879. TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
  880. const int kRangeSize = static_cast<int>(kVectorSize) / 3;
  881. ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);
  882. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  883. EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
  884. EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);
  885. EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
  886. static_cast<int>(kVectorSize));
  887. }
  888. TEST_F(VectorShuffleTest, ShufflesRepeatably) {
  889. TestingVector vector2;
  890. for (size_t i = 0; i < kVectorSize; i++) {
  891. vector2.push_back(static_cast<int>(i));
  892. }
  893. random_.Reseed(1234);
  894. Shuffle(&random_, &vector_);
  895. random_.Reseed(1234);
  896. Shuffle(&random_, &vector2);
  897. ASSERT_PRED1(VectorIsNotCorrupt, vector_);
  898. ASSERT_PRED1(VectorIsNotCorrupt, vector2);
  899. for (size_t i = 0; i < kVectorSize; i++) {
  900. EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
  901. }
  902. }
  903. // Tests the size of the AssertHelper class.
  904. TEST(AssertHelperTest, AssertHelperIsSmall) {
  905. // To avoid breaking clients that use lots of assertions in one
  906. // function, we cannot grow the size of AssertHelper.
  907. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
  908. }
  909. // Tests String::EndsWithCaseInsensitive().
  910. TEST(StringTest, EndsWithCaseInsensitive) {
  911. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
  912. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
  913. EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
  914. EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
  915. EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
  916. EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
  917. EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
  918. }
  919. // C++Builder's preprocessor is buggy; it fails to expand macros that
  920. // appear in macro parameters after wide char literals. Provide an alias
  921. // for NULL as a workaround.
  922. static const wchar_t* const kNull = nullptr;
  923. // Tests String::CaseInsensitiveWideCStringEquals
  924. TEST(StringTest, CaseInsensitiveWideCStringEquals) {
  925. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
  926. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
  927. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
  928. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
  929. EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
  930. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
  931. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
  932. EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
  933. }
  934. #ifdef GTEST_OS_WINDOWS
  935. // Tests String::ShowWideCString().
  936. TEST(StringTest, ShowWideCString) {
  937. EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str());
  938. EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
  939. EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
  940. }
  941. #ifdef GTEST_OS_WINDOWS_MOBILE
  942. TEST(StringTest, AnsiAndUtf16Null) {
  943. EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
  944. EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
  945. }
  946. TEST(StringTest, AnsiAndUtf16ConvertBasic) {
  947. const char* ansi = String::Utf16ToAnsi(L"str");
  948. EXPECT_STREQ("str", ansi);
  949. delete[] ansi;
  950. const WCHAR* utf16 = String::AnsiToUtf16("str");
  951. EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
  952. delete[] utf16;
  953. }
  954. TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
  955. const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
  956. EXPECT_STREQ(".:\\ \"*?", ansi);
  957. delete[] ansi;
  958. const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
  959. EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
  960. delete[] utf16;
  961. }
  962. #endif // GTEST_OS_WINDOWS_MOBILE
  963. #endif // GTEST_OS_WINDOWS
  964. // Tests TestProperty construction.
  965. TEST(TestPropertyTest, StringValue) {
  966. TestProperty property("key", "1");
  967. EXPECT_STREQ("key", property.key());
  968. EXPECT_STREQ("1", property.value());
  969. }
  970. // Tests TestProperty replacing a value.
  971. TEST(TestPropertyTest, ReplaceStringValue) {
  972. TestProperty property("key", "1");
  973. EXPECT_STREQ("1", property.value());
  974. property.SetValue("2");
  975. EXPECT_STREQ("2", property.value());
  976. }
  977. // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
  978. // functions (i.e. their definitions cannot be inlined at the call
  979. // sites), or C++Builder won't compile the code.
  980. static void AddFatalFailure() { FAIL() << "Expected fatal failure."; }
  981. static void AddNonfatalFailure() {
  982. ADD_FAILURE() << "Expected non-fatal failure.";
  983. }
  984. class ScopedFakeTestPartResultReporterTest : public Test {
  985. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  986. enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
  987. static void AddFailure(FailureMode failure) {
  988. if (failure == FATAL_FAILURE) {
  989. AddFatalFailure();
  990. } else {
  991. AddNonfatalFailure();
  992. }
  993. }
  994. };
  995. // Tests that ScopedFakeTestPartResultReporter intercepts test
  996. // failures.
  997. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
  998. TestPartResultArray results;
  999. {
  1000. ScopedFakeTestPartResultReporter reporter(
  1001. ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
  1002. &results);
  1003. AddFailure(NONFATAL_FAILURE);
  1004. AddFailure(FATAL_FAILURE);
  1005. }
  1006. EXPECT_EQ(2, results.size());
  1007. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1008. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1009. }
  1010. TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
  1011. TestPartResultArray results;
  1012. {
  1013. // Tests, that the deprecated constructor still works.
  1014. ScopedFakeTestPartResultReporter reporter(&results);
  1015. AddFailure(NONFATAL_FAILURE);
  1016. }
  1017. EXPECT_EQ(1, results.size());
  1018. }
  1019. #ifdef GTEST_IS_THREADSAFE
  1020. class ScopedFakeTestPartResultReporterWithThreadsTest
  1021. : public ScopedFakeTestPartResultReporterTest {
  1022. protected:
  1023. static void AddFailureInOtherThread(FailureMode failure) {
  1024. ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
  1025. thread.Join();
  1026. }
  1027. };
  1028. TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
  1029. InterceptsTestFailuresInAllThreads) {
  1030. TestPartResultArray results;
  1031. {
  1032. ScopedFakeTestPartResultReporter reporter(
  1033. ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
  1034. AddFailure(NONFATAL_FAILURE);
  1035. AddFailure(FATAL_FAILURE);
  1036. AddFailureInOtherThread(NONFATAL_FAILURE);
  1037. AddFailureInOtherThread(FATAL_FAILURE);
  1038. }
  1039. EXPECT_EQ(4, results.size());
  1040. EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
  1041. EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
  1042. EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
  1043. EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
  1044. }
  1045. #endif // GTEST_IS_THREADSAFE
  1046. // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
  1047. // work even if the failure is generated in a called function rather than
  1048. // the current context.
  1049. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
  1050. TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
  1051. EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
  1052. }
  1053. TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
  1054. EXPECT_FATAL_FAILURE(AddFatalFailure(),
  1055. ::std::string("Expected fatal failure."));
  1056. }
  1057. TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
  1058. // We have another test below to verify that the macro catches fatal
  1059. // failures generated on another thread.
  1060. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
  1061. "Expected fatal failure.");
  1062. }
  1063. #ifdef __BORLANDC__
  1064. // Silences warnings: "Condition is always true"
  1065. #pragma option push -w-ccc
  1066. #endif
  1067. // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
  1068. // function even when the statement in it contains ASSERT_*.
  1069. int NonVoidFunction() {
  1070. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1071. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1072. return 0;
  1073. }
  1074. TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
  1075. NonVoidFunction();
  1076. }
  1077. // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
  1078. // current function even though 'statement' generates a fatal failure.
  1079. void DoesNotAbortHelper(bool* aborted) {
  1080. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
  1081. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
  1082. *aborted = false;
  1083. }
  1084. #ifdef __BORLANDC__
  1085. // Restores warnings after previous "#pragma option push" suppressed them.
  1086. #pragma option pop
  1087. #endif
  1088. TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
  1089. bool aborted = true;
  1090. DoesNotAbortHelper(&aborted);
  1091. EXPECT_FALSE(aborted);
  1092. }
  1093. // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1094. // statement that contains a macro which expands to code containing an
  1095. // unprotected comma.
  1096. static int global_var = 0;
  1097. #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
  1098. TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1099. #ifndef __BORLANDC__
  1100. // ICE's in C++Builder.
  1101. EXPECT_FATAL_FAILURE(
  1102. {
  1103. GTEST_USE_UNPROTECTED_COMMA_;
  1104. AddFatalFailure();
  1105. },
  1106. "");
  1107. #endif
  1108. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
  1109. {
  1110. GTEST_USE_UNPROTECTED_COMMA_;
  1111. AddFatalFailure();
  1112. },
  1113. "");
  1114. }
  1115. // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
  1116. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
  1117. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
  1118. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure.");
  1119. }
  1120. TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
  1121. EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
  1122. ::std::string("Expected non-fatal failure."));
  1123. }
  1124. TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
  1125. // We have another test below to verify that the macro catches
  1126. // non-fatal failures generated on another thread.
  1127. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
  1128. "Expected non-fatal failure.");
  1129. }
  1130. // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
  1131. // statement that contains a macro which expands to code containing an
  1132. // unprotected comma.
  1133. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
  1134. EXPECT_NONFATAL_FAILURE(
  1135. {
  1136. GTEST_USE_UNPROTECTED_COMMA_;
  1137. AddNonfatalFailure();
  1138. },
  1139. "");
  1140. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  1141. {
  1142. GTEST_USE_UNPROTECTED_COMMA_;
  1143. AddNonfatalFailure();
  1144. },
  1145. "");
  1146. }
  1147. #ifdef GTEST_IS_THREADSAFE
  1148. typedef ScopedFakeTestPartResultReporterWithThreadsTest
  1149. ExpectFailureWithThreadsTest;
  1150. TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
  1151. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
  1152. "Expected fatal failure.");
  1153. }
  1154. TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  1155. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  1156. AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
  1157. }
  1158. #endif // GTEST_IS_THREADSAFE
  1159. // Tests the TestProperty class.
  1160. TEST(TestPropertyTest, ConstructorWorks) {
  1161. const TestProperty property("key", "value");
  1162. EXPECT_STREQ("key", property.key());
  1163. EXPECT_STREQ("value", property.value());
  1164. }
  1165. TEST(TestPropertyTest, SetValue) {
  1166. TestProperty property("key", "value_1");
  1167. EXPECT_STREQ("key", property.key());
  1168. property.SetValue("value_2");
  1169. EXPECT_STREQ("key", property.key());
  1170. EXPECT_STREQ("value_2", property.value());
  1171. }
  1172. // Tests the TestResult class
  1173. // The test fixture for testing TestResult.
  1174. class TestResultTest : public Test {
  1175. protected:
  1176. typedef std::vector<TestPartResult> TPRVector;
  1177. // We make use of 2 TestPartResult objects,
  1178. TestPartResult *pr1, *pr2;
  1179. // ... and 3 TestResult objects.
  1180. TestResult *r0, *r1, *r2;
  1181. void SetUp() override {
  1182. // pr1 is for success.
  1183. pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10,
  1184. "Success!");
  1185. // pr2 is for fatal failure.
  1186. pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc",
  1187. -1, // This line number means "unknown"
  1188. "Failure!");
  1189. // Creates the TestResult objects.
  1190. r0 = new TestResult();
  1191. r1 = new TestResult();
  1192. r2 = new TestResult();
  1193. // In order to test TestResult, we need to modify its internal
  1194. // state, in particular the TestPartResult vector it holds.
  1195. // test_part_results() returns a const reference to this vector.
  1196. // We cast it to a non-const object s.t. it can be modified
  1197. TPRVector* results1 =
  1198. const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));
  1199. TPRVector* results2 =
  1200. const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));
  1201. // r0 is an empty TestResult.
  1202. // r1 contains a single SUCCESS TestPartResult.
  1203. results1->push_back(*pr1);
  1204. // r2 contains a SUCCESS, and a FAILURE.
  1205. results2->push_back(*pr1);
  1206. results2->push_back(*pr2);
  1207. }
  1208. void TearDown() override {
  1209. delete pr1;
  1210. delete pr2;
  1211. delete r0;
  1212. delete r1;
  1213. delete r2;
  1214. }
  1215. // Helper that compares two TestPartResults.
  1216. static void CompareTestPartResult(const TestPartResult& expected,
  1217. const TestPartResult& actual) {
  1218. EXPECT_EQ(expected.type(), actual.type());
  1219. EXPECT_STREQ(expected.file_name(), actual.file_name());
  1220. EXPECT_EQ(expected.line_number(), actual.line_number());
  1221. EXPECT_STREQ(expected.summary(), actual.summary());
  1222. EXPECT_STREQ(expected.message(), actual.message());
  1223. EXPECT_EQ(expected.passed(), actual.passed());
  1224. EXPECT_EQ(expected.failed(), actual.failed());
  1225. EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
  1226. EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
  1227. }
  1228. };
  1229. // Tests TestResult::total_part_count().
  1230. TEST_F(TestResultTest, total_part_count) {
  1231. ASSERT_EQ(0, r0->total_part_count());
  1232. ASSERT_EQ(1, r1->total_part_count());
  1233. ASSERT_EQ(2, r2->total_part_count());
  1234. }
  1235. // Tests TestResult::Passed().
  1236. TEST_F(TestResultTest, Passed) {
  1237. ASSERT_TRUE(r0->Passed());
  1238. ASSERT_TRUE(r1->Passed());
  1239. ASSERT_FALSE(r2->Passed());
  1240. }
  1241. // Tests TestResult::Failed().
  1242. TEST_F(TestResultTest, Failed) {
  1243. ASSERT_FALSE(r0->Failed());
  1244. ASSERT_FALSE(r1->Failed());
  1245. ASSERT_TRUE(r2->Failed());
  1246. }
  1247. // Tests TestResult::GetTestPartResult().
  1248. typedef TestResultTest TestResultDeathTest;
  1249. TEST_F(TestResultDeathTest, GetTestPartResult) {
  1250. CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
  1251. CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
  1252. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
  1253. EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
  1254. }
  1255. // Tests TestResult has no properties when none are added.
  1256. TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
  1257. TestResult test_result;
  1258. ASSERT_EQ(0, test_result.test_property_count());
  1259. }
  1260. // Tests TestResult has the expected property when added.
  1261. TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
  1262. TestResult test_result;
  1263. TestProperty property("key_1", "1");
  1264. TestResultAccessor::RecordProperty(&test_result, "testcase", property);
  1265. ASSERT_EQ(1, test_result.test_property_count());
  1266. const TestProperty& actual_property = test_result.GetTestProperty(0);
  1267. EXPECT_STREQ("key_1", actual_property.key());
  1268. EXPECT_STREQ("1", actual_property.value());
  1269. }
  1270. // Tests TestResult has multiple properties when added.
  1271. TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
  1272. TestResult test_result;
  1273. TestProperty property_1("key_1", "1");
  1274. TestProperty property_2("key_2", "2");
  1275. TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
  1276. TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
  1277. ASSERT_EQ(2, test_result.test_property_count());
  1278. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1279. EXPECT_STREQ("key_1", actual_property_1.key());
  1280. EXPECT_STREQ("1", actual_property_1.value());
  1281. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1282. EXPECT_STREQ("key_2", actual_property_2.key());
  1283. EXPECT_STREQ("2", actual_property_2.value());
  1284. }
  1285. // Tests TestResult::RecordProperty() overrides values for duplicate keys.
  1286. TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
  1287. TestResult test_result;
  1288. TestProperty property_1_1("key_1", "1");
  1289. TestProperty property_2_1("key_2", "2");
  1290. TestProperty property_1_2("key_1", "12");
  1291. TestProperty property_2_2("key_2", "22");
  1292. TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
  1293. TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
  1294. TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
  1295. TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
  1296. ASSERT_EQ(2, test_result.test_property_count());
  1297. const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
  1298. EXPECT_STREQ("key_1", actual_property_1.key());
  1299. EXPECT_STREQ("12", actual_property_1.value());
  1300. const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
  1301. EXPECT_STREQ("key_2", actual_property_2.key());
  1302. EXPECT_STREQ("22", actual_property_2.value());
  1303. }
  1304. // Tests TestResult::GetTestProperty().
  1305. TEST(TestResultPropertyTest, GetTestProperty) {
  1306. TestResult test_result;
  1307. TestProperty property_1("key_1", "1");
  1308. TestProperty property_2("key_2", "2");
  1309. TestProperty property_3("key_3", "3");
  1310. TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
  1311. TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
  1312. TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
  1313. const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
  1314. const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
  1315. const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
  1316. EXPECT_STREQ("key_1", fetched_property_1.key());
  1317. EXPECT_STREQ("1", fetched_property_1.value());
  1318. EXPECT_STREQ("key_2", fetched_property_2.key());
  1319. EXPECT_STREQ("2", fetched_property_2.value());
  1320. EXPECT_STREQ("key_3", fetched_property_3.key());
  1321. EXPECT_STREQ("3", fetched_property_3.value());
  1322. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
  1323. EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
  1324. }
  1325. // Tests the Test class.
  1326. //
  1327. // It's difficult to test every public method of this class (we are
  1328. // already stretching the limit of Google Test by using it to test itself!).
  1329. // Fortunately, we don't have to do that, as we are already testing
  1330. // the functionalities of the Test class extensively by using Google Test
  1331. // alone.
  1332. //
  1333. // Therefore, this section only contains one test.
  1334. // Tests that GTestFlagSaver works on Windows and Mac.
  1335. class GTestFlagSaverTest : public Test {
  1336. protected:
  1337. // Saves the Google Test flags such that we can restore them later, and
  1338. // then sets them to their default values. This will be called
  1339. // before the first test in this test case is run.
  1340. static void SetUpTestSuite() {
  1341. saver_ = new GTestFlagSaver;
  1342. GTEST_FLAG_SET(also_run_disabled_tests, false);
  1343. GTEST_FLAG_SET(break_on_failure, false);
  1344. GTEST_FLAG_SET(catch_exceptions, false);
  1345. GTEST_FLAG_SET(death_test_use_fork, false);
  1346. GTEST_FLAG_SET(color, "auto");
  1347. GTEST_FLAG_SET(fail_fast, false);
  1348. GTEST_FLAG_SET(filter, "");
  1349. GTEST_FLAG_SET(list_tests, false);
  1350. GTEST_FLAG_SET(output, "");
  1351. GTEST_FLAG_SET(brief, false);
  1352. GTEST_FLAG_SET(print_time, true);
  1353. GTEST_FLAG_SET(random_seed, 0);
  1354. GTEST_FLAG_SET(repeat, 1);
  1355. GTEST_FLAG_SET(recreate_environments_when_repeating, true);
  1356. GTEST_FLAG_SET(shuffle, false);
  1357. GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
  1358. GTEST_FLAG_SET(stream_result_to, "");
  1359. GTEST_FLAG_SET(throw_on_failure, false);
  1360. }
  1361. // Restores the Google Test flags that the tests have modified. This will
  1362. // be called after the last test in this test case is run.
  1363. static void TearDownTestSuite() {
  1364. delete saver_;
  1365. saver_ = nullptr;
  1366. }
  1367. // Verifies that the Google Test flags have their default values, and then
  1368. // modifies each of them.
  1369. void VerifyAndModifyFlags() {
  1370. EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
  1371. EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
  1372. EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
  1373. EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
  1374. EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
  1375. EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
  1376. EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
  1377. EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
  1378. EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
  1379. EXPECT_FALSE(GTEST_FLAG_GET(brief));
  1380. EXPECT_TRUE(GTEST_FLAG_GET(print_time));
  1381. EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
  1382. EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
  1383. EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
  1384. EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
  1385. EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
  1386. EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
  1387. EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
  1388. GTEST_FLAG_SET(also_run_disabled_tests, true);
  1389. GTEST_FLAG_SET(break_on_failure, true);
  1390. GTEST_FLAG_SET(catch_exceptions, true);
  1391. GTEST_FLAG_SET(color, "no");
  1392. GTEST_FLAG_SET(death_test_use_fork, true);
  1393. GTEST_FLAG_SET(fail_fast, true);
  1394. GTEST_FLAG_SET(filter, "abc");
  1395. GTEST_FLAG_SET(list_tests, true);
  1396. GTEST_FLAG_SET(output, "xml:foo.xml");
  1397. GTEST_FLAG_SET(brief, true);
  1398. GTEST_FLAG_SET(print_time, false);
  1399. GTEST_FLAG_SET(random_seed, 1);
  1400. GTEST_FLAG_SET(repeat, 100);
  1401. GTEST_FLAG_SET(recreate_environments_when_repeating, false);
  1402. GTEST_FLAG_SET(shuffle, true);
  1403. GTEST_FLAG_SET(stack_trace_depth, 1);
  1404. GTEST_FLAG_SET(stream_result_to, "localhost:1234");
  1405. GTEST_FLAG_SET(throw_on_failure, true);
  1406. }
  1407. private:
  1408. // For saving Google Test flags during this test case.
  1409. static GTestFlagSaver* saver_;
  1410. };
  1411. GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
  1412. // Google Test doesn't guarantee the order of tests. The following two
  1413. // tests are designed to work regardless of their order.
  1414. // Modifies the Google Test flags in the test body.
  1415. TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
  1416. // Verifies that the Google Test flags in the body of the previous test were
  1417. // restored to their original values.
  1418. TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
  1419. // Sets an environment variable with the given name to the given
  1420. // value. If the value argument is "", unsets the environment
  1421. // variable. The caller must ensure that both arguments are not NULL.
  1422. static void SetEnv(const char* name, const char* value) {
  1423. #ifdef GTEST_OS_WINDOWS_MOBILE
  1424. // Environment variables are not supported on Windows CE.
  1425. return;
  1426. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  1427. // C++Builder's putenv only stores a pointer to its parameter; we have to
  1428. // ensure that the string remains valid as long as it might be needed.
  1429. // We use an std::map to do so.
  1430. static std::map<std::string, std::string*> added_env;
  1431. // Because putenv stores a pointer to the string buffer, we can't delete the
  1432. // previous string (if present) until after it's replaced.
  1433. std::string* prev_env = NULL;
  1434. if (added_env.find(name) != added_env.end()) {
  1435. prev_env = added_env[name];
  1436. }
  1437. added_env[name] =
  1438. new std::string((Message() << name << "=" << value).GetString());
  1439. // The standard signature of putenv accepts a 'char*' argument. Other
  1440. // implementations, like C++Builder's, accept a 'const char*'.
  1441. // We cast away the 'const' since that would work for both variants.
  1442. putenv(const_cast<char*>(added_env[name]->c_str()));
  1443. delete prev_env;
  1444. #elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper.
  1445. _putenv((Message() << name << "=" << value).GetString().c_str());
  1446. #else
  1447. if (*value == '\0') {
  1448. unsetenv(name);
  1449. } else {
  1450. setenv(name, value, 1);
  1451. }
  1452. #endif // GTEST_OS_WINDOWS_MOBILE
  1453. }
  1454. #ifndef GTEST_OS_WINDOWS_MOBILE
  1455. // Environment variables are not supported on Windows CE.
  1456. using testing::internal::Int32FromGTestEnv;
  1457. // Tests Int32FromGTestEnv().
  1458. // Tests that Int32FromGTestEnv() returns the default value when the
  1459. // environment variable is not set.
  1460. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
  1461. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
  1462. EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
  1463. }
  1464. #if !defined(GTEST_GET_INT32_FROM_ENV_)
  1465. // Tests that Int32FromGTestEnv() returns the default value when the
  1466. // environment variable overflows as an Int32.
  1467. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
  1468. printf("(expecting 2 warnings)\n");
  1469. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
  1470. EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
  1471. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
  1472. EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
  1473. }
  1474. // Tests that Int32FromGTestEnv() returns the default value when the
  1475. // environment variable does not represent a valid decimal integer.
  1476. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
  1477. printf("(expecting 2 warnings)\n");
  1478. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
  1479. EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
  1480. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
  1481. EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
  1482. }
  1483. #endif // !defined(GTEST_GET_INT32_FROM_ENV_)
  1484. // Tests that Int32FromGTestEnv() parses and returns the value of the
  1485. // environment variable when it represents a valid decimal integer in
  1486. // the range of an Int32.
  1487. TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
  1488. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
  1489. EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
  1490. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
  1491. EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
  1492. }
  1493. #endif // !GTEST_OS_WINDOWS_MOBILE
  1494. // Tests ParseFlag().
  1495. // Tests that ParseInt32Flag() returns false and doesn't change the
  1496. // output value when the flag has wrong format
  1497. TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
  1498. int32_t value = 123;
  1499. EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
  1500. EXPECT_EQ(123, value);
  1501. EXPECT_FALSE(ParseFlag("a=100", "a", &value));
  1502. EXPECT_EQ(123, value);
  1503. }
  1504. // Tests that ParseFlag() returns false and doesn't change the
  1505. // output value when the flag overflows as an Int32.
  1506. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
  1507. printf("(expecting 2 warnings)\n");
  1508. int32_t value = 123;
  1509. EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
  1510. EXPECT_EQ(123, value);
  1511. EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
  1512. EXPECT_EQ(123, value);
  1513. }
  1514. // Tests that ParseInt32Flag() returns false and doesn't change the
  1515. // output value when the flag does not represent a valid decimal
  1516. // integer.
  1517. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
  1518. printf("(expecting 2 warnings)\n");
  1519. int32_t value = 123;
  1520. EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
  1521. EXPECT_EQ(123, value);
  1522. EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
  1523. EXPECT_EQ(123, value);
  1524. }
  1525. // Tests that ParseInt32Flag() parses the value of the flag and
  1526. // returns true when the flag represents a valid decimal integer in
  1527. // the range of an Int32.
  1528. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
  1529. int32_t value = 123;
  1530. EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
  1531. EXPECT_EQ(456, value);
  1532. EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
  1533. EXPECT_EQ(-789, value);
  1534. }
  1535. // Tests that Int32FromEnvOrDie() parses the value of the var or
  1536. // returns the correct default.
  1537. // Environment variables are not supported on Windows CE.
  1538. #ifndef GTEST_OS_WINDOWS_MOBILE
  1539. TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
  1540. EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1541. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
  1542. EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1543. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
  1544. EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
  1545. }
  1546. #endif // !GTEST_OS_WINDOWS_MOBILE
  1547. // Tests that Int32FromEnvOrDie() aborts with an error message
  1548. // if the variable is not an int32_t.
  1549. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
  1550. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
  1551. EXPECT_DEATH_IF_SUPPORTED(
  1552. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
  1553. }
  1554. // Tests that Int32FromEnvOrDie() aborts with an error message
  1555. // if the variable cannot be represented by an int32_t.
  1556. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
  1557. SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
  1558. EXPECT_DEATH_IF_SUPPORTED(
  1559. Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
  1560. }
  1561. // Tests that ShouldRunTestOnShard() selects all tests
  1562. // where there is 1 shard.
  1563. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
  1564. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
  1565. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
  1566. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
  1567. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
  1568. EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
  1569. }
  1570. class ShouldShardTest : public testing::Test {
  1571. protected:
  1572. void SetUp() override {
  1573. index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
  1574. total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
  1575. }
  1576. void TearDown() override {
  1577. SetEnv(index_var_, "");
  1578. SetEnv(total_var_, "");
  1579. }
  1580. const char* index_var_;
  1581. const char* total_var_;
  1582. };
  1583. // Tests that sharding is disabled if neither of the environment variables
  1584. // are set.
  1585. TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
  1586. SetEnv(index_var_, "");
  1587. SetEnv(total_var_, "");
  1588. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1589. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1590. }
  1591. // Tests that sharding is not enabled if total_shards == 1.
  1592. TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
  1593. SetEnv(index_var_, "0");
  1594. SetEnv(total_var_, "1");
  1595. EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
  1596. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1597. }
  1598. // Tests that sharding is enabled if total_shards > 1 and
  1599. // we are not in a death test subprocess.
  1600. // Environment variables are not supported on Windows CE.
  1601. #ifndef GTEST_OS_WINDOWS_MOBILE
  1602. TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
  1603. SetEnv(index_var_, "4");
  1604. SetEnv(total_var_, "22");
  1605. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1606. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1607. SetEnv(index_var_, "8");
  1608. SetEnv(total_var_, "9");
  1609. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1610. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1611. SetEnv(index_var_, "0");
  1612. SetEnv(total_var_, "9");
  1613. EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
  1614. EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
  1615. }
  1616. #endif // !GTEST_OS_WINDOWS_MOBILE
  1617. // Tests that we exit in error if the sharding values are not valid.
  1618. typedef ShouldShardTest ShouldShardDeathTest;
  1619. TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
  1620. SetEnv(index_var_, "4");
  1621. SetEnv(total_var_, "4");
  1622. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1623. SetEnv(index_var_, "4");
  1624. SetEnv(total_var_, "-2");
  1625. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1626. SetEnv(index_var_, "5");
  1627. SetEnv(total_var_, "");
  1628. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1629. SetEnv(index_var_, "");
  1630. SetEnv(total_var_, "5");
  1631. EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
  1632. }
  1633. // Tests that ShouldRunTestOnShard is a partition when 5
  1634. // shards are used.
  1635. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
  1636. // Choose an arbitrary number of tests and shards.
  1637. const int num_tests = 17;
  1638. const int num_shards = 5;
  1639. // Check partitioning: each test should be on exactly 1 shard.
  1640. for (int test_id = 0; test_id < num_tests; test_id++) {
  1641. int prev_selected_shard_index = -1;
  1642. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1643. if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
  1644. if (prev_selected_shard_index < 0) {
  1645. prev_selected_shard_index = shard_index;
  1646. } else {
  1647. ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
  1648. << shard_index << " are both selected to run test "
  1649. << test_id;
  1650. }
  1651. }
  1652. }
  1653. }
  1654. // Check balance: This is not required by the sharding protocol, but is a
  1655. // desirable property for performance.
  1656. for (int shard_index = 0; shard_index < num_shards; shard_index++) {
  1657. int num_tests_on_shard = 0;
  1658. for (int test_id = 0; test_id < num_tests; test_id++) {
  1659. num_tests_on_shard +=
  1660. ShouldRunTestOnShard(num_shards, shard_index, test_id);
  1661. }
  1662. EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
  1663. }
  1664. }
  1665. // For the same reason we are not explicitly testing everything in the
  1666. // Test class, there are no separate tests for the following classes
  1667. // (except for some trivial cases):
  1668. //
  1669. // TestSuite, UnitTest, UnitTestResultPrinter.
  1670. //
  1671. // Similarly, there are no separate tests for the following macros:
  1672. //
  1673. // TEST, TEST_F, RUN_ALL_TESTS
  1674. TEST(UnitTestTest, CanGetOriginalWorkingDir) {
  1675. ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
  1676. EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
  1677. }
  1678. TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
  1679. EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
  1680. EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
  1681. }
  1682. // When a property using a reserved key is supplied to this function, it
  1683. // tests that a non-fatal failure is added, a fatal failure is not added,
  1684. // and that the property is not recorded.
  1685. void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
  1686. const TestResult& test_result, const char* key) {
  1687. EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
  1688. ASSERT_EQ(0, test_result.test_property_count())
  1689. << "Property for key '" << key << "' recorded unexpectedly.";
  1690. }
  1691. void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
  1692. const char* key) {
  1693. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
  1694. ASSERT_TRUE(test_info != nullptr);
  1695. ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
  1696. key);
  1697. }
  1698. void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1699. const char* key) {
  1700. const testing::TestSuite* test_suite =
  1701. UnitTest::GetInstance()->current_test_suite();
  1702. ASSERT_TRUE(test_suite != nullptr);
  1703. ExpectNonFatalFailureRecordingPropertyWithReservedKey(
  1704. test_suite->ad_hoc_test_result(), key);
  1705. }
  1706. void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1707. const char* key) {
  1708. ExpectNonFatalFailureRecordingPropertyWithReservedKey(
  1709. UnitTest::GetInstance()->ad_hoc_test_result(), key);
  1710. }
  1711. // Tests that property recording functions in UnitTest outside of tests
  1712. // functions correctly. Creating a separate instance of UnitTest ensures it
  1713. // is in a state similar to the UnitTest's singleton's between tests.
  1714. class UnitTestRecordPropertyTest
  1715. : public testing::internal::UnitTestRecordPropertyTestHelper {
  1716. public:
  1717. static void SetUpTestSuite() {
  1718. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1719. "disabled");
  1720. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1721. "errors");
  1722. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1723. "failures");
  1724. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1725. "name");
  1726. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1727. "tests");
  1728. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
  1729. "time");
  1730. Test::RecordProperty("test_case_key_1", "1");
  1731. const testing::TestSuite* test_suite =
  1732. UnitTest::GetInstance()->current_test_suite();
  1733. ASSERT_TRUE(test_suite != nullptr);
  1734. ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
  1735. EXPECT_STREQ("test_case_key_1",
  1736. test_suite->ad_hoc_test_result().GetTestProperty(0).key());
  1737. EXPECT_STREQ("1",
  1738. test_suite->ad_hoc_test_result().GetTestProperty(0).value());
  1739. }
  1740. };
  1741. // Tests TestResult has the expected property when added.
  1742. TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
  1743. UnitTestRecordProperty("key_1", "1");
  1744. ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
  1745. EXPECT_STREQ("key_1",
  1746. unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  1747. EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
  1748. }
  1749. // Tests TestResult has multiple properties when added.
  1750. TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
  1751. UnitTestRecordProperty("key_1", "1");
  1752. UnitTestRecordProperty("key_2", "2");
  1753. ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
  1754. EXPECT_STREQ("key_1",
  1755. unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  1756. EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
  1757. EXPECT_STREQ("key_2",
  1758. unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
  1759. EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
  1760. }
  1761. // Tests TestResult::RecordProperty() overrides values for duplicate keys.
  1762. TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
  1763. UnitTestRecordProperty("key_1", "1");
  1764. UnitTestRecordProperty("key_2", "2");
  1765. UnitTestRecordProperty("key_1", "12");
  1766. UnitTestRecordProperty("key_2", "22");
  1767. ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
  1768. EXPECT_STREQ("key_1",
  1769. unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
  1770. EXPECT_STREQ("12",
  1771. unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
  1772. EXPECT_STREQ("key_2",
  1773. unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
  1774. EXPECT_STREQ("22",
  1775. unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
  1776. }
  1777. TEST_F(UnitTestRecordPropertyTest,
  1778. AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
  1779. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name");
  1780. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
  1781. "value_param");
  1782. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
  1783. "type_param");
  1784. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status");
  1785. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time");
  1786. ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
  1787. "classname");
  1788. }
  1789. TEST_F(UnitTestRecordPropertyTest,
  1790. AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
  1791. EXPECT_NONFATAL_FAILURE(
  1792. Test::RecordProperty("name", "1"),
  1793. "'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
  1794. " 'file', and 'line' are reserved");
  1795. }
  1796. class UnitTestRecordPropertyTestEnvironment : public Environment {
  1797. public:
  1798. void TearDown() override {
  1799. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1800. "tests");
  1801. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1802. "failures");
  1803. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1804. "disabled");
  1805. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1806. "errors");
  1807. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1808. "name");
  1809. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1810. "timestamp");
  1811. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1812. "time");
  1813. ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
  1814. "random_seed");
  1815. }
  1816. };
  1817. // This will test property recording outside of any test or test case.
  1818. GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static Environment* record_property_env =
  1819. AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
  1820. // This group of tests is for predicate assertions (ASSERT_PRED*, etc)
  1821. // of various arities. They do not attempt to be exhaustive. Rather,
  1822. // view them as smoke tests that can be easily reviewed and verified.
  1823. // A more complete set of tests for predicate assertions can be found
  1824. // in gtest_pred_impl_unittest.cc.
  1825. // First, some predicates and predicate-formatters needed by the tests.
  1826. // Returns true if and only if the argument is an even number.
  1827. bool IsEven(int n) { return (n % 2) == 0; }
  1828. // A functor that returns true if and only if the argument is an even number.
  1829. struct IsEvenFunctor {
  1830. bool operator()(int n) { return IsEven(n); }
  1831. };
  1832. // A predicate-formatter function that asserts the argument is an even
  1833. // number.
  1834. AssertionResult AssertIsEven(const char* expr, int n) {
  1835. if (IsEven(n)) {
  1836. return AssertionSuccess();
  1837. }
  1838. Message msg;
  1839. msg << expr << " evaluates to " << n << ", which is not even.";
  1840. return AssertionFailure(msg);
  1841. }
  1842. // A predicate function that returns AssertionResult for use in
  1843. // EXPECT/ASSERT_TRUE/FALSE.
  1844. AssertionResult ResultIsEven(int n) {
  1845. if (IsEven(n))
  1846. return AssertionSuccess() << n << " is even";
  1847. else
  1848. return AssertionFailure() << n << " is odd";
  1849. }
  1850. // A predicate function that returns AssertionResult but gives no
  1851. // explanation why it succeeds. Needed for testing that
  1852. // EXPECT/ASSERT_FALSE handles such functions correctly.
  1853. AssertionResult ResultIsEvenNoExplanation(int n) {
  1854. if (IsEven(n))
  1855. return AssertionSuccess();
  1856. else
  1857. return AssertionFailure() << n << " is odd";
  1858. }
  1859. // A predicate-formatter functor that asserts the argument is an even
  1860. // number.
  1861. struct AssertIsEvenFunctor {
  1862. AssertionResult operator()(const char* expr, int n) {
  1863. return AssertIsEven(expr, n);
  1864. }
  1865. };
  1866. // Returns true if and only if the sum of the arguments is an even number.
  1867. bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }
  1868. // A functor that returns true if and only if the sum of the arguments is an
  1869. // even number.
  1870. struct SumIsEven3Functor {
  1871. bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }
  1872. };
  1873. // A predicate-formatter function that asserts the sum of the
  1874. // arguments is an even number.
  1875. AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,
  1876. const char* e4, int n1, int n2, int n3,
  1877. int n4) {
  1878. const int sum = n1 + n2 + n3 + n4;
  1879. if (IsEven(sum)) {
  1880. return AssertionSuccess();
  1881. }
  1882. Message msg;
  1883. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + "
  1884. << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum
  1885. << ", which is not even.";
  1886. return AssertionFailure(msg);
  1887. }
  1888. // A predicate-formatter functor that asserts the sum of the arguments
  1889. // is an even number.
  1890. struct AssertSumIsEven5Functor {
  1891. AssertionResult operator()(const char* e1, const char* e2, const char* e3,
  1892. const char* e4, const char* e5, int n1, int n2,
  1893. int n3, int n4, int n5) {
  1894. const int sum = n1 + n2 + n3 + n4 + n5;
  1895. if (IsEven(sum)) {
  1896. return AssertionSuccess();
  1897. }
  1898. Message msg;
  1899. msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
  1900. << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + "
  1901. << n5 << ") evaluates to " << sum << ", which is not even.";
  1902. return AssertionFailure(msg);
  1903. }
  1904. };
  1905. // Tests unary predicate assertions.
  1906. // Tests unary predicate assertions that don't use a custom formatter.
  1907. TEST(Pred1Test, WithoutFormat) {
  1908. // Success cases.
  1909. EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
  1910. ASSERT_PRED1(IsEven, 4);
  1911. // Failure cases.
  1912. EXPECT_NONFATAL_FAILURE(
  1913. { // NOLINT
  1914. EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
  1915. },
  1916. "This failure is expected.");
  1917. EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false");
  1918. }
  1919. // Tests unary predicate assertions that use a custom formatter.
  1920. TEST(Pred1Test, WithFormat) {
  1921. // Success cases.
  1922. EXPECT_PRED_FORMAT1(AssertIsEven, 2);
  1923. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
  1924. << "This failure is UNEXPECTED!";
  1925. // Failure cases.
  1926. const int n = 5;
  1927. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
  1928. "n evaluates to 5, which is not even.");
  1929. EXPECT_FATAL_FAILURE(
  1930. { // NOLINT
  1931. ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
  1932. },
  1933. "This failure is expected.");
  1934. }
  1935. // Tests that unary predicate assertions evaluates their arguments
  1936. // exactly once.
  1937. TEST(Pred1Test, SingleEvaluationOnFailure) {
  1938. // A success case.
  1939. static int n = 0;
  1940. EXPECT_PRED1(IsEven, n++);
  1941. EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
  1942. // A failure case.
  1943. EXPECT_FATAL_FAILURE(
  1944. { // NOLINT
  1945. ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
  1946. << "This failure is expected.";
  1947. },
  1948. "This failure is expected.");
  1949. EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
  1950. }
  1951. // Tests predicate assertions whose arity is >= 2.
  1952. // Tests predicate assertions that don't use a custom formatter.
  1953. TEST(PredTest, WithoutFormat) {
  1954. // Success cases.
  1955. ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
  1956. EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
  1957. // Failure cases.
  1958. const int n1 = 1;
  1959. const int n2 = 2;
  1960. EXPECT_NONFATAL_FAILURE(
  1961. { // NOLINT
  1962. EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
  1963. },
  1964. "This failure is expected.");
  1965. EXPECT_FATAL_FAILURE(
  1966. { // NOLINT
  1967. ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
  1968. },
  1969. "evaluates to false");
  1970. }
  1971. // Tests predicate assertions that use a custom formatter.
  1972. TEST(PredTest, WithFormat) {
  1973. // Success cases.
  1974. ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)
  1975. << "This failure is UNEXPECTED!";
  1976. EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
  1977. // Failure cases.
  1978. const int n1 = 1;
  1979. const int n2 = 2;
  1980. const int n3 = 4;
  1981. const int n4 = 6;
  1982. EXPECT_NONFATAL_FAILURE(
  1983. { // NOLINT
  1984. EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
  1985. },
  1986. "evaluates to 13, which is not even.");
  1987. EXPECT_FATAL_FAILURE(
  1988. { // NOLINT
  1989. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
  1990. << "This failure is expected.";
  1991. },
  1992. "This failure is expected.");
  1993. }
  1994. // Tests that predicate assertions evaluates their arguments
  1995. // exactly once.
  1996. TEST(PredTest, SingleEvaluationOnFailure) {
  1997. // A success case.
  1998. int n1 = 0;
  1999. int n2 = 0;
  2000. EXPECT_PRED2(SumIsEven2, n1++, n2++);
  2001. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  2002. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  2003. // Another success case.
  2004. n1 = n2 = 0;
  2005. int n3 = 0;
  2006. int n4 = 0;
  2007. int n5 = 0;
  2008. ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)
  2009. << "This failure is UNEXPECTED!";
  2010. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  2011. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  2012. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  2013. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  2014. EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
  2015. // A failure case.
  2016. n1 = n2 = n3 = 0;
  2017. EXPECT_NONFATAL_FAILURE(
  2018. { // NOLINT
  2019. EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
  2020. << "This failure is expected.";
  2021. },
  2022. "This failure is expected.");
  2023. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  2024. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  2025. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  2026. // Another failure case.
  2027. n1 = n2 = n3 = n4 = 0;
  2028. EXPECT_NONFATAL_FAILURE(
  2029. { // NOLINT
  2030. EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
  2031. },
  2032. "evaluates to 1, which is not even.");
  2033. EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
  2034. EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
  2035. EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
  2036. EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
  2037. }
  2038. // Test predicate assertions for sets
  2039. TEST(PredTest, ExpectPredEvalFailure) {
  2040. std::set<int> set_a = {2, 1, 3, 4, 5};
  2041. std::set<int> set_b = {0, 4, 8};
  2042. const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };
  2043. EXPECT_NONFATAL_FAILURE(
  2044. EXPECT_PRED2(compare_sets, set_a, set_b),
  2045. "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
  2046. "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
  2047. }
  2048. // Some helper functions for testing using overloaded/template
  2049. // functions with ASSERT_PREDn and EXPECT_PREDn.
  2050. bool IsPositive(double x) { return x > 0; }
  2051. template <typename T>
  2052. bool IsNegative(T x) {
  2053. return x < 0;
  2054. }
  2055. template <typename T1, typename T2>
  2056. bool GreaterThan(T1 x1, T2 x2) {
  2057. return x1 > x2;
  2058. }
  2059. // Tests that overloaded functions can be used in *_PRED* as long as
  2060. // their types are explicitly specified.
  2061. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
  2062. // C++Builder requires C-style casts rather than static_cast.
  2063. EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
  2064. ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
  2065. }
  2066. // Tests that template functions can be used in *_PRED* as long as
  2067. // their types are explicitly specified.
  2068. TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
  2069. EXPECT_PRED1(IsNegative<int>, -5);
  2070. // Makes sure that we can handle templates with more than one
  2071. // parameter.
  2072. ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
  2073. }
  2074. // Some helper functions for testing using overloaded/template
  2075. // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
  2076. AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
  2077. return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
  2078. }
  2079. AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
  2080. return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
  2081. }
  2082. template <typename T>
  2083. AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
  2084. return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
  2085. }
  2086. template <typename T1, typename T2>
  2087. AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
  2088. const T1& x1, const T2& x2) {
  2089. return x1 == x2 ? AssertionSuccess()
  2090. : AssertionFailure(Message() << "Failure");
  2091. }
  2092. // Tests that overloaded functions can be used in *_PRED_FORMAT*
  2093. // without explicitly specifying their types.
  2094. TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
  2095. EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
  2096. ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
  2097. }
  2098. // Tests that template functions can be used in *_PRED_FORMAT* without
  2099. // explicitly specifying their types.
  2100. TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
  2101. EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
  2102. ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
  2103. }
  2104. // Tests string assertions.
  2105. // Tests ASSERT_STREQ with non-NULL arguments.
  2106. TEST(StringAssertionTest, ASSERT_STREQ) {
  2107. const char* const p1 = "good";
  2108. ASSERT_STREQ(p1, p1);
  2109. // Let p2 have the same content as p1, but be at a different address.
  2110. const char p2[] = "good";
  2111. ASSERT_STREQ(p1, p2);
  2112. EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\"");
  2113. }
  2114. // Tests ASSERT_STREQ with NULL arguments.
  2115. TEST(StringAssertionTest, ASSERT_STREQ_Null) {
  2116. ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
  2117. EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
  2118. }
  2119. // Tests ASSERT_STREQ with NULL arguments.
  2120. TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
  2121. EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
  2122. }
  2123. // Tests ASSERT_STRNE.
  2124. TEST(StringAssertionTest, ASSERT_STRNE) {
  2125. ASSERT_STRNE("hi", "Hi");
  2126. ASSERT_STRNE("Hi", nullptr);
  2127. ASSERT_STRNE(nullptr, "Hi");
  2128. ASSERT_STRNE("", nullptr);
  2129. ASSERT_STRNE(nullptr, "");
  2130. ASSERT_STRNE("", "Hi");
  2131. ASSERT_STRNE("Hi", "");
  2132. EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\"");
  2133. }
  2134. // Tests ASSERT_STRCASEEQ.
  2135. TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
  2136. ASSERT_STRCASEEQ("hi", "Hi");
  2137. ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
  2138. ASSERT_STRCASEEQ("", "");
  2139. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case");
  2140. }
  2141. // Tests ASSERT_STRCASENE.
  2142. TEST(StringAssertionTest, ASSERT_STRCASENE) {
  2143. ASSERT_STRCASENE("hi1", "Hi2");
  2144. ASSERT_STRCASENE("Hi", nullptr);
  2145. ASSERT_STRCASENE(nullptr, "Hi");
  2146. ASSERT_STRCASENE("", nullptr);
  2147. ASSERT_STRCASENE(nullptr, "");
  2148. ASSERT_STRCASENE("", "Hi");
  2149. ASSERT_STRCASENE("Hi", "");
  2150. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)");
  2151. }
  2152. // Tests *_STREQ on wide strings.
  2153. TEST(StringAssertionTest, STREQ_Wide) {
  2154. // NULL strings.
  2155. ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
  2156. // Empty strings.
  2157. ASSERT_STREQ(L"", L"");
  2158. // Non-null vs NULL.
  2159. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
  2160. // Equal strings.
  2161. EXPECT_STREQ(L"Hi", L"Hi");
  2162. // Unequal strings.
  2163. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc");
  2164. // Strings containing wide characters.
  2165. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc");
  2166. // The streaming variation.
  2167. EXPECT_NONFATAL_FAILURE(
  2168. { // NOLINT
  2169. EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
  2170. },
  2171. "Expected failure");
  2172. }
  2173. // Tests *_STRNE on wide strings.
  2174. TEST(StringAssertionTest, STRNE_Wide) {
  2175. // NULL strings.
  2176. EXPECT_NONFATAL_FAILURE(
  2177. { // NOLINT
  2178. EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
  2179. },
  2180. "");
  2181. // Empty strings.
  2182. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\"");
  2183. // Non-null vs NULL.
  2184. ASSERT_STRNE(L"non-null", nullptr);
  2185. // Equal strings.
  2186. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\"");
  2187. // Unequal strings.
  2188. EXPECT_STRNE(L"abc", L"Abc");
  2189. // Strings containing wide characters.
  2190. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc");
  2191. // The streaming variation.
  2192. ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
  2193. }
  2194. // Tests for ::testing::IsSubstring().
  2195. // Tests that IsSubstring() returns the correct result when the input
  2196. // argument type is const char*.
  2197. TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
  2198. EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
  2199. EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
  2200. EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
  2201. EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
  2202. EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
  2203. }
  2204. // Tests that IsSubstring() returns the correct result when the input
  2205. // argument type is const wchar_t*.
  2206. TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
  2207. EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
  2208. EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
  2209. EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
  2210. EXPECT_TRUE(
  2211. IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
  2212. EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
  2213. }
  2214. // Tests that IsSubstring() generates the correct message when the input
  2215. // argument type is const char*.
  2216. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
  2217. EXPECT_STREQ(
  2218. "Value of: needle_expr\n"
  2219. " Actual: \"needle\"\n"
  2220. "Expected: a substring of haystack_expr\n"
  2221. "Which is: \"haystack\"",
  2222. IsSubstring("needle_expr", "haystack_expr", "needle", "haystack")
  2223. .failure_message());
  2224. }
  2225. // Tests that IsSubstring returns the correct result when the input
  2226. // argument type is ::std::string.
  2227. TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
  2228. EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
  2229. EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
  2230. }
  2231. #if GTEST_HAS_STD_WSTRING
  2232. // Tests that IsSubstring returns the correct result when the input
  2233. // argument type is ::std::wstring.
  2234. TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
  2235. EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2236. EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2237. }
  2238. // Tests that IsSubstring() generates the correct message when the input
  2239. // argument type is ::std::wstring.
  2240. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
  2241. EXPECT_STREQ(
  2242. "Value of: needle_expr\n"
  2243. " Actual: L\"needle\"\n"
  2244. "Expected: a substring of haystack_expr\n"
  2245. "Which is: L\"haystack\"",
  2246. IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"),
  2247. L"haystack")
  2248. .failure_message());
  2249. }
  2250. #endif // GTEST_HAS_STD_WSTRING
  2251. // Tests for ::testing::IsNotSubstring().
  2252. // Tests that IsNotSubstring() returns the correct result when the input
  2253. // argument type is const char*.
  2254. TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
  2255. EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
  2256. EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
  2257. }
  2258. // Tests that IsNotSubstring() returns the correct result when the input
  2259. // argument type is const wchar_t*.
  2260. TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
  2261. EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
  2262. EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
  2263. }
  2264. // Tests that IsNotSubstring() generates the correct message when the input
  2265. // argument type is const wchar_t*.
  2266. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
  2267. EXPECT_STREQ(
  2268. "Value of: needle_expr\n"
  2269. " Actual: L\"needle\"\n"
  2270. "Expected: not a substring of haystack_expr\n"
  2271. "Which is: L\"two needles\"",
  2272. IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles")
  2273. .failure_message());
  2274. }
  2275. // Tests that IsNotSubstring returns the correct result when the input
  2276. // argument type is ::std::string.
  2277. TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
  2278. EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
  2279. EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
  2280. }
  2281. // Tests that IsNotSubstring() generates the correct message when the input
  2282. // argument type is ::std::string.
  2283. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
  2284. EXPECT_STREQ(
  2285. "Value of: needle_expr\n"
  2286. " Actual: \"needle\"\n"
  2287. "Expected: not a substring of haystack_expr\n"
  2288. "Which is: \"two needles\"",
  2289. IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
  2290. "two needles")
  2291. .failure_message());
  2292. }
  2293. #if GTEST_HAS_STD_WSTRING
  2294. // Tests that IsNotSubstring returns the correct result when the input
  2295. // argument type is ::std::wstring.
  2296. TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
  2297. EXPECT_FALSE(
  2298. IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
  2299. EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
  2300. }
  2301. #endif // GTEST_HAS_STD_WSTRING
  2302. // Tests floating-point assertions.
  2303. template <typename RawType>
  2304. class FloatingPointTest : public Test {
  2305. protected:
  2306. // Pre-calculated numbers to be used by the tests.
  2307. struct TestValues {
  2308. RawType close_to_positive_zero;
  2309. RawType close_to_negative_zero;
  2310. RawType further_from_negative_zero;
  2311. RawType close_to_one;
  2312. RawType further_from_one;
  2313. RawType infinity;
  2314. RawType close_to_infinity;
  2315. RawType further_from_infinity;
  2316. RawType nan1;
  2317. RawType nan2;
  2318. };
  2319. typedef typename testing::internal::FloatingPoint<RawType> Floating;
  2320. typedef typename Floating::Bits Bits;
  2321. void SetUp() override {
  2322. const uint32_t max_ulps = Floating::kMaxUlps;
  2323. // The bits that represent 0.0.
  2324. const Bits zero_bits = Floating(0).bits();
  2325. // Makes some numbers close to 0.0.
  2326. values_.close_to_positive_zero =
  2327. Floating::ReinterpretBits(zero_bits + max_ulps / 2);
  2328. values_.close_to_negative_zero =
  2329. -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);
  2330. values_.further_from_negative_zero =
  2331. -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);
  2332. // The bits that represent 1.0.
  2333. const Bits one_bits = Floating(1).bits();
  2334. // Makes some numbers close to 1.0.
  2335. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
  2336. values_.further_from_one =
  2337. Floating::ReinterpretBits(one_bits + max_ulps + 1);
  2338. // +infinity.
  2339. values_.infinity = Floating::Infinity();
  2340. // The bits that represent +infinity.
  2341. const Bits infinity_bits = Floating(values_.infinity).bits();
  2342. // Makes some numbers close to infinity.
  2343. values_.close_to_infinity =
  2344. Floating::ReinterpretBits(infinity_bits - max_ulps);
  2345. values_.further_from_infinity =
  2346. Floating::ReinterpretBits(infinity_bits - max_ulps - 1);
  2347. // Makes some NAN's. Sets the most significant bit of the fraction so that
  2348. // our NaN's are quiet; trying to process a signaling NaN would raise an
  2349. // exception if our environment enables floating point exceptions.
  2350. values_.nan1 = Floating::ReinterpretBits(
  2351. Floating::kExponentBitMask |
  2352. (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
  2353. values_.nan2 = Floating::ReinterpretBits(
  2354. Floating::kExponentBitMask |
  2355. (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
  2356. }
  2357. void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
  2358. static TestValues values_;
  2359. };
  2360. template <typename RawType>
  2361. typename FloatingPointTest<RawType>::TestValues
  2362. FloatingPointTest<RawType>::values_;
  2363. // Instantiates FloatingPointTest for testing *_FLOAT_EQ.
  2364. typedef FloatingPointTest<float> FloatTest;
  2365. // Tests that the size of Float::Bits matches the size of float.
  2366. TEST_F(FloatTest, Size) { TestSize(); }
  2367. // Tests comparing with +0 and -0.
  2368. TEST_F(FloatTest, Zeros) {
  2369. EXPECT_FLOAT_EQ(0.0, -0.0);
  2370. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0");
  2371. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5");
  2372. }
  2373. // Tests comparing numbers close to 0.
  2374. //
  2375. // This ensures that *_FLOAT_EQ handles the sign correctly and no
  2376. // overflow occurs when comparing numbers whose absolute value is very
  2377. // small.
  2378. TEST_F(FloatTest, AlmostZeros) {
  2379. // In C++Builder, names within local classes (such as used by
  2380. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2381. // scoping class. Use a static local alias as a workaround.
  2382. // We use the assignment syntax since some compilers, like Sun Studio,
  2383. // don't allow initializing references using construction syntax
  2384. // (parentheses).
  2385. static const FloatTest::TestValues& v = this->values_;
  2386. EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
  2387. EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
  2388. EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2389. EXPECT_FATAL_FAILURE(
  2390. { // NOLINT
  2391. ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);
  2392. },
  2393. "v.further_from_negative_zero");
  2394. }
  2395. // Tests comparing numbers close to each other.
  2396. TEST_F(FloatTest, SmallDiff) {
  2397. EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
  2398. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
  2399. "values_.further_from_one");
  2400. }
  2401. // Tests comparing numbers far apart.
  2402. TEST_F(FloatTest, LargeDiff) {
  2403. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0");
  2404. }
  2405. // Tests comparing with infinity.
  2406. //
  2407. // This ensures that no overflow occurs when comparing numbers whose
  2408. // absolute value is very large.
  2409. TEST_F(FloatTest, Infinity) {
  2410. EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
  2411. EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
  2412. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
  2413. "-values_.infinity");
  2414. // This is interesting as the representations of infinity and nan1
  2415. // are only 1 DLP apart.
  2416. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
  2417. "values_.nan1");
  2418. }
  2419. // Tests that comparing with NAN always returns false.
  2420. TEST_F(FloatTest, NaN) {
  2421. // In C++Builder, names within local classes (such as used by
  2422. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2423. // scoping class. Use a static local alias as a workaround.
  2424. // We use the assignment syntax since some compilers, like Sun Studio,
  2425. // don't allow initializing references using construction syntax
  2426. // (parentheses).
  2427. static const FloatTest::TestValues& v = this->values_;
  2428. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
  2429. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
  2430. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
  2431. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
  2432. }
  2433. // Tests that *_FLOAT_EQ are reflexive.
  2434. TEST_F(FloatTest, Reflexive) {
  2435. EXPECT_FLOAT_EQ(0.0, 0.0);
  2436. EXPECT_FLOAT_EQ(1.0, 1.0);
  2437. ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
  2438. }
  2439. // Tests that *_FLOAT_EQ are commutative.
  2440. TEST_F(FloatTest, Commutative) {
  2441. // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
  2442. EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
  2443. // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
  2444. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
  2445. "1.0");
  2446. }
  2447. // Tests EXPECT_NEAR.
  2448. TEST_F(FloatTest, EXPECT_NEAR) {
  2449. EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
  2450. EXPECT_NEAR(2.0f, 3.0f, 1.0f);
  2451. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
  2452. "The difference between 1.0f and 1.5f is 0.5, "
  2453. "which exceeds 0.25f");
  2454. }
  2455. // Tests ASSERT_NEAR.
  2456. TEST_F(FloatTest, ASSERT_NEAR) {
  2457. ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
  2458. ASSERT_NEAR(2.0f, 3.0f, 1.0f);
  2459. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
  2460. "The difference between 1.0f and 1.5f is 0.5, "
  2461. "which exceeds 0.25f");
  2462. }
  2463. // Tests the cases where FloatLE() should succeed.
  2464. TEST_F(FloatTest, FloatLESucceeds) {
  2465. EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
  2466. ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
  2467. // or when val1 is greater than, but almost equals to, val2.
  2468. EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
  2469. }
  2470. // Tests the cases where FloatLE() should fail.
  2471. TEST_F(FloatTest, FloatLEFails) {
  2472. // When val1 is greater than val2 by a large margin,
  2473. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
  2474. "(2.0f) <= (1.0f)");
  2475. // or by a small yet non-negligible margin,
  2476. EXPECT_NONFATAL_FAILURE(
  2477. { // NOLINT
  2478. EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
  2479. },
  2480. "(values_.further_from_one) <= (1.0f)");
  2481. EXPECT_NONFATAL_FAILURE(
  2482. { // NOLINT
  2483. EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
  2484. },
  2485. "(values_.nan1) <= (values_.infinity)");
  2486. EXPECT_NONFATAL_FAILURE(
  2487. { // NOLINT
  2488. EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
  2489. },
  2490. "(-values_.infinity) <= (values_.nan1)");
  2491. EXPECT_FATAL_FAILURE(
  2492. { // NOLINT
  2493. ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
  2494. },
  2495. "(values_.nan1) <= (values_.nan1)");
  2496. }
  2497. // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
  2498. typedef FloatingPointTest<double> DoubleTest;
  2499. // Tests that the size of Double::Bits matches the size of double.
  2500. TEST_F(DoubleTest, Size) { TestSize(); }
  2501. // Tests comparing with +0 and -0.
  2502. TEST_F(DoubleTest, Zeros) {
  2503. EXPECT_DOUBLE_EQ(0.0, -0.0);
  2504. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0");
  2505. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0");
  2506. }
  2507. // Tests comparing numbers close to 0.
  2508. //
  2509. // This ensures that *_DOUBLE_EQ handles the sign correctly and no
  2510. // overflow occurs when comparing numbers whose absolute value is very
  2511. // small.
  2512. TEST_F(DoubleTest, AlmostZeros) {
  2513. // In C++Builder, names within local classes (such as used by
  2514. // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
  2515. // scoping class. Use a static local alias as a workaround.
  2516. // We use the assignment syntax since some compilers, like Sun Studio,
  2517. // don't allow initializing references using construction syntax
  2518. // (parentheses).
  2519. static const DoubleTest::TestValues& v = this->values_;
  2520. EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
  2521. EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
  2522. EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
  2523. EXPECT_FATAL_FAILURE(
  2524. { // NOLINT
  2525. ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
  2526. v.further_from_negative_zero);
  2527. },
  2528. "v.further_from_negative_zero");
  2529. }
  2530. // Tests comparing numbers close to each other.
  2531. TEST_F(DoubleTest, SmallDiff) {
  2532. EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
  2533. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
  2534. "values_.further_from_one");
  2535. }
  2536. // Tests comparing numbers far apart.
  2537. TEST_F(DoubleTest, LargeDiff) {
  2538. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0");
  2539. }
  2540. // Tests comparing with infinity.
  2541. //
  2542. // This ensures that no overflow occurs when comparing numbers whose
  2543. // absolute value is very large.
  2544. TEST_F(DoubleTest, Infinity) {
  2545. EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
  2546. EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
  2547. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
  2548. "-values_.infinity");
  2549. // This is interesting as the representations of infinity_ and nan1_
  2550. // are only 1 DLP apart.
  2551. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
  2552. "values_.nan1");
  2553. }
  2554. // Tests that comparing with NAN always returns false.
  2555. TEST_F(DoubleTest, NaN) {
  2556. static const DoubleTest::TestValues& v = this->values_;
  2557. // Nokia's STLport crashes if we try to output infinity or NaN.
  2558. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
  2559. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
  2560. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
  2561. EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
  2562. }
  2563. // Tests that *_DOUBLE_EQ are reflexive.
  2564. TEST_F(DoubleTest, Reflexive) {
  2565. EXPECT_DOUBLE_EQ(0.0, 0.0);
  2566. EXPECT_DOUBLE_EQ(1.0, 1.0);
  2567. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
  2568. }
  2569. // Tests that *_DOUBLE_EQ are commutative.
  2570. TEST_F(DoubleTest, Commutative) {
  2571. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
  2572. EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
  2573. // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
  2574. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
  2575. "1.0");
  2576. }
  2577. // Tests EXPECT_NEAR.
  2578. TEST_F(DoubleTest, EXPECT_NEAR) {
  2579. EXPECT_NEAR(-1.0, -1.1, 0.2);
  2580. EXPECT_NEAR(2.0, 3.0, 1.0);
  2581. EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2582. "The difference between 1.0 and 1.5 is 0.5, "
  2583. "which exceeds 0.25");
  2584. // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
  2585. // slightly different failure reporting path.
  2586. EXPECT_NONFATAL_FAILURE(
  2587. EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
  2588. "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
  2589. "minimum distance between doubles for numbers of this magnitude which is "
  2590. "512");
  2591. }
  2592. // Tests ASSERT_NEAR.
  2593. TEST_F(DoubleTest, ASSERT_NEAR) {
  2594. ASSERT_NEAR(-1.0, -1.1, 0.2);
  2595. ASSERT_NEAR(2.0, 3.0, 1.0);
  2596. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
  2597. "The difference between 1.0 and 1.5 is 0.5, "
  2598. "which exceeds 0.25");
  2599. }
  2600. // Tests the cases where DoubleLE() should succeed.
  2601. TEST_F(DoubleTest, DoubleLESucceeds) {
  2602. EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
  2603. ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
  2604. // or when val1 is greater than, but almost equals to, val2.
  2605. EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
  2606. }
  2607. // Tests the cases where DoubleLE() should fail.
  2608. TEST_F(DoubleTest, DoubleLEFails) {
  2609. // When val1 is greater than val2 by a large margin,
  2610. EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
  2611. "(2.0) <= (1.0)");
  2612. // or by a small yet non-negligible margin,
  2613. EXPECT_NONFATAL_FAILURE(
  2614. { // NOLINT
  2615. EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
  2616. },
  2617. "(values_.further_from_one) <= (1.0)");
  2618. EXPECT_NONFATAL_FAILURE(
  2619. { // NOLINT
  2620. EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
  2621. },
  2622. "(values_.nan1) <= (values_.infinity)");
  2623. EXPECT_NONFATAL_FAILURE(
  2624. { // NOLINT
  2625. EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
  2626. },
  2627. " (-values_.infinity) <= (values_.nan1)");
  2628. EXPECT_FATAL_FAILURE(
  2629. { // NOLINT
  2630. ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
  2631. },
  2632. "(values_.nan1) <= (values_.nan1)");
  2633. }
  2634. // Verifies that a test or test case whose name starts with DISABLED_ is
  2635. // not run.
  2636. // A test whose name starts with DISABLED_.
  2637. // Should not run.
  2638. TEST(DisabledTest, DISABLED_TestShouldNotRun) {
  2639. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2640. }
  2641. // A test whose name does not start with DISABLED_.
  2642. // Should run.
  2643. TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
  2644. // A test case whose name starts with DISABLED_.
  2645. // Should not run.
  2646. TEST(DISABLED_TestSuite, TestShouldNotRun) {
  2647. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2648. }
  2649. // A test case and test whose names start with DISABLED_.
  2650. // Should not run.
  2651. TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
  2652. FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
  2653. }
  2654. // Check that when all tests in a test case are disabled, SetUpTestSuite() and
  2655. // TearDownTestSuite() are not called.
  2656. class DisabledTestsTest : public Test {
  2657. protected:
  2658. static void SetUpTestSuite() {
  2659. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2660. "SetUpTestSuite() should not be called.";
  2661. }
  2662. static void TearDownTestSuite() {
  2663. FAIL() << "Unexpected failure: All tests disabled in test case. "
  2664. "TearDownTestSuite() should not be called.";
  2665. }
  2666. };
  2667. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
  2668. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2669. }
  2670. TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
  2671. FAIL() << "Unexpected failure: Disabled test should not be run.";
  2672. }
  2673. // Tests that disabled typed tests aren't run.
  2674. template <typename T>
  2675. class TypedTest : public Test {};
  2676. typedef testing::Types<int, double> NumericTypes;
  2677. TYPED_TEST_SUITE(TypedTest, NumericTypes);
  2678. TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
  2679. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2680. }
  2681. template <typename T>
  2682. class DISABLED_TypedTest : public Test {};
  2683. TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
  2684. TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
  2685. FAIL() << "Unexpected failure: Disabled typed test should not run.";
  2686. }
  2687. // Tests that disabled type-parameterized tests aren't run.
  2688. template <typename T>
  2689. class TypedTestP : public Test {};
  2690. TYPED_TEST_SUITE_P(TypedTestP);
  2691. TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
  2692. FAIL() << "Unexpected failure: "
  2693. << "Disabled type-parameterized test should not run.";
  2694. }
  2695. REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
  2696. INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
  2697. template <typename T>
  2698. class DISABLED_TypedTestP : public Test {};
  2699. TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
  2700. TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
  2701. FAIL() << "Unexpected failure: "
  2702. << "Disabled type-parameterized test should not run.";
  2703. }
  2704. REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
  2705. INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
  2706. // Tests that assertion macros evaluate their arguments exactly once.
  2707. class SingleEvaluationTest : public Test {
  2708. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  2709. // This helper function is needed by the FailedASSERT_STREQ test
  2710. // below. It's public to work around C++Builder's bug with scoping local
  2711. // classes.
  2712. static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
  2713. // This helper function is needed by the FailedASSERT_NE test below. It's
  2714. // public to work around C++Builder's bug with scoping local classes.
  2715. static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }
  2716. protected:
  2717. SingleEvaluationTest() {
  2718. p1_ = s1_;
  2719. p2_ = s2_;
  2720. a_ = 0;
  2721. b_ = 0;
  2722. }
  2723. static const char* const s1_;
  2724. static const char* const s2_;
  2725. static const char* p1_;
  2726. static const char* p2_;
  2727. static int a_;
  2728. static int b_;
  2729. };
  2730. const char* const SingleEvaluationTest::s1_ = "01234";
  2731. const char* const SingleEvaluationTest::s2_ = "abcde";
  2732. const char* SingleEvaluationTest::p1_;
  2733. const char* SingleEvaluationTest::p2_;
  2734. int SingleEvaluationTest::a_;
  2735. int SingleEvaluationTest::b_;
  2736. // Tests that when ASSERT_STREQ fails, it evaluates its arguments
  2737. // exactly once.
  2738. TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
  2739. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
  2740. "p2_++");
  2741. EXPECT_EQ(s1_ + 1, p1_);
  2742. EXPECT_EQ(s2_ + 1, p2_);
  2743. }
  2744. // Tests that string assertion arguments are evaluated exactly once.
  2745. TEST_F(SingleEvaluationTest, ASSERT_STR) {
  2746. // successful EXPECT_STRNE
  2747. EXPECT_STRNE(p1_++, p2_++);
  2748. EXPECT_EQ(s1_ + 1, p1_);
  2749. EXPECT_EQ(s2_ + 1, p2_);
  2750. // failed EXPECT_STRCASEEQ
  2751. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case");
  2752. EXPECT_EQ(s1_ + 2, p1_);
  2753. EXPECT_EQ(s2_ + 2, p2_);
  2754. }
  2755. // Tests that when ASSERT_NE fails, it evaluates its arguments exactly
  2756. // once.
  2757. TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
  2758. EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
  2759. "(a_++) != (b_++)");
  2760. EXPECT_EQ(1, a_);
  2761. EXPECT_EQ(1, b_);
  2762. }
  2763. // Tests that assertion arguments are evaluated exactly once.
  2764. TEST_F(SingleEvaluationTest, OtherCases) {
  2765. // successful EXPECT_TRUE
  2766. EXPECT_TRUE(0 == a_++); // NOLINT
  2767. EXPECT_EQ(1, a_);
  2768. // failed EXPECT_TRUE
  2769. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
  2770. EXPECT_EQ(2, a_);
  2771. // successful EXPECT_GT
  2772. EXPECT_GT(a_++, b_++);
  2773. EXPECT_EQ(3, a_);
  2774. EXPECT_EQ(1, b_);
  2775. // failed EXPECT_LT
  2776. EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
  2777. EXPECT_EQ(4, a_);
  2778. EXPECT_EQ(2, b_);
  2779. // successful ASSERT_TRUE
  2780. ASSERT_TRUE(0 < a_++); // NOLINT
  2781. EXPECT_EQ(5, a_);
  2782. // successful ASSERT_GT
  2783. ASSERT_GT(a_++, b_++);
  2784. EXPECT_EQ(6, a_);
  2785. EXPECT_EQ(3, b_);
  2786. }
  2787. #if GTEST_HAS_EXCEPTIONS
  2788. #if GTEST_HAS_RTTI
  2789. #define ERROR_DESC "std::runtime_error"
  2790. #else // GTEST_HAS_RTTI
  2791. #define ERROR_DESC "an std::exception-derived error"
  2792. #endif // GTEST_HAS_RTTI
  2793. void ThrowAnInteger() { throw 1; }
  2794. void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }
  2795. // Tests that assertion arguments are evaluated exactly once.
  2796. TEST_F(SingleEvaluationTest, ExceptionTests) {
  2797. // successful EXPECT_THROW
  2798. EXPECT_THROW(
  2799. { // NOLINT
  2800. a_++;
  2801. ThrowAnInteger();
  2802. },
  2803. int);
  2804. EXPECT_EQ(1, a_);
  2805. // failed EXPECT_THROW, throws different
  2806. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
  2807. { // NOLINT
  2808. a_++;
  2809. ThrowAnInteger();
  2810. },
  2811. bool),
  2812. "throws a different type");
  2813. EXPECT_EQ(2, a_);
  2814. // failed EXPECT_THROW, throws runtime error
  2815. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
  2816. { // NOLINT
  2817. a_++;
  2818. ThrowRuntimeError("A description");
  2819. },
  2820. bool),
  2821. "throws " ERROR_DESC
  2822. " with description \"A description\"");
  2823. EXPECT_EQ(3, a_);
  2824. // failed EXPECT_THROW, throws nothing
  2825. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
  2826. EXPECT_EQ(4, a_);
  2827. // successful EXPECT_NO_THROW
  2828. EXPECT_NO_THROW(a_++);
  2829. EXPECT_EQ(5, a_);
  2830. // failed EXPECT_NO_THROW
  2831. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
  2832. a_++;
  2833. ThrowAnInteger();
  2834. }),
  2835. "it throws");
  2836. EXPECT_EQ(6, a_);
  2837. // successful EXPECT_ANY_THROW
  2838. EXPECT_ANY_THROW({ // NOLINT
  2839. a_++;
  2840. ThrowAnInteger();
  2841. });
  2842. EXPECT_EQ(7, a_);
  2843. // failed EXPECT_ANY_THROW
  2844. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
  2845. EXPECT_EQ(8, a_);
  2846. }
  2847. #endif // GTEST_HAS_EXCEPTIONS
  2848. // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
  2849. class NoFatalFailureTest : public Test {
  2850. protected:
  2851. void Succeeds() {}
  2852. void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; }
  2853. void Fails() { FAIL() << "some fatal failure"; }
  2854. void DoAssertNoFatalFailureOnFails() {
  2855. ASSERT_NO_FATAL_FAILURE(Fails());
  2856. ADD_FAILURE() << "should not reach here.";
  2857. }
  2858. void DoExpectNoFatalFailureOnFails() {
  2859. EXPECT_NO_FATAL_FAILURE(Fails());
  2860. ADD_FAILURE() << "other failure";
  2861. }
  2862. };
  2863. TEST_F(NoFatalFailureTest, NoFailure) {
  2864. EXPECT_NO_FATAL_FAILURE(Succeeds());
  2865. ASSERT_NO_FATAL_FAILURE(Succeeds());
  2866. }
  2867. TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
  2868. EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
  2869. "some non-fatal failure");
  2870. EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
  2871. "some non-fatal failure");
  2872. }
  2873. TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
  2874. TestPartResultArray gtest_failures;
  2875. {
  2876. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2877. DoAssertNoFatalFailureOnFails();
  2878. }
  2879. ASSERT_EQ(2, gtest_failures.size());
  2880. EXPECT_EQ(TestPartResult::kFatalFailure,
  2881. gtest_failures.GetTestPartResult(0).type());
  2882. EXPECT_EQ(TestPartResult::kFatalFailure,
  2883. gtest_failures.GetTestPartResult(1).type());
  2884. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2885. gtest_failures.GetTestPartResult(0).message());
  2886. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2887. gtest_failures.GetTestPartResult(1).message());
  2888. }
  2889. TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
  2890. TestPartResultArray gtest_failures;
  2891. {
  2892. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2893. DoExpectNoFatalFailureOnFails();
  2894. }
  2895. ASSERT_EQ(3, gtest_failures.size());
  2896. EXPECT_EQ(TestPartResult::kFatalFailure,
  2897. gtest_failures.GetTestPartResult(0).type());
  2898. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2899. gtest_failures.GetTestPartResult(1).type());
  2900. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2901. gtest_failures.GetTestPartResult(2).type());
  2902. EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
  2903. gtest_failures.GetTestPartResult(0).message());
  2904. EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
  2905. gtest_failures.GetTestPartResult(1).message());
  2906. EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
  2907. gtest_failures.GetTestPartResult(2).message());
  2908. }
  2909. TEST_F(NoFatalFailureTest, MessageIsStreamable) {
  2910. TestPartResultArray gtest_failures;
  2911. {
  2912. ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);
  2913. EXPECT_NO_FATAL_FAILURE([] { FAIL() << "foo"; }()) << "my message";
  2914. }
  2915. ASSERT_EQ(2, gtest_failures.size());
  2916. EXPECT_EQ(TestPartResult::kFatalFailure,
  2917. gtest_failures.GetTestPartResult(0).type());
  2918. EXPECT_EQ(TestPartResult::kNonFatalFailure,
  2919. gtest_failures.GetTestPartResult(1).type());
  2920. EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
  2921. gtest_failures.GetTestPartResult(0).message());
  2922. EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
  2923. gtest_failures.GetTestPartResult(1).message());
  2924. }
  2925. // Tests non-string assertions.
  2926. std::string EditsToString(const std::vector<EditType>& edits) {
  2927. std::string out;
  2928. for (size_t i = 0; i < edits.size(); ++i) {
  2929. static const char kEdits[] = " +-/";
  2930. out.append(1, kEdits[edits[i]]);
  2931. }
  2932. return out;
  2933. }
  2934. std::vector<size_t> CharsToIndices(const std::string& str) {
  2935. std::vector<size_t> out;
  2936. for (size_t i = 0; i < str.size(); ++i) {
  2937. out.push_back(static_cast<size_t>(str[i]));
  2938. }
  2939. return out;
  2940. }
  2941. std::vector<std::string> CharsToLines(const std::string& str) {
  2942. std::vector<std::string> out;
  2943. for (size_t i = 0; i < str.size(); ++i) {
  2944. out.push_back(str.substr(i, 1));
  2945. }
  2946. return out;
  2947. }
  2948. TEST(EditDistance, TestSuites) {
  2949. struct Case {
  2950. int line;
  2951. const char* left;
  2952. const char* right;
  2953. const char* expected_edits;
  2954. const char* expected_diff;
  2955. };
  2956. static const Case kCases[] = {
  2957. // No change.
  2958. {__LINE__, "A", "A", " ", ""},
  2959. {__LINE__, "ABCDE", "ABCDE", " ", ""},
  2960. // Simple adds.
  2961. {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
  2962. {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
  2963. // Simple removes.
  2964. {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
  2965. {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
  2966. // Simple replaces.
  2967. {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
  2968. {__LINE__, "ABCD", "abcd", "////",
  2969. "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
  2970. // Path finding.
  2971. {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
  2972. "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
  2973. {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
  2974. "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
  2975. {__LINE__, "ABCDE", "BCDCD", "- +/",
  2976. "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
  2977. {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
  2978. "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
  2979. "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
  2980. {}};
  2981. for (const Case* c = kCases; c->left; ++c) {
  2982. EXPECT_TRUE(c->expected_edits ==
  2983. EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
  2984. CharsToIndices(c->right))))
  2985. << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
  2986. << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
  2987. CharsToIndices(c->right)))
  2988. << ">";
  2989. EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
  2990. CharsToLines(c->right)))
  2991. << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
  2992. << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
  2993. << ">";
  2994. }
  2995. }
  2996. // Tests EqFailure(), used for implementing *EQ* assertions.
  2997. TEST(AssertionTest, EqFailure) {
  2998. const std::string foo_val("5"), bar_val("6");
  2999. const std::string msg1(
  3000. EqFailure("foo", "bar", foo_val, bar_val, false).failure_message());
  3001. EXPECT_STREQ(
  3002. "Expected equality of these values:\n"
  3003. " foo\n"
  3004. " Which is: 5\n"
  3005. " bar\n"
  3006. " Which is: 6",
  3007. msg1.c_str());
  3008. const std::string msg2(
  3009. EqFailure("foo", "6", foo_val, bar_val, false).failure_message());
  3010. EXPECT_STREQ(
  3011. "Expected equality of these values:\n"
  3012. " foo\n"
  3013. " Which is: 5\n"
  3014. " 6",
  3015. msg2.c_str());
  3016. const std::string msg3(
  3017. EqFailure("5", "bar", foo_val, bar_val, false).failure_message());
  3018. EXPECT_STREQ(
  3019. "Expected equality of these values:\n"
  3020. " 5\n"
  3021. " bar\n"
  3022. " Which is: 6",
  3023. msg3.c_str());
  3024. const std::string msg4(
  3025. EqFailure("5", "6", foo_val, bar_val, false).failure_message());
  3026. EXPECT_STREQ(
  3027. "Expected equality of these values:\n"
  3028. " 5\n"
  3029. " 6",
  3030. msg4.c_str());
  3031. const std::string msg5(
  3032. EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
  3033. .failure_message());
  3034. EXPECT_STREQ(
  3035. "Expected equality of these values:\n"
  3036. " foo\n"
  3037. " Which is: \"x\"\n"
  3038. " bar\n"
  3039. " Which is: \"y\"\n"
  3040. "Ignoring case",
  3041. msg5.c_str());
  3042. }
  3043. TEST(AssertionTest, EqFailureWithDiff) {
  3044. const std::string left(
  3045. "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
  3046. const std::string right(
  3047. "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
  3048. const std::string msg1(
  3049. EqFailure("left", "right", left, right, false).failure_message());
  3050. EXPECT_STREQ(
  3051. "Expected equality of these values:\n"
  3052. " left\n"
  3053. " Which is: "
  3054. "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
  3055. " right\n"
  3056. " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
  3057. "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
  3058. "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
  3059. msg1.c_str());
  3060. }
  3061. // Tests AppendUserMessage(), used for implementing the *EQ* macros.
  3062. TEST(AssertionTest, AppendUserMessage) {
  3063. const std::string foo("foo");
  3064. Message msg;
  3065. EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str());
  3066. msg << "bar";
  3067. EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str());
  3068. }
  3069. #ifdef __BORLANDC__
  3070. // Silences warnings: "Condition is always true", "Unreachable code"
  3071. #pragma option push -w-ccc -w-rch
  3072. #endif
  3073. // Tests ASSERT_TRUE.
  3074. TEST(AssertionTest, ASSERT_TRUE) {
  3075. ASSERT_TRUE(2 > 1); // NOLINT
  3076. EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1");
  3077. }
  3078. // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
  3079. TEST(AssertionTest, AssertTrueWithAssertionResult) {
  3080. ASSERT_TRUE(ResultIsEven(2));
  3081. #ifndef __BORLANDC__
  3082. // ICE's in C++Builder.
  3083. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
  3084. "Value of: ResultIsEven(3)\n"
  3085. " Actual: false (3 is odd)\n"
  3086. "Expected: true");
  3087. #endif
  3088. ASSERT_TRUE(ResultIsEvenNoExplanation(2));
  3089. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
  3090. "Value of: ResultIsEvenNoExplanation(3)\n"
  3091. " Actual: false (3 is odd)\n"
  3092. "Expected: true");
  3093. }
  3094. // Tests ASSERT_FALSE.
  3095. TEST(AssertionTest, ASSERT_FALSE) {
  3096. ASSERT_FALSE(2 < 1); // NOLINT
  3097. EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
  3098. "Value of: 2 > 1\n"
  3099. " Actual: true\n"
  3100. "Expected: false");
  3101. }
  3102. // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
  3103. TEST(AssertionTest, AssertFalseWithAssertionResult) {
  3104. ASSERT_FALSE(ResultIsEven(3));
  3105. #ifndef __BORLANDC__
  3106. // ICE's in C++Builder.
  3107. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
  3108. "Value of: ResultIsEven(2)\n"
  3109. " Actual: true (2 is even)\n"
  3110. "Expected: false");
  3111. #endif
  3112. ASSERT_FALSE(ResultIsEvenNoExplanation(3));
  3113. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
  3114. "Value of: ResultIsEvenNoExplanation(2)\n"
  3115. " Actual: true\n"
  3116. "Expected: false");
  3117. }
  3118. #ifdef __BORLANDC__
  3119. // Restores warnings after previous "#pragma option push" suppressed them
  3120. #pragma option pop
  3121. #endif
  3122. // Tests using ASSERT_EQ on double values. The purpose is to make
  3123. // sure that the specialization we did for integer and anonymous enums
  3124. // isn't used for double arguments.
  3125. TEST(ExpectTest, ASSERT_EQ_Double) {
  3126. // A success.
  3127. ASSERT_EQ(5.6, 5.6);
  3128. // A failure.
  3129. EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1");
  3130. }
  3131. // Tests ASSERT_EQ.
  3132. TEST(AssertionTest, ASSERT_EQ) {
  3133. ASSERT_EQ(5, 2 + 3);
  3134. // clang-format off
  3135. EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
  3136. "Expected equality of these values:\n"
  3137. " 5\n"
  3138. " 2*3\n"
  3139. " Which is: 6");
  3140. // clang-format on
  3141. }
  3142. // Tests ASSERT_EQ(NULL, pointer).
  3143. TEST(AssertionTest, ASSERT_EQ_NULL) {
  3144. // A success.
  3145. const char* p = nullptr;
  3146. ASSERT_EQ(nullptr, p);
  3147. // A failure.
  3148. static int n = 0;
  3149. EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
  3150. }
  3151. // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
  3152. // treated as a null pointer by the compiler, we need to make sure
  3153. // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
  3154. // ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
  3155. TEST(ExpectTest, ASSERT_EQ_0) {
  3156. int n = 0;
  3157. // A success.
  3158. ASSERT_EQ(0, n);
  3159. // A failure.
  3160. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6");
  3161. }
  3162. // Tests ASSERT_NE.
  3163. TEST(AssertionTest, ASSERT_NE) {
  3164. ASSERT_NE(6, 7);
  3165. EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
  3166. "Expected: ('a') != ('a'), "
  3167. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  3168. }
  3169. // Tests ASSERT_LE.
  3170. TEST(AssertionTest, ASSERT_LE) {
  3171. ASSERT_LE(2, 3);
  3172. ASSERT_LE(2, 2);
  3173. EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0");
  3174. }
  3175. // Tests ASSERT_LT.
  3176. TEST(AssertionTest, ASSERT_LT) {
  3177. ASSERT_LT(2, 3);
  3178. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2");
  3179. }
  3180. // Tests ASSERT_GE.
  3181. TEST(AssertionTest, ASSERT_GE) {
  3182. ASSERT_GE(2, 1);
  3183. ASSERT_GE(2, 2);
  3184. EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3");
  3185. }
  3186. // Tests ASSERT_GT.
  3187. TEST(AssertionTest, ASSERT_GT) {
  3188. ASSERT_GT(2, 1);
  3189. EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2");
  3190. }
  3191. #if GTEST_HAS_EXCEPTIONS
  3192. void ThrowNothing() {}
  3193. // Tests ASSERT_THROW.
  3194. TEST(AssertionTest, ASSERT_THROW) {
  3195. ASSERT_THROW(ThrowAnInteger(), int);
  3196. #ifndef __BORLANDC__
  3197. // ICE's in C++Builder 2007 and 2009.
  3198. EXPECT_FATAL_FAILURE(
  3199. ASSERT_THROW(ThrowAnInteger(), bool),
  3200. "Expected: ThrowAnInteger() throws an exception of type bool.\n"
  3201. " Actual: it throws a different type.");
  3202. EXPECT_FATAL_FAILURE(
  3203. ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
  3204. "Expected: ThrowRuntimeError(\"A description\") "
  3205. "throws an exception of type std::logic_error.\n "
  3206. "Actual: it throws " ERROR_DESC
  3207. " "
  3208. "with description \"A description\".");
  3209. #endif
  3210. EXPECT_FATAL_FAILURE(
  3211. ASSERT_THROW(ThrowNothing(), bool),
  3212. "Expected: ThrowNothing() throws an exception of type bool.\n"
  3213. " Actual: it throws nothing.");
  3214. }
  3215. // Tests ASSERT_NO_THROW.
  3216. TEST(AssertionTest, ASSERT_NO_THROW) {
  3217. ASSERT_NO_THROW(ThrowNothing());
  3218. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
  3219. "Expected: ThrowAnInteger() doesn't throw an exception."
  3220. "\n Actual: it throws.");
  3221. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
  3222. "Expected: ThrowRuntimeError(\"A description\") "
  3223. "doesn't throw an exception.\n "
  3224. "Actual: it throws " ERROR_DESC
  3225. " "
  3226. "with description \"A description\".");
  3227. }
  3228. // Tests ASSERT_ANY_THROW.
  3229. TEST(AssertionTest, ASSERT_ANY_THROW) {
  3230. ASSERT_ANY_THROW(ThrowAnInteger());
  3231. EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),
  3232. "Expected: ThrowNothing() throws an exception.\n"
  3233. " Actual: it doesn't.");
  3234. }
  3235. #endif // GTEST_HAS_EXCEPTIONS
  3236. // Makes sure we deal with the precedence of <<. This test should
  3237. // compile.
  3238. TEST(AssertionTest, AssertPrecedence) {
  3239. ASSERT_EQ(1 < 2, true);
  3240. bool false_value = false;
  3241. ASSERT_EQ(true && false_value, false);
  3242. }
  3243. // A subroutine used by the following test.
  3244. void TestEq1(int x) { ASSERT_EQ(1, x); }
  3245. // Tests calling a test subroutine that's not part of a fixture.
  3246. TEST(AssertionTest, NonFixtureSubroutine) {
  3247. EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2");
  3248. }
  3249. // An uncopyable class.
  3250. class Uncopyable {
  3251. public:
  3252. explicit Uncopyable(int a_value) : value_(a_value) {}
  3253. int value() const { return value_; }
  3254. bool operator==(const Uncopyable& rhs) const {
  3255. return value() == rhs.value();
  3256. }
  3257. private:
  3258. // This constructor deliberately has no implementation, as we don't
  3259. // want this class to be copyable.
  3260. Uncopyable(const Uncopyable&); // NOLINT
  3261. int value_;
  3262. };
  3263. ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
  3264. return os << value.value();
  3265. }
  3266. bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }
  3267. // A subroutine used by the following test.
  3268. void TestAssertNonPositive() {
  3269. Uncopyable y(-1);
  3270. ASSERT_PRED1(IsPositiveUncopyable, y);
  3271. }
  3272. // A subroutine used by the following test.
  3273. void TestAssertEqualsUncopyable() {
  3274. Uncopyable x(5);
  3275. Uncopyable y(-1);
  3276. ASSERT_EQ(x, y);
  3277. }
  3278. // Tests that uncopyable objects can be used in assertions.
  3279. TEST(AssertionTest, AssertWorksWithUncopyableObject) {
  3280. Uncopyable x(5);
  3281. ASSERT_PRED1(IsPositiveUncopyable, x);
  3282. ASSERT_EQ(x, x);
  3283. EXPECT_FATAL_FAILURE(
  3284. TestAssertNonPositive(),
  3285. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3286. EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
  3287. "Expected equality of these values:\n"
  3288. " x\n Which is: 5\n y\n Which is: -1");
  3289. }
  3290. // Tests that uncopyable objects can be used in expects.
  3291. TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
  3292. Uncopyable x(5);
  3293. EXPECT_PRED1(IsPositiveUncopyable, x);
  3294. Uncopyable y(-1);
  3295. EXPECT_NONFATAL_FAILURE(
  3296. EXPECT_PRED1(IsPositiveUncopyable, y),
  3297. "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
  3298. EXPECT_EQ(x, x);
  3299. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
  3300. "Expected equality of these values:\n"
  3301. " x\n Which is: 5\n y\n Which is: -1");
  3302. }
  3303. enum NamedEnum { kE1 = 0, kE2 = 1 };
  3304. TEST(AssertionTest, NamedEnum) {
  3305. EXPECT_EQ(kE1, kE1);
  3306. EXPECT_LT(kE1, kE2);
  3307. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
  3308. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
  3309. }
  3310. // Sun Studio and HP aCC2reject this code.
  3311. #if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
  3312. // Tests using assertions with anonymous enums.
  3313. enum {
  3314. kCaseA = -1,
  3315. #ifdef GTEST_OS_LINUX
  3316. // We want to test the case where the size of the anonymous enum is
  3317. // larger than sizeof(int), to make sure our implementation of the
  3318. // assertions doesn't truncate the enums. However, MSVC
  3319. // (incorrectly) doesn't allow an enum value to exceed the range of
  3320. // an int, so this has to be conditionally compiled.
  3321. //
  3322. // On Linux, kCaseB and kCaseA have the same value when truncated to
  3323. // int size. We want to test whether this will confuse the
  3324. // assertions.
  3325. kCaseB = testing::internal::kMaxBiggestInt,
  3326. #else
  3327. kCaseB = INT_MAX,
  3328. #endif // GTEST_OS_LINUX
  3329. kCaseC = 42
  3330. };
  3331. TEST(AssertionTest, AnonymousEnum) {
  3332. #ifdef GTEST_OS_LINUX
  3333. EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
  3334. #endif // GTEST_OS_LINUX
  3335. EXPECT_EQ(kCaseA, kCaseA);
  3336. EXPECT_NE(kCaseA, kCaseB);
  3337. EXPECT_LT(kCaseA, kCaseB);
  3338. EXPECT_LE(kCaseA, kCaseB);
  3339. EXPECT_GT(kCaseB, kCaseA);
  3340. EXPECT_GE(kCaseA, kCaseA);
  3341. EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)");
  3342. EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42");
  3343. ASSERT_EQ(kCaseA, kCaseA);
  3344. ASSERT_NE(kCaseA, kCaseB);
  3345. ASSERT_LT(kCaseA, kCaseB);
  3346. ASSERT_LE(kCaseA, kCaseB);
  3347. ASSERT_GT(kCaseB, kCaseA);
  3348. ASSERT_GE(kCaseA, kCaseA);
  3349. #ifndef __BORLANDC__
  3350. // ICE's in C++Builder.
  3351. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: ");
  3352. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42");
  3353. #endif
  3354. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1");
  3355. }
  3356. #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
  3357. #ifdef GTEST_OS_WINDOWS
  3358. static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
  3359. static HRESULT OkHRESULTSuccess() { return S_OK; }
  3360. static HRESULT FalseHRESULTSuccess() { return S_FALSE; }
  3361. // HRESULT assertion tests test both zero and non-zero
  3362. // success codes as well as failure message for each.
  3363. //
  3364. // Windows CE doesn't support message texts.
  3365. TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
  3366. EXPECT_HRESULT_SUCCEEDED(S_OK);
  3367. EXPECT_HRESULT_SUCCEEDED(S_FALSE);
  3368. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3369. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3370. " Actual: 0x8000FFFF");
  3371. }
  3372. TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
  3373. ASSERT_HRESULT_SUCCEEDED(S_OK);
  3374. ASSERT_HRESULT_SUCCEEDED(S_FALSE);
  3375. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
  3376. "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
  3377. " Actual: 0x8000FFFF");
  3378. }
  3379. TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
  3380. EXPECT_HRESULT_FAILED(E_UNEXPECTED);
  3381. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
  3382. "Expected: (OkHRESULTSuccess()) fails.\n"
  3383. " Actual: 0x0");
  3384. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3385. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3386. " Actual: 0x1");
  3387. }
  3388. TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
  3389. ASSERT_HRESULT_FAILED(E_UNEXPECTED);
  3390. #ifndef __BORLANDC__
  3391. // ICE's in C++Builder 2007 and 2009.
  3392. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
  3393. "Expected: (OkHRESULTSuccess()) fails.\n"
  3394. " Actual: 0x0");
  3395. #endif
  3396. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
  3397. "Expected: (FalseHRESULTSuccess()) fails.\n"
  3398. " Actual: 0x1");
  3399. }
  3400. // Tests that streaming to the HRESULT macros works.
  3401. TEST(HRESULTAssertionTest, Streaming) {
  3402. EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3403. ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
  3404. EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3405. ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
  3406. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)
  3407. << "expected failure",
  3408. "expected failure");
  3409. #ifndef __BORLANDC__
  3410. // ICE's in C++Builder 2007 and 2009.
  3411. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)
  3412. << "expected failure",
  3413. "expected failure");
  3414. #endif
  3415. EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
  3416. "expected failure");
  3417. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
  3418. "expected failure");
  3419. }
  3420. #endif // GTEST_OS_WINDOWS
  3421. // The following code intentionally tests a suboptimal syntax.
  3422. #ifdef __GNUC__
  3423. #pragma GCC diagnostic push
  3424. #pragma GCC diagnostic ignored "-Wdangling-else"
  3425. #pragma GCC diagnostic ignored "-Wempty-body"
  3426. #pragma GCC diagnostic ignored "-Wpragmas"
  3427. #endif
  3428. // Tests that the assertion macros behave like single statements.
  3429. TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
  3430. if (AlwaysFalse())
  3431. ASSERT_TRUE(false) << "This should never be executed; "
  3432. "It's a compilation test only.";
  3433. if (AlwaysTrue())
  3434. EXPECT_FALSE(false);
  3435. else
  3436. ; // NOLINT
  3437. if (AlwaysFalse()) ASSERT_LT(1, 3);
  3438. if (AlwaysFalse())
  3439. ; // NOLINT
  3440. else
  3441. EXPECT_GT(3, 2) << "";
  3442. }
  3443. #ifdef __GNUC__
  3444. #pragma GCC diagnostic pop
  3445. #endif
  3446. #if GTEST_HAS_EXCEPTIONS
  3447. // Tests that the compiler will not complain about unreachable code in the
  3448. // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
  3449. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
  3450. int n = 0;
  3451. EXPECT_THROW(throw 1, int);
  3452. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
  3453. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw n, const char*), "");
  3454. EXPECT_NO_THROW(n++);
  3455. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
  3456. EXPECT_ANY_THROW(throw 1);
  3457. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
  3458. }
  3459. TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
  3460. EXPECT_THROW(throw std::exception(), std::exception);
  3461. }
  3462. // The following code intentionally tests a suboptimal syntax.
  3463. #ifdef __GNUC__
  3464. #pragma GCC diagnostic push
  3465. #pragma GCC diagnostic ignored "-Wdangling-else"
  3466. #pragma GCC diagnostic ignored "-Wempty-body"
  3467. #pragma GCC diagnostic ignored "-Wpragmas"
  3468. #endif
  3469. TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
  3470. if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);
  3471. if (AlwaysTrue())
  3472. EXPECT_THROW(ThrowAnInteger(), int);
  3473. else
  3474. ; // NOLINT
  3475. if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());
  3476. if (AlwaysTrue())
  3477. EXPECT_NO_THROW(ThrowNothing());
  3478. else
  3479. ; // NOLINT
  3480. if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());
  3481. if (AlwaysTrue())
  3482. EXPECT_ANY_THROW(ThrowAnInteger());
  3483. else
  3484. ; // NOLINT
  3485. }
  3486. #ifdef __GNUC__
  3487. #pragma GCC diagnostic pop
  3488. #endif
  3489. #endif // GTEST_HAS_EXCEPTIONS
  3490. // The following code intentionally tests a suboptimal syntax.
  3491. #ifdef __GNUC__
  3492. #pragma GCC diagnostic push
  3493. #pragma GCC diagnostic ignored "-Wdangling-else"
  3494. #pragma GCC diagnostic ignored "-Wempty-body"
  3495. #pragma GCC diagnostic ignored "-Wpragmas"
  3496. #endif
  3497. TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
  3498. if (AlwaysFalse())
  3499. EXPECT_NO_FATAL_FAILURE(FAIL())
  3500. << "This should never be executed. " << "It's a compilation test only.";
  3501. else
  3502. ; // NOLINT
  3503. if (AlwaysFalse())
  3504. ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
  3505. else
  3506. ; // NOLINT
  3507. if (AlwaysTrue())
  3508. EXPECT_NO_FATAL_FAILURE(SUCCEED());
  3509. else
  3510. ; // NOLINT
  3511. if (AlwaysFalse())
  3512. ; // NOLINT
  3513. else
  3514. ASSERT_NO_FATAL_FAILURE(SUCCEED());
  3515. }
  3516. #ifdef __GNUC__
  3517. #pragma GCC diagnostic pop
  3518. #endif
  3519. // Tests that the assertion macros work well with switch statements.
  3520. TEST(AssertionSyntaxTest, WorksWithSwitch) {
  3521. switch (0) {
  3522. case 1:
  3523. break;
  3524. default:
  3525. ASSERT_TRUE(true);
  3526. }
  3527. switch (0)
  3528. case 0:
  3529. EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
  3530. // Binary assertions are implemented using a different code path
  3531. // than the Boolean assertions. Hence we test them separately.
  3532. switch (0) {
  3533. case 1:
  3534. default:
  3535. ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
  3536. }
  3537. switch (0)
  3538. case 0:
  3539. EXPECT_NE(1, 2);
  3540. }
  3541. #if GTEST_HAS_EXCEPTIONS
  3542. void ThrowAString() { throw "std::string"; }
  3543. // Test that the exception assertion macros compile and work with const
  3544. // type qualifier.
  3545. TEST(AssertionSyntaxTest, WorksWithConst) {
  3546. ASSERT_THROW(ThrowAString(), const char*);
  3547. EXPECT_THROW(ThrowAString(), const char*);
  3548. }
  3549. #endif // GTEST_HAS_EXCEPTIONS
  3550. } // namespace
  3551. namespace testing {
  3552. // Tests that Google Test tracks SUCCEED*.
  3553. TEST(SuccessfulAssertionTest, SUCCEED) {
  3554. SUCCEED();
  3555. SUCCEED() << "OK";
  3556. EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
  3557. }
  3558. // Tests that Google Test doesn't track successful EXPECT_*.
  3559. TEST(SuccessfulAssertionTest, EXPECT) {
  3560. EXPECT_TRUE(true);
  3561. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3562. }
  3563. // Tests that Google Test doesn't track successful EXPECT_STR*.
  3564. TEST(SuccessfulAssertionTest, EXPECT_STR) {
  3565. EXPECT_STREQ("", "");
  3566. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3567. }
  3568. // Tests that Google Test doesn't track successful ASSERT_*.
  3569. TEST(SuccessfulAssertionTest, ASSERT) {
  3570. ASSERT_TRUE(true);
  3571. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3572. }
  3573. // Tests that Google Test doesn't track successful ASSERT_STR*.
  3574. TEST(SuccessfulAssertionTest, ASSERT_STR) {
  3575. ASSERT_STREQ("", "");
  3576. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  3577. }
  3578. } // namespace testing
  3579. namespace {
  3580. // Tests the message streaming variation of assertions.
  3581. TEST(AssertionWithMessageTest, EXPECT) {
  3582. EXPECT_EQ(1, 1) << "This should succeed.";
  3583. EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
  3584. "Expected failure #1");
  3585. EXPECT_LE(1, 2) << "This should succeed.";
  3586. EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
  3587. "Expected failure #2.");
  3588. EXPECT_GE(1, 0) << "This should succeed.";
  3589. EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
  3590. "Expected failure #3.");
  3591. EXPECT_STREQ("1", "1") << "This should succeed.";
  3592. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
  3593. "Expected failure #4.");
  3594. EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
  3595. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
  3596. "Expected failure #5.");
  3597. EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
  3598. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
  3599. "Expected failure #6.");
  3600. EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
  3601. }
  3602. TEST(AssertionWithMessageTest, ASSERT) {
  3603. ASSERT_EQ(1, 1) << "This should succeed.";
  3604. ASSERT_NE(1, 2) << "This should succeed.";
  3605. ASSERT_LE(1, 2) << "This should succeed.";
  3606. ASSERT_LT(1, 2) << "This should succeed.";
  3607. ASSERT_GE(1, 0) << "This should succeed.";
  3608. EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
  3609. "Expected failure.");
  3610. }
  3611. TEST(AssertionWithMessageTest, ASSERT_STR) {
  3612. ASSERT_STREQ("1", "1") << "This should succeed.";
  3613. ASSERT_STRNE("1", "2") << "This should succeed.";
  3614. ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
  3615. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
  3616. "Expected failure.");
  3617. }
  3618. TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
  3619. ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
  3620. ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
  3621. EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
  3622. "Expect failure.");
  3623. }
  3624. // Tests using ASSERT_FALSE with a streamed message.
  3625. TEST(AssertionWithMessageTest, ASSERT_FALSE) {
  3626. ASSERT_FALSE(false) << "This shouldn't fail.";
  3627. EXPECT_FATAL_FAILURE(
  3628. { // NOLINT
  3629. ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
  3630. << " evaluates to " << true;
  3631. },
  3632. "Expected failure");
  3633. }
  3634. // Tests using FAIL with a streamed message.
  3635. TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); }
  3636. // Tests using SUCCEED with a streamed message.
  3637. TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; }
  3638. // Tests using ASSERT_TRUE with a streamed message.
  3639. TEST(AssertionWithMessageTest, ASSERT_TRUE) {
  3640. ASSERT_TRUE(true) << "This should succeed.";
  3641. ASSERT_TRUE(true) << true;
  3642. EXPECT_FATAL_FAILURE(
  3643. { // NOLINT
  3644. ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
  3645. << static_cast<char*>(nullptr);
  3646. },
  3647. "(null)(null)");
  3648. }
  3649. #ifdef GTEST_OS_WINDOWS
  3650. // Tests using wide strings in assertion messages.
  3651. TEST(AssertionWithMessageTest, WideStringMessage) {
  3652. EXPECT_NONFATAL_FAILURE(
  3653. { // NOLINT
  3654. EXPECT_TRUE(false) << L"This failure is expected.\x8119";
  3655. },
  3656. "This failure is expected.");
  3657. EXPECT_FATAL_FAILURE(
  3658. { // NOLINT
  3659. ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120";
  3660. },
  3661. "This failure is expected too.");
  3662. }
  3663. #endif // GTEST_OS_WINDOWS
  3664. // Tests EXPECT_TRUE.
  3665. TEST(ExpectTest, EXPECT_TRUE) {
  3666. EXPECT_TRUE(true) << "Intentional success";
  3667. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
  3668. "Intentional failure #1.");
  3669. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
  3670. "Intentional failure #2.");
  3671. EXPECT_TRUE(2 > 1); // NOLINT
  3672. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
  3673. "Value of: 2 < 1\n"
  3674. " Actual: false\n"
  3675. "Expected: true");
  3676. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3");
  3677. }
  3678. // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
  3679. TEST(ExpectTest, ExpectTrueWithAssertionResult) {
  3680. EXPECT_TRUE(ResultIsEven(2));
  3681. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
  3682. "Value of: ResultIsEven(3)\n"
  3683. " Actual: false (3 is odd)\n"
  3684. "Expected: true");
  3685. EXPECT_TRUE(ResultIsEvenNoExplanation(2));
  3686. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
  3687. "Value of: ResultIsEvenNoExplanation(3)\n"
  3688. " Actual: false (3 is odd)\n"
  3689. "Expected: true");
  3690. }
  3691. // Tests EXPECT_FALSE with a streamed message.
  3692. TEST(ExpectTest, EXPECT_FALSE) {
  3693. EXPECT_FALSE(2 < 1); // NOLINT
  3694. EXPECT_FALSE(false) << "Intentional success";
  3695. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
  3696. "Intentional failure #1.");
  3697. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
  3698. "Intentional failure #2.");
  3699. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
  3700. "Value of: 2 > 1\n"
  3701. " Actual: true\n"
  3702. "Expected: false");
  3703. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3");
  3704. }
  3705. // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
  3706. TEST(ExpectTest, ExpectFalseWithAssertionResult) {
  3707. EXPECT_FALSE(ResultIsEven(3));
  3708. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
  3709. "Value of: ResultIsEven(2)\n"
  3710. " Actual: true (2 is even)\n"
  3711. "Expected: false");
  3712. EXPECT_FALSE(ResultIsEvenNoExplanation(3));
  3713. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
  3714. "Value of: ResultIsEvenNoExplanation(2)\n"
  3715. " Actual: true\n"
  3716. "Expected: false");
  3717. }
  3718. #ifdef __BORLANDC__
  3719. // Restores warnings after previous "#pragma option push" suppressed them
  3720. #pragma option pop
  3721. #endif
  3722. // Tests EXPECT_EQ.
  3723. TEST(ExpectTest, EXPECT_EQ) {
  3724. EXPECT_EQ(5, 2 + 3);
  3725. // clang-format off
  3726. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
  3727. "Expected equality of these values:\n"
  3728. " 5\n"
  3729. " 2*3\n"
  3730. " Which is: 6");
  3731. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3");
  3732. // clang-format on
  3733. }
  3734. // Tests using EXPECT_EQ on double values. The purpose is to make
  3735. // sure that the specialization we did for integer and anonymous enums
  3736. // isn't used for double arguments.
  3737. TEST(ExpectTest, EXPECT_EQ_Double) {
  3738. // A success.
  3739. EXPECT_EQ(5.6, 5.6);
  3740. // A failure.
  3741. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1");
  3742. }
  3743. // Tests EXPECT_EQ(NULL, pointer).
  3744. TEST(ExpectTest, EXPECT_EQ_NULL) {
  3745. // A success.
  3746. const char* p = nullptr;
  3747. EXPECT_EQ(nullptr, p);
  3748. // A failure.
  3749. int n = 0;
  3750. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
  3751. }
  3752. // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
  3753. // treated as a null pointer by the compiler, we need to make sure
  3754. // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
  3755. // EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
  3756. TEST(ExpectTest, EXPECT_EQ_0) {
  3757. int n = 0;
  3758. // A success.
  3759. EXPECT_EQ(0, n);
  3760. // A failure.
  3761. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6");
  3762. }
  3763. // Tests EXPECT_NE.
  3764. TEST(ExpectTest, EXPECT_NE) {
  3765. EXPECT_NE(6, 7);
  3766. EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
  3767. "Expected: ('a') != ('a'), "
  3768. "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
  3769. EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2");
  3770. char* const p0 = nullptr;
  3771. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0");
  3772. // Only way to get the Nokia compiler to compile the cast
  3773. // is to have a separate void* variable first. Putting
  3774. // the two casts on the same line doesn't work, neither does
  3775. // a direct C-style to char*.
  3776. void* pv1 = (void*)0x1234; // NOLINT
  3777. char* const p1 = reinterpret_cast<char*>(pv1);
  3778. EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1");
  3779. }
  3780. // Tests EXPECT_LE.
  3781. TEST(ExpectTest, EXPECT_LE) {
  3782. EXPECT_LE(2, 3);
  3783. EXPECT_LE(2, 2);
  3784. EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
  3785. "Expected: (2) <= (0), actual: 2 vs 0");
  3786. EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)");
  3787. }
  3788. // Tests EXPECT_LT.
  3789. TEST(ExpectTest, EXPECT_LT) {
  3790. EXPECT_LT(2, 3);
  3791. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
  3792. "Expected: (2) < (2), actual: 2 vs 2");
  3793. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)");
  3794. }
  3795. // Tests EXPECT_GE.
  3796. TEST(ExpectTest, EXPECT_GE) {
  3797. EXPECT_GE(2, 1);
  3798. EXPECT_GE(2, 2);
  3799. EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
  3800. "Expected: (2) >= (3), actual: 2 vs 3");
  3801. EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)");
  3802. }
  3803. // Tests EXPECT_GT.
  3804. TEST(ExpectTest, EXPECT_GT) {
  3805. EXPECT_GT(2, 1);
  3806. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
  3807. "Expected: (2) > (2), actual: 2 vs 2");
  3808. EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)");
  3809. }
  3810. #if GTEST_HAS_EXCEPTIONS
  3811. // Tests EXPECT_THROW.
  3812. TEST(ExpectTest, EXPECT_THROW) {
  3813. EXPECT_THROW(ThrowAnInteger(), int);
  3814. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
  3815. "Expected: ThrowAnInteger() throws an exception of "
  3816. "type bool.\n Actual: it throws a different type.");
  3817. EXPECT_NONFATAL_FAILURE(
  3818. EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error),
  3819. "Expected: ThrowRuntimeError(\"A description\") "
  3820. "throws an exception of type std::logic_error.\n "
  3821. "Actual: it throws " ERROR_DESC
  3822. " "
  3823. "with description \"A description\".");
  3824. EXPECT_NONFATAL_FAILURE(
  3825. EXPECT_THROW(ThrowNothing(), bool),
  3826. "Expected: ThrowNothing() throws an exception of type bool.\n"
  3827. " Actual: it throws nothing.");
  3828. }
  3829. // Tests EXPECT_NO_THROW.
  3830. TEST(ExpectTest, EXPECT_NO_THROW) {
  3831. EXPECT_NO_THROW(ThrowNothing());
  3832. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
  3833. "Expected: ThrowAnInteger() doesn't throw an "
  3834. "exception.\n Actual: it throws.");
  3835. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
  3836. "Expected: ThrowRuntimeError(\"A description\") "
  3837. "doesn't throw an exception.\n "
  3838. "Actual: it throws " ERROR_DESC
  3839. " "
  3840. "with description \"A description\".");
  3841. }
  3842. // Tests EXPECT_ANY_THROW.
  3843. TEST(ExpectTest, EXPECT_ANY_THROW) {
  3844. EXPECT_ANY_THROW(ThrowAnInteger());
  3845. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()),
  3846. "Expected: ThrowNothing() throws an exception.\n"
  3847. " Actual: it doesn't.");
  3848. }
  3849. #endif // GTEST_HAS_EXCEPTIONS
  3850. // Make sure we deal with the precedence of <<.
  3851. TEST(ExpectTest, ExpectPrecedence) {
  3852. EXPECT_EQ(1 < 2, true);
  3853. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
  3854. " true && false\n Which is: false");
  3855. }
  3856. // Tests the StreamableToString() function.
  3857. // Tests using StreamableToString() on a scalar.
  3858. TEST(StreamableToStringTest, Scalar) {
  3859. EXPECT_STREQ("5", StreamableToString(5).c_str());
  3860. }
  3861. // Tests using StreamableToString() on a non-char pointer.
  3862. TEST(StreamableToStringTest, Pointer) {
  3863. int n = 0;
  3864. int* p = &n;
  3865. EXPECT_STRNE("(null)", StreamableToString(p).c_str());
  3866. }
  3867. // Tests using StreamableToString() on a NULL non-char pointer.
  3868. TEST(StreamableToStringTest, NullPointer) {
  3869. int* p = nullptr;
  3870. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3871. }
  3872. // Tests using StreamableToString() on a C string.
  3873. TEST(StreamableToStringTest, CString) {
  3874. EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
  3875. }
  3876. // Tests using StreamableToString() on a NULL C string.
  3877. TEST(StreamableToStringTest, NullCString) {
  3878. char* p = nullptr;
  3879. EXPECT_STREQ("(null)", StreamableToString(p).c_str());
  3880. }
  3881. // Tests using streamable values as assertion messages.
  3882. // Tests using std::string as an assertion message.
  3883. TEST(StreamableTest, string) {
  3884. static const std::string str(
  3885. "This failure message is a std::string, and is expected.");
  3886. EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());
  3887. }
  3888. // Tests that we can output strings containing embedded NULs.
  3889. // Limited to Linux because we can only do this with std::string's.
  3890. TEST(StreamableTest, stringWithEmbeddedNUL) {
  3891. static const char char_array_with_nul[] =
  3892. "Here's a NUL\0 and some more string";
  3893. static const std::string string_with_nul(
  3894. char_array_with_nul,
  3895. sizeof(char_array_with_nul) - 1); // drops the trailing NUL
  3896. EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
  3897. "Here's a NUL\\0 and some more string");
  3898. }
  3899. // Tests that we can output a NUL char.
  3900. TEST(StreamableTest, NULChar) {
  3901. EXPECT_FATAL_FAILURE(
  3902. { // NOLINT
  3903. FAIL() << "A NUL" << '\0' << " and some more string";
  3904. },
  3905. "A NUL\\0 and some more string");
  3906. }
  3907. // Tests using int as an assertion message.
  3908. TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); }
  3909. // Tests using NULL char pointer as an assertion message.
  3910. //
  3911. // In MSVC, streaming a NULL char * causes access violation. Google Test
  3912. // implemented a workaround (substituting "(null)" for NULL). This
  3913. // tests whether the workaround works.
  3914. TEST(StreamableTest, NullCharPtr) {
  3915. EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
  3916. }
  3917. // Tests that basic IO manipulators (endl, ends, and flush) can be
  3918. // streamed to testing::Message.
  3919. TEST(StreamableTest, BasicIoManip) {
  3920. EXPECT_FATAL_FAILURE(
  3921. { // NOLINT
  3922. FAIL() << "Line 1." << std::endl
  3923. << "A NUL char " << std::ends << std::flush << " in line 2.";
  3924. },
  3925. "Line 1.\nA NUL char \\0 in line 2.");
  3926. }
  3927. // Tests the macros that haven't been covered so far.
  3928. void AddFailureHelper(bool* aborted) {
  3929. *aborted = true;
  3930. ADD_FAILURE() << "Intentional failure.";
  3931. *aborted = false;
  3932. }
  3933. // Tests ADD_FAILURE.
  3934. TEST(MacroTest, ADD_FAILURE) {
  3935. bool aborted = true;
  3936. EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure.");
  3937. EXPECT_FALSE(aborted);
  3938. }
  3939. // Tests ADD_FAILURE_AT.
  3940. TEST(MacroTest, ADD_FAILURE_AT) {
  3941. // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
  3942. // the failure message contains the user-streamed part.
  3943. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
  3944. // Verifies that the user-streamed part is optional.
  3945. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
  3946. // Unfortunately, we cannot verify that the failure message contains
  3947. // the right file path and line number the same way, as
  3948. // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
  3949. // line number. Instead, we do that in googletest-output-test_.cc.
  3950. }
  3951. // Tests FAIL.
  3952. TEST(MacroTest, FAIL) {
  3953. EXPECT_FATAL_FAILURE(FAIL(), "Failed");
  3954. EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
  3955. "Intentional failure.");
  3956. }
  3957. // Tests GTEST_FAIL_AT.
  3958. TEST(MacroTest, GTEST_FAIL_AT) {
  3959. // Verifies that GTEST_FAIL_AT does generate a fatal failure and
  3960. // the failure message contains the user-streamed part.
  3961. EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
  3962. // Verifies that the user-streamed part is optional.
  3963. EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
  3964. // See the ADD_FAIL_AT test above to see how we test that the failure message
  3965. // contains the right filename and line number -- the same applies here.
  3966. }
  3967. // Tests SUCCEED
  3968. TEST(MacroTest, SUCCEED) {
  3969. SUCCEED();
  3970. SUCCEED() << "Explicit success.";
  3971. }
  3972. // Tests for EXPECT_EQ() and ASSERT_EQ().
  3973. //
  3974. // These tests fail *intentionally*, s.t. the failure messages can be
  3975. // generated and tested.
  3976. //
  3977. // We have different tests for different argument types.
  3978. // Tests using bool values in {EXPECT|ASSERT}_EQ.
  3979. TEST(EqAssertionTest, Bool) {
  3980. EXPECT_EQ(true, true);
  3981. EXPECT_FATAL_FAILURE(
  3982. {
  3983. bool false_value = false;
  3984. ASSERT_EQ(false_value, true);
  3985. },
  3986. " false_value\n Which is: false\n true");
  3987. }
  3988. // Tests using int values in {EXPECT|ASSERT}_EQ.
  3989. TEST(EqAssertionTest, Int) {
  3990. ASSERT_EQ(32, 32);
  3991. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33");
  3992. }
  3993. // Tests using time_t values in {EXPECT|ASSERT}_EQ.
  3994. TEST(EqAssertionTest, Time_T) {
  3995. EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));
  3996. EXPECT_FATAL_FAILURE(
  3997. ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234");
  3998. }
  3999. // Tests using char values in {EXPECT|ASSERT}_EQ.
  4000. TEST(EqAssertionTest, Char) {
  4001. ASSERT_EQ('z', 'z');
  4002. const char ch = 'b';
  4003. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'");
  4004. EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'");
  4005. }
  4006. // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
  4007. TEST(EqAssertionTest, WideChar) {
  4008. EXPECT_EQ(L'b', L'b');
  4009. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
  4010. "Expected equality of these values:\n"
  4011. " L'\0'\n"
  4012. " Which is: L'\0' (0, 0x0)\n"
  4013. " L'x'\n"
  4014. " Which is: L'x' (120, 0x78)");
  4015. static wchar_t wchar;
  4016. wchar = L'b';
  4017. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar");
  4018. wchar = 0x8119;
  4019. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
  4020. " wchar\n Which is: L'");
  4021. }
  4022. // Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
  4023. TEST(EqAssertionTest, StdString) {
  4024. // Compares a const char* to an std::string that has identical
  4025. // content.
  4026. ASSERT_EQ("Test", ::std::string("Test"));
  4027. // Compares two identical std::strings.
  4028. static const ::std::string str1("A * in the middle");
  4029. static const ::std::string str2(str1);
  4030. EXPECT_EQ(str1, str2);
  4031. // Compares a const char* to an std::string that has different
  4032. // content
  4033. EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\"");
  4034. // Compares an std::string to a char* that has different content.
  4035. char* const p1 = const_cast<char*>("foo");
  4036. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1");
  4037. // Compares two std::strings that have different contents, one of
  4038. // which having a NUL character in the middle. This should fail.
  4039. static ::std::string str3(str1);
  4040. str3.at(2) = '\0';
  4041. EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
  4042. " str3\n Which is: \"A \\0 in the middle\"");
  4043. }
  4044. #if GTEST_HAS_STD_WSTRING
  4045. // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
  4046. TEST(EqAssertionTest, StdWideString) {
  4047. // Compares two identical std::wstrings.
  4048. const ::std::wstring wstr1(L"A * in the middle");
  4049. const ::std::wstring wstr2(wstr1);
  4050. ASSERT_EQ(wstr1, wstr2);
  4051. // Compares an std::wstring to a const wchar_t* that has identical
  4052. // content.
  4053. const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'};
  4054. EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
  4055. // Compares an std::wstring to a const wchar_t* that has different
  4056. // content.
  4057. const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'};
  4058. EXPECT_NONFATAL_FAILURE(
  4059. { // NOLINT
  4060. EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
  4061. },
  4062. "kTestX8120");
  4063. // Compares two std::wstrings that have different contents, one of
  4064. // which having a NUL character in the middle.
  4065. ::std::wstring wstr3(wstr1);
  4066. wstr3.at(2) = L'\0';
  4067. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3");
  4068. // Compares a wchar_t* to an std::wstring that has different
  4069. // content.
  4070. EXPECT_FATAL_FAILURE(
  4071. { // NOLINT
  4072. ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
  4073. },
  4074. "");
  4075. }
  4076. #endif // GTEST_HAS_STD_WSTRING
  4077. // Tests using char pointers in {EXPECT|ASSERT}_EQ.
  4078. TEST(EqAssertionTest, CharPointer) {
  4079. char* const p0 = nullptr;
  4080. // Only way to get the Nokia compiler to compile the cast
  4081. // is to have a separate void* variable first. Putting
  4082. // the two casts on the same line doesn't work, neither does
  4083. // a direct C-style to char*.
  4084. void* pv1 = (void*)0x1234; // NOLINT
  4085. void* pv2 = (void*)0xABC0; // NOLINT
  4086. char* const p1 = reinterpret_cast<char*>(pv1);
  4087. char* const p2 = reinterpret_cast<char*>(pv2);
  4088. ASSERT_EQ(p1, p1);
  4089. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
  4090. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
  4091. EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
  4092. reinterpret_cast<char*>(0xABC0)),
  4093. "ABC0");
  4094. }
  4095. // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
  4096. TEST(EqAssertionTest, WideCharPointer) {
  4097. wchar_t* const p0 = nullptr;
  4098. // Only way to get the Nokia compiler to compile the cast
  4099. // is to have a separate void* variable first. Putting
  4100. // the two casts on the same line doesn't work, neither does
  4101. // a direct C-style to char*.
  4102. void* pv1 = (void*)0x1234; // NOLINT
  4103. void* pv2 = (void*)0xABC0; // NOLINT
  4104. wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
  4105. wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
  4106. EXPECT_EQ(p0, p0);
  4107. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:");
  4108. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:");
  4109. void* pv3 = (void*)0x1234; // NOLINT
  4110. void* pv4 = (void*)0xABC0; // NOLINT
  4111. const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
  4112. const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
  4113. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4");
  4114. }
  4115. // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
  4116. TEST(EqAssertionTest, OtherPointer) {
  4117. ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
  4118. EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
  4119. reinterpret_cast<const int*>(0x1234)),
  4120. "0x1234");
  4121. }
  4122. // A class that supports binary comparison operators but not streaming.
  4123. class UnprintableChar {
  4124. public:
  4125. explicit UnprintableChar(char ch) : char_(ch) {}
  4126. bool operator==(const UnprintableChar& rhs) const {
  4127. return char_ == rhs.char_;
  4128. }
  4129. bool operator!=(const UnprintableChar& rhs) const {
  4130. return char_ != rhs.char_;
  4131. }
  4132. bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }
  4133. bool operator<=(const UnprintableChar& rhs) const {
  4134. return char_ <= rhs.char_;
  4135. }
  4136. bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }
  4137. bool operator>=(const UnprintableChar& rhs) const {
  4138. return char_ >= rhs.char_;
  4139. }
  4140. private:
  4141. char char_;
  4142. };
  4143. // Tests that ASSERT_EQ() and friends don't require the arguments to
  4144. // be printable.
  4145. TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
  4146. const UnprintableChar x('x'), y('y');
  4147. ASSERT_EQ(x, x);
  4148. EXPECT_NE(x, y);
  4149. ASSERT_LT(x, y);
  4150. EXPECT_LE(x, y);
  4151. ASSERT_GT(y, x);
  4152. EXPECT_GE(x, x);
  4153. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
  4154. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
  4155. EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
  4156. EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
  4157. EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
  4158. // Code tested by EXPECT_FATAL_FAILURE cannot reference local
  4159. // variables, so we have to write UnprintableChar('x') instead of x.
  4160. #ifndef __BORLANDC__
  4161. // ICE's in C++Builder.
  4162. EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
  4163. "1-byte object <78>");
  4164. EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
  4165. "1-byte object <78>");
  4166. #endif
  4167. EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
  4168. "1-byte object <79>");
  4169. EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
  4170. "1-byte object <78>");
  4171. EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
  4172. "1-byte object <79>");
  4173. }
  4174. // Tests the FRIEND_TEST macro.
  4175. // This class has a private member we want to test. We will test it
  4176. // both in a TEST and in a TEST_F.
  4177. class Foo {
  4178. public:
  4179. Foo() = default;
  4180. private:
  4181. int Bar() const { return 1; }
  4182. // Declares the friend tests that can access the private member
  4183. // Bar().
  4184. FRIEND_TEST(FRIEND_TEST_Test, TEST);
  4185. FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
  4186. };
  4187. // Tests that the FRIEND_TEST declaration allows a TEST to access a
  4188. // class's private members. This should compile.
  4189. TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
  4190. // The fixture needed to test using FRIEND_TEST with TEST_F.
  4191. class FRIEND_TEST_Test2 : public Test {
  4192. protected:
  4193. Foo foo;
  4194. };
  4195. // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
  4196. // class's private members. This should compile.
  4197. TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
  4198. // Tests the life cycle of Test objects.
  4199. // The test fixture for testing the life cycle of Test objects.
  4200. //
  4201. // This class counts the number of live test objects that uses this
  4202. // fixture.
  4203. class TestLifeCycleTest : public Test {
  4204. protected:
  4205. // Constructor. Increments the number of test objects that uses
  4206. // this fixture.
  4207. TestLifeCycleTest() { count_++; }
  4208. // Destructor. Decrements the number of test objects that uses this
  4209. // fixture.
  4210. ~TestLifeCycleTest() override { count_--; }
  4211. // Returns the number of live test objects that uses this fixture.
  4212. int count() const { return count_; }
  4213. private:
  4214. static int count_;
  4215. };
  4216. int TestLifeCycleTest::count_ = 0;
  4217. // Tests the life cycle of test objects.
  4218. TEST_F(TestLifeCycleTest, Test1) {
  4219. // There should be only one test object in this test case that's
  4220. // currently alive.
  4221. ASSERT_EQ(1, count());
  4222. }
  4223. // Tests the life cycle of test objects.
  4224. TEST_F(TestLifeCycleTest, Test2) {
  4225. // After Test1 is done and Test2 is started, there should still be
  4226. // only one live test object, as the object for Test1 should've been
  4227. // deleted.
  4228. ASSERT_EQ(1, count());
  4229. }
  4230. } // namespace
  4231. // Tests that the copy constructor works when it is NOT optimized away by
  4232. // the compiler.
  4233. TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
  4234. // Checks that the copy constructor doesn't try to dereference NULL pointers
  4235. // in the source object.
  4236. AssertionResult r1 = AssertionSuccess();
  4237. AssertionResult r2 = r1;
  4238. // The following line is added to prevent the compiler from optimizing
  4239. // away the constructor call.
  4240. r1 << "abc";
  4241. AssertionResult r3 = r1;
  4242. EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
  4243. EXPECT_STREQ("abc", r1.message());
  4244. }
  4245. // Tests that AssertionSuccess and AssertionFailure construct
  4246. // AssertionResult objects as expected.
  4247. TEST(AssertionResultTest, ConstructionWorks) {
  4248. AssertionResult r1 = AssertionSuccess();
  4249. EXPECT_TRUE(r1);
  4250. EXPECT_STREQ("", r1.message());
  4251. AssertionResult r2 = AssertionSuccess() << "abc";
  4252. EXPECT_TRUE(r2);
  4253. EXPECT_STREQ("abc", r2.message());
  4254. AssertionResult r3 = AssertionFailure();
  4255. EXPECT_FALSE(r3);
  4256. EXPECT_STREQ("", r3.message());
  4257. AssertionResult r4 = AssertionFailure() << "def";
  4258. EXPECT_FALSE(r4);
  4259. EXPECT_STREQ("def", r4.message());
  4260. AssertionResult r5 = AssertionFailure(Message() << "ghi");
  4261. EXPECT_FALSE(r5);
  4262. EXPECT_STREQ("ghi", r5.message());
  4263. }
  4264. // Tests that the negation flips the predicate result but keeps the message.
  4265. TEST(AssertionResultTest, NegationWorks) {
  4266. AssertionResult r1 = AssertionSuccess() << "abc";
  4267. EXPECT_FALSE(!r1);
  4268. EXPECT_STREQ("abc", (!r1).message());
  4269. AssertionResult r2 = AssertionFailure() << "def";
  4270. EXPECT_TRUE(!r2);
  4271. EXPECT_STREQ("def", (!r2).message());
  4272. }
  4273. TEST(AssertionResultTest, StreamingWorks) {
  4274. AssertionResult r = AssertionSuccess();
  4275. r << "abc" << 'd' << 0 << true;
  4276. EXPECT_STREQ("abcd0true", r.message());
  4277. }
  4278. TEST(AssertionResultTest, CanStreamOstreamManipulators) {
  4279. AssertionResult r = AssertionSuccess();
  4280. r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
  4281. EXPECT_STREQ("Data\n\\0Will be visible", r.message());
  4282. }
  4283. // The next test uses explicit conversion operators
  4284. TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
  4285. struct ExplicitlyConvertibleToBool {
  4286. explicit operator bool() const { return value; }
  4287. bool value;
  4288. };
  4289. ExplicitlyConvertibleToBool v1 = {false};
  4290. ExplicitlyConvertibleToBool v2 = {true};
  4291. EXPECT_FALSE(v1);
  4292. EXPECT_TRUE(v2);
  4293. }
  4294. struct ConvertibleToAssertionResult {
  4295. operator AssertionResult() const { return AssertionResult(true); }
  4296. };
  4297. TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
  4298. ConvertibleToAssertionResult obj;
  4299. EXPECT_TRUE(obj);
  4300. }
  4301. // Tests streaming a user type whose definition and operator << are
  4302. // both in the global namespace.
  4303. class Base {
  4304. public:
  4305. explicit Base(int an_x) : x_(an_x) {}
  4306. int x() const { return x_; }
  4307. private:
  4308. int x_;
  4309. };
  4310. std::ostream& operator<<(std::ostream& os, const Base& val) {
  4311. return os << val.x();
  4312. }
  4313. std::ostream& operator<<(std::ostream& os, const Base* pointer) {
  4314. return os << "(" << pointer->x() << ")";
  4315. }
  4316. TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
  4317. Message msg;
  4318. Base a(1);
  4319. msg << a << &a; // Uses ::operator<<.
  4320. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4321. }
  4322. // Tests streaming a user type whose definition and operator<< are
  4323. // both in an unnamed namespace.
  4324. namespace {
  4325. class MyTypeInUnnamedNameSpace : public Base {
  4326. public:
  4327. explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}
  4328. };
  4329. std::ostream& operator<<(std::ostream& os,
  4330. const MyTypeInUnnamedNameSpace& val) {
  4331. return os << val.x();
  4332. }
  4333. std::ostream& operator<<(std::ostream& os,
  4334. const MyTypeInUnnamedNameSpace* pointer) {
  4335. return os << "(" << pointer->x() << ")";
  4336. }
  4337. } // namespace
  4338. TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
  4339. Message msg;
  4340. MyTypeInUnnamedNameSpace a(1);
  4341. msg << a << &a; // Uses <unnamed_namespace>::operator<<.
  4342. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4343. }
  4344. // Tests streaming a user type whose definition and operator<< are
  4345. // both in a user namespace.
  4346. namespace namespace1 {
  4347. class MyTypeInNameSpace1 : public Base {
  4348. public:
  4349. explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}
  4350. };
  4351. std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {
  4352. return os << val.x();
  4353. }
  4354. std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {
  4355. return os << "(" << pointer->x() << ")";
  4356. }
  4357. } // namespace namespace1
  4358. TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
  4359. Message msg;
  4360. namespace1::MyTypeInNameSpace1 a(1);
  4361. msg << a << &a; // Uses namespace1::operator<<.
  4362. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4363. }
  4364. // Tests streaming a user type whose definition is in a user namespace
  4365. // but whose operator<< is in the global namespace.
  4366. namespace namespace2 {
  4367. class MyTypeInNameSpace2 : public ::Base {
  4368. public:
  4369. explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}
  4370. };
  4371. } // namespace namespace2
  4372. std::ostream& operator<<(std::ostream& os,
  4373. const namespace2::MyTypeInNameSpace2& val) {
  4374. return os << val.x();
  4375. }
  4376. std::ostream& operator<<(std::ostream& os,
  4377. const namespace2::MyTypeInNameSpace2* pointer) {
  4378. return os << "(" << pointer->x() << ")";
  4379. }
  4380. TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
  4381. Message msg;
  4382. namespace2::MyTypeInNameSpace2 a(1);
  4383. msg << a << &a; // Uses ::operator<<.
  4384. EXPECT_STREQ("1(1)", msg.GetString().c_str());
  4385. }
  4386. // Tests streaming NULL pointers to testing::Message.
  4387. TEST(MessageTest, NullPointers) {
  4388. Message msg;
  4389. char* const p1 = nullptr;
  4390. unsigned char* const p2 = nullptr;
  4391. int* p3 = nullptr;
  4392. double* p4 = nullptr;
  4393. bool* p5 = nullptr;
  4394. Message* p6 = nullptr;
  4395. msg << p1 << p2 << p3 << p4 << p5 << p6;
  4396. ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
  4397. }
  4398. // Tests streaming wide strings to testing::Message.
  4399. TEST(MessageTest, WideStrings) {
  4400. // Streams a NULL of type const wchar_t*.
  4401. const wchar_t* const_wstr = nullptr;
  4402. EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str());
  4403. // Streams a NULL of type wchar_t*.
  4404. wchar_t* wstr = nullptr;
  4405. EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str());
  4406. // Streams a non-NULL of type const wchar_t*.
  4407. const_wstr = L"abc\x8119";
  4408. EXPECT_STREQ("abc\xe8\x84\x99",
  4409. (Message() << const_wstr).GetString().c_str());
  4410. // Streams a non-NULL of type wchar_t*.
  4411. wstr = const_cast<wchar_t*>(const_wstr);
  4412. EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str());
  4413. }
  4414. // This line tests that we can define tests in the testing namespace.
  4415. namespace testing {
  4416. // Tests the TestInfo class.
  4417. class TestInfoTest : public Test {
  4418. protected:
  4419. static const TestInfo* GetTestInfo(const char* test_name) {
  4420. const TestSuite* const test_suite =
  4421. GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
  4422. for (int i = 0; i < test_suite->total_test_count(); ++i) {
  4423. const TestInfo* const test_info = test_suite->GetTestInfo(i);
  4424. if (strcmp(test_name, test_info->name()) == 0) return test_info;
  4425. }
  4426. return nullptr;
  4427. }
  4428. static const TestResult* GetTestResult(const TestInfo* test_info) {
  4429. return test_info->result();
  4430. }
  4431. };
  4432. // Tests TestInfo::test_case_name() and TestInfo::name().
  4433. TEST_F(TestInfoTest, Names) {
  4434. const TestInfo* const test_info = GetTestInfo("Names");
  4435. ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
  4436. ASSERT_STREQ("Names", test_info->name());
  4437. }
  4438. // Tests TestInfo::result().
  4439. TEST_F(TestInfoTest, result) {
  4440. const TestInfo* const test_info = GetTestInfo("result");
  4441. // Initially, there is no TestPartResult for this test.
  4442. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4443. // After the previous assertion, there is still none.
  4444. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
  4445. }
  4446. #define VERIFY_CODE_LOCATION \
  4447. const int expected_line = __LINE__ - 1; \
  4448. const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
  4449. ASSERT_TRUE(test_info); \
  4450. EXPECT_STREQ(__FILE__, test_info->file()); \
  4451. EXPECT_EQ(expected_line, test_info->line())
  4452. // clang-format off
  4453. TEST(CodeLocationForTEST, Verify) {
  4454. VERIFY_CODE_LOCATION;
  4455. }
  4456. class CodeLocationForTESTF : public Test {};
  4457. TEST_F(CodeLocationForTESTF, Verify) {
  4458. VERIFY_CODE_LOCATION;
  4459. }
  4460. class CodeLocationForTESTP : public TestWithParam<int> {};
  4461. TEST_P(CodeLocationForTESTP, Verify) {
  4462. VERIFY_CODE_LOCATION;
  4463. }
  4464. INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
  4465. template <typename T>
  4466. class CodeLocationForTYPEDTEST : public Test {};
  4467. TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
  4468. TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
  4469. VERIFY_CODE_LOCATION;
  4470. }
  4471. template <typename T>
  4472. class CodeLocationForTYPEDTESTP : public Test {};
  4473. TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
  4474. TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
  4475. VERIFY_CODE_LOCATION;
  4476. }
  4477. REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
  4478. INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
  4479. #undef VERIFY_CODE_LOCATION
  4480. // clang-format on
  4481. // Tests setting up and tearing down a test case.
  4482. // Legacy API is deprecated but still available
  4483. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4484. class SetUpTestCaseTest : public Test {
  4485. protected:
  4486. // This will be called once before the first test in this test case
  4487. // is run.
  4488. static void SetUpTestCase() {
  4489. printf("Setting up the test case . . .\n");
  4490. // Initializes some shared resource. In this simple example, we
  4491. // just create a C string. More complex stuff can be done if
  4492. // desired.
  4493. shared_resource_ = "123";
  4494. // Increments the number of test cases that have been set up.
  4495. counter_++;
  4496. // SetUpTestCase() should be called only once.
  4497. EXPECT_EQ(1, counter_);
  4498. }
  4499. // This will be called once after the last test in this test case is
  4500. // run.
  4501. static void TearDownTestCase() {
  4502. printf("Tearing down the test case . . .\n");
  4503. // Decrements the number of test cases that have been set up.
  4504. counter_--;
  4505. // TearDownTestCase() should be called only once.
  4506. EXPECT_EQ(0, counter_);
  4507. // Cleans up the shared resource.
  4508. shared_resource_ = nullptr;
  4509. }
  4510. // This will be called before each test in this test case.
  4511. void SetUp() override {
  4512. // SetUpTestCase() should be called only once, so counter_ should
  4513. // always be 1.
  4514. EXPECT_EQ(1, counter_);
  4515. }
  4516. // Number of test cases that have been set up.
  4517. static int counter_;
  4518. // Some resource to be shared by all tests in this test case.
  4519. static const char* shared_resource_;
  4520. };
  4521. int SetUpTestCaseTest::counter_ = 0;
  4522. const char* SetUpTestCaseTest::shared_resource_ = nullptr;
  4523. // A test that uses the shared resource.
  4524. TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
  4525. // Another test that uses the shared resource.
  4526. TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
  4527. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4528. // Tests SetupTestSuite/TearDown TestSuite
  4529. class SetUpTestSuiteTest : public Test {
  4530. protected:
  4531. // This will be called once before the first test in this test case
  4532. // is run.
  4533. static void SetUpTestSuite() {
  4534. printf("Setting up the test suite . . .\n");
  4535. // Initializes some shared resource. In this simple example, we
  4536. // just create a C string. More complex stuff can be done if
  4537. // desired.
  4538. shared_resource_ = "123";
  4539. // Increments the number of test cases that have been set up.
  4540. counter_++;
  4541. // SetUpTestSuite() should be called only once.
  4542. EXPECT_EQ(1, counter_);
  4543. }
  4544. // This will be called once after the last test in this test case is
  4545. // run.
  4546. static void TearDownTestSuite() {
  4547. printf("Tearing down the test suite . . .\n");
  4548. // Decrements the number of test suites that have been set up.
  4549. counter_--;
  4550. // TearDownTestSuite() should be called only once.
  4551. EXPECT_EQ(0, counter_);
  4552. // Cleans up the shared resource.
  4553. shared_resource_ = nullptr;
  4554. }
  4555. // This will be called before each test in this test case.
  4556. void SetUp() override {
  4557. // SetUpTestSuite() should be called only once, so counter_ should
  4558. // always be 1.
  4559. EXPECT_EQ(1, counter_);
  4560. }
  4561. // Number of test suites that have been set up.
  4562. static int counter_;
  4563. // Some resource to be shared by all tests in this test case.
  4564. static const char* shared_resource_;
  4565. };
  4566. int SetUpTestSuiteTest::counter_ = 0;
  4567. const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
  4568. // A test that uses the shared resource.
  4569. TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
  4570. EXPECT_STRNE(nullptr, shared_resource_);
  4571. }
  4572. // Another test that uses the shared resource.
  4573. TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
  4574. EXPECT_STREQ("123", shared_resource_);
  4575. }
  4576. // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
  4577. // The Flags struct stores a copy of all Google Test flags.
  4578. struct Flags {
  4579. // Constructs a Flags struct where each flag has its default value.
  4580. Flags()
  4581. : also_run_disabled_tests(false),
  4582. break_on_failure(false),
  4583. catch_exceptions(false),
  4584. death_test_use_fork(false),
  4585. fail_fast(false),
  4586. filter(""),
  4587. list_tests(false),
  4588. output(""),
  4589. brief(false),
  4590. print_time(true),
  4591. random_seed(0),
  4592. repeat(1),
  4593. recreate_environments_when_repeating(true),
  4594. shuffle(false),
  4595. stack_trace_depth(kMaxStackTraceDepth),
  4596. stream_result_to(""),
  4597. throw_on_failure(false) {}
  4598. // Factory methods.
  4599. // Creates a Flags struct where the gtest_also_run_disabled_tests flag has
  4600. // the given value.
  4601. static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
  4602. Flags flags;
  4603. flags.also_run_disabled_tests = also_run_disabled_tests;
  4604. return flags;
  4605. }
  4606. // Creates a Flags struct where the gtest_break_on_failure flag has
  4607. // the given value.
  4608. static Flags BreakOnFailure(bool break_on_failure) {
  4609. Flags flags;
  4610. flags.break_on_failure = break_on_failure;
  4611. return flags;
  4612. }
  4613. // Creates a Flags struct where the gtest_catch_exceptions flag has
  4614. // the given value.
  4615. static Flags CatchExceptions(bool catch_exceptions) {
  4616. Flags flags;
  4617. flags.catch_exceptions = catch_exceptions;
  4618. return flags;
  4619. }
  4620. // Creates a Flags struct where the gtest_death_test_use_fork flag has
  4621. // the given value.
  4622. static Flags DeathTestUseFork(bool death_test_use_fork) {
  4623. Flags flags;
  4624. flags.death_test_use_fork = death_test_use_fork;
  4625. return flags;
  4626. }
  4627. // Creates a Flags struct where the gtest_fail_fast flag has
  4628. // the given value.
  4629. static Flags FailFast(bool fail_fast) {
  4630. Flags flags;
  4631. flags.fail_fast = fail_fast;
  4632. return flags;
  4633. }
  4634. // Creates a Flags struct where the gtest_filter flag has the given
  4635. // value.
  4636. static Flags Filter(const char* filter) {
  4637. Flags flags;
  4638. flags.filter = filter;
  4639. return flags;
  4640. }
  4641. // Creates a Flags struct where the gtest_list_tests flag has the
  4642. // given value.
  4643. static Flags ListTests(bool list_tests) {
  4644. Flags flags;
  4645. flags.list_tests = list_tests;
  4646. return flags;
  4647. }
  4648. // Creates a Flags struct where the gtest_output flag has the given
  4649. // value.
  4650. static Flags Output(const char* output) {
  4651. Flags flags;
  4652. flags.output = output;
  4653. return flags;
  4654. }
  4655. // Creates a Flags struct where the gtest_brief flag has the given
  4656. // value.
  4657. static Flags Brief(bool brief) {
  4658. Flags flags;
  4659. flags.brief = brief;
  4660. return flags;
  4661. }
  4662. // Creates a Flags struct where the gtest_print_time flag has the given
  4663. // value.
  4664. static Flags PrintTime(bool print_time) {
  4665. Flags flags;
  4666. flags.print_time = print_time;
  4667. return flags;
  4668. }
  4669. // Creates a Flags struct where the gtest_random_seed flag has the given
  4670. // value.
  4671. static Flags RandomSeed(int32_t random_seed) {
  4672. Flags flags;
  4673. flags.random_seed = random_seed;
  4674. return flags;
  4675. }
  4676. // Creates a Flags struct where the gtest_repeat flag has the given
  4677. // value.
  4678. static Flags Repeat(int32_t repeat) {
  4679. Flags flags;
  4680. flags.repeat = repeat;
  4681. return flags;
  4682. }
  4683. // Creates a Flags struct where the gtest_recreate_environments_when_repeating
  4684. // flag has the given value.
  4685. static Flags RecreateEnvironmentsWhenRepeating(
  4686. bool recreate_environments_when_repeating) {
  4687. Flags flags;
  4688. flags.recreate_environments_when_repeating =
  4689. recreate_environments_when_repeating;
  4690. return flags;
  4691. }
  4692. // Creates a Flags struct where the gtest_shuffle flag has the given
  4693. // value.
  4694. static Flags Shuffle(bool shuffle) {
  4695. Flags flags;
  4696. flags.shuffle = shuffle;
  4697. return flags;
  4698. }
  4699. // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
  4700. // the given value.
  4701. static Flags StackTraceDepth(int32_t stack_trace_depth) {
  4702. Flags flags;
  4703. flags.stack_trace_depth = stack_trace_depth;
  4704. return flags;
  4705. }
  4706. // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
  4707. // the given value.
  4708. static Flags StreamResultTo(const char* stream_result_to) {
  4709. Flags flags;
  4710. flags.stream_result_to = stream_result_to;
  4711. return flags;
  4712. }
  4713. // Creates a Flags struct where the gtest_throw_on_failure flag has
  4714. // the given value.
  4715. static Flags ThrowOnFailure(bool throw_on_failure) {
  4716. Flags flags;
  4717. flags.throw_on_failure = throw_on_failure;
  4718. return flags;
  4719. }
  4720. // These fields store the flag values.
  4721. bool also_run_disabled_tests;
  4722. bool break_on_failure;
  4723. bool catch_exceptions;
  4724. bool death_test_use_fork;
  4725. bool fail_fast;
  4726. const char* filter;
  4727. bool list_tests;
  4728. const char* output;
  4729. bool brief;
  4730. bool print_time;
  4731. int32_t random_seed;
  4732. int32_t repeat;
  4733. bool recreate_environments_when_repeating;
  4734. bool shuffle;
  4735. int32_t stack_trace_depth;
  4736. const char* stream_result_to;
  4737. bool throw_on_failure;
  4738. };
  4739. // Fixture for testing ParseGoogleTestFlagsOnly().
  4740. class ParseFlagsTest : public Test {
  4741. protected:
  4742. // Clears the flags before each test.
  4743. void SetUp() override {
  4744. GTEST_FLAG_SET(also_run_disabled_tests, false);
  4745. GTEST_FLAG_SET(break_on_failure, false);
  4746. GTEST_FLAG_SET(catch_exceptions, false);
  4747. GTEST_FLAG_SET(death_test_use_fork, false);
  4748. GTEST_FLAG_SET(fail_fast, false);
  4749. GTEST_FLAG_SET(filter, "");
  4750. GTEST_FLAG_SET(list_tests, false);
  4751. GTEST_FLAG_SET(output, "");
  4752. GTEST_FLAG_SET(brief, false);
  4753. GTEST_FLAG_SET(print_time, true);
  4754. GTEST_FLAG_SET(random_seed, 0);
  4755. GTEST_FLAG_SET(repeat, 1);
  4756. GTEST_FLAG_SET(recreate_environments_when_repeating, true);
  4757. GTEST_FLAG_SET(shuffle, false);
  4758. GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
  4759. GTEST_FLAG_SET(stream_result_to, "");
  4760. GTEST_FLAG_SET(throw_on_failure, false);
  4761. }
  4762. // Asserts that two narrow or wide string arrays are equal.
  4763. template <typename CharType>
  4764. static void AssertStringArrayEq(int size1, CharType** array1, int size2,
  4765. CharType** array2) {
  4766. ASSERT_EQ(size1, size2) << " Array sizes different.";
  4767. for (int i = 0; i != size1; i++) {
  4768. ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
  4769. }
  4770. }
  4771. // Verifies that the flag values match the expected values.
  4772. static void CheckFlags(const Flags& expected) {
  4773. EXPECT_EQ(expected.also_run_disabled_tests,
  4774. GTEST_FLAG_GET(also_run_disabled_tests));
  4775. EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
  4776. EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
  4777. EXPECT_EQ(expected.death_test_use_fork,
  4778. GTEST_FLAG_GET(death_test_use_fork));
  4779. EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
  4780. EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
  4781. EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
  4782. EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
  4783. EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
  4784. EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
  4785. EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
  4786. EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
  4787. EXPECT_EQ(expected.recreate_environments_when_repeating,
  4788. GTEST_FLAG_GET(recreate_environments_when_repeating));
  4789. EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
  4790. EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
  4791. EXPECT_STREQ(expected.stream_result_to,
  4792. GTEST_FLAG_GET(stream_result_to).c_str());
  4793. EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
  4794. }
  4795. // Parses a command line (specified by argc1 and argv1), then
  4796. // verifies that the flag values are expected and that the
  4797. // recognized flags are removed from the command line.
  4798. template <typename CharType>
  4799. static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,
  4800. const CharType** argv2, const Flags& expected,
  4801. bool should_print_help) {
  4802. const bool saved_help_flag = ::testing::internal::g_help_flag;
  4803. ::testing::internal::g_help_flag = false;
  4804. #if GTEST_HAS_STREAM_REDIRECTION
  4805. CaptureStdout();
  4806. #endif
  4807. // Parses the command line.
  4808. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
  4809. #if GTEST_HAS_STREAM_REDIRECTION
  4810. const std::string captured_stdout = GetCapturedStdout();
  4811. #endif
  4812. // Verifies the flag values.
  4813. CheckFlags(expected);
  4814. // Verifies that the recognized flags are removed from the command
  4815. // line.
  4816. AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
  4817. // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
  4818. // help message for the flags it recognizes.
  4819. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
  4820. #if GTEST_HAS_STREAM_REDIRECTION
  4821. const char* const expected_help_fragment =
  4822. "This program contains tests written using";
  4823. if (should_print_help) {
  4824. EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
  4825. } else {
  4826. EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment,
  4827. captured_stdout);
  4828. }
  4829. #endif // GTEST_HAS_STREAM_REDIRECTION
  4830. ::testing::internal::g_help_flag = saved_help_flag;
  4831. }
  4832. // This macro wraps TestParsingFlags s.t. the user doesn't need
  4833. // to specify the array sizes.
  4834. #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
  4835. TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \
  4836. sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \
  4837. should_print_help)
  4838. };
  4839. // Tests parsing an empty command line.
  4840. TEST_F(ParseFlagsTest, Empty) {
  4841. const char* argv[] = {nullptr};
  4842. const char* argv2[] = {nullptr};
  4843. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4844. }
  4845. // Tests parsing a command line that has no flag.
  4846. TEST_F(ParseFlagsTest, NoFlag) {
  4847. const char* argv[] = {"foo.exe", nullptr};
  4848. const char* argv2[] = {"foo.exe", nullptr};
  4849. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  4850. }
  4851. // Tests parsing --gtest_fail_fast.
  4852. TEST_F(ParseFlagsTest, FailFast) {
  4853. const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
  4854. const char* argv2[] = {"foo.exe", nullptr};
  4855. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
  4856. }
  4857. // Tests parsing an empty --gtest_filter flag.
  4858. TEST_F(ParseFlagsTest, FilterEmpty) {
  4859. const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
  4860. const char* argv2[] = {"foo.exe", nullptr};
  4861. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
  4862. }
  4863. // Tests parsing a non-empty --gtest_filter flag.
  4864. TEST_F(ParseFlagsTest, FilterNonEmpty) {
  4865. const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
  4866. const char* argv2[] = {"foo.exe", nullptr};
  4867. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
  4868. }
  4869. // Tests parsing --gtest_break_on_failure.
  4870. TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
  4871. const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
  4872. const char* argv2[] = {"foo.exe", nullptr};
  4873. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4874. }
  4875. // Tests parsing --gtest_break_on_failure=0.
  4876. TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
  4877. const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
  4878. const char* argv2[] = {"foo.exe", nullptr};
  4879. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4880. }
  4881. // Tests parsing --gtest_break_on_failure=f.
  4882. TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
  4883. const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
  4884. const char* argv2[] = {"foo.exe", nullptr};
  4885. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4886. }
  4887. // Tests parsing --gtest_break_on_failure=F.
  4888. TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
  4889. const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
  4890. const char* argv2[] = {"foo.exe", nullptr};
  4891. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
  4892. }
  4893. // Tests parsing a --gtest_break_on_failure flag that has a "true"
  4894. // definition.
  4895. TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
  4896. const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
  4897. const char* argv2[] = {"foo.exe", nullptr};
  4898. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
  4899. }
  4900. // Tests parsing --gtest_catch_exceptions.
  4901. TEST_F(ParseFlagsTest, CatchExceptions) {
  4902. const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
  4903. const char* argv2[] = {"foo.exe", nullptr};
  4904. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
  4905. }
  4906. // Tests parsing --gtest_death_test_use_fork.
  4907. TEST_F(ParseFlagsTest, DeathTestUseFork) {
  4908. const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
  4909. const char* argv2[] = {"foo.exe", nullptr};
  4910. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
  4911. }
  4912. // Tests having the same flag twice with different values. The
  4913. // expected behavior is that the one coming last takes precedence.
  4914. TEST_F(ParseFlagsTest, DuplicatedFlags) {
  4915. const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
  4916. nullptr};
  4917. const char* argv2[] = {"foo.exe", nullptr};
  4918. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
  4919. }
  4920. // Tests having an unrecognized flag on the command line.
  4921. TEST_F(ParseFlagsTest, UnrecognizedFlag) {
  4922. const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
  4923. "bar", // Unrecognized by Google Test.
  4924. "--gtest_filter=b", nullptr};
  4925. const char* argv2[] = {"foo.exe", "bar", nullptr};
  4926. Flags flags;
  4927. flags.break_on_failure = true;
  4928. flags.filter = "b";
  4929. GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
  4930. }
  4931. // Tests having a --gtest_list_tests flag
  4932. TEST_F(ParseFlagsTest, ListTestsFlag) {
  4933. const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
  4934. const char* argv2[] = {"foo.exe", nullptr};
  4935. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4936. }
  4937. // Tests having a --gtest_list_tests flag with a "true" value
  4938. TEST_F(ParseFlagsTest, ListTestsTrue) {
  4939. const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
  4940. const char* argv2[] = {"foo.exe", nullptr};
  4941. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
  4942. }
  4943. // Tests having a --gtest_list_tests flag with a "false" value
  4944. TEST_F(ParseFlagsTest, ListTestsFalse) {
  4945. const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
  4946. const char* argv2[] = {"foo.exe", nullptr};
  4947. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4948. }
  4949. // Tests parsing --gtest_list_tests=f.
  4950. TEST_F(ParseFlagsTest, ListTestsFalse_f) {
  4951. const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
  4952. const char* argv2[] = {"foo.exe", nullptr};
  4953. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4954. }
  4955. // Tests parsing --gtest_list_tests=F.
  4956. TEST_F(ParseFlagsTest, ListTestsFalse_F) {
  4957. const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
  4958. const char* argv2[] = {"foo.exe", nullptr};
  4959. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
  4960. }
  4961. // Tests parsing --gtest_output=xml
  4962. TEST_F(ParseFlagsTest, OutputXml) {
  4963. const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
  4964. const char* argv2[] = {"foo.exe", nullptr};
  4965. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
  4966. }
  4967. // Tests parsing --gtest_output=xml:file
  4968. TEST_F(ParseFlagsTest, OutputXmlFile) {
  4969. const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
  4970. const char* argv2[] = {"foo.exe", nullptr};
  4971. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
  4972. }
  4973. // Tests parsing --gtest_output=xml:directory/path/
  4974. TEST_F(ParseFlagsTest, OutputXmlDirectory) {
  4975. const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
  4976. nullptr};
  4977. const char* argv2[] = {"foo.exe", nullptr};
  4978. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"),
  4979. false);
  4980. }
  4981. // Tests having a --gtest_brief flag
  4982. TEST_F(ParseFlagsTest, BriefFlag) {
  4983. const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
  4984. const char* argv2[] = {"foo.exe", nullptr};
  4985. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
  4986. }
  4987. // Tests having a --gtest_brief flag with a "true" value
  4988. TEST_F(ParseFlagsTest, BriefFlagTrue) {
  4989. const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
  4990. const char* argv2[] = {"foo.exe", nullptr};
  4991. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
  4992. }
  4993. // Tests having a --gtest_brief flag with a "false" value
  4994. TEST_F(ParseFlagsTest, BriefFlagFalse) {
  4995. const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
  4996. const char* argv2[] = {"foo.exe", nullptr};
  4997. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
  4998. }
  4999. // Tests having a --gtest_print_time flag
  5000. TEST_F(ParseFlagsTest, PrintTimeFlag) {
  5001. const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
  5002. const char* argv2[] = {"foo.exe", nullptr};
  5003. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  5004. }
  5005. // Tests having a --gtest_print_time flag with a "true" value
  5006. TEST_F(ParseFlagsTest, PrintTimeTrue) {
  5007. const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
  5008. const char* argv2[] = {"foo.exe", nullptr};
  5009. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
  5010. }
  5011. // Tests having a --gtest_print_time flag with a "false" value
  5012. TEST_F(ParseFlagsTest, PrintTimeFalse) {
  5013. const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
  5014. const char* argv2[] = {"foo.exe", nullptr};
  5015. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  5016. }
  5017. // Tests parsing --gtest_print_time=f.
  5018. TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
  5019. const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
  5020. const char* argv2[] = {"foo.exe", nullptr};
  5021. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  5022. }
  5023. // Tests parsing --gtest_print_time=F.
  5024. TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
  5025. const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
  5026. const char* argv2[] = {"foo.exe", nullptr};
  5027. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
  5028. }
  5029. // Tests parsing --gtest_random_seed=number
  5030. TEST_F(ParseFlagsTest, RandomSeed) {
  5031. const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
  5032. const char* argv2[] = {"foo.exe", nullptr};
  5033. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
  5034. }
  5035. // Tests parsing --gtest_repeat=number
  5036. TEST_F(ParseFlagsTest, Repeat) {
  5037. const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
  5038. const char* argv2[] = {"foo.exe", nullptr};
  5039. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
  5040. }
  5041. // Tests parsing --gtest_recreate_environments_when_repeating
  5042. TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
  5043. const char* argv[] = {
  5044. "foo.exe",
  5045. "--gtest_recreate_environments_when_repeating=0",
  5046. nullptr,
  5047. };
  5048. const char* argv2[] = {"foo.exe", nullptr};
  5049. GTEST_TEST_PARSING_FLAGS_(
  5050. argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
  5051. }
  5052. // Tests having a --gtest_also_run_disabled_tests flag
  5053. TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
  5054. const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
  5055. const char* argv2[] = {"foo.exe", nullptr};
  5056. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
  5057. false);
  5058. }
  5059. // Tests having a --gtest_also_run_disabled_tests flag with a "true" value
  5060. TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
  5061. const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
  5062. nullptr};
  5063. const char* argv2[] = {"foo.exe", nullptr};
  5064. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
  5065. false);
  5066. }
  5067. // Tests having a --gtest_also_run_disabled_tests flag with a "false" value
  5068. TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
  5069. const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
  5070. nullptr};
  5071. const char* argv2[] = {"foo.exe", nullptr};
  5072. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
  5073. false);
  5074. }
  5075. // Tests parsing --gtest_shuffle.
  5076. TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
  5077. const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
  5078. const char* argv2[] = {"foo.exe", nullptr};
  5079. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  5080. }
  5081. // Tests parsing --gtest_shuffle=0.
  5082. TEST_F(ParseFlagsTest, ShuffleFalse_0) {
  5083. const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
  5084. const char* argv2[] = {"foo.exe", nullptr};
  5085. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
  5086. }
  5087. // Tests parsing a --gtest_shuffle flag that has a "true" definition.
  5088. TEST_F(ParseFlagsTest, ShuffleTrue) {
  5089. const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
  5090. const char* argv2[] = {"foo.exe", nullptr};
  5091. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
  5092. }
  5093. // Tests parsing --gtest_stack_trace_depth=number.
  5094. TEST_F(ParseFlagsTest, StackTraceDepth) {
  5095. const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
  5096. const char* argv2[] = {"foo.exe", nullptr};
  5097. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
  5098. }
  5099. TEST_F(ParseFlagsTest, StreamResultTo) {
  5100. const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
  5101. nullptr};
  5102. const char* argv2[] = {"foo.exe", nullptr};
  5103. GTEST_TEST_PARSING_FLAGS_(argv, argv2,
  5104. Flags::StreamResultTo("localhost:1234"), false);
  5105. }
  5106. // Tests parsing --gtest_throw_on_failure.
  5107. TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
  5108. const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
  5109. const char* argv2[] = {"foo.exe", nullptr};
  5110. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  5111. }
  5112. // Tests parsing --gtest_throw_on_failure=0.
  5113. TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
  5114. const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
  5115. const char* argv2[] = {"foo.exe", nullptr};
  5116. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
  5117. }
  5118. // Tests parsing a --gtest_throw_on_failure flag that has a "true"
  5119. // definition.
  5120. TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
  5121. const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
  5122. const char* argv2[] = {"foo.exe", nullptr};
  5123. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  5124. }
  5125. // Tests parsing a bad --gtest_filter flag.
  5126. TEST_F(ParseFlagsTest, FilterBad) {
  5127. const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
  5128. const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
  5129. #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
  5130. // Invalid flag arguments are a fatal error when using the Abseil Flags.
  5131. EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
  5132. testing::ExitedWithCode(1),
  5133. "ERROR: Missing the value for the flag 'gtest_filter'");
  5134. #elif !defined(GTEST_HAS_ABSL)
  5135. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
  5136. #else
  5137. static_cast<void>(argv);
  5138. static_cast<void>(argv2);
  5139. #endif
  5140. }
  5141. // Tests parsing --gtest_output (invalid).
  5142. TEST_F(ParseFlagsTest, OutputEmpty) {
  5143. const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
  5144. const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
  5145. #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
  5146. // Invalid flag arguments are a fatal error when using the Abseil Flags.
  5147. EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
  5148. testing::ExitedWithCode(1),
  5149. "ERROR: Missing the value for the flag 'gtest_output'");
  5150. #elif !defined(GTEST_HAS_ABSL)
  5151. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
  5152. #else
  5153. static_cast<void>(argv);
  5154. static_cast<void>(argv2);
  5155. #endif
  5156. }
  5157. #ifdef GTEST_HAS_ABSL
  5158. TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
  5159. const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
  5160. "--other_flag", nullptr};
  5161. // When using Abseil flags, it should be possible to pass flags not recognized
  5162. // using "--" to delimit positional arguments. These flags should be returned
  5163. // though argv.
  5164. const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
  5165. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
  5166. }
  5167. #endif
  5168. TEST_F(ParseFlagsTest, UnrecognizedFlags) {
  5169. const char* argv[] = {"foo.exe", "--gtest_filter=abcd", "--other_flag",
  5170. nullptr};
  5171. const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
  5172. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abcd"), false);
  5173. }
  5174. #ifdef GTEST_OS_WINDOWS
  5175. // Tests parsing wide strings.
  5176. TEST_F(ParseFlagsTest, WideStrings) {
  5177. const wchar_t* argv[] = {L"foo.exe",
  5178. L"--gtest_filter=Foo*",
  5179. L"--gtest_list_tests=1",
  5180. L"--gtest_break_on_failure",
  5181. L"--non_gtest_flag",
  5182. NULL};
  5183. const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL};
  5184. Flags expected_flags;
  5185. expected_flags.break_on_failure = true;
  5186. expected_flags.filter = "Foo*";
  5187. expected_flags.list_tests = true;
  5188. GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
  5189. }
  5190. #endif // GTEST_OS_WINDOWS
  5191. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  5192. class FlagfileTest : public ParseFlagsTest {
  5193. public:
  5194. void SetUp() override {
  5195. ParseFlagsTest::SetUp();
  5196. testdata_path_.Set(internal::FilePath(
  5197. testing::TempDir() + internal::GetCurrentExecutableName().string() +
  5198. "_flagfile_test"));
  5199. testing::internal::posix::RmDir(testdata_path_.c_str());
  5200. EXPECT_TRUE(testdata_path_.CreateFolder());
  5201. }
  5202. void TearDown() override {
  5203. testing::internal::posix::RmDir(testdata_path_.c_str());
  5204. ParseFlagsTest::TearDown();
  5205. }
  5206. internal::FilePath CreateFlagfile(const char* contents) {
  5207. internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
  5208. testdata_path_, internal::FilePath("unique"), "txt"));
  5209. FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
  5210. fprintf(f, "%s", contents);
  5211. fclose(f);
  5212. return file_path;
  5213. }
  5214. private:
  5215. internal::FilePath testdata_path_;
  5216. };
  5217. // Tests an empty flagfile.
  5218. TEST_F(FlagfileTest, Empty) {
  5219. internal::FilePath flagfile_path(CreateFlagfile(""));
  5220. std::string flagfile_flag =
  5221. std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
  5222. const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
  5223. const char* argv2[] = {"foo.exe", nullptr};
  5224. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
  5225. }
  5226. // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
  5227. TEST_F(FlagfileTest, FilterNonEmpty) {
  5228. internal::FilePath flagfile_path(
  5229. CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc"));
  5230. std::string flagfile_flag =
  5231. std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
  5232. const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
  5233. const char* argv2[] = {"foo.exe", nullptr};
  5234. GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
  5235. }
  5236. // Tests passing several flags via --gtest_flagfile.
  5237. TEST_F(FlagfileTest, SeveralFlags) {
  5238. internal::FilePath flagfile_path(
  5239. CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n"
  5240. "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
  5241. "--" GTEST_FLAG_PREFIX_ "list_tests"));
  5242. std::string flagfile_flag =
  5243. std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
  5244. const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
  5245. const char* argv2[] = {"foo.exe", nullptr};
  5246. Flags expected_flags;
  5247. expected_flags.break_on_failure = true;
  5248. expected_flags.filter = "abc";
  5249. expected_flags.list_tests = true;
  5250. GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
  5251. }
  5252. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  5253. // Tests current_test_info() in UnitTest.
  5254. class CurrentTestInfoTest : public Test {
  5255. protected:
  5256. // Tests that current_test_info() returns NULL before the first test in
  5257. // the test case is run.
  5258. static void SetUpTestSuite() {
  5259. // There should be no tests running at this point.
  5260. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
  5261. EXPECT_TRUE(test_info == nullptr)
  5262. << "There should be no tests running at this point.";
  5263. }
  5264. // Tests that current_test_info() returns NULL after the last test in
  5265. // the test case has run.
  5266. static void TearDownTestSuite() {
  5267. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
  5268. EXPECT_TRUE(test_info == nullptr)
  5269. << "There should be no tests running at this point.";
  5270. }
  5271. };
  5272. // Tests that current_test_info() returns TestInfo for currently running
  5273. // test by checking the expected test name against the actual one.
  5274. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
  5275. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
  5276. ASSERT_TRUE(nullptr != test_info)
  5277. << "There is a test running so we should have a valid TestInfo.";
  5278. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
  5279. << "Expected the name of the currently running test suite.";
  5280. EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
  5281. << "Expected the name of the currently running test.";
  5282. }
  5283. // Tests that current_test_info() returns TestInfo for currently running
  5284. // test by checking the expected test name against the actual one. We
  5285. // use this test to see that the TestInfo object actually changed from
  5286. // the previous invocation.
  5287. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
  5288. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
  5289. ASSERT_TRUE(nullptr != test_info)
  5290. << "There is a test running so we should have a valid TestInfo.";
  5291. EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
  5292. << "Expected the name of the currently running test suite.";
  5293. EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
  5294. << "Expected the name of the currently running test.";
  5295. }
  5296. } // namespace testing
  5297. // These two lines test that we can define tests in a namespace that
  5298. // has the name "testing" and is nested in another namespace.
  5299. namespace my_namespace {
  5300. namespace testing {
  5301. // Makes sure that TEST knows to use ::testing::Test instead of
  5302. // ::my_namespace::testing::Test.
  5303. class Test {};
  5304. // Makes sure that an assertion knows to use ::testing::Message instead of
  5305. // ::my_namespace::testing::Message.
  5306. class Message {};
  5307. // Makes sure that an assertion knows to use
  5308. // ::testing::AssertionResult instead of
  5309. // ::my_namespace::testing::AssertionResult.
  5310. class AssertionResult {};
  5311. // Tests that an assertion that should succeed works as expected.
  5312. TEST(NestedTestingNamespaceTest, Success) {
  5313. EXPECT_EQ(1, 1) << "This shouldn't fail.";
  5314. }
  5315. // Tests that an assertion that should fail works as expected.
  5316. TEST(NestedTestingNamespaceTest, Failure) {
  5317. EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
  5318. "This failure is expected.");
  5319. }
  5320. } // namespace testing
  5321. } // namespace my_namespace
  5322. // Tests that one can call superclass SetUp and TearDown methods--
  5323. // that is, that they are not private.
  5324. // No tests are based on this fixture; the test "passes" if it compiles
  5325. // successfully.
  5326. class ProtectedFixtureMethodsTest : public Test {
  5327. protected:
  5328. void SetUp() override { Test::SetUp(); }
  5329. void TearDown() override { Test::TearDown(); }
  5330. };
  5331. // StreamingAssertionsTest tests the streaming versions of a representative
  5332. // sample of assertions.
  5333. TEST(StreamingAssertionsTest, Unconditional) {
  5334. SUCCEED() << "expected success";
  5335. EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
  5336. "expected failure");
  5337. EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure");
  5338. }
  5339. #ifdef __BORLANDC__
  5340. // Silences warnings: "Condition is always true", "Unreachable code"
  5341. #pragma option push -w-ccc -w-rch
  5342. #endif
  5343. TEST(StreamingAssertionsTest, Truth) {
  5344. EXPECT_TRUE(true) << "unexpected failure";
  5345. ASSERT_TRUE(true) << "unexpected failure";
  5346. EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
  5347. "expected failure");
  5348. EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
  5349. "expected failure");
  5350. }
  5351. TEST(StreamingAssertionsTest, Truth2) {
  5352. EXPECT_FALSE(false) << "unexpected failure";
  5353. ASSERT_FALSE(false) << "unexpected failure";
  5354. EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
  5355. "expected failure");
  5356. EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
  5357. "expected failure");
  5358. }
  5359. #ifdef __BORLANDC__
  5360. // Restores warnings after previous "#pragma option push" suppressed them
  5361. #pragma option pop
  5362. #endif
  5363. TEST(StreamingAssertionsTest, IntegerEquals) {
  5364. EXPECT_EQ(1, 1) << "unexpected failure";
  5365. ASSERT_EQ(1, 1) << "unexpected failure";
  5366. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
  5367. "expected failure");
  5368. EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
  5369. "expected failure");
  5370. }
  5371. TEST(StreamingAssertionsTest, IntegerLessThan) {
  5372. EXPECT_LT(1, 2) << "unexpected failure";
  5373. ASSERT_LT(1, 2) << "unexpected failure";
  5374. EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
  5375. "expected failure");
  5376. EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
  5377. "expected failure");
  5378. }
  5379. TEST(StreamingAssertionsTest, StringsEqual) {
  5380. EXPECT_STREQ("foo", "foo") << "unexpected failure";
  5381. ASSERT_STREQ("foo", "foo") << "unexpected failure";
  5382. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
  5383. "expected failure");
  5384. EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
  5385. "expected failure");
  5386. }
  5387. TEST(StreamingAssertionsTest, StringsNotEqual) {
  5388. EXPECT_STRNE("foo", "bar") << "unexpected failure";
  5389. ASSERT_STRNE("foo", "bar") << "unexpected failure";
  5390. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
  5391. "expected failure");
  5392. EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
  5393. "expected failure");
  5394. }
  5395. TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
  5396. EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5397. ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
  5398. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
  5399. "expected failure");
  5400. EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
  5401. "expected failure");
  5402. }
  5403. TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
  5404. EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
  5405. ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
  5406. EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
  5407. "expected failure");
  5408. EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
  5409. "expected failure");
  5410. }
  5411. TEST(StreamingAssertionsTest, FloatingPointEquals) {
  5412. EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5413. ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
  5414. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5415. "expected failure");
  5416. EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
  5417. "expected failure");
  5418. }
  5419. #if GTEST_HAS_EXCEPTIONS
  5420. TEST(StreamingAssertionsTest, Throw) {
  5421. EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5422. ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
  5423. EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)
  5424. << "expected failure",
  5425. "expected failure");
  5426. EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)
  5427. << "expected failure",
  5428. "expected failure");
  5429. }
  5430. TEST(StreamingAssertionsTest, NoThrow) {
  5431. EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5432. ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
  5433. EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger())
  5434. << "expected failure",
  5435. "expected failure");
  5436. EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure",
  5437. "expected failure");
  5438. }
  5439. TEST(StreamingAssertionsTest, AnyThrow) {
  5440. EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5441. ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
  5442. EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing())
  5443. << "expected failure",
  5444. "expected failure");
  5445. EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure",
  5446. "expected failure");
  5447. }
  5448. #endif // GTEST_HAS_EXCEPTIONS
  5449. // Tests that Google Test correctly decides whether to use colors in the output.
  5450. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
  5451. GTEST_FLAG_SET(color, "yes");
  5452. SetEnv("TERM", "xterm"); // TERM supports colors.
  5453. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5454. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5455. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5456. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5457. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5458. }
  5459. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
  5460. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5461. GTEST_FLAG_SET(color, "True");
  5462. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5463. GTEST_FLAG_SET(color, "t");
  5464. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5465. GTEST_FLAG_SET(color, "1");
  5466. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
  5467. }
  5468. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
  5469. GTEST_FLAG_SET(color, "no");
  5470. SetEnv("TERM", "xterm"); // TERM supports colors.
  5471. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5472. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5473. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5474. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5475. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5476. }
  5477. TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
  5478. SetEnv("TERM", "xterm"); // TERM supports colors.
  5479. GTEST_FLAG_SET(color, "F");
  5480. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5481. GTEST_FLAG_SET(color, "0");
  5482. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5483. GTEST_FLAG_SET(color, "unknown");
  5484. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5485. }
  5486. TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
  5487. GTEST_FLAG_SET(color, "auto");
  5488. SetEnv("TERM", "xterm"); // TERM supports colors.
  5489. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
  5490. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5491. }
  5492. TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
  5493. GTEST_FLAG_SET(color, "auto");
  5494. #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
  5495. // On Windows, we ignore the TERM variable as it's usually not set.
  5496. SetEnv("TERM", "dumb");
  5497. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5498. SetEnv("TERM", "");
  5499. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5500. SetEnv("TERM", "xterm");
  5501. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5502. #else
  5503. // On non-Windows platforms, we rely on TERM to determine if the
  5504. // terminal supports colors.
  5505. SetEnv("TERM", "dumb"); // TERM doesn't support colors.
  5506. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5507. SetEnv("TERM", "emacs"); // TERM doesn't support colors.
  5508. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5509. SetEnv("TERM", "vt100"); // TERM doesn't support colors.
  5510. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5511. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
  5512. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
  5513. SetEnv("TERM", "xterm"); // TERM supports colors.
  5514. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5515. SetEnv("TERM", "xterm-color"); // TERM supports colors.
  5516. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5517. SetEnv("TERM", "xterm-kitty"); // TERM supports colors.
  5518. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5519. SetEnv("TERM", "alacritty"); // TERM supports colors.
  5520. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5521. SetEnv("TERM", "xterm-256color"); // TERM supports colors.
  5522. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5523. SetEnv("TERM", "screen"); // TERM supports colors.
  5524. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5525. SetEnv("TERM", "screen-256color"); // TERM supports colors.
  5526. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5527. SetEnv("TERM", "tmux"); // TERM supports colors.
  5528. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5529. SetEnv("TERM", "tmux-256color"); // TERM supports colors.
  5530. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5531. SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
  5532. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5533. SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
  5534. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5535. SetEnv("TERM", "linux"); // TERM supports colors.
  5536. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5537. SetEnv("TERM", "cygwin"); // TERM supports colors.
  5538. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
  5539. #endif // GTEST_OS_WINDOWS
  5540. }
  5541. // Verifies that StaticAssertTypeEq works in a namespace scope.
  5542. GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy1 =
  5543. StaticAssertTypeEq<bool, bool>();
  5544. GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy2 =
  5545. StaticAssertTypeEq<const int, const int>();
  5546. // Verifies that StaticAssertTypeEq works in a class.
  5547. template <typename T>
  5548. class StaticAssertTypeEqTestHelper {
  5549. public:
  5550. StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
  5551. };
  5552. TEST(StaticAssertTypeEqTest, WorksInClass) {
  5553. StaticAssertTypeEqTestHelper<bool>();
  5554. }
  5555. // Verifies that StaticAssertTypeEq works inside a function.
  5556. typedef int IntAlias;
  5557. TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
  5558. StaticAssertTypeEq<int, IntAlias>();
  5559. StaticAssertTypeEq<int*, IntAlias*>();
  5560. }
  5561. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5562. EXPECT_FALSE(HasNonfatalFailure());
  5563. }
  5564. static void FailFatally() { FAIL(); }
  5565. TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
  5566. FailFatally();
  5567. const bool has_nonfatal_failure = HasNonfatalFailure();
  5568. ClearCurrentTestPartResults();
  5569. EXPECT_FALSE(has_nonfatal_failure);
  5570. }
  5571. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5572. ADD_FAILURE();
  5573. const bool has_nonfatal_failure = HasNonfatalFailure();
  5574. ClearCurrentTestPartResults();
  5575. EXPECT_TRUE(has_nonfatal_failure);
  5576. }
  5577. TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5578. FailFatally();
  5579. ADD_FAILURE();
  5580. const bool has_nonfatal_failure = HasNonfatalFailure();
  5581. ClearCurrentTestPartResults();
  5582. EXPECT_TRUE(has_nonfatal_failure);
  5583. }
  5584. // A wrapper for calling HasNonfatalFailure outside of a test body.
  5585. static bool HasNonfatalFailureHelper() {
  5586. return testing::Test::HasNonfatalFailure();
  5587. }
  5588. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
  5589. EXPECT_FALSE(HasNonfatalFailureHelper());
  5590. }
  5591. TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
  5592. ADD_FAILURE();
  5593. const bool has_nonfatal_failure = HasNonfatalFailureHelper();
  5594. ClearCurrentTestPartResults();
  5595. EXPECT_TRUE(has_nonfatal_failure);
  5596. }
  5597. TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
  5598. EXPECT_FALSE(HasFailure());
  5599. }
  5600. TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
  5601. FailFatally();
  5602. const bool has_failure = HasFailure();
  5603. ClearCurrentTestPartResults();
  5604. EXPECT_TRUE(has_failure);
  5605. }
  5606. TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
  5607. ADD_FAILURE();
  5608. const bool has_failure = HasFailure();
  5609. ClearCurrentTestPartResults();
  5610. EXPECT_TRUE(has_failure);
  5611. }
  5612. TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
  5613. FailFatally();
  5614. ADD_FAILURE();
  5615. const bool has_failure = HasFailure();
  5616. ClearCurrentTestPartResults();
  5617. EXPECT_TRUE(has_failure);
  5618. }
  5619. // A wrapper for calling HasFailure outside of a test body.
  5620. static bool HasFailureHelper() { return testing::Test::HasFailure(); }
  5621. TEST(HasFailureTest, WorksOutsideOfTestBody) {
  5622. EXPECT_FALSE(HasFailureHelper());
  5623. }
  5624. TEST(HasFailureTest, WorksOutsideOfTestBody2) {
  5625. ADD_FAILURE();
  5626. const bool has_failure = HasFailureHelper();
  5627. ClearCurrentTestPartResults();
  5628. EXPECT_TRUE(has_failure);
  5629. }
  5630. class TestListener : public EmptyTestEventListener {
  5631. public:
  5632. TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
  5633. TestListener(int* on_start_counter, bool* is_destroyed)
  5634. : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}
  5635. ~TestListener() override {
  5636. if (is_destroyed_) *is_destroyed_ = true;
  5637. }
  5638. protected:
  5639. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
  5640. if (on_start_counter_ != nullptr) (*on_start_counter_)++;
  5641. }
  5642. private:
  5643. int* on_start_counter_;
  5644. bool* is_destroyed_;
  5645. };
  5646. // Tests the constructor.
  5647. TEST(TestEventListenersTest, ConstructionWorks) {
  5648. TestEventListeners listeners;
  5649. EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
  5650. EXPECT_TRUE(listeners.default_result_printer() == nullptr);
  5651. EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
  5652. }
  5653. // Tests that the TestEventListeners destructor deletes all the listeners it
  5654. // owns.
  5655. TEST(TestEventListenersTest, DestructionWorks) {
  5656. bool default_result_printer_is_destroyed = false;
  5657. bool default_xml_printer_is_destroyed = false;
  5658. bool extra_listener_is_destroyed = false;
  5659. TestListener* default_result_printer =
  5660. new TestListener(nullptr, &default_result_printer_is_destroyed);
  5661. TestListener* default_xml_printer =
  5662. new TestListener(nullptr, &default_xml_printer_is_destroyed);
  5663. TestListener* extra_listener =
  5664. new TestListener(nullptr, &extra_listener_is_destroyed);
  5665. {
  5666. TestEventListeners listeners;
  5667. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
  5668. default_result_printer);
  5669. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
  5670. default_xml_printer);
  5671. listeners.Append(extra_listener);
  5672. }
  5673. EXPECT_TRUE(default_result_printer_is_destroyed);
  5674. EXPECT_TRUE(default_xml_printer_is_destroyed);
  5675. EXPECT_TRUE(extra_listener_is_destroyed);
  5676. }
  5677. // Tests that a listener Append'ed to a TestEventListeners list starts
  5678. // receiving events.
  5679. TEST(TestEventListenersTest, Append) {
  5680. int on_start_counter = 0;
  5681. bool is_destroyed = false;
  5682. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5683. {
  5684. TestEventListeners listeners;
  5685. listeners.Append(listener);
  5686. TestEventListenersAccessor::GetRepeater(&listeners)
  5687. ->OnTestProgramStart(*UnitTest::GetInstance());
  5688. EXPECT_EQ(1, on_start_counter);
  5689. }
  5690. EXPECT_TRUE(is_destroyed);
  5691. }
  5692. // Tests that listeners receive events in the order they were appended to
  5693. // the list, except for *End requests, which must be received in the reverse
  5694. // order.
  5695. class SequenceTestingListener : public EmptyTestEventListener {
  5696. public:
  5697. SequenceTestingListener(std::vector<std::string>* vector, const char* id)
  5698. : vector_(vector), id_(id) {}
  5699. protected:
  5700. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
  5701. vector_->push_back(GetEventDescription("OnTestProgramStart"));
  5702. }
  5703. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
  5704. vector_->push_back(GetEventDescription("OnTestProgramEnd"));
  5705. }
  5706. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  5707. int /*iteration*/) override {
  5708. vector_->push_back(GetEventDescription("OnTestIterationStart"));
  5709. }
  5710. void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  5711. int /*iteration*/) override {
  5712. vector_->push_back(GetEventDescription("OnTestIterationEnd"));
  5713. }
  5714. private:
  5715. std::string GetEventDescription(const char* method) {
  5716. Message message;
  5717. message << id_ << "." << method;
  5718. return message.GetString();
  5719. }
  5720. std::vector<std::string>* vector_;
  5721. const char* const id_;
  5722. SequenceTestingListener(const SequenceTestingListener&) = delete;
  5723. SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;
  5724. };
  5725. TEST(EventListenerTest, AppendKeepsOrder) {
  5726. std::vector<std::string> vec;
  5727. TestEventListeners listeners;
  5728. listeners.Append(new SequenceTestingListener(&vec, "1st"));
  5729. listeners.Append(new SequenceTestingListener(&vec, "2nd"));
  5730. listeners.Append(new SequenceTestingListener(&vec, "3rd"));
  5731. TestEventListenersAccessor::GetRepeater(&listeners)
  5732. ->OnTestProgramStart(*UnitTest::GetInstance());
  5733. ASSERT_EQ(3U, vec.size());
  5734. EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
  5735. EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
  5736. EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
  5737. vec.clear();
  5738. TestEventListenersAccessor::GetRepeater(&listeners)
  5739. ->OnTestProgramEnd(*UnitTest::GetInstance());
  5740. ASSERT_EQ(3U, vec.size());
  5741. EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
  5742. EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
  5743. EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
  5744. vec.clear();
  5745. TestEventListenersAccessor::GetRepeater(&listeners)
  5746. ->OnTestIterationStart(*UnitTest::GetInstance(), 0);
  5747. ASSERT_EQ(3U, vec.size());
  5748. EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
  5749. EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
  5750. EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
  5751. vec.clear();
  5752. TestEventListenersAccessor::GetRepeater(&listeners)
  5753. ->OnTestIterationEnd(*UnitTest::GetInstance(), 0);
  5754. ASSERT_EQ(3U, vec.size());
  5755. EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
  5756. EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
  5757. EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
  5758. }
  5759. // Tests that a listener removed from a TestEventListeners list stops receiving
  5760. // events and is not deleted when the list is destroyed.
  5761. TEST(TestEventListenersTest, Release) {
  5762. int on_start_counter = 0;
  5763. bool is_destroyed = false;
  5764. // Although Append passes the ownership of this object to the list,
  5765. // the following calls release it, and we need to delete it before the
  5766. // test ends.
  5767. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5768. {
  5769. TestEventListeners listeners;
  5770. listeners.Append(listener);
  5771. EXPECT_EQ(listener, listeners.Release(listener));
  5772. TestEventListenersAccessor::GetRepeater(&listeners)
  5773. ->OnTestProgramStart(*UnitTest::GetInstance());
  5774. EXPECT_TRUE(listeners.Release(listener) == nullptr);
  5775. }
  5776. EXPECT_EQ(0, on_start_counter);
  5777. EXPECT_FALSE(is_destroyed);
  5778. delete listener;
  5779. }
  5780. // Tests that no events are forwarded when event forwarding is disabled.
  5781. TEST(EventListenerTest, SuppressEventForwarding) {
  5782. int on_start_counter = 0;
  5783. TestListener* listener = new TestListener(&on_start_counter, nullptr);
  5784. TestEventListeners listeners;
  5785. listeners.Append(listener);
  5786. ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5787. TestEventListenersAccessor::SuppressEventForwarding(&listeners);
  5788. ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
  5789. TestEventListenersAccessor::GetRepeater(&listeners)
  5790. ->OnTestProgramStart(*UnitTest::GetInstance());
  5791. EXPECT_EQ(0, on_start_counter);
  5792. }
  5793. // Tests that events generated by Google Test are not forwarded in
  5794. // death test subprocesses.
  5795. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) {
  5796. EXPECT_DEATH_IF_SUPPORTED(
  5797. {
  5798. GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
  5799. *GetUnitTestImpl()->listeners()))
  5800. << "expected failure";
  5801. },
  5802. "expected failure");
  5803. }
  5804. // Tests that a listener installed via SetDefaultResultPrinter() starts
  5805. // receiving events and is returned via default_result_printer() and that
  5806. // the previous default_result_printer is removed from the list and deleted.
  5807. TEST(EventListenerTest, default_result_printer) {
  5808. int on_start_counter = 0;
  5809. bool is_destroyed = false;
  5810. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5811. TestEventListeners listeners;
  5812. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5813. EXPECT_EQ(listener, listeners.default_result_printer());
  5814. TestEventListenersAccessor::GetRepeater(&listeners)
  5815. ->OnTestProgramStart(*UnitTest::GetInstance());
  5816. EXPECT_EQ(1, on_start_counter);
  5817. // Replacing default_result_printer with something else should remove it
  5818. // from the list and destroy it.
  5819. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
  5820. EXPECT_TRUE(listeners.default_result_printer() == nullptr);
  5821. EXPECT_TRUE(is_destroyed);
  5822. // After broadcasting an event the counter is still the same, indicating
  5823. // the listener is not in the list anymore.
  5824. TestEventListenersAccessor::GetRepeater(&listeners)
  5825. ->OnTestProgramStart(*UnitTest::GetInstance());
  5826. EXPECT_EQ(1, on_start_counter);
  5827. }
  5828. // Tests that the default_result_printer listener stops receiving events
  5829. // when removed via Release and that is not owned by the list anymore.
  5830. TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
  5831. int on_start_counter = 0;
  5832. bool is_destroyed = false;
  5833. // Although Append passes the ownership of this object to the list,
  5834. // the following calls release it, and we need to delete it before the
  5835. // test ends.
  5836. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5837. {
  5838. TestEventListeners listeners;
  5839. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
  5840. EXPECT_EQ(listener, listeners.Release(listener));
  5841. EXPECT_TRUE(listeners.default_result_printer() == nullptr);
  5842. EXPECT_FALSE(is_destroyed);
  5843. // Broadcasting events now should not affect default_result_printer.
  5844. TestEventListenersAccessor::GetRepeater(&listeners)
  5845. ->OnTestProgramStart(*UnitTest::GetInstance());
  5846. EXPECT_EQ(0, on_start_counter);
  5847. }
  5848. // Destroying the list should not affect the listener now, too.
  5849. EXPECT_FALSE(is_destroyed);
  5850. delete listener;
  5851. }
  5852. // Tests that a listener installed via SetDefaultXmlGenerator() starts
  5853. // receiving events and is returned via default_xml_generator() and that
  5854. // the previous default_xml_generator is removed from the list and deleted.
  5855. TEST(EventListenerTest, default_xml_generator) {
  5856. int on_start_counter = 0;
  5857. bool is_destroyed = false;
  5858. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5859. TestEventListeners listeners;
  5860. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5861. EXPECT_EQ(listener, listeners.default_xml_generator());
  5862. TestEventListenersAccessor::GetRepeater(&listeners)
  5863. ->OnTestProgramStart(*UnitTest::GetInstance());
  5864. EXPECT_EQ(1, on_start_counter);
  5865. // Replacing default_xml_generator with something else should remove it
  5866. // from the list and destroy it.
  5867. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
  5868. EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
  5869. EXPECT_TRUE(is_destroyed);
  5870. // After broadcasting an event the counter is still the same, indicating
  5871. // the listener is not in the list anymore.
  5872. TestEventListenersAccessor::GetRepeater(&listeners)
  5873. ->OnTestProgramStart(*UnitTest::GetInstance());
  5874. EXPECT_EQ(1, on_start_counter);
  5875. }
  5876. // Tests that the default_xml_generator listener stops receiving events
  5877. // when removed via Release and that is not owned by the list anymore.
  5878. TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
  5879. int on_start_counter = 0;
  5880. bool is_destroyed = false;
  5881. // Although Append passes the ownership of this object to the list,
  5882. // the following calls release it, and we need to delete it before the
  5883. // test ends.
  5884. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
  5885. {
  5886. TestEventListeners listeners;
  5887. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
  5888. EXPECT_EQ(listener, listeners.Release(listener));
  5889. EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
  5890. EXPECT_FALSE(is_destroyed);
  5891. // Broadcasting events now should not affect default_xml_generator.
  5892. TestEventListenersAccessor::GetRepeater(&listeners)
  5893. ->OnTestProgramStart(*UnitTest::GetInstance());
  5894. EXPECT_EQ(0, on_start_counter);
  5895. }
  5896. // Destroying the list should not affect the listener now, too.
  5897. EXPECT_FALSE(is_destroyed);
  5898. delete listener;
  5899. }
  5900. // Tests to ensure that the alternative, verbose spellings of
  5901. // some of the macros work. We don't test them thoroughly as that
  5902. // would be quite involved. Since their implementations are
  5903. // straightforward, and they are rarely used, we'll just rely on the
  5904. // users to tell us when they are broken.
  5905. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
  5906. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
  5907. // GTEST_FAIL is the same as FAIL.
  5908. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
  5909. "An expected failure");
  5910. // GTEST_ASSERT_XY is the same as ASSERT_XY.
  5911. GTEST_ASSERT_EQ(0, 0);
  5912. EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
  5913. "An expected failure");
  5914. EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
  5915. "An expected failure");
  5916. GTEST_ASSERT_NE(0, 1);
  5917. GTEST_ASSERT_NE(1, 0);
  5918. EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
  5919. "An expected failure");
  5920. GTEST_ASSERT_LE(0, 0);
  5921. GTEST_ASSERT_LE(0, 1);
  5922. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
  5923. "An expected failure");
  5924. GTEST_ASSERT_LT(0, 1);
  5925. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
  5926. "An expected failure");
  5927. EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
  5928. "An expected failure");
  5929. GTEST_ASSERT_GE(0, 0);
  5930. GTEST_ASSERT_GE(1, 0);
  5931. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
  5932. "An expected failure");
  5933. GTEST_ASSERT_GT(1, 0);
  5934. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
  5935. "An expected failure");
  5936. EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
  5937. "An expected failure");
  5938. }
  5939. // Tests for internal utilities necessary for implementation of the universal
  5940. // printing.
  5941. class ConversionHelperBase {};
  5942. class ConversionHelperDerived : public ConversionHelperBase {};
  5943. struct HasDebugStringMethods {
  5944. std::string DebugString() const { return ""; }
  5945. std::string ShortDebugString() const { return ""; }
  5946. };
  5947. struct InheritsDebugStringMethods : public HasDebugStringMethods {};
  5948. struct WrongTypeDebugStringMethod {
  5949. std::string DebugString() const { return ""; }
  5950. int ShortDebugString() const { return 1; }
  5951. };
  5952. struct NotConstDebugStringMethod {
  5953. std::string DebugString() { return ""; }
  5954. std::string ShortDebugString() const { return ""; }
  5955. };
  5956. struct MissingDebugStringMethod {
  5957. std::string DebugString() { return ""; }
  5958. };
  5959. struct IncompleteType;
  5960. // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
  5961. // constant.
  5962. TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
  5963. static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
  5964. "const_true");
  5965. static_assert(
  5966. HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
  5967. "const_true");
  5968. static_assert(HasDebugStringAndShortDebugString<
  5969. const InheritsDebugStringMethods>::value,
  5970. "const_true");
  5971. static_assert(
  5972. !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
  5973. "const_false");
  5974. static_assert(
  5975. !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
  5976. "const_false");
  5977. static_assert(
  5978. !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
  5979. "const_false");
  5980. static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value,
  5981. "const_false");
  5982. static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false");
  5983. }
  5984. // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
  5985. // needed methods.
  5986. TEST(HasDebugStringAndShortDebugStringTest,
  5987. ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
  5988. EXPECT_TRUE(
  5989. HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
  5990. }
  5991. // Tests that HasDebugStringAndShortDebugString<T>::value is false when T
  5992. // doesn't have needed methods.
  5993. TEST(HasDebugStringAndShortDebugStringTest,
  5994. ValueIsFalseWhenTypeIsNotAProtocolMessage) {
  5995. EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
  5996. EXPECT_FALSE(
  5997. HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
  5998. }
  5999. // Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
  6000. template <typename T1, typename T2>
  6001. void TestGTestRemoveReferenceAndConst() {
  6002. static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
  6003. "GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
  6004. }
  6005. TEST(RemoveReferenceToConstTest, Works) {
  6006. TestGTestRemoveReferenceAndConst<int, int>();
  6007. TestGTestRemoveReferenceAndConst<double, double&>();
  6008. TestGTestRemoveReferenceAndConst<char, const char>();
  6009. TestGTestRemoveReferenceAndConst<char, const char&>();
  6010. TestGTestRemoveReferenceAndConst<const char*, const char*>();
  6011. }
  6012. // Tests GTEST_REFERENCE_TO_CONST_.
  6013. template <typename T1, typename T2>
  6014. void TestGTestReferenceToConst() {
  6015. static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
  6016. "GTEST_REFERENCE_TO_CONST_ failed.");
  6017. }
  6018. TEST(GTestReferenceToConstTest, Works) {
  6019. TestGTestReferenceToConst<const char&, char>();
  6020. TestGTestReferenceToConst<const int&, const int>();
  6021. TestGTestReferenceToConst<const double&, double>();
  6022. TestGTestReferenceToConst<const std::string&, const std::string&>();
  6023. }
  6024. // Tests IsContainerTest.
  6025. class NonContainer {};
  6026. TEST(IsContainerTestTest, WorksForNonContainer) {
  6027. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
  6028. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
  6029. EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
  6030. }
  6031. TEST(IsContainerTestTest, WorksForContainer) {
  6032. EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));
  6033. EXPECT_EQ(sizeof(IsContainer),
  6034. sizeof(IsContainerTest<std::map<int, double>>(0)));
  6035. }
  6036. struct ConstOnlyContainerWithPointerIterator {
  6037. using const_iterator = int*;
  6038. const_iterator begin() const;
  6039. const_iterator end() const;
  6040. };
  6041. struct ConstOnlyContainerWithClassIterator {
  6042. struct const_iterator {
  6043. const int& operator*() const;
  6044. const_iterator& operator++(/* pre-increment */);
  6045. };
  6046. const_iterator begin() const;
  6047. const_iterator end() const;
  6048. };
  6049. TEST(IsContainerTestTest, ConstOnlyContainer) {
  6050. EXPECT_EQ(sizeof(IsContainer),
  6051. sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
  6052. EXPECT_EQ(sizeof(IsContainer),
  6053. sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
  6054. }
  6055. // Tests IsHashTable.
  6056. struct AHashTable {
  6057. typedef void hasher;
  6058. };
  6059. struct NotReallyAHashTable {
  6060. typedef void hasher;
  6061. typedef void reverse_iterator;
  6062. };
  6063. TEST(IsHashTable, Basic) {
  6064. EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
  6065. EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
  6066. EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
  6067. EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
  6068. }
  6069. // Tests ArrayEq().
  6070. TEST(ArrayEqTest, WorksForDegeneratedArrays) {
  6071. EXPECT_TRUE(ArrayEq(5, 5L));
  6072. EXPECT_FALSE(ArrayEq('a', 0));
  6073. }
  6074. TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
  6075. // Note that a and b are distinct but compatible types.
  6076. const int a[] = {0, 1};
  6077. long b[] = {0, 1};
  6078. EXPECT_TRUE(ArrayEq(a, b));
  6079. EXPECT_TRUE(ArrayEq(a, 2, b));
  6080. b[0] = 2;
  6081. EXPECT_FALSE(ArrayEq(a, b));
  6082. EXPECT_FALSE(ArrayEq(a, 1, b));
  6083. }
  6084. TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
  6085. const char a[][3] = {"hi", "lo"};
  6086. const char b[][3] = {"hi", "lo"};
  6087. const char c[][3] = {"hi", "li"};
  6088. EXPECT_TRUE(ArrayEq(a, b));
  6089. EXPECT_TRUE(ArrayEq(a, 2, b));
  6090. EXPECT_FALSE(ArrayEq(a, c));
  6091. EXPECT_FALSE(ArrayEq(a, 2, c));
  6092. }
  6093. // Tests ArrayAwareFind().
  6094. TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
  6095. const char a[] = "hello";
  6096. EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
  6097. EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
  6098. }
  6099. TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
  6100. int a[][2] = {{0, 1}, {2, 3}, {4, 5}};
  6101. const int b[2] = {2, 3};
  6102. EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
  6103. const int c[2] = {6, 7};
  6104. EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
  6105. }
  6106. // Tests CopyArray().
  6107. TEST(CopyArrayTest, WorksForDegeneratedArrays) {
  6108. int n = 0;
  6109. CopyArray('a', &n);
  6110. EXPECT_EQ('a', n);
  6111. }
  6112. TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
  6113. const char a[3] = "hi";
  6114. int b[3];
  6115. #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
  6116. CopyArray(a, &b);
  6117. EXPECT_TRUE(ArrayEq(a, b));
  6118. #endif
  6119. int c[3];
  6120. CopyArray(a, 3, c);
  6121. EXPECT_TRUE(ArrayEq(a, c));
  6122. }
  6123. TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
  6124. const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
  6125. int b[2][3];
  6126. #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
  6127. CopyArray(a, &b);
  6128. EXPECT_TRUE(ArrayEq(a, b));
  6129. #endif
  6130. int c[2][3];
  6131. CopyArray(a, 2, c);
  6132. EXPECT_TRUE(ArrayEq(a, c));
  6133. }
  6134. // Tests NativeArray.
  6135. TEST(NativeArrayTest, ConstructorFromArrayWorks) {
  6136. const int a[3] = {0, 1, 2};
  6137. NativeArray<int> na(a, 3, RelationToSourceReference());
  6138. EXPECT_EQ(3U, na.size());
  6139. EXPECT_EQ(a, na.begin());
  6140. }
  6141. TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
  6142. typedef int Array[2];
  6143. Array* a = new Array[1];
  6144. (*a)[0] = 0;
  6145. (*a)[1] = 1;
  6146. NativeArray<int> na(*a, 2, RelationToSourceCopy());
  6147. EXPECT_NE(*a, na.begin());
  6148. delete[] a;
  6149. EXPECT_EQ(0, na.begin()[0]);
  6150. EXPECT_EQ(1, na.begin()[1]);
  6151. // We rely on the heap checker to verify that na deletes the copy of
  6152. // array.
  6153. }
  6154. TEST(NativeArrayTest, TypeMembersAreCorrect) {
  6155. StaticAssertTypeEq<char, NativeArray<char>::value_type>();
  6156. StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
  6157. StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
  6158. StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
  6159. }
  6160. TEST(NativeArrayTest, MethodsWork) {
  6161. const int a[3] = {0, 1, 2};
  6162. NativeArray<int> na(a, 3, RelationToSourceCopy());
  6163. ASSERT_EQ(3U, na.size());
  6164. EXPECT_EQ(3, na.end() - na.begin());
  6165. NativeArray<int>::const_iterator it = na.begin();
  6166. EXPECT_EQ(0, *it);
  6167. ++it;
  6168. EXPECT_EQ(1, *it);
  6169. it++;
  6170. EXPECT_EQ(2, *it);
  6171. ++it;
  6172. EXPECT_EQ(na.end(), it);
  6173. EXPECT_TRUE(na == na);
  6174. NativeArray<int> na2(a, 3, RelationToSourceReference());
  6175. EXPECT_TRUE(na == na2);
  6176. const int b1[3] = {0, 1, 1};
  6177. const int b2[4] = {0, 1, 2, 3};
  6178. EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
  6179. EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
  6180. }
  6181. TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
  6182. const char a[2][3] = {"hi", "lo"};
  6183. NativeArray<char[3]> na(a, 2, RelationToSourceReference());
  6184. ASSERT_EQ(2U, na.size());
  6185. EXPECT_EQ(a, na.begin());
  6186. }
  6187. // ElemFromList
  6188. TEST(ElemFromList, Basic) {
  6189. using testing::internal::ElemFromList;
  6190. EXPECT_TRUE(
  6191. (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
  6192. EXPECT_TRUE(
  6193. (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
  6194. EXPECT_TRUE(
  6195. (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
  6196. EXPECT_TRUE((
  6197. std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
  6198. char, int, int, int, int>::type>::value));
  6199. }
  6200. // FlatTuple
  6201. TEST(FlatTuple, Basic) {
  6202. using testing::internal::FlatTuple;
  6203. FlatTuple<int, double, const char*> tuple = {};
  6204. EXPECT_EQ(0, tuple.Get<0>());
  6205. EXPECT_EQ(0.0, tuple.Get<1>());
  6206. EXPECT_EQ(nullptr, tuple.Get<2>());
  6207. tuple = FlatTuple<int, double, const char*>(
  6208. testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
  6209. EXPECT_EQ(7, tuple.Get<0>());
  6210. EXPECT_EQ(3.2, tuple.Get<1>());
  6211. EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
  6212. tuple.Get<1>() = 5.1;
  6213. EXPECT_EQ(5.1, tuple.Get<1>());
  6214. }
  6215. namespace {
  6216. std::string AddIntToString(int i, const std::string& s) {
  6217. return s + std::to_string(i);
  6218. }
  6219. } // namespace
  6220. TEST(FlatTuple, Apply) {
  6221. using testing::internal::FlatTuple;
  6222. FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
  6223. 5, "Hello"};
  6224. // Lambda.
  6225. EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
  6226. return i == static_cast<int>(s.size());
  6227. }));
  6228. // Function.
  6229. EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
  6230. // Mutating operations.
  6231. tuple.Apply([](int& i, std::string& s) {
  6232. ++i;
  6233. s += s;
  6234. });
  6235. EXPECT_EQ(tuple.Get<0>(), 6);
  6236. EXPECT_EQ(tuple.Get<1>(), "HelloHello");
  6237. }
  6238. struct ConstructionCounting {
  6239. ConstructionCounting() { ++default_ctor_calls; }
  6240. ~ConstructionCounting() { ++dtor_calls; }
  6241. ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
  6242. ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
  6243. ConstructionCounting& operator=(const ConstructionCounting&) {
  6244. ++copy_assignment_calls;
  6245. return *this;
  6246. }
  6247. ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
  6248. ++move_assignment_calls;
  6249. return *this;
  6250. }
  6251. static void Reset() {
  6252. default_ctor_calls = 0;
  6253. dtor_calls = 0;
  6254. copy_ctor_calls = 0;
  6255. move_ctor_calls = 0;
  6256. copy_assignment_calls = 0;
  6257. move_assignment_calls = 0;
  6258. }
  6259. static int default_ctor_calls;
  6260. static int dtor_calls;
  6261. static int copy_ctor_calls;
  6262. static int move_ctor_calls;
  6263. static int copy_assignment_calls;
  6264. static int move_assignment_calls;
  6265. };
  6266. int ConstructionCounting::default_ctor_calls = 0;
  6267. int ConstructionCounting::dtor_calls = 0;
  6268. int ConstructionCounting::copy_ctor_calls = 0;
  6269. int ConstructionCounting::move_ctor_calls = 0;
  6270. int ConstructionCounting::copy_assignment_calls = 0;
  6271. int ConstructionCounting::move_assignment_calls = 0;
  6272. TEST(FlatTuple, ConstructorCalls) {
  6273. using testing::internal::FlatTuple;
  6274. // Default construction.
  6275. ConstructionCounting::Reset();
  6276. { FlatTuple<ConstructionCounting> tuple; }
  6277. EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
  6278. EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
  6279. EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
  6280. EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
  6281. EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
  6282. EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
  6283. // Copy construction.
  6284. ConstructionCounting::Reset();
  6285. {
  6286. ConstructionCounting elem;
  6287. FlatTuple<ConstructionCounting> tuple{
  6288. testing::internal::FlatTupleConstructTag{}, elem};
  6289. }
  6290. EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
  6291. EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
  6292. EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
  6293. EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
  6294. EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
  6295. EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
  6296. // Move construction.
  6297. ConstructionCounting::Reset();
  6298. {
  6299. FlatTuple<ConstructionCounting> tuple{
  6300. testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
  6301. }
  6302. EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
  6303. EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
  6304. EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
  6305. EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
  6306. EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
  6307. EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
  6308. // Copy assignment.
  6309. // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
  6310. // elements
  6311. ConstructionCounting::Reset();
  6312. {
  6313. FlatTuple<ConstructionCounting> tuple;
  6314. ConstructionCounting elem;
  6315. tuple.Get<0>() = elem;
  6316. }
  6317. EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
  6318. EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
  6319. EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
  6320. EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
  6321. EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
  6322. EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
  6323. // Move assignment.
  6324. // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
  6325. // elements
  6326. ConstructionCounting::Reset();
  6327. {
  6328. FlatTuple<ConstructionCounting> tuple;
  6329. tuple.Get<0>() = ConstructionCounting{};
  6330. }
  6331. EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
  6332. EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
  6333. EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
  6334. EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
  6335. EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
  6336. EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
  6337. ConstructionCounting::Reset();
  6338. }
  6339. TEST(FlatTuple, ManyTypes) {
  6340. using testing::internal::FlatTuple;
  6341. // Instantiate FlatTuple with 257 ints.
  6342. // Tests show that we can do it with thousands of elements, but very long
  6343. // compile times makes it unusuitable for this test.
  6344. #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
  6345. #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
  6346. #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
  6347. #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
  6348. #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
  6349. #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
  6350. // Let's make sure that we can have a very long list of types without blowing
  6351. // up the template instantiation depth.
  6352. FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
  6353. tuple.Get<0>() = 7;
  6354. tuple.Get<99>() = 17;
  6355. tuple.Get<256>() = 1000;
  6356. EXPECT_EQ(7, tuple.Get<0>());
  6357. EXPECT_EQ(17, tuple.Get<99>());
  6358. EXPECT_EQ(1000, tuple.Get<256>());
  6359. }
  6360. // Tests SkipPrefix().
  6361. TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
  6362. const char* const str = "hello";
  6363. const char* p = str;
  6364. EXPECT_TRUE(SkipPrefix("", &p));
  6365. EXPECT_EQ(str, p);
  6366. p = str;
  6367. EXPECT_TRUE(SkipPrefix("hell", &p));
  6368. EXPECT_EQ(str + 4, p);
  6369. }
  6370. TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
  6371. const char* const str = "world";
  6372. const char* p = str;
  6373. EXPECT_FALSE(SkipPrefix("W", &p));
  6374. EXPECT_EQ(str, p);
  6375. p = str;
  6376. EXPECT_FALSE(SkipPrefix("world!", &p));
  6377. EXPECT_EQ(str, p);
  6378. }
  6379. // Tests ad_hoc_test_result().
  6380. TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
  6381. const testing::TestResult& test_result =
  6382. testing::UnitTest::GetInstance()->ad_hoc_test_result();
  6383. EXPECT_FALSE(test_result.Failed());
  6384. }
  6385. class DynamicUnitTestFixture : public testing::Test {};
  6386. class DynamicTest : public DynamicUnitTestFixture {
  6387. void TestBody() override { EXPECT_TRUE(true); }
  6388. };
  6389. auto* dynamic_test = testing::RegisterTest(
  6390. "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
  6391. __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
  6392. TEST(RegisterTest, WasRegistered) {
  6393. const auto& unittest = testing::UnitTest::GetInstance();
  6394. for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
  6395. auto* tests = unittest->GetTestSuite(i);
  6396. if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
  6397. for (int j = 0; j < tests->total_test_count(); ++j) {
  6398. if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
  6399. // Found it.
  6400. EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
  6401. EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
  6402. return;
  6403. }
  6404. }
  6405. FAIL() << "Didn't find the test!";
  6406. }
  6407. // Test that the pattern globbing algorithm is linear. If not, this test should
  6408. // time out.
  6409. TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
  6410. std::string name(100, 'a'); // Construct the string (a^100)b
  6411. name.push_back('b');
  6412. std::string pattern; // Construct the string ((a*)^100)b
  6413. for (int i = 0; i < 100; ++i) {
  6414. pattern.append("a*");
  6415. }
  6416. pattern.push_back('b');
  6417. EXPECT_TRUE(
  6418. testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));
  6419. }
  6420. TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
  6421. const std::string name = "aaaa";
  6422. EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*"));
  6423. EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:"));
  6424. EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab"));
  6425. EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:"));
  6426. EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*"));
  6427. }
  6428. TEST(PatternGlobbingTest, MatchesFilterEdgeCases) {
  6429. EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a"));
  6430. EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*"));
  6431. EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", ""));
  6432. EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", ""));
  6433. }