gtest_unittest.cc 254 KB

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