gtest_unittest.cc 257 KB

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