gtest_unittest.cc 242 KB

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