gtest_unittest.cc 245 KB

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