gtest_unittest.cc 234 KB

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