gmock-matchers.h 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623
  1. // Copyright 2007, 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. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // The MATCHER* family of macros can be used in a namespace scope to
  32. // define custom matchers easily.
  33. //
  34. // Basic Usage
  35. // ===========
  36. //
  37. // The syntax
  38. //
  39. // MATCHER(name, description_string) { statements; }
  40. //
  41. // defines a matcher with the given name that executes the statements,
  42. // which must return a bool to indicate if the match succeeds. Inside
  43. // the statements, you can refer to the value being matched by 'arg',
  44. // and refer to its type by 'arg_type'.
  45. //
  46. // The description string documents what the matcher does, and is used
  47. // to generate the failure message when the match fails. Since a
  48. // MATCHER() is usually defined in a header file shared by multiple
  49. // C++ source files, we require the description to be a C-string
  50. // literal to avoid possible side effects. It can be empty, in which
  51. // case we'll use the sequence of words in the matcher name as the
  52. // description.
  53. //
  54. // For example:
  55. //
  56. // MATCHER(IsEven, "") { return (arg % 2) == 0; }
  57. //
  58. // allows you to write
  59. //
  60. // // Expects mock_foo.Bar(n) to be called where n is even.
  61. // EXPECT_CALL(mock_foo, Bar(IsEven()));
  62. //
  63. // or,
  64. //
  65. // // Verifies that the value of some_expression is even.
  66. // EXPECT_THAT(some_expression, IsEven());
  67. //
  68. // If the above assertion fails, it will print something like:
  69. //
  70. // Value of: some_expression
  71. // Expected: is even
  72. // Actual: 7
  73. //
  74. // where the description "is even" is automatically calculated from the
  75. // matcher name IsEven.
  76. //
  77. // Argument Type
  78. // =============
  79. //
  80. // Note that the type of the value being matched (arg_type) is
  81. // determined by the context in which you use the matcher and is
  82. // supplied to you by the compiler, so you don't need to worry about
  83. // declaring it (nor can you). This allows the matcher to be
  84. // polymorphic. For example, IsEven() can be used to match any type
  85. // where the value of "(arg % 2) == 0" can be implicitly converted to
  86. // a bool. In the "Bar(IsEven())" example above, if method Bar()
  87. // takes an int, 'arg_type' will be int; if it takes an unsigned long,
  88. // 'arg_type' will be unsigned long; and so on.
  89. //
  90. // Parameterizing Matchers
  91. // =======================
  92. //
  93. // Sometimes you'll want to parameterize the matcher. For that you
  94. // can use another macro:
  95. //
  96. // MATCHER_P(name, param_name, description_string) { statements; }
  97. //
  98. // For example:
  99. //
  100. // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
  101. //
  102. // will allow you to write:
  103. //
  104. // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
  105. //
  106. // which may lead to this message (assuming n is 10):
  107. //
  108. // Value of: Blah("a")
  109. // Expected: has absolute value 10
  110. // Actual: -9
  111. //
  112. // Note that both the matcher description and its parameter are
  113. // printed, making the message human-friendly.
  114. //
  115. // In the matcher definition body, you can write 'foo_type' to
  116. // reference the type of a parameter named 'foo'. For example, in the
  117. // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
  118. // 'value_type' to refer to the type of 'value'.
  119. //
  120. // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
  121. // support multi-parameter matchers.
  122. //
  123. // Describing Parameterized Matchers
  124. // =================================
  125. //
  126. // The last argument to MATCHER*() is a string-typed expression. The
  127. // expression can reference all of the matcher's parameters and a
  128. // special bool-typed variable named 'negation'. When 'negation' is
  129. // false, the expression should evaluate to the matcher's description;
  130. // otherwise it should evaluate to the description of the negation of
  131. // the matcher. For example,
  132. //
  133. // using testing::PrintToString;
  134. //
  135. // MATCHER_P2(InClosedRange, low, hi,
  136. // std::string(negation ? "is not" : "is") + " in range [" +
  137. // PrintToString(low) + ", " + PrintToString(hi) + "]") {
  138. // return low <= arg && arg <= hi;
  139. // }
  140. // ...
  141. // EXPECT_THAT(3, InClosedRange(4, 6));
  142. // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
  143. //
  144. // would generate two failures that contain the text:
  145. //
  146. // Expected: is in range [4, 6]
  147. // ...
  148. // Expected: is not in range [2, 4]
  149. //
  150. // If you specify "" as the description, the failure message will
  151. // contain the sequence of words in the matcher name followed by the
  152. // parameter values printed as a tuple. For example,
  153. //
  154. // MATCHER_P2(InClosedRange, low, hi, "") { ... }
  155. // ...
  156. // EXPECT_THAT(3, InClosedRange(4, 6));
  157. // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
  158. //
  159. // would generate two failures that contain the text:
  160. //
  161. // Expected: in closed range (4, 6)
  162. // ...
  163. // Expected: not (in closed range (2, 4))
  164. //
  165. // Types of Matcher Parameters
  166. // ===========================
  167. //
  168. // For the purpose of typing, you can view
  169. //
  170. // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
  171. //
  172. // as shorthand for
  173. //
  174. // template <typename p1_type, ..., typename pk_type>
  175. // FooMatcherPk<p1_type, ..., pk_type>
  176. // Foo(p1_type p1, ..., pk_type pk) { ... }
  177. //
  178. // When you write Foo(v1, ..., vk), the compiler infers the types of
  179. // the parameters v1, ..., and vk for you. If you are not happy with
  180. // the result of the type inference, you can specify the types by
  181. // explicitly instantiating the template, as in Foo<long, bool>(5,
  182. // false). As said earlier, you don't get to (or need to) specify
  183. // 'arg_type' as that's determined by the context in which the matcher
  184. // is used. You can assign the result of expression Foo(p1, ..., pk)
  185. // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
  186. // can be useful when composing matchers.
  187. //
  188. // While you can instantiate a matcher template with reference types,
  189. // passing the parameters by pointer usually makes your code more
  190. // readable. If, however, you still want to pass a parameter by
  191. // reference, be aware that in the failure message generated by the
  192. // matcher you will see the value of the referenced object but not its
  193. // address.
  194. //
  195. // Explaining Match Results
  196. // ========================
  197. //
  198. // Sometimes the matcher description alone isn't enough to explain why
  199. // the match has failed or succeeded. For example, when expecting a
  200. // long string, it can be very helpful to also print the diff between
  201. // the expected string and the actual one. To achieve that, you can
  202. // optionally stream additional information to a special variable
  203. // named result_listener, whose type is a pointer to class
  204. // MatchResultListener:
  205. //
  206. // MATCHER_P(EqualsLongString, str, "") {
  207. // if (arg == str) return true;
  208. //
  209. // *result_listener << "the difference: "
  210. /// << DiffStrings(str, arg);
  211. // return false;
  212. // }
  213. //
  214. // Overloading Matchers
  215. // ====================
  216. //
  217. // You can overload matchers with different numbers of parameters:
  218. //
  219. // MATCHER_P(Blah, a, description_string1) { ... }
  220. // MATCHER_P2(Blah, a, b, description_string2) { ... }
  221. //
  222. // Caveats
  223. // =======
  224. //
  225. // When defining a new matcher, you should also consider implementing
  226. // MatcherInterface or using MakePolymorphicMatcher(). These
  227. // approaches require more work than the MATCHER* macros, but also
  228. // give you more control on the types of the value being matched and
  229. // the matcher parameters, which may leads to better compiler error
  230. // messages when the matcher is used wrong. They also allow
  231. // overloading matchers based on parameter types (as opposed to just
  232. // based on the number of parameters).
  233. //
  234. // MATCHER*() can only be used in a namespace scope as templates cannot be
  235. // declared inside of a local class.
  236. //
  237. // More Information
  238. // ================
  239. //
  240. // To learn more about using these macros, please search for 'MATCHER'
  241. // on
  242. // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
  243. //
  244. // This file also implements some commonly used argument matchers. More
  245. // matchers can be defined by the user implementing the
  246. // MatcherInterface<T> interface if necessary.
  247. //
  248. // See googletest/include/gtest/gtest-matchers.h for the definition of class
  249. // Matcher, class MatcherInterface, and others.
  250. // IWYU pragma: private, include "gmock/gmock.h"
  251. // IWYU pragma: friend gmock/.*
  252. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  253. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  254. #include <algorithm>
  255. #include <cmath>
  256. #include <exception>
  257. #include <functional>
  258. #include <initializer_list>
  259. #include <ios>
  260. #include <iterator>
  261. #include <limits>
  262. #include <memory>
  263. #include <ostream> // NOLINT
  264. #include <sstream>
  265. #include <string>
  266. #include <type_traits>
  267. #include <utility>
  268. #include <vector>
  269. #include "gmock/internal/gmock-internal-utils.h"
  270. #include "gmock/internal/gmock-port.h"
  271. #include "gmock/internal/gmock-pp.h"
  272. #include "gtest/gtest.h"
  273. // MSVC warning C5046 is new as of VS2017 version 15.8.
  274. #if defined(_MSC_VER) && _MSC_VER >= 1915
  275. #define GMOCK_MAYBE_5046_ 5046
  276. #else
  277. #define GMOCK_MAYBE_5046_
  278. #endif
  279. GTEST_DISABLE_MSC_WARNINGS_PUSH_(
  280. 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by
  281. clients of class B */
  282. /* Symbol involving type with internal linkage not defined */)
  283. namespace testing {
  284. // To implement a matcher Foo for type T, define:
  285. // 1. a class FooMatcherImpl that implements the
  286. // MatcherInterface<T> interface, and
  287. // 2. a factory function that creates a Matcher<T> object from a
  288. // FooMatcherImpl*.
  289. //
  290. // The two-level delegation design makes it possible to allow a user
  291. // to write "v" instead of "Eq(v)" where a Matcher is expected, which
  292. // is impossible if we pass matchers by pointers. It also eases
  293. // ownership management as Matcher objects can now be copied like
  294. // plain values.
  295. // A match result listener that stores the explanation in a string.
  296. class StringMatchResultListener : public MatchResultListener {
  297. public:
  298. StringMatchResultListener() : MatchResultListener(&ss_) {}
  299. // Returns the explanation accumulated so far.
  300. std::string str() const { return ss_.str(); }
  301. // Clears the explanation accumulated so far.
  302. void Clear() { ss_.str(""); }
  303. private:
  304. ::std::stringstream ss_;
  305. StringMatchResultListener(const StringMatchResultListener&) = delete;
  306. StringMatchResultListener& operator=(const StringMatchResultListener&) =
  307. delete;
  308. };
  309. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  310. // and MUST NOT BE USED IN USER CODE!!!
  311. namespace internal {
  312. // The MatcherCastImpl class template is a helper for implementing
  313. // MatcherCast(). We need this helper in order to partially
  314. // specialize the implementation of MatcherCast() (C++ allows
  315. // class/struct templates to be partially specialized, but not
  316. // function templates.).
  317. // This general version is used when MatcherCast()'s argument is a
  318. // polymorphic matcher (i.e. something that can be converted to a
  319. // Matcher but is not one yet; for example, Eq(value)) or a value (for
  320. // example, "hello").
  321. template <typename T, typename M>
  322. class MatcherCastImpl {
  323. public:
  324. static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
  325. // M can be a polymorphic matcher, in which case we want to use
  326. // its conversion operator to create Matcher<T>. Or it can be a value
  327. // that should be passed to the Matcher<T>'s constructor.
  328. //
  329. // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
  330. // polymorphic matcher because it'll be ambiguous if T has an implicit
  331. // constructor from M (this usually happens when T has an implicit
  332. // constructor from any type).
  333. //
  334. // It won't work to unconditionally implicit_cast
  335. // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
  336. // a user-defined conversion from M to T if one exists (assuming M is
  337. // a value).
  338. return CastImpl(polymorphic_matcher_or_value,
  339. std::is_convertible<M, Matcher<T>>{},
  340. std::is_convertible<M, T>{});
  341. }
  342. private:
  343. template <bool Ignore>
  344. static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
  345. std::true_type /* convertible_to_matcher */,
  346. std::integral_constant<bool, Ignore>) {
  347. // M is implicitly convertible to Matcher<T>, which means that either
  348. // M is a polymorphic matcher or Matcher<T> has an implicit constructor
  349. // from M. In both cases using the implicit conversion will produce a
  350. // matcher.
  351. //
  352. // Even if T has an implicit constructor from M, it won't be called because
  353. // creating Matcher<T> would require a chain of two user-defined conversions
  354. // (first to create T from M and then to create Matcher<T> from T).
  355. return polymorphic_matcher_or_value;
  356. }
  357. // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
  358. // matcher. It's a value of a type implicitly convertible to T. Use direct
  359. // initialization to create a matcher.
  360. static Matcher<T> CastImpl(const M& value,
  361. std::false_type /* convertible_to_matcher */,
  362. std::true_type /* convertible_to_T */) {
  363. return Matcher<T>(ImplicitCast_<T>(value));
  364. }
  365. // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
  366. // polymorphic matcher Eq(value) in this case.
  367. //
  368. // Note that we first attempt to perform an implicit cast on the value and
  369. // only fall back to the polymorphic Eq() matcher afterwards because the
  370. // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
  371. // which might be undefined even when Rhs is implicitly convertible to Lhs
  372. // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
  373. //
  374. // We don't define this method inline as we need the declaration of Eq().
  375. static Matcher<T> CastImpl(const M& value,
  376. std::false_type /* convertible_to_matcher */,
  377. std::false_type /* convertible_to_T */);
  378. };
  379. // This more specialized version is used when MatcherCast()'s argument
  380. // is already a Matcher. This only compiles when type T can be
  381. // statically converted to type U.
  382. template <typename T, typename U>
  383. class MatcherCastImpl<T, Matcher<U>> {
  384. public:
  385. static Matcher<T> Cast(const Matcher<U>& source_matcher) {
  386. return Matcher<T>(new Impl(source_matcher));
  387. }
  388. private:
  389. class Impl : public MatcherInterface<T> {
  390. public:
  391. explicit Impl(const Matcher<U>& source_matcher)
  392. : source_matcher_(source_matcher) {}
  393. // We delegate the matching logic to the source matcher.
  394. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  395. using FromType = typename std::remove_cv<typename std::remove_pointer<
  396. typename std::remove_reference<T>::type>::type>::type;
  397. using ToType = typename std::remove_cv<typename std::remove_pointer<
  398. typename std::remove_reference<U>::type>::type>::type;
  399. // Do not allow implicitly converting base*/& to derived*/&.
  400. static_assert(
  401. // Do not trigger if only one of them is a pointer. That implies a
  402. // regular conversion and not a down_cast.
  403. (std::is_pointer<typename std::remove_reference<T>::type>::value !=
  404. std::is_pointer<typename std::remove_reference<U>::type>::value) ||
  405. std::is_same<FromType, ToType>::value ||
  406. !std::is_base_of<FromType, ToType>::value,
  407. "Can't implicitly convert from <base> to <derived>");
  408. // Do the cast to `U` explicitly if necessary.
  409. // Otherwise, let implicit conversions do the trick.
  410. using CastType =
  411. typename std::conditional<std::is_convertible<T&, const U&>::value,
  412. T&, U>::type;
  413. return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
  414. listener);
  415. }
  416. void DescribeTo(::std::ostream* os) const override {
  417. source_matcher_.DescribeTo(os);
  418. }
  419. void DescribeNegationTo(::std::ostream* os) const override {
  420. source_matcher_.DescribeNegationTo(os);
  421. }
  422. private:
  423. const Matcher<U> source_matcher_;
  424. };
  425. };
  426. // This even more specialized version is used for efficiently casting
  427. // a matcher to its own type.
  428. template <typename T>
  429. class MatcherCastImpl<T, Matcher<T>> {
  430. public:
  431. static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
  432. };
  433. // Template specialization for parameterless Matcher.
  434. template <typename Derived>
  435. class MatcherBaseImpl {
  436. public:
  437. MatcherBaseImpl() = default;
  438. template <typename T>
  439. operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
  440. return ::testing::Matcher<T>(new
  441. typename Derived::template gmock_Impl<T>());
  442. }
  443. };
  444. // Template specialization for Matcher with parameters.
  445. template <template <typename...> class Derived, typename... Ts>
  446. class MatcherBaseImpl<Derived<Ts...>> {
  447. public:
  448. // Mark the constructor explicit for single argument T to avoid implicit
  449. // conversions.
  450. template <typename E = std::enable_if<sizeof...(Ts) == 1>,
  451. typename E::type* = nullptr>
  452. explicit MatcherBaseImpl(Ts... params)
  453. : params_(std::forward<Ts>(params)...) {}
  454. template <typename E = std::enable_if<sizeof...(Ts) != 1>,
  455. typename = typename E::type>
  456. MatcherBaseImpl(Ts... params) // NOLINT
  457. : params_(std::forward<Ts>(params)...) {}
  458. template <typename F>
  459. operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
  460. return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
  461. }
  462. private:
  463. template <typename F, std::size_t... tuple_ids>
  464. ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
  465. return ::testing::Matcher<F>(
  466. new typename Derived<Ts...>::template gmock_Impl<F>(
  467. std::get<tuple_ids>(params_)...));
  468. }
  469. const std::tuple<Ts...> params_;
  470. };
  471. } // namespace internal
  472. // In order to be safe and clear, casting between different matcher
  473. // types is done explicitly via MatcherCast<T>(m), which takes a
  474. // matcher m and returns a Matcher<T>. It compiles only when T can be
  475. // statically converted to the argument type of m.
  476. template <typename T, typename M>
  477. inline Matcher<T> MatcherCast(const M& matcher) {
  478. return internal::MatcherCastImpl<T, M>::Cast(matcher);
  479. }
  480. // This overload handles polymorphic matchers and values only since
  481. // monomorphic matchers are handled by the next one.
  482. template <typename T, typename M>
  483. inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
  484. return MatcherCast<T>(polymorphic_matcher_or_value);
  485. }
  486. // This overload handles monomorphic matchers.
  487. //
  488. // In general, if type T can be implicitly converted to type U, we can
  489. // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
  490. // contravariant): just keep a copy of the original Matcher<U>, convert the
  491. // argument from type T to U, and then pass it to the underlying Matcher<U>.
  492. // The only exception is when U is a reference and T is not, as the
  493. // underlying Matcher<U> may be interested in the argument's address, which
  494. // is not preserved in the conversion from T to U.
  495. template <typename T, typename U>
  496. inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
  497. // Enforce that T can be implicitly converted to U.
  498. static_assert(std::is_convertible<const T&, const U&>::value,
  499. "T must be implicitly convertible to U");
  500. // Enforce that we are not converting a non-reference type T to a reference
  501. // type U.
  502. static_assert(std::is_reference<T>::value || !std::is_reference<U>::value,
  503. "cannot convert non reference arg to reference");
  504. // In case both T and U are arithmetic types, enforce that the
  505. // conversion is not lossy.
  506. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
  507. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
  508. constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
  509. constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
  510. static_assert(
  511. kTIsOther || kUIsOther ||
  512. (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
  513. "conversion of arithmetic types must be lossless");
  514. return MatcherCast<T>(matcher);
  515. }
  516. // A<T>() returns a matcher that matches any value of type T.
  517. template <typename T>
  518. Matcher<T> A();
  519. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  520. // and MUST NOT BE USED IN USER CODE!!!
  521. namespace internal {
  522. // If the explanation is not empty, prints it to the ostream.
  523. inline void PrintIfNotEmpty(const std::string& explanation,
  524. ::std::ostream* os) {
  525. if (!explanation.empty() && os != nullptr) {
  526. *os << ", " << explanation;
  527. }
  528. }
  529. // Returns true if the given type name is easy to read by a human.
  530. // This is used to decide whether printing the type of a value might
  531. // be helpful.
  532. inline bool IsReadableTypeName(const std::string& type_name) {
  533. // We consider a type name readable if it's short or doesn't contain
  534. // a template or function type.
  535. return (type_name.length() <= 20 ||
  536. type_name.find_first_of("<(") == std::string::npos);
  537. }
  538. // Matches the value against the given matcher, prints the value and explains
  539. // the match result to the listener. Returns the match result.
  540. // 'listener' must not be NULL.
  541. // Value cannot be passed by const reference, because some matchers take a
  542. // non-const argument.
  543. template <typename Value, typename T>
  544. bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
  545. MatchResultListener* listener) {
  546. if (!listener->IsInterested()) {
  547. // If the listener is not interested, we do not need to construct the
  548. // inner explanation.
  549. return matcher.Matches(value);
  550. }
  551. StringMatchResultListener inner_listener;
  552. const bool match = matcher.MatchAndExplain(value, &inner_listener);
  553. UniversalPrint(value, listener->stream());
  554. #if GTEST_HAS_RTTI
  555. const std::string& type_name = GetTypeName<Value>();
  556. if (IsReadableTypeName(type_name))
  557. *listener->stream() << " (of type " << type_name << ")";
  558. #endif
  559. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  560. return match;
  561. }
  562. // An internal helper class for doing compile-time loop on a tuple's
  563. // fields.
  564. template <size_t N>
  565. class TuplePrefix {
  566. public:
  567. // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
  568. // if and only if the first N fields of matcher_tuple matches
  569. // the first N fields of value_tuple, respectively.
  570. template <typename MatcherTuple, typename ValueTuple>
  571. static bool Matches(const MatcherTuple& matcher_tuple,
  572. const ValueTuple& value_tuple) {
  573. return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&
  574. std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));
  575. }
  576. // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
  577. // describes failures in matching the first N fields of matchers
  578. // against the first N fields of values. If there is no failure,
  579. // nothing will be streamed to os.
  580. template <typename MatcherTuple, typename ValueTuple>
  581. static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
  582. const ValueTuple& values,
  583. ::std::ostream* os) {
  584. // First, describes failures in the first N - 1 fields.
  585. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
  586. // Then describes the failure (if any) in the (N - 1)-th (0-based)
  587. // field.
  588. typename std::tuple_element<N - 1, MatcherTuple>::type matcher =
  589. std::get<N - 1>(matchers);
  590. typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;
  591. const Value& value = std::get<N - 1>(values);
  592. StringMatchResultListener listener;
  593. if (!matcher.MatchAndExplain(value, &listener)) {
  594. *os << " Expected arg #" << N - 1 << ": ";
  595. std::get<N - 1>(matchers).DescribeTo(os);
  596. *os << "\n Actual: ";
  597. // We remove the reference in type Value to prevent the
  598. // universal printer from printing the address of value, which
  599. // isn't interesting to the user most of the time. The
  600. // matcher's MatchAndExplain() method handles the case when
  601. // the address is interesting.
  602. internal::UniversalPrint(value, os);
  603. PrintIfNotEmpty(listener.str(), os);
  604. *os << "\n";
  605. }
  606. }
  607. };
  608. // The base case.
  609. template <>
  610. class TuplePrefix<0> {
  611. public:
  612. template <typename MatcherTuple, typename ValueTuple>
  613. static bool Matches(const MatcherTuple& /* matcher_tuple */,
  614. const ValueTuple& /* value_tuple */) {
  615. return true;
  616. }
  617. template <typename MatcherTuple, typename ValueTuple>
  618. static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
  619. const ValueTuple& /* values */,
  620. ::std::ostream* /* os */) {}
  621. };
  622. // TupleMatches(matcher_tuple, value_tuple) returns true if and only if
  623. // all matchers in matcher_tuple match the corresponding fields in
  624. // value_tuple. It is a compiler error if matcher_tuple and
  625. // value_tuple have different number of fields or incompatible field
  626. // types.
  627. template <typename MatcherTuple, typename ValueTuple>
  628. bool TupleMatches(const MatcherTuple& matcher_tuple,
  629. const ValueTuple& value_tuple) {
  630. // Makes sure that matcher_tuple and value_tuple have the same
  631. // number of fields.
  632. static_assert(std::tuple_size<MatcherTuple>::value ==
  633. std::tuple_size<ValueTuple>::value,
  634. "matcher and value have different numbers of fields");
  635. return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
  636. value_tuple);
  637. }
  638. // Describes failures in matching matchers against values. If there
  639. // is no failure, nothing will be streamed to os.
  640. template <typename MatcherTuple, typename ValueTuple>
  641. void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
  642. const ValueTuple& values, ::std::ostream* os) {
  643. TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
  644. matchers, values, os);
  645. }
  646. // TransformTupleValues and its helper.
  647. //
  648. // TransformTupleValuesHelper hides the internal machinery that
  649. // TransformTupleValues uses to implement a tuple traversal.
  650. template <typename Tuple, typename Func, typename OutIter>
  651. class TransformTupleValuesHelper {
  652. private:
  653. typedef ::std::tuple_size<Tuple> TupleSize;
  654. public:
  655. // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
  656. // Returns the final value of 'out' in case the caller needs it.
  657. static OutIter Run(Func f, const Tuple& t, OutIter out) {
  658. return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
  659. }
  660. private:
  661. template <typename Tup, size_t kRemainingSize>
  662. struct IterateOverTuple {
  663. OutIter operator()(Func f, const Tup& t, OutIter out) const {
  664. *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
  665. return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
  666. }
  667. };
  668. template <typename Tup>
  669. struct IterateOverTuple<Tup, 0> {
  670. OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const {
  671. return out;
  672. }
  673. };
  674. };
  675. // Successively invokes 'f(element)' on each element of the tuple 't',
  676. // appending each result to the 'out' iterator. Returns the final value
  677. // of 'out'.
  678. template <typename Tuple, typename Func, typename OutIter>
  679. OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
  680. return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
  681. }
  682. // Implements _, a matcher that matches any value of any
  683. // type. This is a polymorphic matcher, so we need a template type
  684. // conversion operator to make it appearing as a Matcher<T> for any
  685. // type T.
  686. class AnythingMatcher {
  687. public:
  688. using is_gtest_matcher = void;
  689. template <typename T>
  690. bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
  691. return true;
  692. }
  693. void DescribeTo(std::ostream* os) const { *os << "is anything"; }
  694. void DescribeNegationTo(::std::ostream* os) const {
  695. // This is mostly for completeness' sake, as it's not very useful
  696. // to write Not(A<bool>()). However we cannot completely rule out
  697. // such a possibility, and it doesn't hurt to be prepared.
  698. *os << "never matches";
  699. }
  700. };
  701. // Implements the polymorphic IsNull() matcher, which matches any raw or smart
  702. // pointer that is NULL.
  703. class IsNullMatcher {
  704. public:
  705. template <typename Pointer>
  706. bool MatchAndExplain(const Pointer& p,
  707. MatchResultListener* /* listener */) const {
  708. return p == nullptr;
  709. }
  710. void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
  711. void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; }
  712. };
  713. // Implements the polymorphic NotNull() matcher, which matches any raw or smart
  714. // pointer that is not NULL.
  715. class NotNullMatcher {
  716. public:
  717. template <typename Pointer>
  718. bool MatchAndExplain(const Pointer& p,
  719. MatchResultListener* /* listener */) const {
  720. return p != nullptr;
  721. }
  722. void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
  723. void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
  724. };
  725. // Ref(variable) matches any argument that is a reference to
  726. // 'variable'. This matcher is polymorphic as it can match any
  727. // super type of the type of 'variable'.
  728. //
  729. // The RefMatcher template class implements Ref(variable). It can
  730. // only be instantiated with a reference type. This prevents a user
  731. // from mistakenly using Ref(x) to match a non-reference function
  732. // argument. For example, the following will righteously cause a
  733. // compiler error:
  734. //
  735. // int n;
  736. // Matcher<int> m1 = Ref(n); // This won't compile.
  737. // Matcher<int&> m2 = Ref(n); // This will compile.
  738. template <typename T>
  739. class RefMatcher;
  740. template <typename T>
  741. class RefMatcher<T&> {
  742. // Google Mock is a generic framework and thus needs to support
  743. // mocking any function types, including those that take non-const
  744. // reference arguments. Therefore the template parameter T (and
  745. // Super below) can be instantiated to either a const type or a
  746. // non-const type.
  747. public:
  748. // RefMatcher() takes a T& instead of const T&, as we want the
  749. // compiler to catch using Ref(const_value) as a matcher for a
  750. // non-const reference.
  751. explicit RefMatcher(T& x) : object_(x) {} // NOLINT
  752. template <typename Super>
  753. operator Matcher<Super&>() const {
  754. // By passing object_ (type T&) to Impl(), which expects a Super&,
  755. // we make sure that Super is a super type of T. In particular,
  756. // this catches using Ref(const_value) as a matcher for a
  757. // non-const reference, as you cannot implicitly convert a const
  758. // reference to a non-const reference.
  759. return MakeMatcher(new Impl<Super>(object_));
  760. }
  761. private:
  762. template <typename Super>
  763. class Impl : public MatcherInterface<Super&> {
  764. public:
  765. explicit Impl(Super& x) : object_(x) {} // NOLINT
  766. // MatchAndExplain() takes a Super& (as opposed to const Super&)
  767. // in order to match the interface MatcherInterface<Super&>.
  768. bool MatchAndExplain(Super& x,
  769. MatchResultListener* listener) const override {
  770. *listener << "which is located @" << static_cast<const void*>(&x);
  771. return &x == &object_;
  772. }
  773. void DescribeTo(::std::ostream* os) const override {
  774. *os << "references the variable ";
  775. UniversalPrinter<Super&>::Print(object_, os);
  776. }
  777. void DescribeNegationTo(::std::ostream* os) const override {
  778. *os << "does not reference the variable ";
  779. UniversalPrinter<Super&>::Print(object_, os);
  780. }
  781. private:
  782. const Super& object_;
  783. };
  784. T& object_;
  785. };
  786. // Polymorphic helper functions for narrow and wide string matchers.
  787. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
  788. return String::CaseInsensitiveCStringEquals(lhs, rhs);
  789. }
  790. inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
  791. const wchar_t* rhs) {
  792. return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
  793. }
  794. // String comparison for narrow or wide strings that can have embedded NUL
  795. // characters.
  796. template <typename StringType>
  797. bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) {
  798. // Are the heads equal?
  799. if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
  800. return false;
  801. }
  802. // Skip the equal heads.
  803. const typename StringType::value_type nul = 0;
  804. const size_t i1 = s1.find(nul), i2 = s2.find(nul);
  805. // Are we at the end of either s1 or s2?
  806. if (i1 == StringType::npos || i2 == StringType::npos) {
  807. return i1 == i2;
  808. }
  809. // Are the tails equal?
  810. return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
  811. }
  812. // String matchers.
  813. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
  814. template <typename StringType>
  815. class StrEqualityMatcher {
  816. public:
  817. StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
  818. : string_(std::move(str)),
  819. expect_eq_(expect_eq),
  820. case_sensitive_(case_sensitive) {}
  821. #if GTEST_INTERNAL_HAS_STRING_VIEW
  822. bool MatchAndExplain(const internal::StringView& s,
  823. MatchResultListener* listener) const {
  824. // This should fail to compile if StringView is used with wide
  825. // strings.
  826. const StringType& str = std::string(s);
  827. return MatchAndExplain(str, listener);
  828. }
  829. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  830. // Accepts pointer types, particularly:
  831. // const char*
  832. // char*
  833. // const wchar_t*
  834. // wchar_t*
  835. template <typename CharType>
  836. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  837. if (s == nullptr) {
  838. return !expect_eq_;
  839. }
  840. return MatchAndExplain(StringType(s), listener);
  841. }
  842. // Matches anything that can convert to StringType.
  843. //
  844. // This is a template, not just a plain function with const StringType&,
  845. // because StringView has some interfering non-explicit constructors.
  846. template <typename MatcheeStringType>
  847. bool MatchAndExplain(const MatcheeStringType& s,
  848. MatchResultListener* /* listener */) const {
  849. const StringType s2(s);
  850. const bool eq = case_sensitive_ ? s2 == string_
  851. : CaseInsensitiveStringEquals(s2, string_);
  852. return expect_eq_ == eq;
  853. }
  854. void DescribeTo(::std::ostream* os) const {
  855. DescribeToHelper(expect_eq_, os);
  856. }
  857. void DescribeNegationTo(::std::ostream* os) const {
  858. DescribeToHelper(!expect_eq_, os);
  859. }
  860. private:
  861. void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
  862. *os << (expect_eq ? "is " : "isn't ");
  863. *os << "equal to ";
  864. if (!case_sensitive_) {
  865. *os << "(ignoring case) ";
  866. }
  867. UniversalPrint(string_, os);
  868. }
  869. const StringType string_;
  870. const bool expect_eq_;
  871. const bool case_sensitive_;
  872. };
  873. // Implements the polymorphic HasSubstr(substring) matcher, which
  874. // can be used as a Matcher<T> as long as T can be converted to a
  875. // string.
  876. template <typename StringType>
  877. class HasSubstrMatcher {
  878. public:
  879. explicit HasSubstrMatcher(const StringType& substring)
  880. : substring_(substring) {}
  881. #if GTEST_INTERNAL_HAS_STRING_VIEW
  882. bool MatchAndExplain(const internal::StringView& s,
  883. MatchResultListener* listener) const {
  884. // This should fail to compile if StringView is used with wide
  885. // strings.
  886. const StringType& str = std::string(s);
  887. return MatchAndExplain(str, listener);
  888. }
  889. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  890. // Accepts pointer types, particularly:
  891. // const char*
  892. // char*
  893. // const wchar_t*
  894. // wchar_t*
  895. template <typename CharType>
  896. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  897. return s != nullptr && MatchAndExplain(StringType(s), listener);
  898. }
  899. // Matches anything that can convert to StringType.
  900. //
  901. // This is a template, not just a plain function with const StringType&,
  902. // because StringView has some interfering non-explicit constructors.
  903. template <typename MatcheeStringType>
  904. bool MatchAndExplain(const MatcheeStringType& s,
  905. MatchResultListener* /* listener */) const {
  906. return StringType(s).find(substring_) != StringType::npos;
  907. }
  908. // Describes what this matcher matches.
  909. void DescribeTo(::std::ostream* os) const {
  910. *os << "has substring ";
  911. UniversalPrint(substring_, os);
  912. }
  913. void DescribeNegationTo(::std::ostream* os) const {
  914. *os << "has no substring ";
  915. UniversalPrint(substring_, os);
  916. }
  917. private:
  918. const StringType substring_;
  919. };
  920. // Implements the polymorphic StartsWith(substring) matcher, which
  921. // can be used as a Matcher<T> as long as T can be converted to a
  922. // string.
  923. template <typename StringType>
  924. class StartsWithMatcher {
  925. public:
  926. explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}
  927. #if GTEST_INTERNAL_HAS_STRING_VIEW
  928. bool MatchAndExplain(const internal::StringView& s,
  929. MatchResultListener* listener) const {
  930. // This should fail to compile if StringView is used with wide
  931. // strings.
  932. const StringType& str = std::string(s);
  933. return MatchAndExplain(str, listener);
  934. }
  935. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  936. // Accepts pointer types, particularly:
  937. // const char*
  938. // char*
  939. // const wchar_t*
  940. // wchar_t*
  941. template <typename CharType>
  942. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  943. return s != nullptr && MatchAndExplain(StringType(s), listener);
  944. }
  945. // Matches anything that can convert to StringType.
  946. //
  947. // This is a template, not just a plain function with const StringType&,
  948. // because StringView has some interfering non-explicit constructors.
  949. template <typename MatcheeStringType>
  950. bool MatchAndExplain(const MatcheeStringType& s,
  951. MatchResultListener* /* listener */) const {
  952. const StringType& s2(s);
  953. return s2.length() >= prefix_.length() &&
  954. s2.substr(0, prefix_.length()) == prefix_;
  955. }
  956. void DescribeTo(::std::ostream* os) const {
  957. *os << "starts with ";
  958. UniversalPrint(prefix_, os);
  959. }
  960. void DescribeNegationTo(::std::ostream* os) const {
  961. *os << "doesn't start with ";
  962. UniversalPrint(prefix_, os);
  963. }
  964. private:
  965. const StringType prefix_;
  966. };
  967. // Implements the polymorphic EndsWith(substring) matcher, which
  968. // can be used as a Matcher<T> as long as T can be converted to a
  969. // string.
  970. template <typename StringType>
  971. class EndsWithMatcher {
  972. public:
  973. explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
  974. #if GTEST_INTERNAL_HAS_STRING_VIEW
  975. bool MatchAndExplain(const internal::StringView& s,
  976. MatchResultListener* listener) const {
  977. // This should fail to compile if StringView is used with wide
  978. // strings.
  979. const StringType& str = std::string(s);
  980. return MatchAndExplain(str, listener);
  981. }
  982. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  983. // Accepts pointer types, particularly:
  984. // const char*
  985. // char*
  986. // const wchar_t*
  987. // wchar_t*
  988. template <typename CharType>
  989. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  990. return s != nullptr && MatchAndExplain(StringType(s), listener);
  991. }
  992. // Matches anything that can convert to StringType.
  993. //
  994. // This is a template, not just a plain function with const StringType&,
  995. // because StringView has some interfering non-explicit constructors.
  996. template <typename MatcheeStringType>
  997. bool MatchAndExplain(const MatcheeStringType& s,
  998. MatchResultListener* /* listener */) const {
  999. const StringType& s2(s);
  1000. return s2.length() >= suffix_.length() &&
  1001. s2.substr(s2.length() - suffix_.length()) == suffix_;
  1002. }
  1003. void DescribeTo(::std::ostream* os) const {
  1004. *os << "ends with ";
  1005. UniversalPrint(suffix_, os);
  1006. }
  1007. void DescribeNegationTo(::std::ostream* os) const {
  1008. *os << "doesn't end with ";
  1009. UniversalPrint(suffix_, os);
  1010. }
  1011. private:
  1012. const StringType suffix_;
  1013. };
  1014. // Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be
  1015. // used as a Matcher<T> as long as T can be converted to a string.
  1016. class WhenBase64UnescapedMatcher {
  1017. public:
  1018. using is_gtest_matcher = void;
  1019. explicit WhenBase64UnescapedMatcher(
  1020. const Matcher<const std::string&>& internal_matcher)
  1021. : internal_matcher_(internal_matcher) {}
  1022. // Matches anything that can convert to std::string.
  1023. template <typename MatcheeStringType>
  1024. bool MatchAndExplain(const MatcheeStringType& s,
  1025. MatchResultListener* listener) const {
  1026. const std::string s2(s); // NOLINT (needed for working with string_view).
  1027. std::string unescaped;
  1028. if (!internal::Base64Unescape(s2, &unescaped)) {
  1029. if (listener != nullptr) {
  1030. *listener << "is not a valid base64 escaped string";
  1031. }
  1032. return false;
  1033. }
  1034. return MatchPrintAndExplain(unescaped, internal_matcher_, listener);
  1035. }
  1036. void DescribeTo(::std::ostream* os) const {
  1037. *os << "matches after Base64Unescape ";
  1038. internal_matcher_.DescribeTo(os);
  1039. }
  1040. void DescribeNegationTo(::std::ostream* os) const {
  1041. *os << "does not match after Base64Unescape ";
  1042. internal_matcher_.DescribeTo(os);
  1043. }
  1044. private:
  1045. const Matcher<const std::string&> internal_matcher_;
  1046. };
  1047. // Implements a matcher that compares the two fields of a 2-tuple
  1048. // using one of the ==, <=, <, etc, operators. The two fields being
  1049. // compared don't have to have the same type.
  1050. //
  1051. // The matcher defined here is polymorphic (for example, Eq() can be
  1052. // used to match a std::tuple<int, short>, a std::tuple<const long&, double>,
  1053. // etc). Therefore we use a template type conversion operator in the
  1054. // implementation.
  1055. template <typename D, typename Op>
  1056. class PairMatchBase {
  1057. public:
  1058. template <typename T1, typename T2>
  1059. operator Matcher<::std::tuple<T1, T2>>() const {
  1060. return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);
  1061. }
  1062. template <typename T1, typename T2>
  1063. operator Matcher<const ::std::tuple<T1, T2>&>() const {
  1064. return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);
  1065. }
  1066. private:
  1067. static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
  1068. return os << D::Desc();
  1069. }
  1070. template <typename Tuple>
  1071. class Impl : public MatcherInterface<Tuple> {
  1072. public:
  1073. bool MatchAndExplain(Tuple args,
  1074. MatchResultListener* /* listener */) const override {
  1075. return Op()(::std::get<0>(args), ::std::get<1>(args));
  1076. }
  1077. void DescribeTo(::std::ostream* os) const override {
  1078. *os << "are " << GetDesc;
  1079. }
  1080. void DescribeNegationTo(::std::ostream* os) const override {
  1081. *os << "aren't " << GetDesc;
  1082. }
  1083. };
  1084. };
  1085. class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {
  1086. public:
  1087. static const char* Desc() { return "an equal pair"; }
  1088. };
  1089. class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {
  1090. public:
  1091. static const char* Desc() { return "an unequal pair"; }
  1092. };
  1093. class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {
  1094. public:
  1095. static const char* Desc() { return "a pair where the first < the second"; }
  1096. };
  1097. class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {
  1098. public:
  1099. static const char* Desc() { return "a pair where the first > the second"; }
  1100. };
  1101. class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {
  1102. public:
  1103. static const char* Desc() { return "a pair where the first <= the second"; }
  1104. };
  1105. class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {
  1106. public:
  1107. static const char* Desc() { return "a pair where the first >= the second"; }
  1108. };
  1109. // Implements the Not(...) matcher for a particular argument type T.
  1110. // We do not nest it inside the NotMatcher class template, as that
  1111. // will prevent different instantiations of NotMatcher from sharing
  1112. // the same NotMatcherImpl<T> class.
  1113. template <typename T>
  1114. class NotMatcherImpl : public MatcherInterface<const T&> {
  1115. public:
  1116. explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {}
  1117. bool MatchAndExplain(const T& x,
  1118. MatchResultListener* listener) const override {
  1119. return !matcher_.MatchAndExplain(x, listener);
  1120. }
  1121. void DescribeTo(::std::ostream* os) const override {
  1122. matcher_.DescribeNegationTo(os);
  1123. }
  1124. void DescribeNegationTo(::std::ostream* os) const override {
  1125. matcher_.DescribeTo(os);
  1126. }
  1127. private:
  1128. const Matcher<T> matcher_;
  1129. };
  1130. // Implements the Not(m) matcher, which matches a value that doesn't
  1131. // match matcher m.
  1132. template <typename InnerMatcher>
  1133. class NotMatcher {
  1134. public:
  1135. explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
  1136. // This template type conversion operator allows Not(m) to be used
  1137. // to match any type m can match.
  1138. template <typename T>
  1139. operator Matcher<T>() const {
  1140. return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
  1141. }
  1142. private:
  1143. InnerMatcher matcher_;
  1144. };
  1145. // Implements the AllOf(m1, m2) matcher for a particular argument type
  1146. // T. We do not nest it inside the BothOfMatcher class template, as
  1147. // that will prevent different instantiations of BothOfMatcher from
  1148. // sharing the same BothOfMatcherImpl<T> class.
  1149. template <typename T>
  1150. class AllOfMatcherImpl : public MatcherInterface<const T&> {
  1151. public:
  1152. explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers)
  1153. : matchers_(std::move(matchers)) {}
  1154. void DescribeTo(::std::ostream* os) const override {
  1155. *os << "(";
  1156. for (size_t i = 0; i < matchers_.size(); ++i) {
  1157. if (i != 0) *os << ") and (";
  1158. matchers_[i].DescribeTo(os);
  1159. }
  1160. *os << ")";
  1161. }
  1162. void DescribeNegationTo(::std::ostream* os) const override {
  1163. *os << "(";
  1164. for (size_t i = 0; i < matchers_.size(); ++i) {
  1165. if (i != 0) *os << ") or (";
  1166. matchers_[i].DescribeNegationTo(os);
  1167. }
  1168. *os << ")";
  1169. }
  1170. bool MatchAndExplain(const T& x,
  1171. MatchResultListener* listener) const override {
  1172. // If either matcher1_ or matcher2_ doesn't match x, we only need
  1173. // to explain why one of them fails.
  1174. std::string all_match_result;
  1175. for (size_t i = 0; i < matchers_.size(); ++i) {
  1176. StringMatchResultListener slistener;
  1177. if (matchers_[i].MatchAndExplain(x, &slistener)) {
  1178. if (all_match_result.empty()) {
  1179. all_match_result = slistener.str();
  1180. } else {
  1181. std::string result = slistener.str();
  1182. if (!result.empty()) {
  1183. all_match_result += ", and ";
  1184. all_match_result += result;
  1185. }
  1186. }
  1187. } else {
  1188. *listener << slistener.str();
  1189. return false;
  1190. }
  1191. }
  1192. // Otherwise we need to explain why *both* of them match.
  1193. *listener << all_match_result;
  1194. return true;
  1195. }
  1196. private:
  1197. const std::vector<Matcher<T>> matchers_;
  1198. };
  1199. // VariadicMatcher is used for the variadic implementation of
  1200. // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
  1201. // CombiningMatcher<T> is used to recursively combine the provided matchers
  1202. // (of type Args...).
  1203. template <template <typename T> class CombiningMatcher, typename... Args>
  1204. class VariadicMatcher {
  1205. public:
  1206. VariadicMatcher(const Args&... matchers) // NOLINT
  1207. : matchers_(matchers...) {
  1208. static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
  1209. }
  1210. VariadicMatcher(const VariadicMatcher&) = default;
  1211. VariadicMatcher& operator=(const VariadicMatcher&) = delete;
  1212. // This template type conversion operator allows an
  1213. // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
  1214. // all of the provided matchers (Matcher1, Matcher2, ...) can match.
  1215. template <typename T>
  1216. operator Matcher<T>() const {
  1217. std::vector<Matcher<T>> values;
  1218. CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
  1219. return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
  1220. }
  1221. private:
  1222. template <typename T, size_t I>
  1223. void CreateVariadicMatcher(std::vector<Matcher<T>>* values,
  1224. std::integral_constant<size_t, I>) const {
  1225. values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
  1226. CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
  1227. }
  1228. template <typename T>
  1229. void CreateVariadicMatcher(
  1230. std::vector<Matcher<T>>*,
  1231. std::integral_constant<size_t, sizeof...(Args)>) const {}
  1232. std::tuple<Args...> matchers_;
  1233. };
  1234. template <typename... Args>
  1235. using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
  1236. // Implements the AnyOf(m1, m2) matcher for a particular argument type
  1237. // T. We do not nest it inside the AnyOfMatcher class template, as
  1238. // that will prevent different instantiations of AnyOfMatcher from
  1239. // sharing the same EitherOfMatcherImpl<T> class.
  1240. template <typename T>
  1241. class AnyOfMatcherImpl : public MatcherInterface<const T&> {
  1242. public:
  1243. explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers)
  1244. : matchers_(std::move(matchers)) {}
  1245. void DescribeTo(::std::ostream* os) const override {
  1246. *os << "(";
  1247. for (size_t i = 0; i < matchers_.size(); ++i) {
  1248. if (i != 0) *os << ") or (";
  1249. matchers_[i].DescribeTo(os);
  1250. }
  1251. *os << ")";
  1252. }
  1253. void DescribeNegationTo(::std::ostream* os) const override {
  1254. *os << "(";
  1255. for (size_t i = 0; i < matchers_.size(); ++i) {
  1256. if (i != 0) *os << ") and (";
  1257. matchers_[i].DescribeNegationTo(os);
  1258. }
  1259. *os << ")";
  1260. }
  1261. bool MatchAndExplain(const T& x,
  1262. MatchResultListener* listener) const override {
  1263. std::string no_match_result;
  1264. // If either matcher1_ or matcher2_ matches x, we just need to
  1265. // explain why *one* of them matches.
  1266. for (size_t i = 0; i < matchers_.size(); ++i) {
  1267. StringMatchResultListener slistener;
  1268. if (matchers_[i].MatchAndExplain(x, &slistener)) {
  1269. *listener << slistener.str();
  1270. return true;
  1271. } else {
  1272. if (no_match_result.empty()) {
  1273. no_match_result = slistener.str();
  1274. } else {
  1275. std::string result = slistener.str();
  1276. if (!result.empty()) {
  1277. no_match_result += ", and ";
  1278. no_match_result += result;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. // Otherwise we need to explain why *both* of them fail.
  1284. *listener << no_match_result;
  1285. return false;
  1286. }
  1287. private:
  1288. const std::vector<Matcher<T>> matchers_;
  1289. };
  1290. // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
  1291. template <typename... Args>
  1292. using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
  1293. // ConditionalMatcher is the implementation of Conditional(cond, m1, m2)
  1294. template <typename MatcherTrue, typename MatcherFalse>
  1295. class ConditionalMatcher {
  1296. public:
  1297. ConditionalMatcher(bool condition, MatcherTrue matcher_true,
  1298. MatcherFalse matcher_false)
  1299. : condition_(condition),
  1300. matcher_true_(std::move(matcher_true)),
  1301. matcher_false_(std::move(matcher_false)) {}
  1302. template <typename T>
  1303. operator Matcher<T>() const { // NOLINT(runtime/explicit)
  1304. return condition_ ? SafeMatcherCast<T>(matcher_true_)
  1305. : SafeMatcherCast<T>(matcher_false_);
  1306. }
  1307. private:
  1308. bool condition_;
  1309. MatcherTrue matcher_true_;
  1310. MatcherFalse matcher_false_;
  1311. };
  1312. // Wrapper for implementation of Any/AllOfArray().
  1313. template <template <class> class MatcherImpl, typename T>
  1314. class SomeOfArrayMatcher {
  1315. public:
  1316. // Constructs the matcher from a sequence of element values or
  1317. // element matchers.
  1318. template <typename Iter>
  1319. SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
  1320. template <typename U>
  1321. operator Matcher<U>() const { // NOLINT
  1322. using RawU = typename std::decay<U>::type;
  1323. std::vector<Matcher<RawU>> matchers;
  1324. matchers.reserve(matchers_.size());
  1325. for (const auto& matcher : matchers_) {
  1326. matchers.push_back(MatcherCast<RawU>(matcher));
  1327. }
  1328. return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));
  1329. }
  1330. private:
  1331. const ::std::vector<T> matchers_;
  1332. };
  1333. template <typename T>
  1334. using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;
  1335. template <typename T>
  1336. using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;
  1337. // Used for implementing Truly(pred), which turns a predicate into a
  1338. // matcher.
  1339. template <typename Predicate>
  1340. class TrulyMatcher {
  1341. public:
  1342. explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
  1343. // This method template allows Truly(pred) to be used as a matcher
  1344. // for type T where T is the argument type of predicate 'pred'. The
  1345. // argument is passed by reference as the predicate may be
  1346. // interested in the address of the argument.
  1347. template <typename T>
  1348. bool MatchAndExplain(T& x, // NOLINT
  1349. MatchResultListener* listener) const {
  1350. // Without the if-statement, MSVC sometimes warns about converting
  1351. // a value to bool (warning 4800).
  1352. //
  1353. // We cannot write 'return !!predicate_(x);' as that doesn't work
  1354. // when predicate_(x) returns a class convertible to bool but
  1355. // having no operator!().
  1356. if (predicate_(x)) return true;
  1357. *listener << "didn't satisfy the given predicate";
  1358. return false;
  1359. }
  1360. void DescribeTo(::std::ostream* os) const {
  1361. *os << "satisfies the given predicate";
  1362. }
  1363. void DescribeNegationTo(::std::ostream* os) const {
  1364. *os << "doesn't satisfy the given predicate";
  1365. }
  1366. private:
  1367. Predicate predicate_;
  1368. };
  1369. // Used for implementing Matches(matcher), which turns a matcher into
  1370. // a predicate.
  1371. template <typename M>
  1372. class MatcherAsPredicate {
  1373. public:
  1374. explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
  1375. // This template operator() allows Matches(m) to be used as a
  1376. // predicate on type T where m is a matcher on type T.
  1377. //
  1378. // The argument x is passed by reference instead of by value, as
  1379. // some matcher may be interested in its address (e.g. as in
  1380. // Matches(Ref(n))(x)).
  1381. template <typename T>
  1382. bool operator()(const T& x) const {
  1383. // We let matcher_ commit to a particular type here instead of
  1384. // when the MatcherAsPredicate object was constructed. This
  1385. // allows us to write Matches(m) where m is a polymorphic matcher
  1386. // (e.g. Eq(5)).
  1387. //
  1388. // If we write Matcher<T>(matcher_).Matches(x) here, it won't
  1389. // compile when matcher_ has type Matcher<const T&>; if we write
  1390. // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
  1391. // when matcher_ has type Matcher<T>; if we just write
  1392. // matcher_.Matches(x), it won't compile when matcher_ is
  1393. // polymorphic, e.g. Eq(5).
  1394. //
  1395. // MatcherCast<const T&>() is necessary for making the code work
  1396. // in all of the above situations.
  1397. return MatcherCast<const T&>(matcher_).Matches(x);
  1398. }
  1399. private:
  1400. M matcher_;
  1401. };
  1402. // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
  1403. // argument M must be a type that can be converted to a matcher.
  1404. template <typename M>
  1405. class PredicateFormatterFromMatcher {
  1406. public:
  1407. explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}
  1408. // This template () operator allows a PredicateFormatterFromMatcher
  1409. // object to act as a predicate-formatter suitable for using with
  1410. // Google Test's EXPECT_PRED_FORMAT1() macro.
  1411. template <typename T>
  1412. AssertionResult operator()(const char* value_text, const T& x) const {
  1413. // We convert matcher_ to a Matcher<const T&> *now* instead of
  1414. // when the PredicateFormatterFromMatcher object was constructed,
  1415. // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
  1416. // know which type to instantiate it to until we actually see the
  1417. // type of x here.
  1418. //
  1419. // We write SafeMatcherCast<const T&>(matcher_) instead of
  1420. // Matcher<const T&>(matcher_), as the latter won't compile when
  1421. // matcher_ has type Matcher<T> (e.g. An<int>()).
  1422. // We don't write MatcherCast<const T&> either, as that allows
  1423. // potentially unsafe downcasting of the matcher argument.
  1424. const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
  1425. // The expected path here is that the matcher should match (i.e. that most
  1426. // tests pass) so optimize for this case.
  1427. if (matcher.Matches(x)) {
  1428. return AssertionSuccess();
  1429. }
  1430. ::std::stringstream ss;
  1431. ss << "Value of: " << value_text << "\n"
  1432. << "Expected: ";
  1433. matcher.DescribeTo(&ss);
  1434. // Rerun the matcher to "PrintAndExplain" the failure.
  1435. StringMatchResultListener listener;
  1436. if (MatchPrintAndExplain(x, matcher, &listener)) {
  1437. ss << "\n The matcher failed on the initial attempt; but passed when "
  1438. "rerun to generate the explanation.";
  1439. }
  1440. ss << "\n Actual: " << listener.str();
  1441. return AssertionFailure() << ss.str();
  1442. }
  1443. private:
  1444. const M matcher_;
  1445. };
  1446. // A helper function for converting a matcher to a predicate-formatter
  1447. // without the user needing to explicitly write the type. This is
  1448. // used for implementing ASSERT_THAT() and EXPECT_THAT().
  1449. // Implementation detail: 'matcher' is received by-value to force decaying.
  1450. template <typename M>
  1451. inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(
  1452. M matcher) {
  1453. return PredicateFormatterFromMatcher<M>(std::move(matcher));
  1454. }
  1455. // Implements the polymorphic IsNan() matcher, which matches any floating type
  1456. // value that is Nan.
  1457. class IsNanMatcher {
  1458. public:
  1459. template <typename FloatType>
  1460. bool MatchAndExplain(const FloatType& f,
  1461. MatchResultListener* /* listener */) const {
  1462. return (::std::isnan)(f);
  1463. }
  1464. void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
  1465. void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN"; }
  1466. };
  1467. // Implements the polymorphic floating point equality matcher, which matches
  1468. // two float values using ULP-based approximation or, optionally, a
  1469. // user-specified epsilon. The template is meant to be instantiated with
  1470. // FloatType being either float or double.
  1471. template <typename FloatType>
  1472. class FloatingEqMatcher {
  1473. public:
  1474. // Constructor for FloatingEqMatcher.
  1475. // The matcher's input will be compared with expected. The matcher treats two
  1476. // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
  1477. // equality comparisons between NANs will always return false. We specify a
  1478. // negative max_abs_error_ term to indicate that ULP-based approximation will
  1479. // be used for comparison.
  1480. FloatingEqMatcher(FloatType expected, bool nan_eq_nan)
  1481. : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {}
  1482. // Constructor that supports a user-specified max_abs_error that will be used
  1483. // for comparison instead of ULP-based approximation. The max absolute
  1484. // should be non-negative.
  1485. FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
  1486. FloatType max_abs_error)
  1487. : expected_(expected),
  1488. nan_eq_nan_(nan_eq_nan),
  1489. max_abs_error_(max_abs_error) {
  1490. GTEST_CHECK_(max_abs_error >= 0)
  1491. << ", where max_abs_error is" << max_abs_error;
  1492. }
  1493. // Implements floating point equality matcher as a Matcher<T>.
  1494. template <typename T>
  1495. class Impl : public MatcherInterface<T> {
  1496. public:
  1497. Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
  1498. : expected_(expected),
  1499. nan_eq_nan_(nan_eq_nan),
  1500. max_abs_error_(max_abs_error) {}
  1501. bool MatchAndExplain(T value,
  1502. MatchResultListener* listener) const override {
  1503. const FloatingPoint<FloatType> actual(value), expected(expected_);
  1504. // Compares NaNs first, if nan_eq_nan_ is true.
  1505. if (actual.is_nan() || expected.is_nan()) {
  1506. if (actual.is_nan() && expected.is_nan()) {
  1507. return nan_eq_nan_;
  1508. }
  1509. // One is nan; the other is not nan.
  1510. return false;
  1511. }
  1512. if (HasMaxAbsError()) {
  1513. // We perform an equality check so that inf will match inf, regardless
  1514. // of error bounds. If the result of value - expected_ would result in
  1515. // overflow or if either value is inf, the default result is infinity,
  1516. // which should only match if max_abs_error_ is also infinity.
  1517. if (value == expected_) {
  1518. return true;
  1519. }
  1520. const FloatType diff = value - expected_;
  1521. if (::std::fabs(diff) <= max_abs_error_) {
  1522. return true;
  1523. }
  1524. if (listener->IsInterested()) {
  1525. *listener << "which is " << diff << " from " << expected_;
  1526. }
  1527. return false;
  1528. } else {
  1529. return actual.AlmostEquals(expected);
  1530. }
  1531. }
  1532. void DescribeTo(::std::ostream* os) const override {
  1533. // os->precision() returns the previously set precision, which we
  1534. // store to restore the ostream to its original configuration
  1535. // after outputting.
  1536. const ::std::streamsize old_precision =
  1537. os->precision(::std::numeric_limits<FloatType>::digits10 + 2);
  1538. if (FloatingPoint<FloatType>(expected_).is_nan()) {
  1539. if (nan_eq_nan_) {
  1540. *os << "is NaN";
  1541. } else {
  1542. *os << "never matches";
  1543. }
  1544. } else {
  1545. *os << "is approximately " << expected_;
  1546. if (HasMaxAbsError()) {
  1547. *os << " (absolute error <= " << max_abs_error_ << ")";
  1548. }
  1549. }
  1550. os->precision(old_precision);
  1551. }
  1552. void DescribeNegationTo(::std::ostream* os) const override {
  1553. // As before, get original precision.
  1554. const ::std::streamsize old_precision =
  1555. os->precision(::std::numeric_limits<FloatType>::digits10 + 2);
  1556. if (FloatingPoint<FloatType>(expected_).is_nan()) {
  1557. if (nan_eq_nan_) {
  1558. *os << "isn't NaN";
  1559. } else {
  1560. *os << "is anything";
  1561. }
  1562. } else {
  1563. *os << "isn't approximately " << expected_;
  1564. if (HasMaxAbsError()) {
  1565. *os << " (absolute error > " << max_abs_error_ << ")";
  1566. }
  1567. }
  1568. // Restore original precision.
  1569. os->precision(old_precision);
  1570. }
  1571. private:
  1572. bool HasMaxAbsError() const { return max_abs_error_ >= 0; }
  1573. const FloatType expected_;
  1574. const bool nan_eq_nan_;
  1575. // max_abs_error will be used for value comparison when >= 0.
  1576. const FloatType max_abs_error_;
  1577. };
  1578. // The following 3 type conversion operators allow FloatEq(expected) and
  1579. // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
  1580. // Matcher<const float&>, or a Matcher<float&>, but nothing else.
  1581. operator Matcher<FloatType>() const {
  1582. return MakeMatcher(
  1583. new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
  1584. }
  1585. operator Matcher<const FloatType&>() const {
  1586. return MakeMatcher(
  1587. new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
  1588. }
  1589. operator Matcher<FloatType&>() const {
  1590. return MakeMatcher(
  1591. new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
  1592. }
  1593. private:
  1594. const FloatType expected_;
  1595. const bool nan_eq_nan_;
  1596. // max_abs_error will be used for value comparison when >= 0.
  1597. const FloatType max_abs_error_;
  1598. };
  1599. // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
  1600. // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
  1601. // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
  1602. // against y. The former implements "Eq", the latter "Near". At present, there
  1603. // is no version that compares NaNs as equal.
  1604. template <typename FloatType>
  1605. class FloatingEq2Matcher {
  1606. public:
  1607. FloatingEq2Matcher() { Init(-1, false); }
  1608. explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
  1609. explicit FloatingEq2Matcher(FloatType max_abs_error) {
  1610. Init(max_abs_error, false);
  1611. }
  1612. FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
  1613. Init(max_abs_error, nan_eq_nan);
  1614. }
  1615. template <typename T1, typename T2>
  1616. operator Matcher<::std::tuple<T1, T2>>() const {
  1617. return MakeMatcher(
  1618. new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));
  1619. }
  1620. template <typename T1, typename T2>
  1621. operator Matcher<const ::std::tuple<T1, T2>&>() const {
  1622. return MakeMatcher(
  1623. new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
  1624. }
  1625. private:
  1626. static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
  1627. return os << "an almost-equal pair";
  1628. }
  1629. template <typename Tuple>
  1630. class Impl : public MatcherInterface<Tuple> {
  1631. public:
  1632. Impl(FloatType max_abs_error, bool nan_eq_nan)
  1633. : max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {}
  1634. bool MatchAndExplain(Tuple args,
  1635. MatchResultListener* listener) const override {
  1636. if (max_abs_error_ == -1) {
  1637. FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);
  1638. return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
  1639. ::std::get<1>(args), listener);
  1640. } else {
  1641. FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,
  1642. max_abs_error_);
  1643. return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
  1644. ::std::get<1>(args), listener);
  1645. }
  1646. }
  1647. void DescribeTo(::std::ostream* os) const override {
  1648. *os << "are " << GetDesc;
  1649. }
  1650. void DescribeNegationTo(::std::ostream* os) const override {
  1651. *os << "aren't " << GetDesc;
  1652. }
  1653. private:
  1654. FloatType max_abs_error_;
  1655. const bool nan_eq_nan_;
  1656. };
  1657. void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
  1658. max_abs_error_ = max_abs_error_val;
  1659. nan_eq_nan_ = nan_eq_nan_val;
  1660. }
  1661. FloatType max_abs_error_;
  1662. bool nan_eq_nan_;
  1663. };
  1664. // Implements the Pointee(m) matcher for matching a pointer whose
  1665. // pointee matches matcher m. The pointer can be either raw or smart.
  1666. template <typename InnerMatcher>
  1667. class PointeeMatcher {
  1668. public:
  1669. explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
  1670. // This type conversion operator template allows Pointee(m) to be
  1671. // used as a matcher for any pointer type whose pointee type is
  1672. // compatible with the inner matcher, where type Pointer can be
  1673. // either a raw pointer or a smart pointer.
  1674. //
  1675. // The reason we do this instead of relying on
  1676. // MakePolymorphicMatcher() is that the latter is not flexible
  1677. // enough for implementing the DescribeTo() method of Pointee().
  1678. template <typename Pointer>
  1679. operator Matcher<Pointer>() const {
  1680. return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));
  1681. }
  1682. private:
  1683. // The monomorphic implementation that works for a particular pointer type.
  1684. template <typename Pointer>
  1685. class Impl : public MatcherInterface<Pointer> {
  1686. public:
  1687. using Pointee =
  1688. typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
  1689. Pointer)>::element_type;
  1690. explicit Impl(const InnerMatcher& matcher)
  1691. : matcher_(MatcherCast<const Pointee&>(matcher)) {}
  1692. void DescribeTo(::std::ostream* os) const override {
  1693. *os << "points to a value that ";
  1694. matcher_.DescribeTo(os);
  1695. }
  1696. void DescribeNegationTo(::std::ostream* os) const override {
  1697. *os << "does not point to a value that ";
  1698. matcher_.DescribeTo(os);
  1699. }
  1700. bool MatchAndExplain(Pointer pointer,
  1701. MatchResultListener* listener) const override {
  1702. if (GetRawPointer(pointer) == nullptr) return false;
  1703. *listener << "which points to ";
  1704. return MatchPrintAndExplain(*pointer, matcher_, listener);
  1705. }
  1706. private:
  1707. const Matcher<const Pointee&> matcher_;
  1708. };
  1709. const InnerMatcher matcher_;
  1710. };
  1711. // Implements the Pointer(m) matcher
  1712. // Implements the Pointer(m) matcher for matching a pointer that matches matcher
  1713. // m. The pointer can be either raw or smart, and will match `m` against the
  1714. // raw pointer.
  1715. template <typename InnerMatcher>
  1716. class PointerMatcher {
  1717. public:
  1718. explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
  1719. // This type conversion operator template allows Pointer(m) to be
  1720. // used as a matcher for any pointer type whose pointer type is
  1721. // compatible with the inner matcher, where type PointerType can be
  1722. // either a raw pointer or a smart pointer.
  1723. //
  1724. // The reason we do this instead of relying on
  1725. // MakePolymorphicMatcher() is that the latter is not flexible
  1726. // enough for implementing the DescribeTo() method of Pointer().
  1727. template <typename PointerType>
  1728. operator Matcher<PointerType>() const { // NOLINT
  1729. return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
  1730. }
  1731. private:
  1732. // The monomorphic implementation that works for a particular pointer type.
  1733. template <typename PointerType>
  1734. class Impl : public MatcherInterface<PointerType> {
  1735. public:
  1736. using Pointer =
  1737. const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
  1738. PointerType)>::element_type*;
  1739. explicit Impl(const InnerMatcher& matcher)
  1740. : matcher_(MatcherCast<Pointer>(matcher)) {}
  1741. void DescribeTo(::std::ostream* os) const override {
  1742. *os << "is a pointer that ";
  1743. matcher_.DescribeTo(os);
  1744. }
  1745. void DescribeNegationTo(::std::ostream* os) const override {
  1746. *os << "is not a pointer that ";
  1747. matcher_.DescribeTo(os);
  1748. }
  1749. bool MatchAndExplain(PointerType pointer,
  1750. MatchResultListener* listener) const override {
  1751. *listener << "which is a pointer that ";
  1752. Pointer p = GetRawPointer(pointer);
  1753. return MatchPrintAndExplain(p, matcher_, listener);
  1754. }
  1755. private:
  1756. Matcher<Pointer> matcher_;
  1757. };
  1758. const InnerMatcher matcher_;
  1759. };
  1760. #if GTEST_HAS_RTTI
  1761. // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
  1762. // reference that matches inner_matcher when dynamic_cast<T> is applied.
  1763. // The result of dynamic_cast<To> is forwarded to the inner matcher.
  1764. // If To is a pointer and the cast fails, the inner matcher will receive NULL.
  1765. // If To is a reference and the cast fails, this matcher returns false
  1766. // immediately.
  1767. template <typename To>
  1768. class WhenDynamicCastToMatcherBase {
  1769. public:
  1770. explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
  1771. : matcher_(matcher) {}
  1772. void DescribeTo(::std::ostream* os) const {
  1773. GetCastTypeDescription(os);
  1774. matcher_.DescribeTo(os);
  1775. }
  1776. void DescribeNegationTo(::std::ostream* os) const {
  1777. GetCastTypeDescription(os);
  1778. matcher_.DescribeNegationTo(os);
  1779. }
  1780. protected:
  1781. const Matcher<To> matcher_;
  1782. static std::string GetToName() { return GetTypeName<To>(); }
  1783. private:
  1784. static void GetCastTypeDescription(::std::ostream* os) {
  1785. *os << "when dynamic_cast to " << GetToName() << ", ";
  1786. }
  1787. };
  1788. // Primary template.
  1789. // To is a pointer. Cast and forward the result.
  1790. template <typename To>
  1791. class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
  1792. public:
  1793. explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
  1794. : WhenDynamicCastToMatcherBase<To>(matcher) {}
  1795. template <typename From>
  1796. bool MatchAndExplain(From from, MatchResultListener* listener) const {
  1797. To to = dynamic_cast<To>(from);
  1798. return MatchPrintAndExplain(to, this->matcher_, listener);
  1799. }
  1800. };
  1801. // Specialize for references.
  1802. // In this case we return false if the dynamic_cast fails.
  1803. template <typename To>
  1804. class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
  1805. public:
  1806. explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
  1807. : WhenDynamicCastToMatcherBase<To&>(matcher) {}
  1808. template <typename From>
  1809. bool MatchAndExplain(From& from, MatchResultListener* listener) const {
  1810. // We don't want an std::bad_cast here, so do the cast with pointers.
  1811. To* to = dynamic_cast<To*>(&from);
  1812. if (to == nullptr) {
  1813. *listener << "which cannot be dynamic_cast to " << this->GetToName();
  1814. return false;
  1815. }
  1816. return MatchPrintAndExplain(*to, this->matcher_, listener);
  1817. }
  1818. };
  1819. #endif // GTEST_HAS_RTTI
  1820. // Implements the Field() matcher for matching a field (i.e. member
  1821. // variable) of an object.
  1822. template <typename Class, typename FieldType>
  1823. class FieldMatcher {
  1824. public:
  1825. FieldMatcher(FieldType Class::*field,
  1826. const Matcher<const FieldType&>& matcher)
  1827. : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
  1828. FieldMatcher(const std::string& field_name, FieldType Class::*field,
  1829. const Matcher<const FieldType&>& matcher)
  1830. : field_(field),
  1831. matcher_(matcher),
  1832. whose_field_("whose field `" + field_name + "` ") {}
  1833. void DescribeTo(::std::ostream* os) const {
  1834. *os << "is an object " << whose_field_;
  1835. matcher_.DescribeTo(os);
  1836. }
  1837. void DescribeNegationTo(::std::ostream* os) const {
  1838. *os << "is an object " << whose_field_;
  1839. matcher_.DescribeNegationTo(os);
  1840. }
  1841. template <typename T>
  1842. bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
  1843. // FIXME: The dispatch on std::is_pointer was introduced as a workaround for
  1844. // a compiler bug, and can now be removed.
  1845. return MatchAndExplainImpl(
  1846. typename std::is_pointer<typename std::remove_const<T>::type>::type(),
  1847. value, listener);
  1848. }
  1849. private:
  1850. bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
  1851. const Class& obj,
  1852. MatchResultListener* listener) const {
  1853. *listener << whose_field_ << "is ";
  1854. return MatchPrintAndExplain(obj.*field_, matcher_, listener);
  1855. }
  1856. bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
  1857. MatchResultListener* listener) const {
  1858. if (p == nullptr) return false;
  1859. *listener << "which points to an object ";
  1860. // Since *p has a field, it must be a class/struct/union type and
  1861. // thus cannot be a pointer. Therefore we pass false_type() as
  1862. // the first argument.
  1863. return MatchAndExplainImpl(std::false_type(), *p, listener);
  1864. }
  1865. const FieldType Class::*field_;
  1866. const Matcher<const FieldType&> matcher_;
  1867. // Contains either "whose given field " if the name of the field is unknown
  1868. // or "whose field `name_of_field` " if the name is known.
  1869. const std::string whose_field_;
  1870. };
  1871. // Implements the Property() matcher for matching a property
  1872. // (i.e. return value of a getter method) of an object.
  1873. //
  1874. // Property is a const-qualified member function of Class returning
  1875. // PropertyType.
  1876. template <typename Class, typename PropertyType, typename Property>
  1877. class PropertyMatcher {
  1878. public:
  1879. typedef const PropertyType& RefToConstProperty;
  1880. PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
  1881. : property_(property),
  1882. matcher_(matcher),
  1883. whose_property_("whose given property ") {}
  1884. PropertyMatcher(const std::string& property_name, Property property,
  1885. const Matcher<RefToConstProperty>& matcher)
  1886. : property_(property),
  1887. matcher_(matcher),
  1888. whose_property_("whose property `" + property_name + "` ") {}
  1889. void DescribeTo(::std::ostream* os) const {
  1890. *os << "is an object " << whose_property_;
  1891. matcher_.DescribeTo(os);
  1892. }
  1893. void DescribeNegationTo(::std::ostream* os) const {
  1894. *os << "is an object " << whose_property_;
  1895. matcher_.DescribeNegationTo(os);
  1896. }
  1897. template <typename T>
  1898. bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
  1899. return MatchAndExplainImpl(
  1900. typename std::is_pointer<typename std::remove_const<T>::type>::type(),
  1901. value, listener);
  1902. }
  1903. private:
  1904. bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
  1905. const Class& obj,
  1906. MatchResultListener* listener) const {
  1907. *listener << whose_property_ << "is ";
  1908. // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
  1909. // which takes a non-const reference as argument.
  1910. RefToConstProperty result = (obj.*property_)();
  1911. return MatchPrintAndExplain(result, matcher_, listener);
  1912. }
  1913. bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
  1914. MatchResultListener* listener) const {
  1915. if (p == nullptr) return false;
  1916. *listener << "which points to an object ";
  1917. // Since *p has a property method, it must be a class/struct/union
  1918. // type and thus cannot be a pointer. Therefore we pass
  1919. // false_type() as the first argument.
  1920. return MatchAndExplainImpl(std::false_type(), *p, listener);
  1921. }
  1922. Property property_;
  1923. const Matcher<RefToConstProperty> matcher_;
  1924. // Contains either "whose given property " if the name of the property is
  1925. // unknown or "whose property `name_of_property` " if the name is known.
  1926. const std::string whose_property_;
  1927. };
  1928. // Type traits specifying various features of different functors for ResultOf.
  1929. // The default template specifies features for functor objects.
  1930. template <typename Functor>
  1931. struct CallableTraits {
  1932. typedef Functor StorageType;
  1933. static void CheckIsValid(Functor /* functor */) {}
  1934. template <typename T>
  1935. static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {
  1936. return f(arg);
  1937. }
  1938. };
  1939. // Specialization for function pointers.
  1940. template <typename ArgType, typename ResType>
  1941. struct CallableTraits<ResType (*)(ArgType)> {
  1942. typedef ResType ResultType;
  1943. typedef ResType (*StorageType)(ArgType);
  1944. static void CheckIsValid(ResType (*f)(ArgType)) {
  1945. GTEST_CHECK_(f != nullptr)
  1946. << "NULL function pointer is passed into ResultOf().";
  1947. }
  1948. template <typename T>
  1949. static ResType Invoke(ResType (*f)(ArgType), T arg) {
  1950. return (*f)(arg);
  1951. }
  1952. };
  1953. // Implements the ResultOf() matcher for matching a return value of a
  1954. // unary function of an object.
  1955. template <typename Callable, typename InnerMatcher>
  1956. class ResultOfMatcher {
  1957. public:
  1958. ResultOfMatcher(Callable callable, InnerMatcher matcher)
  1959. : ResultOfMatcher(/*result_description=*/"", std::move(callable),
  1960. std::move(matcher)) {}
  1961. ResultOfMatcher(const std::string& result_description, Callable callable,
  1962. InnerMatcher matcher)
  1963. : result_description_(result_description),
  1964. callable_(std::move(callable)),
  1965. matcher_(std::move(matcher)) {
  1966. CallableTraits<Callable>::CheckIsValid(callable_);
  1967. }
  1968. template <typename T>
  1969. operator Matcher<T>() const {
  1970. return Matcher<T>(
  1971. new Impl<const T&>(result_description_, callable_, matcher_));
  1972. }
  1973. private:
  1974. typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
  1975. template <typename T>
  1976. class Impl : public MatcherInterface<T> {
  1977. using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
  1978. std::declval<CallableStorageType>(), std::declval<T>()));
  1979. public:
  1980. template <typename M>
  1981. Impl(const std::string& result_description,
  1982. const CallableStorageType& callable, const M& matcher)
  1983. : result_description_(result_description),
  1984. callable_(callable),
  1985. matcher_(MatcherCast<ResultType>(matcher)) {}
  1986. void DescribeTo(::std::ostream* os) const override {
  1987. if (result_description_.empty()) {
  1988. *os << "is mapped by the given callable to a value that ";
  1989. } else {
  1990. *os << "whose " << result_description_ << " ";
  1991. }
  1992. matcher_.DescribeTo(os);
  1993. }
  1994. void DescribeNegationTo(::std::ostream* os) const override {
  1995. if (result_description_.empty()) {
  1996. *os << "is mapped by the given callable to a value that ";
  1997. } else {
  1998. *os << "whose " << result_description_ << " ";
  1999. }
  2000. matcher_.DescribeNegationTo(os);
  2001. }
  2002. bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
  2003. if (result_description_.empty()) {
  2004. *listener << "which is mapped by the given callable to ";
  2005. } else {
  2006. *listener << "whose " << result_description_ << " is ";
  2007. }
  2008. // Cannot pass the return value directly to MatchPrintAndExplain, which
  2009. // takes a non-const reference as argument.
  2010. // Also, specifying template argument explicitly is needed because T could
  2011. // be a non-const reference (e.g. Matcher<Uncopyable&>).
  2012. ResultType result =
  2013. CallableTraits<Callable>::template Invoke<T>(callable_, obj);
  2014. return MatchPrintAndExplain(result, matcher_, listener);
  2015. }
  2016. private:
  2017. const std::string result_description_;
  2018. // Functors often define operator() as non-const method even though
  2019. // they are actually stateless. But we need to use them even when
  2020. // 'this' is a const pointer. It's the user's responsibility not to
  2021. // use stateful callables with ResultOf(), which doesn't guarantee
  2022. // how many times the callable will be invoked.
  2023. mutable CallableStorageType callable_;
  2024. const Matcher<ResultType> matcher_;
  2025. }; // class Impl
  2026. const std::string result_description_;
  2027. const CallableStorageType callable_;
  2028. const InnerMatcher matcher_;
  2029. };
  2030. // Implements a matcher that checks the size of an STL-style container.
  2031. template <typename SizeMatcher>
  2032. class SizeIsMatcher {
  2033. public:
  2034. explicit SizeIsMatcher(const SizeMatcher& size_matcher)
  2035. : size_matcher_(size_matcher) {}
  2036. template <typename Container>
  2037. operator Matcher<Container>() const {
  2038. return Matcher<Container>(new Impl<const Container&>(size_matcher_));
  2039. }
  2040. template <typename Container>
  2041. class Impl : public MatcherInterface<Container> {
  2042. public:
  2043. using SizeType = decltype(std::declval<Container>().size());
  2044. explicit Impl(const SizeMatcher& size_matcher)
  2045. : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
  2046. void DescribeTo(::std::ostream* os) const override {
  2047. *os << "has a size that ";
  2048. size_matcher_.DescribeTo(os);
  2049. }
  2050. void DescribeNegationTo(::std::ostream* os) const override {
  2051. *os << "has a size that ";
  2052. size_matcher_.DescribeNegationTo(os);
  2053. }
  2054. bool MatchAndExplain(Container container,
  2055. MatchResultListener* listener) const override {
  2056. SizeType size = container.size();
  2057. StringMatchResultListener size_listener;
  2058. const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
  2059. *listener << "whose size " << size
  2060. << (result ? " matches" : " doesn't match");
  2061. PrintIfNotEmpty(size_listener.str(), listener->stream());
  2062. return result;
  2063. }
  2064. private:
  2065. const Matcher<SizeType> size_matcher_;
  2066. };
  2067. private:
  2068. const SizeMatcher size_matcher_;
  2069. };
  2070. // Implements a matcher that checks the begin()..end() distance of an STL-style
  2071. // container.
  2072. template <typename DistanceMatcher>
  2073. class BeginEndDistanceIsMatcher {
  2074. public:
  2075. explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
  2076. : distance_matcher_(distance_matcher) {}
  2077. template <typename Container>
  2078. operator Matcher<Container>() const {
  2079. return Matcher<Container>(new Impl<const Container&>(distance_matcher_));
  2080. }
  2081. template <typename Container>
  2082. class Impl : public MatcherInterface<Container> {
  2083. public:
  2084. typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
  2085. Container)>
  2086. ContainerView;
  2087. typedef typename std::iterator_traits<
  2088. typename ContainerView::type::const_iterator>::difference_type
  2089. DistanceType;
  2090. explicit Impl(const DistanceMatcher& distance_matcher)
  2091. : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
  2092. void DescribeTo(::std::ostream* os) const override {
  2093. *os << "distance between begin() and end() ";
  2094. distance_matcher_.DescribeTo(os);
  2095. }
  2096. void DescribeNegationTo(::std::ostream* os) const override {
  2097. *os << "distance between begin() and end() ";
  2098. distance_matcher_.DescribeNegationTo(os);
  2099. }
  2100. bool MatchAndExplain(Container container,
  2101. MatchResultListener* listener) const override {
  2102. using std::begin;
  2103. using std::end;
  2104. DistanceType distance = std::distance(begin(container), end(container));
  2105. StringMatchResultListener distance_listener;
  2106. const bool result =
  2107. distance_matcher_.MatchAndExplain(distance, &distance_listener);
  2108. *listener << "whose distance between begin() and end() " << distance
  2109. << (result ? " matches" : " doesn't match");
  2110. PrintIfNotEmpty(distance_listener.str(), listener->stream());
  2111. return result;
  2112. }
  2113. private:
  2114. const Matcher<DistanceType> distance_matcher_;
  2115. };
  2116. private:
  2117. const DistanceMatcher distance_matcher_;
  2118. };
  2119. // Implements an equality matcher for any STL-style container whose elements
  2120. // support ==. This matcher is like Eq(), but its failure explanations provide
  2121. // more detailed information that is useful when the container is used as a set.
  2122. // The failure message reports elements that are in one of the operands but not
  2123. // the other. The failure messages do not report duplicate or out-of-order
  2124. // elements in the containers (which don't properly matter to sets, but can
  2125. // occur if the containers are vectors or lists, for example).
  2126. //
  2127. // Uses the container's const_iterator, value_type, operator ==,
  2128. // begin(), and end().
  2129. template <typename Container>
  2130. class ContainerEqMatcher {
  2131. public:
  2132. typedef internal::StlContainerView<Container> View;
  2133. typedef typename View::type StlContainer;
  2134. typedef typename View::const_reference StlContainerReference;
  2135. static_assert(!std::is_const<Container>::value,
  2136. "Container type must not be const");
  2137. static_assert(!std::is_reference<Container>::value,
  2138. "Container type must not be a reference");
  2139. // We make a copy of expected in case the elements in it are modified
  2140. // after this matcher is created.
  2141. explicit ContainerEqMatcher(const Container& expected)
  2142. : expected_(View::Copy(expected)) {}
  2143. void DescribeTo(::std::ostream* os) const {
  2144. *os << "equals ";
  2145. UniversalPrint(expected_, os);
  2146. }
  2147. void DescribeNegationTo(::std::ostream* os) const {
  2148. *os << "does not equal ";
  2149. UniversalPrint(expected_, os);
  2150. }
  2151. template <typename LhsContainer>
  2152. bool MatchAndExplain(const LhsContainer& lhs,
  2153. MatchResultListener* listener) const {
  2154. typedef internal::StlContainerView<
  2155. typename std::remove_const<LhsContainer>::type>
  2156. LhsView;
  2157. StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  2158. if (lhs_stl_container == expected_) return true;
  2159. ::std::ostream* const os = listener->stream();
  2160. if (os != nullptr) {
  2161. // Something is different. Check for extra values first.
  2162. bool printed_header = false;
  2163. for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end();
  2164. ++it) {
  2165. if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
  2166. expected_.end()) {
  2167. if (printed_header) {
  2168. *os << ", ";
  2169. } else {
  2170. *os << "which has these unexpected elements: ";
  2171. printed_header = true;
  2172. }
  2173. UniversalPrint(*it, os);
  2174. }
  2175. }
  2176. // Now check for missing values.
  2177. bool printed_header2 = false;
  2178. for (auto it = expected_.begin(); it != expected_.end(); ++it) {
  2179. if (internal::ArrayAwareFind(lhs_stl_container.begin(),
  2180. lhs_stl_container.end(),
  2181. *it) == lhs_stl_container.end()) {
  2182. if (printed_header2) {
  2183. *os << ", ";
  2184. } else {
  2185. *os << (printed_header ? ",\nand" : "which")
  2186. << " doesn't have these expected elements: ";
  2187. printed_header2 = true;
  2188. }
  2189. UniversalPrint(*it, os);
  2190. }
  2191. }
  2192. }
  2193. return false;
  2194. }
  2195. private:
  2196. const StlContainer expected_;
  2197. };
  2198. // A comparator functor that uses the < operator to compare two values.
  2199. struct LessComparator {
  2200. template <typename T, typename U>
  2201. bool operator()(const T& lhs, const U& rhs) const {
  2202. return lhs < rhs;
  2203. }
  2204. };
  2205. // Implements WhenSortedBy(comparator, container_matcher).
  2206. template <typename Comparator, typename ContainerMatcher>
  2207. class WhenSortedByMatcher {
  2208. public:
  2209. WhenSortedByMatcher(const Comparator& comparator,
  2210. const ContainerMatcher& matcher)
  2211. : comparator_(comparator), matcher_(matcher) {}
  2212. template <typename LhsContainer>
  2213. operator Matcher<LhsContainer>() const {
  2214. return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
  2215. }
  2216. template <typename LhsContainer>
  2217. class Impl : public MatcherInterface<LhsContainer> {
  2218. public:
  2219. typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
  2220. LhsContainer)>
  2221. LhsView;
  2222. typedef typename LhsView::type LhsStlContainer;
  2223. typedef typename LhsView::const_reference LhsStlContainerReference;
  2224. // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
  2225. // so that we can match associative containers.
  2226. typedef
  2227. typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type
  2228. LhsValue;
  2229. Impl(const Comparator& comparator, const ContainerMatcher& matcher)
  2230. : comparator_(comparator), matcher_(matcher) {}
  2231. void DescribeTo(::std::ostream* os) const override {
  2232. *os << "(when sorted) ";
  2233. matcher_.DescribeTo(os);
  2234. }
  2235. void DescribeNegationTo(::std::ostream* os) const override {
  2236. *os << "(when sorted) ";
  2237. matcher_.DescribeNegationTo(os);
  2238. }
  2239. bool MatchAndExplain(LhsContainer lhs,
  2240. MatchResultListener* listener) const override {
  2241. LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  2242. ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
  2243. lhs_stl_container.end());
  2244. ::std::sort(sorted_container.begin(), sorted_container.end(),
  2245. comparator_);
  2246. if (!listener->IsInterested()) {
  2247. // If the listener is not interested, we do not need to
  2248. // construct the inner explanation.
  2249. return matcher_.Matches(sorted_container);
  2250. }
  2251. *listener << "which is ";
  2252. UniversalPrint(sorted_container, listener->stream());
  2253. *listener << " when sorted";
  2254. StringMatchResultListener inner_listener;
  2255. const bool match =
  2256. matcher_.MatchAndExplain(sorted_container, &inner_listener);
  2257. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  2258. return match;
  2259. }
  2260. private:
  2261. const Comparator comparator_;
  2262. const Matcher<const ::std::vector<LhsValue>&> matcher_;
  2263. Impl(const Impl&) = delete;
  2264. Impl& operator=(const Impl&) = delete;
  2265. };
  2266. private:
  2267. const Comparator comparator_;
  2268. const ContainerMatcher matcher_;
  2269. };
  2270. // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
  2271. // must be able to be safely cast to Matcher<std::tuple<const T1&, const
  2272. // T2&> >, where T1 and T2 are the types of elements in the LHS
  2273. // container and the RHS container respectively.
  2274. template <typename TupleMatcher, typename RhsContainer>
  2275. class PointwiseMatcher {
  2276. static_assert(
  2277. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
  2278. "use UnorderedPointwise with hash tables");
  2279. public:
  2280. typedef internal::StlContainerView<RhsContainer> RhsView;
  2281. typedef typename RhsView::type RhsStlContainer;
  2282. typedef typename RhsStlContainer::value_type RhsValue;
  2283. static_assert(!std::is_const<RhsContainer>::value,
  2284. "RhsContainer type must not be const");
  2285. static_assert(!std::is_reference<RhsContainer>::value,
  2286. "RhsContainer type must not be a reference");
  2287. // Like ContainerEq, we make a copy of rhs in case the elements in
  2288. // it are modified after this matcher is created.
  2289. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
  2290. : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}
  2291. template <typename LhsContainer>
  2292. operator Matcher<LhsContainer>() const {
  2293. static_assert(
  2294. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
  2295. "use UnorderedPointwise with hash tables");
  2296. return Matcher<LhsContainer>(
  2297. new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
  2298. }
  2299. template <typename LhsContainer>
  2300. class Impl : public MatcherInterface<LhsContainer> {
  2301. public:
  2302. typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
  2303. LhsContainer)>
  2304. LhsView;
  2305. typedef typename LhsView::type LhsStlContainer;
  2306. typedef typename LhsView::const_reference LhsStlContainerReference;
  2307. typedef typename LhsStlContainer::value_type LhsValue;
  2308. // We pass the LHS value and the RHS value to the inner matcher by
  2309. // reference, as they may be expensive to copy. We must use tuple
  2310. // instead of pair here, as a pair cannot hold references (C++ 98,
  2311. // 20.2.2 [lib.pairs]).
  2312. typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
  2313. Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
  2314. // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
  2315. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
  2316. rhs_(rhs) {}
  2317. void DescribeTo(::std::ostream* os) const override {
  2318. *os << "contains " << rhs_.size()
  2319. << " values, where each value and its corresponding value in ";
  2320. UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
  2321. *os << " ";
  2322. mono_tuple_matcher_.DescribeTo(os);
  2323. }
  2324. void DescribeNegationTo(::std::ostream* os) const override {
  2325. *os << "doesn't contain exactly " << rhs_.size()
  2326. << " values, or contains a value x at some index i"
  2327. << " where x and the i-th value of ";
  2328. UniversalPrint(rhs_, os);
  2329. *os << " ";
  2330. mono_tuple_matcher_.DescribeNegationTo(os);
  2331. }
  2332. bool MatchAndExplain(LhsContainer lhs,
  2333. MatchResultListener* listener) const override {
  2334. LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  2335. const size_t actual_size = lhs_stl_container.size();
  2336. if (actual_size != rhs_.size()) {
  2337. *listener << "which contains " << actual_size << " values";
  2338. return false;
  2339. }
  2340. auto left = lhs_stl_container.begin();
  2341. auto right = rhs_.begin();
  2342. for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
  2343. if (listener->IsInterested()) {
  2344. StringMatchResultListener inner_listener;
  2345. // Create InnerMatcherArg as a temporarily object to avoid it outlives
  2346. // *left and *right. Dereference or the conversion to `const T&` may
  2347. // return temp objects, e.g. for vector<bool>.
  2348. if (!mono_tuple_matcher_.MatchAndExplain(
  2349. InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
  2350. ImplicitCast_<const RhsValue&>(*right)),
  2351. &inner_listener)) {
  2352. *listener << "where the value pair (";
  2353. UniversalPrint(*left, listener->stream());
  2354. *listener << ", ";
  2355. UniversalPrint(*right, listener->stream());
  2356. *listener << ") at index #" << i << " don't match";
  2357. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  2358. return false;
  2359. }
  2360. } else {
  2361. if (!mono_tuple_matcher_.Matches(
  2362. InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
  2363. ImplicitCast_<const RhsValue&>(*right))))
  2364. return false;
  2365. }
  2366. }
  2367. return true;
  2368. }
  2369. private:
  2370. const Matcher<InnerMatcherArg> mono_tuple_matcher_;
  2371. const RhsStlContainer rhs_;
  2372. };
  2373. private:
  2374. const TupleMatcher tuple_matcher_;
  2375. const RhsStlContainer rhs_;
  2376. };
  2377. // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
  2378. template <typename Container>
  2379. class QuantifierMatcherImpl : public MatcherInterface<Container> {
  2380. public:
  2381. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  2382. typedef StlContainerView<RawContainer> View;
  2383. typedef typename View::type StlContainer;
  2384. typedef typename View::const_reference StlContainerReference;
  2385. typedef typename StlContainer::value_type Element;
  2386. template <typename InnerMatcher>
  2387. explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
  2388. : inner_matcher_(
  2389. testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
  2390. // Checks whether:
  2391. // * All elements in the container match, if all_elements_should_match.
  2392. // * Any element in the container matches, if !all_elements_should_match.
  2393. bool MatchAndExplainImpl(bool all_elements_should_match, Container container,
  2394. MatchResultListener* listener) const {
  2395. StlContainerReference stl_container = View::ConstReference(container);
  2396. size_t i = 0;
  2397. for (auto it = stl_container.begin(); it != stl_container.end();
  2398. ++it, ++i) {
  2399. StringMatchResultListener inner_listener;
  2400. const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
  2401. if (matches != all_elements_should_match) {
  2402. *listener << "whose element #" << i
  2403. << (matches ? " matches" : " doesn't match");
  2404. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  2405. return !all_elements_should_match;
  2406. }
  2407. }
  2408. return all_elements_should_match;
  2409. }
  2410. bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher,
  2411. Container container,
  2412. MatchResultListener* listener) const {
  2413. StlContainerReference stl_container = View::ConstReference(container);
  2414. size_t i = 0;
  2415. std::vector<size_t> match_elements;
  2416. for (auto it = stl_container.begin(); it != stl_container.end();
  2417. ++it, ++i) {
  2418. StringMatchResultListener inner_listener;
  2419. const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
  2420. if (matches) {
  2421. match_elements.push_back(i);
  2422. }
  2423. }
  2424. if (listener->IsInterested()) {
  2425. if (match_elements.empty()) {
  2426. *listener << "has no element that matches";
  2427. } else if (match_elements.size() == 1) {
  2428. *listener << "whose element #" << match_elements[0] << " matches";
  2429. } else {
  2430. *listener << "whose elements (";
  2431. std::string sep = "";
  2432. for (size_t e : match_elements) {
  2433. *listener << sep << e;
  2434. sep = ", ";
  2435. }
  2436. *listener << ") match";
  2437. }
  2438. }
  2439. StringMatchResultListener count_listener;
  2440. if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) {
  2441. *listener << " and whose match quantity of " << match_elements.size()
  2442. << " matches";
  2443. PrintIfNotEmpty(count_listener.str(), listener->stream());
  2444. return true;
  2445. } else {
  2446. if (match_elements.empty()) {
  2447. *listener << " and";
  2448. } else {
  2449. *listener << " but";
  2450. }
  2451. *listener << " whose match quantity of " << match_elements.size()
  2452. << " does not match";
  2453. PrintIfNotEmpty(count_listener.str(), listener->stream());
  2454. return false;
  2455. }
  2456. }
  2457. protected:
  2458. const Matcher<const Element&> inner_matcher_;
  2459. };
  2460. // Implements Contains(element_matcher) for the given argument type Container.
  2461. // Symmetric to EachMatcherImpl.
  2462. template <typename Container>
  2463. class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
  2464. public:
  2465. template <typename InnerMatcher>
  2466. explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
  2467. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  2468. // Describes what this matcher does.
  2469. void DescribeTo(::std::ostream* os) const override {
  2470. *os << "contains at least one element that ";
  2471. this->inner_matcher_.DescribeTo(os);
  2472. }
  2473. void DescribeNegationTo(::std::ostream* os) const override {
  2474. *os << "doesn't contain any element that ";
  2475. this->inner_matcher_.DescribeTo(os);
  2476. }
  2477. bool MatchAndExplain(Container container,
  2478. MatchResultListener* listener) const override {
  2479. return this->MatchAndExplainImpl(false, container, listener);
  2480. }
  2481. };
  2482. // Implements Each(element_matcher) for the given argument type Container.
  2483. // Symmetric to ContainsMatcherImpl.
  2484. template <typename Container>
  2485. class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
  2486. public:
  2487. template <typename InnerMatcher>
  2488. explicit EachMatcherImpl(InnerMatcher inner_matcher)
  2489. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  2490. // Describes what this matcher does.
  2491. void DescribeTo(::std::ostream* os) const override {
  2492. *os << "only contains elements that ";
  2493. this->inner_matcher_.DescribeTo(os);
  2494. }
  2495. void DescribeNegationTo(::std::ostream* os) const override {
  2496. *os << "contains some element that ";
  2497. this->inner_matcher_.DescribeNegationTo(os);
  2498. }
  2499. bool MatchAndExplain(Container container,
  2500. MatchResultListener* listener) const override {
  2501. return this->MatchAndExplainImpl(true, container, listener);
  2502. }
  2503. };
  2504. // Implements Contains(element_matcher).Times(n) for the given argument type
  2505. // Container.
  2506. template <typename Container>
  2507. class ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> {
  2508. public:
  2509. template <typename InnerMatcher>
  2510. explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher,
  2511. Matcher<size_t> count_matcher)
  2512. : QuantifierMatcherImpl<Container>(inner_matcher),
  2513. count_matcher_(std::move(count_matcher)) {}
  2514. void DescribeTo(::std::ostream* os) const override {
  2515. *os << "quantity of elements that match ";
  2516. this->inner_matcher_.DescribeTo(os);
  2517. *os << " ";
  2518. count_matcher_.DescribeTo(os);
  2519. }
  2520. void DescribeNegationTo(::std::ostream* os) const override {
  2521. *os << "quantity of elements that match ";
  2522. this->inner_matcher_.DescribeTo(os);
  2523. *os << " ";
  2524. count_matcher_.DescribeNegationTo(os);
  2525. }
  2526. bool MatchAndExplain(Container container,
  2527. MatchResultListener* listener) const override {
  2528. return this->MatchAndExplainImpl(count_matcher_, container, listener);
  2529. }
  2530. private:
  2531. const Matcher<size_t> count_matcher_;
  2532. };
  2533. // Implements polymorphic Contains(element_matcher).Times(n).
  2534. template <typename M>
  2535. class ContainsTimesMatcher {
  2536. public:
  2537. explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher)
  2538. : inner_matcher_(m), count_matcher_(std::move(count_matcher)) {}
  2539. template <typename Container>
  2540. operator Matcher<Container>() const { // NOLINT
  2541. return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>(
  2542. inner_matcher_, count_matcher_));
  2543. }
  2544. private:
  2545. const M inner_matcher_;
  2546. const Matcher<size_t> count_matcher_;
  2547. };
  2548. // Implements polymorphic Contains(element_matcher).
  2549. template <typename M>
  2550. class ContainsMatcher {
  2551. public:
  2552. explicit ContainsMatcher(M m) : inner_matcher_(m) {}
  2553. template <typename Container>
  2554. operator Matcher<Container>() const { // NOLINT
  2555. return Matcher<Container>(
  2556. new ContainsMatcherImpl<const Container&>(inner_matcher_));
  2557. }
  2558. ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const {
  2559. return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher));
  2560. }
  2561. private:
  2562. const M inner_matcher_;
  2563. };
  2564. // Implements polymorphic Each(element_matcher).
  2565. template <typename M>
  2566. class EachMatcher {
  2567. public:
  2568. explicit EachMatcher(M m) : inner_matcher_(m) {}
  2569. template <typename Container>
  2570. operator Matcher<Container>() const { // NOLINT
  2571. return Matcher<Container>(
  2572. new EachMatcherImpl<const Container&>(inner_matcher_));
  2573. }
  2574. private:
  2575. const M inner_matcher_;
  2576. };
  2577. struct Rank1 {};
  2578. struct Rank0 : Rank1 {};
  2579. namespace pair_getters {
  2580. using std::get;
  2581. template <typename T>
  2582. auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
  2583. return get<0>(x);
  2584. }
  2585. template <typename T>
  2586. auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
  2587. return x.first;
  2588. }
  2589. template <typename T>
  2590. auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
  2591. return get<1>(x);
  2592. }
  2593. template <typename T>
  2594. auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
  2595. return x.second;
  2596. }
  2597. } // namespace pair_getters
  2598. // Implements Key(inner_matcher) for the given argument pair type.
  2599. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  2600. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  2601. // std::map that contains at least one element whose key is >= 5.
  2602. template <typename PairType>
  2603. class KeyMatcherImpl : public MatcherInterface<PairType> {
  2604. public:
  2605. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  2606. typedef typename RawPairType::first_type KeyType;
  2607. template <typename InnerMatcher>
  2608. explicit KeyMatcherImpl(InnerMatcher inner_matcher)
  2609. : inner_matcher_(
  2610. testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {}
  2611. // Returns true if and only if 'key_value.first' (the key) matches the inner
  2612. // matcher.
  2613. bool MatchAndExplain(PairType key_value,
  2614. MatchResultListener* listener) const override {
  2615. StringMatchResultListener inner_listener;
  2616. const bool match = inner_matcher_.MatchAndExplain(
  2617. pair_getters::First(key_value, Rank0()), &inner_listener);
  2618. const std::string explanation = inner_listener.str();
  2619. if (!explanation.empty()) {
  2620. *listener << "whose first field is a value " << explanation;
  2621. }
  2622. return match;
  2623. }
  2624. // Describes what this matcher does.
  2625. void DescribeTo(::std::ostream* os) const override {
  2626. *os << "has a key that ";
  2627. inner_matcher_.DescribeTo(os);
  2628. }
  2629. // Describes what the negation of this matcher does.
  2630. void DescribeNegationTo(::std::ostream* os) const override {
  2631. *os << "doesn't have a key that ";
  2632. inner_matcher_.DescribeTo(os);
  2633. }
  2634. private:
  2635. const Matcher<const KeyType&> inner_matcher_;
  2636. };
  2637. // Implements polymorphic Key(matcher_for_key).
  2638. template <typename M>
  2639. class KeyMatcher {
  2640. public:
  2641. explicit KeyMatcher(M m) : matcher_for_key_(m) {}
  2642. template <typename PairType>
  2643. operator Matcher<PairType>() const {
  2644. return Matcher<PairType>(
  2645. new KeyMatcherImpl<const PairType&>(matcher_for_key_));
  2646. }
  2647. private:
  2648. const M matcher_for_key_;
  2649. };
  2650. // Implements polymorphic Address(matcher_for_address).
  2651. template <typename InnerMatcher>
  2652. class AddressMatcher {
  2653. public:
  2654. explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
  2655. template <typename Type>
  2656. operator Matcher<Type>() const { // NOLINT
  2657. return Matcher<Type>(new Impl<const Type&>(matcher_));
  2658. }
  2659. private:
  2660. // The monomorphic implementation that works for a particular object type.
  2661. template <typename Type>
  2662. class Impl : public MatcherInterface<Type> {
  2663. public:
  2664. using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
  2665. explicit Impl(const InnerMatcher& matcher)
  2666. : matcher_(MatcherCast<Address>(matcher)) {}
  2667. void DescribeTo(::std::ostream* os) const override {
  2668. *os << "has address that ";
  2669. matcher_.DescribeTo(os);
  2670. }
  2671. void DescribeNegationTo(::std::ostream* os) const override {
  2672. *os << "does not have address that ";
  2673. matcher_.DescribeTo(os);
  2674. }
  2675. bool MatchAndExplain(Type object,
  2676. MatchResultListener* listener) const override {
  2677. *listener << "which has address ";
  2678. Address address = std::addressof(object);
  2679. return MatchPrintAndExplain(address, matcher_, listener);
  2680. }
  2681. private:
  2682. const Matcher<Address> matcher_;
  2683. };
  2684. const InnerMatcher matcher_;
  2685. };
  2686. // Implements Pair(first_matcher, second_matcher) for the given argument pair
  2687. // type with its two matchers. See Pair() function below.
  2688. template <typename PairType>
  2689. class PairMatcherImpl : public MatcherInterface<PairType> {
  2690. public:
  2691. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  2692. typedef typename RawPairType::first_type FirstType;
  2693. typedef typename RawPairType::second_type SecondType;
  2694. template <typename FirstMatcher, typename SecondMatcher>
  2695. PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
  2696. : first_matcher_(
  2697. testing::SafeMatcherCast<const FirstType&>(first_matcher)),
  2698. second_matcher_(
  2699. testing::SafeMatcherCast<const SecondType&>(second_matcher)) {}
  2700. // Describes what this matcher does.
  2701. void DescribeTo(::std::ostream* os) const override {
  2702. *os << "has a first field that ";
  2703. first_matcher_.DescribeTo(os);
  2704. *os << ", and has a second field that ";
  2705. second_matcher_.DescribeTo(os);
  2706. }
  2707. // Describes what the negation of this matcher does.
  2708. void DescribeNegationTo(::std::ostream* os) const override {
  2709. *os << "has a first field that ";
  2710. first_matcher_.DescribeNegationTo(os);
  2711. *os << ", or has a second field that ";
  2712. second_matcher_.DescribeNegationTo(os);
  2713. }
  2714. // Returns true if and only if 'a_pair.first' matches first_matcher and
  2715. // 'a_pair.second' matches second_matcher.
  2716. bool MatchAndExplain(PairType a_pair,
  2717. MatchResultListener* listener) const override {
  2718. if (!listener->IsInterested()) {
  2719. // If the listener is not interested, we don't need to construct the
  2720. // explanation.
  2721. return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
  2722. second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
  2723. }
  2724. StringMatchResultListener first_inner_listener;
  2725. if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
  2726. &first_inner_listener)) {
  2727. *listener << "whose first field does not match";
  2728. PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
  2729. return false;
  2730. }
  2731. StringMatchResultListener second_inner_listener;
  2732. if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
  2733. &second_inner_listener)) {
  2734. *listener << "whose second field does not match";
  2735. PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
  2736. return false;
  2737. }
  2738. ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
  2739. listener);
  2740. return true;
  2741. }
  2742. private:
  2743. void ExplainSuccess(const std::string& first_explanation,
  2744. const std::string& second_explanation,
  2745. MatchResultListener* listener) const {
  2746. *listener << "whose both fields match";
  2747. if (!first_explanation.empty()) {
  2748. *listener << ", where the first field is a value " << first_explanation;
  2749. }
  2750. if (!second_explanation.empty()) {
  2751. *listener << ", ";
  2752. if (!first_explanation.empty()) {
  2753. *listener << "and ";
  2754. } else {
  2755. *listener << "where ";
  2756. }
  2757. *listener << "the second field is a value " << second_explanation;
  2758. }
  2759. }
  2760. const Matcher<const FirstType&> first_matcher_;
  2761. const Matcher<const SecondType&> second_matcher_;
  2762. };
  2763. // Implements polymorphic Pair(first_matcher, second_matcher).
  2764. template <typename FirstMatcher, typename SecondMatcher>
  2765. class PairMatcher {
  2766. public:
  2767. PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
  2768. : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
  2769. template <typename PairType>
  2770. operator Matcher<PairType>() const {
  2771. return Matcher<PairType>(
  2772. new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
  2773. }
  2774. private:
  2775. const FirstMatcher first_matcher_;
  2776. const SecondMatcher second_matcher_;
  2777. };
  2778. template <typename T, size_t... I>
  2779. auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
  2780. -> decltype(std::tie(get<I>(t)...)) {
  2781. static_assert(std::tuple_size<T>::value == sizeof...(I),
  2782. "Number of arguments doesn't match the number of fields.");
  2783. return std::tie(get<I>(t)...);
  2784. }
  2785. #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
  2786. template <typename T>
  2787. auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
  2788. const auto& [a] = t;
  2789. return std::tie(a);
  2790. }
  2791. template <typename T>
  2792. auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
  2793. const auto& [a, b] = t;
  2794. return std::tie(a, b);
  2795. }
  2796. template <typename T>
  2797. auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
  2798. const auto& [a, b, c] = t;
  2799. return std::tie(a, b, c);
  2800. }
  2801. template <typename T>
  2802. auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
  2803. const auto& [a, b, c, d] = t;
  2804. return std::tie(a, b, c, d);
  2805. }
  2806. template <typename T>
  2807. auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
  2808. const auto& [a, b, c, d, e] = t;
  2809. return std::tie(a, b, c, d, e);
  2810. }
  2811. template <typename T>
  2812. auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
  2813. const auto& [a, b, c, d, e, f] = t;
  2814. return std::tie(a, b, c, d, e, f);
  2815. }
  2816. template <typename T>
  2817. auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
  2818. const auto& [a, b, c, d, e, f, g] = t;
  2819. return std::tie(a, b, c, d, e, f, g);
  2820. }
  2821. template <typename T>
  2822. auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
  2823. const auto& [a, b, c, d, e, f, g, h] = t;
  2824. return std::tie(a, b, c, d, e, f, g, h);
  2825. }
  2826. template <typename T>
  2827. auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
  2828. const auto& [a, b, c, d, e, f, g, h, i] = t;
  2829. return std::tie(a, b, c, d, e, f, g, h, i);
  2830. }
  2831. template <typename T>
  2832. auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
  2833. const auto& [a, b, c, d, e, f, g, h, i, j] = t;
  2834. return std::tie(a, b, c, d, e, f, g, h, i, j);
  2835. }
  2836. template <typename T>
  2837. auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
  2838. const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
  2839. return std::tie(a, b, c, d, e, f, g, h, i, j, k);
  2840. }
  2841. template <typename T>
  2842. auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
  2843. const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
  2844. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
  2845. }
  2846. template <typename T>
  2847. auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
  2848. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
  2849. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
  2850. }
  2851. template <typename T>
  2852. auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
  2853. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
  2854. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
  2855. }
  2856. template <typename T>
  2857. auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
  2858. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
  2859. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
  2860. }
  2861. template <typename T>
  2862. auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
  2863. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
  2864. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
  2865. }
  2866. template <typename T>
  2867. auto UnpackStructImpl(const T& t, MakeIndexSequence<17>, char) {
  2868. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;
  2869. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
  2870. }
  2871. template <typename T>
  2872. auto UnpackStructImpl(const T& t, MakeIndexSequence<18>, char) {
  2873. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;
  2874. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);
  2875. }
  2876. template <typename T>
  2877. auto UnpackStructImpl(const T& t, MakeIndexSequence<19>, char) {
  2878. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;
  2879. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);
  2880. }
  2881. #endif // defined(__cpp_structured_bindings)
  2882. template <size_t I, typename T>
  2883. auto UnpackStruct(const T& t)
  2884. -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
  2885. return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
  2886. }
  2887. // Helper function to do comma folding in C++11.
  2888. // The array ensures left-to-right order of evaluation.
  2889. // Usage: VariadicExpand({expr...});
  2890. template <typename T, size_t N>
  2891. void VariadicExpand(const T (&)[N]) {}
  2892. template <typename Struct, typename StructSize>
  2893. class FieldsAreMatcherImpl;
  2894. template <typename Struct, size_t... I>
  2895. class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
  2896. : public MatcherInterface<Struct> {
  2897. using UnpackedType =
  2898. decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
  2899. using MatchersType = std::tuple<
  2900. Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
  2901. public:
  2902. template <typename Inner>
  2903. explicit FieldsAreMatcherImpl(const Inner& matchers)
  2904. : matchers_(testing::SafeMatcherCast<
  2905. const typename std::tuple_element<I, UnpackedType>::type&>(
  2906. std::get<I>(matchers))...) {}
  2907. void DescribeTo(::std::ostream* os) const override {
  2908. const char* separator = "";
  2909. VariadicExpand(
  2910. {(*os << separator << "has field #" << I << " that ",
  2911. std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
  2912. }
  2913. void DescribeNegationTo(::std::ostream* os) const override {
  2914. const char* separator = "";
  2915. VariadicExpand({(*os << separator << "has field #" << I << " that ",
  2916. std::get<I>(matchers_).DescribeNegationTo(os),
  2917. separator = ", or ")...});
  2918. }
  2919. bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
  2920. return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
  2921. }
  2922. private:
  2923. bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
  2924. if (!listener->IsInterested()) {
  2925. // If the listener is not interested, we don't need to construct the
  2926. // explanation.
  2927. bool good = true;
  2928. VariadicExpand({good = good && std::get<I>(matchers_).Matches(
  2929. std::get<I>(tuple))...});
  2930. return good;
  2931. }
  2932. size_t failed_pos = ~size_t{};
  2933. std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
  2934. VariadicExpand(
  2935. {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
  2936. std::get<I>(tuple), &inner_listener[I])
  2937. ? failed_pos = I
  2938. : 0 ...});
  2939. if (failed_pos != ~size_t{}) {
  2940. *listener << "whose field #" << failed_pos << " does not match";
  2941. PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
  2942. return false;
  2943. }
  2944. *listener << "whose all elements match";
  2945. const char* separator = ", where";
  2946. for (size_t index = 0; index < sizeof...(I); ++index) {
  2947. const std::string str = inner_listener[index].str();
  2948. if (!str.empty()) {
  2949. *listener << separator << " field #" << index << " is a value " << str;
  2950. separator = ", and";
  2951. }
  2952. }
  2953. return true;
  2954. }
  2955. MatchersType matchers_;
  2956. };
  2957. template <typename... Inner>
  2958. class FieldsAreMatcher {
  2959. public:
  2960. explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
  2961. template <typename Struct>
  2962. operator Matcher<Struct>() const { // NOLINT
  2963. return Matcher<Struct>(
  2964. new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
  2965. matchers_));
  2966. }
  2967. private:
  2968. std::tuple<Inner...> matchers_;
  2969. };
  2970. // Implements ElementsAre() and ElementsAreArray().
  2971. template <typename Container>
  2972. class ElementsAreMatcherImpl : public MatcherInterface<Container> {
  2973. public:
  2974. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  2975. typedef internal::StlContainerView<RawContainer> View;
  2976. typedef typename View::type StlContainer;
  2977. typedef typename View::const_reference StlContainerReference;
  2978. typedef typename StlContainer::value_type Element;
  2979. // Constructs the matcher from a sequence of element values or
  2980. // element matchers.
  2981. template <typename InputIter>
  2982. ElementsAreMatcherImpl(InputIter first, InputIter last) {
  2983. while (first != last) {
  2984. matchers_.push_back(MatcherCast<const Element&>(*first++));
  2985. }
  2986. }
  2987. // Describes what this matcher does.
  2988. void DescribeTo(::std::ostream* os) const override {
  2989. if (count() == 0) {
  2990. *os << "is empty";
  2991. } else if (count() == 1) {
  2992. *os << "has 1 element that ";
  2993. matchers_[0].DescribeTo(os);
  2994. } else {
  2995. *os << "has " << Elements(count()) << " where\n";
  2996. for (size_t i = 0; i != count(); ++i) {
  2997. *os << "element #" << i << " ";
  2998. matchers_[i].DescribeTo(os);
  2999. if (i + 1 < count()) {
  3000. *os << ",\n";
  3001. }
  3002. }
  3003. }
  3004. }
  3005. // Describes what the negation of this matcher does.
  3006. void DescribeNegationTo(::std::ostream* os) const override {
  3007. if (count() == 0) {
  3008. *os << "isn't empty";
  3009. return;
  3010. }
  3011. *os << "doesn't have " << Elements(count()) << ", or\n";
  3012. for (size_t i = 0; i != count(); ++i) {
  3013. *os << "element #" << i << " ";
  3014. matchers_[i].DescribeNegationTo(os);
  3015. if (i + 1 < count()) {
  3016. *os << ", or\n";
  3017. }
  3018. }
  3019. }
  3020. bool MatchAndExplain(Container container,
  3021. MatchResultListener* listener) const override {
  3022. // To work with stream-like "containers", we must only walk
  3023. // through the elements in one pass.
  3024. const bool listener_interested = listener->IsInterested();
  3025. // explanations[i] is the explanation of the element at index i.
  3026. ::std::vector<std::string> explanations(count());
  3027. StlContainerReference stl_container = View::ConstReference(container);
  3028. auto it = stl_container.begin();
  3029. size_t exam_pos = 0;
  3030. bool mismatch_found = false; // Have we found a mismatched element yet?
  3031. // Go through the elements and matchers in pairs, until we reach
  3032. // the end of either the elements or the matchers, or until we find a
  3033. // mismatch.
  3034. for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
  3035. bool match; // Does the current element match the current matcher?
  3036. if (listener_interested) {
  3037. StringMatchResultListener s;
  3038. match = matchers_[exam_pos].MatchAndExplain(*it, &s);
  3039. explanations[exam_pos] = s.str();
  3040. } else {
  3041. match = matchers_[exam_pos].Matches(*it);
  3042. }
  3043. if (!match) {
  3044. mismatch_found = true;
  3045. break;
  3046. }
  3047. }
  3048. // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
  3049. // Find how many elements the actual container has. We avoid
  3050. // calling size() s.t. this code works for stream-like "containers"
  3051. // that don't define size().
  3052. size_t actual_count = exam_pos;
  3053. for (; it != stl_container.end(); ++it) {
  3054. ++actual_count;
  3055. }
  3056. if (actual_count != count()) {
  3057. // The element count doesn't match. If the container is empty,
  3058. // there's no need to explain anything as Google Mock already
  3059. // prints the empty container. Otherwise we just need to show
  3060. // how many elements there actually are.
  3061. if (listener_interested && (actual_count != 0)) {
  3062. *listener << "which has " << Elements(actual_count);
  3063. }
  3064. return false;
  3065. }
  3066. if (mismatch_found) {
  3067. // The element count matches, but the exam_pos-th element doesn't match.
  3068. if (listener_interested) {
  3069. *listener << "whose element #" << exam_pos << " doesn't match";
  3070. PrintIfNotEmpty(explanations[exam_pos], listener->stream());
  3071. }
  3072. return false;
  3073. }
  3074. // Every element matches its expectation. We need to explain why
  3075. // (the obvious ones can be skipped).
  3076. if (listener_interested) {
  3077. bool reason_printed = false;
  3078. for (size_t i = 0; i != count(); ++i) {
  3079. const std::string& s = explanations[i];
  3080. if (!s.empty()) {
  3081. if (reason_printed) {
  3082. *listener << ",\nand ";
  3083. }
  3084. *listener << "whose element #" << i << " matches, " << s;
  3085. reason_printed = true;
  3086. }
  3087. }
  3088. }
  3089. return true;
  3090. }
  3091. private:
  3092. static Message Elements(size_t count) {
  3093. return Message() << count << (count == 1 ? " element" : " elements");
  3094. }
  3095. size_t count() const { return matchers_.size(); }
  3096. ::std::vector<Matcher<const Element&>> matchers_;
  3097. };
  3098. // Connectivity matrix of (elements X matchers), in element-major order.
  3099. // Initially, there are no edges.
  3100. // Use NextGraph() to iterate over all possible edge configurations.
  3101. // Use Randomize() to generate a random edge configuration.
  3102. class GTEST_API_ MatchMatrix {
  3103. public:
  3104. MatchMatrix(size_t num_elements, size_t num_matchers)
  3105. : num_elements_(num_elements),
  3106. num_matchers_(num_matchers),
  3107. matched_(num_elements_ * num_matchers_, 0) {}
  3108. size_t LhsSize() const { return num_elements_; }
  3109. size_t RhsSize() const { return num_matchers_; }
  3110. bool HasEdge(size_t ilhs, size_t irhs) const {
  3111. return matched_[SpaceIndex(ilhs, irhs)] == 1;
  3112. }
  3113. void SetEdge(size_t ilhs, size_t irhs, bool b) {
  3114. matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
  3115. }
  3116. // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
  3117. // adds 1 to that number; returns false if incrementing the graph left it
  3118. // empty.
  3119. bool NextGraph();
  3120. void Randomize();
  3121. std::string DebugString() const;
  3122. private:
  3123. size_t SpaceIndex(size_t ilhs, size_t irhs) const {
  3124. return ilhs * num_matchers_ + irhs;
  3125. }
  3126. size_t num_elements_;
  3127. size_t num_matchers_;
  3128. // Each element is a char interpreted as bool. They are stored as a
  3129. // flattened array in lhs-major order, use 'SpaceIndex()' to translate
  3130. // a (ilhs, irhs) matrix coordinate into an offset.
  3131. ::std::vector<char> matched_;
  3132. };
  3133. typedef ::std::pair<size_t, size_t> ElementMatcherPair;
  3134. typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
  3135. // Returns a maximum bipartite matching for the specified graph 'g'.
  3136. // The matching is represented as a vector of {element, matcher} pairs.
  3137. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g);
  3138. struct UnorderedMatcherRequire {
  3139. enum Flags {
  3140. Superset = 1 << 0,
  3141. Subset = 1 << 1,
  3142. ExactMatch = Superset | Subset,
  3143. };
  3144. };
  3145. // Untyped base class for implementing UnorderedElementsAre. By
  3146. // putting logic that's not specific to the element type here, we
  3147. // reduce binary bloat and increase compilation speed.
  3148. class GTEST_API_ UnorderedElementsAreMatcherImplBase {
  3149. protected:
  3150. explicit UnorderedElementsAreMatcherImplBase(
  3151. UnorderedMatcherRequire::Flags matcher_flags)
  3152. : match_flags_(matcher_flags) {}
  3153. // A vector of matcher describers, one for each element matcher.
  3154. // Does not own the describers (and thus can be used only when the
  3155. // element matchers are alive).
  3156. typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
  3157. // Describes this UnorderedElementsAre matcher.
  3158. void DescribeToImpl(::std::ostream* os) const;
  3159. // Describes the negation of this UnorderedElementsAre matcher.
  3160. void DescribeNegationToImpl(::std::ostream* os) const;
  3161. bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
  3162. const MatchMatrix& matrix,
  3163. MatchResultListener* listener) const;
  3164. bool FindPairing(const MatchMatrix& matrix,
  3165. MatchResultListener* listener) const;
  3166. MatcherDescriberVec& matcher_describers() { return matcher_describers_; }
  3167. static Message Elements(size_t n) {
  3168. return Message() << n << " element" << (n == 1 ? "" : "s");
  3169. }
  3170. UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
  3171. private:
  3172. UnorderedMatcherRequire::Flags match_flags_;
  3173. MatcherDescriberVec matcher_describers_;
  3174. };
  3175. // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
  3176. // IsSupersetOf.
  3177. template <typename Container>
  3178. class UnorderedElementsAreMatcherImpl
  3179. : public MatcherInterface<Container>,
  3180. public UnorderedElementsAreMatcherImplBase {
  3181. public:
  3182. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  3183. typedef internal::StlContainerView<RawContainer> View;
  3184. typedef typename View::type StlContainer;
  3185. typedef typename View::const_reference StlContainerReference;
  3186. typedef typename StlContainer::value_type Element;
  3187. template <typename InputIter>
  3188. UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
  3189. InputIter first, InputIter last)
  3190. : UnorderedElementsAreMatcherImplBase(matcher_flags) {
  3191. for (; first != last; ++first) {
  3192. matchers_.push_back(MatcherCast<const Element&>(*first));
  3193. }
  3194. for (const auto& m : matchers_) {
  3195. matcher_describers().push_back(m.GetDescriber());
  3196. }
  3197. }
  3198. // Describes what this matcher does.
  3199. void DescribeTo(::std::ostream* os) const override {
  3200. return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
  3201. }
  3202. // Describes what the negation of this matcher does.
  3203. void DescribeNegationTo(::std::ostream* os) const override {
  3204. return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
  3205. }
  3206. bool MatchAndExplain(Container container,
  3207. MatchResultListener* listener) const override {
  3208. StlContainerReference stl_container = View::ConstReference(container);
  3209. ::std::vector<std::string> element_printouts;
  3210. MatchMatrix matrix =
  3211. AnalyzeElements(stl_container.begin(), stl_container.end(),
  3212. &element_printouts, listener);
  3213. return VerifyMatchMatrix(element_printouts, matrix, listener) &&
  3214. FindPairing(matrix, listener);
  3215. }
  3216. private:
  3217. template <typename ElementIter>
  3218. MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
  3219. ::std::vector<std::string>* element_printouts,
  3220. MatchResultListener* listener) const {
  3221. element_printouts->clear();
  3222. ::std::vector<char> did_match;
  3223. size_t num_elements = 0;
  3224. DummyMatchResultListener dummy;
  3225. for (; elem_first != elem_last; ++num_elements, ++elem_first) {
  3226. if (listener->IsInterested()) {
  3227. element_printouts->push_back(PrintToString(*elem_first));
  3228. }
  3229. for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
  3230. did_match.push_back(
  3231. matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
  3232. }
  3233. }
  3234. MatchMatrix matrix(num_elements, matchers_.size());
  3235. ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
  3236. for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
  3237. for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
  3238. matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
  3239. }
  3240. }
  3241. return matrix;
  3242. }
  3243. ::std::vector<Matcher<const Element&>> matchers_;
  3244. };
  3245. // Functor for use in TransformTuple.
  3246. // Performs MatcherCast<Target> on an input argument of any type.
  3247. template <typename Target>
  3248. struct CastAndAppendTransform {
  3249. template <typename Arg>
  3250. Matcher<Target> operator()(const Arg& a) const {
  3251. return MatcherCast<Target>(a);
  3252. }
  3253. };
  3254. // Implements UnorderedElementsAre.
  3255. template <typename MatcherTuple>
  3256. class UnorderedElementsAreMatcher {
  3257. public:
  3258. explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
  3259. : matchers_(args) {}
  3260. template <typename Container>
  3261. operator Matcher<Container>() const {
  3262. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  3263. typedef typename internal::StlContainerView<RawContainer>::type View;
  3264. typedef typename View::value_type Element;
  3265. typedef ::std::vector<Matcher<const Element&>> MatcherVec;
  3266. MatcherVec matchers;
  3267. matchers.reserve(::std::tuple_size<MatcherTuple>::value);
  3268. TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
  3269. ::std::back_inserter(matchers));
  3270. return Matcher<Container>(
  3271. new UnorderedElementsAreMatcherImpl<const Container&>(
  3272. UnorderedMatcherRequire::ExactMatch, matchers.begin(),
  3273. matchers.end()));
  3274. }
  3275. private:
  3276. const MatcherTuple matchers_;
  3277. };
  3278. // Implements ElementsAre.
  3279. template <typename MatcherTuple>
  3280. class ElementsAreMatcher {
  3281. public:
  3282. explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
  3283. template <typename Container>
  3284. operator Matcher<Container>() const {
  3285. static_assert(
  3286. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
  3287. ::std::tuple_size<MatcherTuple>::value < 2,
  3288. "use UnorderedElementsAre with hash tables");
  3289. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  3290. typedef typename internal::StlContainerView<RawContainer>::type View;
  3291. typedef typename View::value_type Element;
  3292. typedef ::std::vector<Matcher<const Element&>> MatcherVec;
  3293. MatcherVec matchers;
  3294. matchers.reserve(::std::tuple_size<MatcherTuple>::value);
  3295. TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
  3296. ::std::back_inserter(matchers));
  3297. return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
  3298. matchers.begin(), matchers.end()));
  3299. }
  3300. private:
  3301. const MatcherTuple matchers_;
  3302. };
  3303. // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
  3304. template <typename T>
  3305. class UnorderedElementsAreArrayMatcher {
  3306. public:
  3307. template <typename Iter>
  3308. UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
  3309. Iter first, Iter last)
  3310. : match_flags_(match_flags), matchers_(first, last) {}
  3311. template <typename Container>
  3312. operator Matcher<Container>() const {
  3313. return Matcher<Container>(
  3314. new UnorderedElementsAreMatcherImpl<const Container&>(
  3315. match_flags_, matchers_.begin(), matchers_.end()));
  3316. }
  3317. private:
  3318. UnorderedMatcherRequire::Flags match_flags_;
  3319. ::std::vector<T> matchers_;
  3320. };
  3321. // Implements ElementsAreArray().
  3322. template <typename T>
  3323. class ElementsAreArrayMatcher {
  3324. public:
  3325. template <typename Iter>
  3326. ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
  3327. template <typename Container>
  3328. operator Matcher<Container>() const {
  3329. static_assert(
  3330. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
  3331. "use UnorderedElementsAreArray with hash tables");
  3332. return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
  3333. matchers_.begin(), matchers_.end()));
  3334. }
  3335. private:
  3336. const ::std::vector<T> matchers_;
  3337. };
  3338. // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
  3339. // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
  3340. // second) is a polymorphic matcher that matches a value x if and only if
  3341. // tm matches tuple (x, second). Useful for implementing
  3342. // UnorderedPointwise() in terms of UnorderedElementsAreArray().
  3343. //
  3344. // BoundSecondMatcher is copyable and assignable, as we need to put
  3345. // instances of this class in a vector when implementing
  3346. // UnorderedPointwise().
  3347. template <typename Tuple2Matcher, typename Second>
  3348. class BoundSecondMatcher {
  3349. public:
  3350. BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
  3351. : tuple2_matcher_(tm), second_value_(second) {}
  3352. BoundSecondMatcher(const BoundSecondMatcher& other) = default;
  3353. template <typename T>
  3354. operator Matcher<T>() const {
  3355. return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
  3356. }
  3357. // We have to define this for UnorderedPointwise() to compile in
  3358. // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
  3359. // which requires the elements to be assignable in C++98. The
  3360. // compiler cannot generate the operator= for us, as Tuple2Matcher
  3361. // and Second may not be assignable.
  3362. //
  3363. // However, this should never be called, so the implementation just
  3364. // need to assert.
  3365. void operator=(const BoundSecondMatcher& /*rhs*/) {
  3366. GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
  3367. }
  3368. private:
  3369. template <typename T>
  3370. class Impl : public MatcherInterface<T> {
  3371. public:
  3372. typedef ::std::tuple<T, Second> ArgTuple;
  3373. Impl(const Tuple2Matcher& tm, const Second& second)
  3374. : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
  3375. second_value_(second) {}
  3376. void DescribeTo(::std::ostream* os) const override {
  3377. *os << "and ";
  3378. UniversalPrint(second_value_, os);
  3379. *os << " ";
  3380. mono_tuple2_matcher_.DescribeTo(os);
  3381. }
  3382. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  3383. return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
  3384. listener);
  3385. }
  3386. private:
  3387. const Matcher<const ArgTuple&> mono_tuple2_matcher_;
  3388. const Second second_value_;
  3389. };
  3390. const Tuple2Matcher tuple2_matcher_;
  3391. const Second second_value_;
  3392. };
  3393. // Given a 2-tuple matcher tm and a value second,
  3394. // MatcherBindSecond(tm, second) returns a matcher that matches a
  3395. // value x if and only if tm matches tuple (x, second). Useful for
  3396. // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().
  3397. template <typename Tuple2Matcher, typename Second>
  3398. BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
  3399. const Tuple2Matcher& tm, const Second& second) {
  3400. return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
  3401. }
  3402. // Returns the description for a matcher defined using the MATCHER*()
  3403. // macro where the user-supplied description string is "", if
  3404. // 'negation' is false; otherwise returns the description of the
  3405. // negation of the matcher. 'param_values' contains a list of strings
  3406. // that are the print-out of the matcher's parameters.
  3407. GTEST_API_ std::string FormatMatcherDescription(
  3408. bool negation, const char* matcher_name,
  3409. const std::vector<const char*>& param_names, const Strings& param_values);
  3410. // Implements a matcher that checks the value of a optional<> type variable.
  3411. template <typename ValueMatcher>
  3412. class OptionalMatcher {
  3413. public:
  3414. explicit OptionalMatcher(const ValueMatcher& value_matcher)
  3415. : value_matcher_(value_matcher) {}
  3416. template <typename Optional>
  3417. operator Matcher<Optional>() const {
  3418. return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));
  3419. }
  3420. template <typename Optional>
  3421. class Impl : public MatcherInterface<Optional> {
  3422. public:
  3423. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
  3424. typedef typename OptionalView::value_type ValueType;
  3425. explicit Impl(const ValueMatcher& value_matcher)
  3426. : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
  3427. void DescribeTo(::std::ostream* os) const override {
  3428. *os << "value ";
  3429. value_matcher_.DescribeTo(os);
  3430. }
  3431. void DescribeNegationTo(::std::ostream* os) const override {
  3432. *os << "value ";
  3433. value_matcher_.DescribeNegationTo(os);
  3434. }
  3435. bool MatchAndExplain(Optional optional,
  3436. MatchResultListener* listener) const override {
  3437. if (!optional) {
  3438. *listener << "which is not engaged";
  3439. return false;
  3440. }
  3441. const ValueType& value = *optional;
  3442. StringMatchResultListener value_listener;
  3443. const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
  3444. *listener << "whose value " << PrintToString(value)
  3445. << (match ? " matches" : " doesn't match");
  3446. PrintIfNotEmpty(value_listener.str(), listener->stream());
  3447. return match;
  3448. }
  3449. private:
  3450. const Matcher<ValueType> value_matcher_;
  3451. };
  3452. private:
  3453. const ValueMatcher value_matcher_;
  3454. };
  3455. namespace variant_matcher {
  3456. // Overloads to allow VariantMatcher to do proper ADL lookup.
  3457. template <typename T>
  3458. void holds_alternative() {}
  3459. template <typename T>
  3460. void get() {}
  3461. // Implements a matcher that checks the value of a variant<> type variable.
  3462. template <typename T>
  3463. class VariantMatcher {
  3464. public:
  3465. explicit VariantMatcher(::testing::Matcher<const T&> matcher)
  3466. : matcher_(std::move(matcher)) {}
  3467. template <typename Variant>
  3468. bool MatchAndExplain(const Variant& value,
  3469. ::testing::MatchResultListener* listener) const {
  3470. using std::get;
  3471. if (!listener->IsInterested()) {
  3472. return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
  3473. }
  3474. if (!holds_alternative<T>(value)) {
  3475. *listener << "whose value is not of type '" << GetTypeName() << "'";
  3476. return false;
  3477. }
  3478. const T& elem = get<T>(value);
  3479. StringMatchResultListener elem_listener;
  3480. const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
  3481. *listener << "whose value " << PrintToString(elem)
  3482. << (match ? " matches" : " doesn't match");
  3483. PrintIfNotEmpty(elem_listener.str(), listener->stream());
  3484. return match;
  3485. }
  3486. void DescribeTo(std::ostream* os) const {
  3487. *os << "is a variant<> with value of type '" << GetTypeName()
  3488. << "' and the value ";
  3489. matcher_.DescribeTo(os);
  3490. }
  3491. void DescribeNegationTo(std::ostream* os) const {
  3492. *os << "is a variant<> with value of type other than '" << GetTypeName()
  3493. << "' or the value ";
  3494. matcher_.DescribeNegationTo(os);
  3495. }
  3496. private:
  3497. static std::string GetTypeName() {
  3498. #if GTEST_HAS_RTTI
  3499. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
  3500. return internal::GetTypeName<T>());
  3501. #endif
  3502. return "the element type";
  3503. }
  3504. const ::testing::Matcher<const T&> matcher_;
  3505. };
  3506. } // namespace variant_matcher
  3507. namespace any_cast_matcher {
  3508. // Overloads to allow AnyCastMatcher to do proper ADL lookup.
  3509. template <typename T>
  3510. void any_cast() {}
  3511. // Implements a matcher that any_casts the value.
  3512. template <typename T>
  3513. class AnyCastMatcher {
  3514. public:
  3515. explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
  3516. : matcher_(matcher) {}
  3517. template <typename AnyType>
  3518. bool MatchAndExplain(const AnyType& value,
  3519. ::testing::MatchResultListener* listener) const {
  3520. if (!listener->IsInterested()) {
  3521. const T* ptr = any_cast<T>(&value);
  3522. return ptr != nullptr && matcher_.Matches(*ptr);
  3523. }
  3524. const T* elem = any_cast<T>(&value);
  3525. if (elem == nullptr) {
  3526. *listener << "whose value is not of type '" << GetTypeName() << "'";
  3527. return false;
  3528. }
  3529. StringMatchResultListener elem_listener;
  3530. const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
  3531. *listener << "whose value " << PrintToString(*elem)
  3532. << (match ? " matches" : " doesn't match");
  3533. PrintIfNotEmpty(elem_listener.str(), listener->stream());
  3534. return match;
  3535. }
  3536. void DescribeTo(std::ostream* os) const {
  3537. *os << "is an 'any' type with value of type '" << GetTypeName()
  3538. << "' and the value ";
  3539. matcher_.DescribeTo(os);
  3540. }
  3541. void DescribeNegationTo(std::ostream* os) const {
  3542. *os << "is an 'any' type with value of type other than '" << GetTypeName()
  3543. << "' or the value ";
  3544. matcher_.DescribeNegationTo(os);
  3545. }
  3546. private:
  3547. static std::string GetTypeName() {
  3548. #if GTEST_HAS_RTTI
  3549. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
  3550. return internal::GetTypeName<T>());
  3551. #endif
  3552. return "the element type";
  3553. }
  3554. const ::testing::Matcher<const T&> matcher_;
  3555. };
  3556. } // namespace any_cast_matcher
  3557. // Implements the Args() matcher.
  3558. template <class ArgsTuple, size_t... k>
  3559. class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
  3560. public:
  3561. using RawArgsTuple = typename std::decay<ArgsTuple>::type;
  3562. using SelectedArgs =
  3563. std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;
  3564. using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;
  3565. template <typename InnerMatcher>
  3566. explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
  3567. : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
  3568. bool MatchAndExplain(ArgsTuple args,
  3569. MatchResultListener* listener) const override {
  3570. // Workaround spurious C4100 on MSVC<=15.7 when k is empty.
  3571. (void)args;
  3572. const SelectedArgs& selected_args =
  3573. std::forward_as_tuple(std::get<k>(args)...);
  3574. if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);
  3575. PrintIndices(listener->stream());
  3576. *listener << "are " << PrintToString(selected_args);
  3577. StringMatchResultListener inner_listener;
  3578. const bool match =
  3579. inner_matcher_.MatchAndExplain(selected_args, &inner_listener);
  3580. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  3581. return match;
  3582. }
  3583. void DescribeTo(::std::ostream* os) const override {
  3584. *os << "are a tuple ";
  3585. PrintIndices(os);
  3586. inner_matcher_.DescribeTo(os);
  3587. }
  3588. void DescribeNegationTo(::std::ostream* os) const override {
  3589. *os << "are a tuple ";
  3590. PrintIndices(os);
  3591. inner_matcher_.DescribeNegationTo(os);
  3592. }
  3593. private:
  3594. // Prints the indices of the selected fields.
  3595. static void PrintIndices(::std::ostream* os) {
  3596. *os << "whose fields (";
  3597. const char* sep = "";
  3598. // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
  3599. (void)sep;
  3600. // The static_cast to void is needed to silence Clang's -Wcomma warning.
  3601. // This pattern looks suspiciously like we may have mismatched parentheses
  3602. // and may have been trying to use the first operation of the comma operator
  3603. // as a member of the array, so Clang warns that we may have made a mistake.
  3604. const char* dummy[] = {
  3605. "", (static_cast<void>(*os << sep << "#" << k), sep = ", ")...};
  3606. (void)dummy;
  3607. *os << ") ";
  3608. }
  3609. MonomorphicInnerMatcher inner_matcher_;
  3610. };
  3611. template <class InnerMatcher, size_t... k>
  3612. class ArgsMatcher {
  3613. public:
  3614. explicit ArgsMatcher(InnerMatcher inner_matcher)
  3615. : inner_matcher_(std::move(inner_matcher)) {}
  3616. template <typename ArgsTuple>
  3617. operator Matcher<ArgsTuple>() const { // NOLINT
  3618. return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));
  3619. }
  3620. private:
  3621. InnerMatcher inner_matcher_;
  3622. };
  3623. } // namespace internal
  3624. // ElementsAreArray(iterator_first, iterator_last)
  3625. // ElementsAreArray(pointer, count)
  3626. // ElementsAreArray(array)
  3627. // ElementsAreArray(container)
  3628. // ElementsAreArray({ e1, e2, ..., en })
  3629. //
  3630. // The ElementsAreArray() functions are like ElementsAre(...), except
  3631. // that they are given a homogeneous sequence rather than taking each
  3632. // element as a function argument. The sequence can be specified as an
  3633. // array, a pointer and count, a vector, an initializer list, or an
  3634. // STL iterator range. In each of these cases, the underlying sequence
  3635. // can be either a sequence of values or a sequence of matchers.
  3636. //
  3637. // All forms of ElementsAreArray() make a copy of the input matcher sequence.
  3638. template <typename Iter>
  3639. inline internal::ElementsAreArrayMatcher<
  3640. typename ::std::iterator_traits<Iter>::value_type>
  3641. ElementsAreArray(Iter first, Iter last) {
  3642. typedef typename ::std::iterator_traits<Iter>::value_type T;
  3643. return internal::ElementsAreArrayMatcher<T>(first, last);
  3644. }
  3645. template <typename T>
  3646. inline auto ElementsAreArray(const T* pointer, size_t count)
  3647. -> decltype(ElementsAreArray(pointer, pointer + count)) {
  3648. return ElementsAreArray(pointer, pointer + count);
  3649. }
  3650. template <typename T, size_t N>
  3651. inline auto ElementsAreArray(const T (&array)[N])
  3652. -> decltype(ElementsAreArray(array, N)) {
  3653. return ElementsAreArray(array, N);
  3654. }
  3655. template <typename Container>
  3656. inline auto ElementsAreArray(const Container& container)
  3657. -> decltype(ElementsAreArray(container.begin(), container.end())) {
  3658. return ElementsAreArray(container.begin(), container.end());
  3659. }
  3660. template <typename T>
  3661. inline auto ElementsAreArray(::std::initializer_list<T> xs)
  3662. -> decltype(ElementsAreArray(xs.begin(), xs.end())) {
  3663. return ElementsAreArray(xs.begin(), xs.end());
  3664. }
  3665. // UnorderedElementsAreArray(iterator_first, iterator_last)
  3666. // UnorderedElementsAreArray(pointer, count)
  3667. // UnorderedElementsAreArray(array)
  3668. // UnorderedElementsAreArray(container)
  3669. // UnorderedElementsAreArray({ e1, e2, ..., en })
  3670. //
  3671. // UnorderedElementsAreArray() verifies that a bijective mapping onto a
  3672. // collection of matchers exists.
  3673. //
  3674. // The matchers can be specified as an array, a pointer and count, a container,
  3675. // an initializer list, or an STL iterator range. In each of these cases, the
  3676. // underlying matchers can be either values or matchers.
  3677. template <typename Iter>
  3678. inline internal::UnorderedElementsAreArrayMatcher<
  3679. typename ::std::iterator_traits<Iter>::value_type>
  3680. UnorderedElementsAreArray(Iter first, Iter last) {
  3681. typedef typename ::std::iterator_traits<Iter>::value_type T;
  3682. return internal::UnorderedElementsAreArrayMatcher<T>(
  3683. internal::UnorderedMatcherRequire::ExactMatch, first, last);
  3684. }
  3685. template <typename T>
  3686. inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
  3687. const T* pointer, size_t count) {
  3688. return UnorderedElementsAreArray(pointer, pointer + count);
  3689. }
  3690. template <typename T, size_t N>
  3691. inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
  3692. const T (&array)[N]) {
  3693. return UnorderedElementsAreArray(array, N);
  3694. }
  3695. template <typename Container>
  3696. inline internal::UnorderedElementsAreArrayMatcher<
  3697. typename Container::value_type>
  3698. UnorderedElementsAreArray(const Container& container) {
  3699. return UnorderedElementsAreArray(container.begin(), container.end());
  3700. }
  3701. template <typename T>
  3702. inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
  3703. ::std::initializer_list<T> xs) {
  3704. return UnorderedElementsAreArray(xs.begin(), xs.end());
  3705. }
  3706. // _ is a matcher that matches anything of any type.
  3707. //
  3708. // This definition is fine as:
  3709. //
  3710. // 1. The C++ standard permits using the name _ in a namespace that
  3711. // is not the global namespace or ::std.
  3712. // 2. The AnythingMatcher class has no data member or constructor,
  3713. // so it's OK to create global variables of this type.
  3714. // 3. c-style has approved of using _ in this case.
  3715. const internal::AnythingMatcher _ = {};
  3716. // Creates a matcher that matches any value of the given type T.
  3717. template <typename T>
  3718. inline Matcher<T> A() {
  3719. return _;
  3720. }
  3721. // Creates a matcher that matches any value of the given type T.
  3722. template <typename T>
  3723. inline Matcher<T> An() {
  3724. return _;
  3725. }
  3726. template <typename T, typename M>
  3727. Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
  3728. const M& value, std::false_type /* convertible_to_matcher */,
  3729. std::false_type /* convertible_to_T */) {
  3730. return Eq(value);
  3731. }
  3732. // Creates a polymorphic matcher that matches any NULL pointer.
  3733. inline PolymorphicMatcher<internal::IsNullMatcher> IsNull() {
  3734. return MakePolymorphicMatcher(internal::IsNullMatcher());
  3735. }
  3736. // Creates a polymorphic matcher that matches any non-NULL pointer.
  3737. // This is convenient as Not(NULL) doesn't compile (the compiler
  3738. // thinks that that expression is comparing a pointer with an integer).
  3739. inline PolymorphicMatcher<internal::NotNullMatcher> NotNull() {
  3740. return MakePolymorphicMatcher(internal::NotNullMatcher());
  3741. }
  3742. // Creates a polymorphic matcher that matches any argument that
  3743. // references variable x.
  3744. template <typename T>
  3745. inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
  3746. return internal::RefMatcher<T&>(x);
  3747. }
  3748. // Creates a polymorphic matcher that matches any NaN floating point.
  3749. inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
  3750. return MakePolymorphicMatcher(internal::IsNanMatcher());
  3751. }
  3752. // Creates a matcher that matches any double argument approximately
  3753. // equal to rhs, where two NANs are considered unequal.
  3754. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
  3755. return internal::FloatingEqMatcher<double>(rhs, false);
  3756. }
  3757. // Creates a matcher that matches any double argument approximately
  3758. // equal to rhs, including NaN values when rhs is NaN.
  3759. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
  3760. return internal::FloatingEqMatcher<double>(rhs, true);
  3761. }
  3762. // Creates a matcher that matches any double argument approximately equal to
  3763. // rhs, up to the specified max absolute error bound, where two NANs are
  3764. // considered unequal. The max absolute error bound must be non-negative.
  3765. inline internal::FloatingEqMatcher<double> DoubleNear(double rhs,
  3766. double max_abs_error) {
  3767. return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
  3768. }
  3769. // Creates a matcher that matches any double argument approximately equal to
  3770. // rhs, up to the specified max absolute error bound, including NaN values when
  3771. // rhs is NaN. The max absolute error bound must be non-negative.
  3772. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
  3773. double rhs, double max_abs_error) {
  3774. return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
  3775. }
  3776. // Creates a matcher that matches any float argument approximately
  3777. // equal to rhs, where two NANs are considered unequal.
  3778. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
  3779. return internal::FloatingEqMatcher<float>(rhs, false);
  3780. }
  3781. // Creates a matcher that matches any float argument approximately
  3782. // equal to rhs, including NaN values when rhs is NaN.
  3783. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
  3784. return internal::FloatingEqMatcher<float>(rhs, true);
  3785. }
  3786. // Creates a matcher that matches any float argument approximately equal to
  3787. // rhs, up to the specified max absolute error bound, where two NANs are
  3788. // considered unequal. The max absolute error bound must be non-negative.
  3789. inline internal::FloatingEqMatcher<float> FloatNear(float rhs,
  3790. float max_abs_error) {
  3791. return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
  3792. }
  3793. // Creates a matcher that matches any float argument approximately equal to
  3794. // rhs, up to the specified max absolute error bound, including NaN values when
  3795. // rhs is NaN. The max absolute error bound must be non-negative.
  3796. inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
  3797. float rhs, float max_abs_error) {
  3798. return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
  3799. }
  3800. // Creates a matcher that matches a pointer (raw or smart) that points
  3801. // to a value that matches inner_matcher.
  3802. template <typename InnerMatcher>
  3803. inline internal::PointeeMatcher<InnerMatcher> Pointee(
  3804. const InnerMatcher& inner_matcher) {
  3805. return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
  3806. }
  3807. #if GTEST_HAS_RTTI
  3808. // Creates a matcher that matches a pointer or reference that matches
  3809. // inner_matcher when dynamic_cast<To> is applied.
  3810. // The result of dynamic_cast<To> is forwarded to the inner matcher.
  3811. // If To is a pointer and the cast fails, the inner matcher will receive NULL.
  3812. // If To is a reference and the cast fails, this matcher returns false
  3813. // immediately.
  3814. template <typename To>
  3815. inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>>
  3816. WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
  3817. return MakePolymorphicMatcher(
  3818. internal::WhenDynamicCastToMatcher<To>(inner_matcher));
  3819. }
  3820. #endif // GTEST_HAS_RTTI
  3821. // Creates a matcher that matches an object whose given field matches
  3822. // 'matcher'. For example,
  3823. // Field(&Foo::number, Ge(5))
  3824. // matches a Foo object x if and only if x.number >= 5.
  3825. template <typename Class, typename FieldType, typename FieldMatcher>
  3826. inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(
  3827. FieldType Class::*field, const FieldMatcher& matcher) {
  3828. return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
  3829. field, MatcherCast<const FieldType&>(matcher)));
  3830. // The call to MatcherCast() is required for supporting inner
  3831. // matchers of compatible types. For example, it allows
  3832. // Field(&Foo::bar, m)
  3833. // to compile where bar is an int32 and m is a matcher for int64.
  3834. }
  3835. // Same as Field() but also takes the name of the field to provide better error
  3836. // messages.
  3837. template <typename Class, typename FieldType, typename FieldMatcher>
  3838. inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(
  3839. const std::string& field_name, FieldType Class::*field,
  3840. const FieldMatcher& matcher) {
  3841. return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
  3842. field_name, field, MatcherCast<const FieldType&>(matcher)));
  3843. }
  3844. // Creates a matcher that matches an object whose given property
  3845. // matches 'matcher'. For example,
  3846. // Property(&Foo::str, StartsWith("hi"))
  3847. // matches a Foo object x if and only if x.str() starts with "hi".
  3848. template <typename Class, typename PropertyType, typename PropertyMatcher>
  3849. inline PolymorphicMatcher<internal::PropertyMatcher<
  3850. Class, PropertyType, PropertyType (Class::*)() const>>
  3851. Property(PropertyType (Class::*property)() const,
  3852. const PropertyMatcher& matcher) {
  3853. return MakePolymorphicMatcher(
  3854. internal::PropertyMatcher<Class, PropertyType,
  3855. PropertyType (Class::*)() const>(
  3856. property, MatcherCast<const PropertyType&>(matcher)));
  3857. // The call to MatcherCast() is required for supporting inner
  3858. // matchers of compatible types. For example, it allows
  3859. // Property(&Foo::bar, m)
  3860. // to compile where bar() returns an int32 and m is a matcher for int64.
  3861. }
  3862. // Same as Property() above, but also takes the name of the property to provide
  3863. // better error messages.
  3864. template <typename Class, typename PropertyType, typename PropertyMatcher>
  3865. inline PolymorphicMatcher<internal::PropertyMatcher<
  3866. Class, PropertyType, PropertyType (Class::*)() const>>
  3867. Property(const std::string& property_name,
  3868. PropertyType (Class::*property)() const,
  3869. const PropertyMatcher& matcher) {
  3870. return MakePolymorphicMatcher(
  3871. internal::PropertyMatcher<Class, PropertyType,
  3872. PropertyType (Class::*)() const>(
  3873. property_name, property, MatcherCast<const PropertyType&>(matcher)));
  3874. }
  3875. // The same as above but for reference-qualified member functions.
  3876. template <typename Class, typename PropertyType, typename PropertyMatcher>
  3877. inline PolymorphicMatcher<internal::PropertyMatcher<
  3878. Class, PropertyType, PropertyType (Class::*)() const&>>
  3879. Property(PropertyType (Class::*property)() const&,
  3880. const PropertyMatcher& matcher) {
  3881. return MakePolymorphicMatcher(
  3882. internal::PropertyMatcher<Class, PropertyType,
  3883. PropertyType (Class::*)() const&>(
  3884. property, MatcherCast<const PropertyType&>(matcher)));
  3885. }
  3886. // Three-argument form for reference-qualified member functions.
  3887. template <typename Class, typename PropertyType, typename PropertyMatcher>
  3888. inline PolymorphicMatcher<internal::PropertyMatcher<
  3889. Class, PropertyType, PropertyType (Class::*)() const&>>
  3890. Property(const std::string& property_name,
  3891. PropertyType (Class::*property)() const&,
  3892. const PropertyMatcher& matcher) {
  3893. return MakePolymorphicMatcher(
  3894. internal::PropertyMatcher<Class, PropertyType,
  3895. PropertyType (Class::*)() const&>(
  3896. property_name, property, MatcherCast<const PropertyType&>(matcher)));
  3897. }
  3898. // Creates a matcher that matches an object if and only if the result of
  3899. // applying a callable to x matches 'matcher'. For example,
  3900. // ResultOf(f, StartsWith("hi"))
  3901. // matches a Foo object x if and only if f(x) starts with "hi".
  3902. // `callable` parameter can be a function, function pointer, or a functor. It is
  3903. // required to keep no state affecting the results of the calls on it and make
  3904. // no assumptions about how many calls will be made. Any state it keeps must be
  3905. // protected from the concurrent access.
  3906. template <typename Callable, typename InnerMatcher>
  3907. internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
  3908. Callable callable, InnerMatcher matcher) {
  3909. return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable),
  3910. std::move(matcher));
  3911. }
  3912. // Same as ResultOf() above, but also takes a description of the `callable`
  3913. // result to provide better error messages.
  3914. template <typename Callable, typename InnerMatcher>
  3915. internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
  3916. const std::string& result_description, Callable callable,
  3917. InnerMatcher matcher) {
  3918. return internal::ResultOfMatcher<Callable, InnerMatcher>(
  3919. result_description, std::move(callable), std::move(matcher));
  3920. }
  3921. // String matchers.
  3922. // Matches a string equal to str.
  3923. template <typename T = std::string>
  3924. PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(
  3925. const internal::StringLike<T>& str) {
  3926. return MakePolymorphicMatcher(
  3927. internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
  3928. }
  3929. // Matches a string not equal to str.
  3930. template <typename T = std::string>
  3931. PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(
  3932. const internal::StringLike<T>& str) {
  3933. return MakePolymorphicMatcher(
  3934. internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
  3935. }
  3936. // Matches a string equal to str, ignoring case.
  3937. template <typename T = std::string>
  3938. PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(
  3939. const internal::StringLike<T>& str) {
  3940. return MakePolymorphicMatcher(
  3941. internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
  3942. }
  3943. // Matches a string not equal to str, ignoring case.
  3944. template <typename T = std::string>
  3945. PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(
  3946. const internal::StringLike<T>& str) {
  3947. return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
  3948. std::string(str), false, false));
  3949. }
  3950. // Creates a matcher that matches any string, std::string, or C string
  3951. // that contains the given substring.
  3952. template <typename T = std::string>
  3953. PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(
  3954. const internal::StringLike<T>& substring) {
  3955. return MakePolymorphicMatcher(
  3956. internal::HasSubstrMatcher<std::string>(std::string(substring)));
  3957. }
  3958. // Matches a string that starts with 'prefix' (case-sensitive).
  3959. template <typename T = std::string>
  3960. PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(
  3961. const internal::StringLike<T>& prefix) {
  3962. return MakePolymorphicMatcher(
  3963. internal::StartsWithMatcher<std::string>(std::string(prefix)));
  3964. }
  3965. // Matches a string that ends with 'suffix' (case-sensitive).
  3966. template <typename T = std::string>
  3967. PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(
  3968. const internal::StringLike<T>& suffix) {
  3969. return MakePolymorphicMatcher(
  3970. internal::EndsWithMatcher<std::string>(std::string(suffix)));
  3971. }
  3972. #if GTEST_HAS_STD_WSTRING
  3973. // Wide string matchers.
  3974. // Matches a string equal to str.
  3975. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq(
  3976. const std::wstring& str) {
  3977. return MakePolymorphicMatcher(
  3978. internal::StrEqualityMatcher<std::wstring>(str, true, true));
  3979. }
  3980. // Matches a string not equal to str.
  3981. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe(
  3982. const std::wstring& str) {
  3983. return MakePolymorphicMatcher(
  3984. internal::StrEqualityMatcher<std::wstring>(str, false, true));
  3985. }
  3986. // Matches a string equal to str, ignoring case.
  3987. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq(
  3988. const std::wstring& str) {
  3989. return MakePolymorphicMatcher(
  3990. internal::StrEqualityMatcher<std::wstring>(str, true, false));
  3991. }
  3992. // Matches a string not equal to str, ignoring case.
  3993. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe(
  3994. const std::wstring& str) {
  3995. return MakePolymorphicMatcher(
  3996. internal::StrEqualityMatcher<std::wstring>(str, false, false));
  3997. }
  3998. // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
  3999. // that contains the given substring.
  4000. inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr(
  4001. const std::wstring& substring) {
  4002. return MakePolymorphicMatcher(
  4003. internal::HasSubstrMatcher<std::wstring>(substring));
  4004. }
  4005. // Matches a string that starts with 'prefix' (case-sensitive).
  4006. inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith(
  4007. const std::wstring& prefix) {
  4008. return MakePolymorphicMatcher(
  4009. internal::StartsWithMatcher<std::wstring>(prefix));
  4010. }
  4011. // Matches a string that ends with 'suffix' (case-sensitive).
  4012. inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith(
  4013. const std::wstring& suffix) {
  4014. return MakePolymorphicMatcher(
  4015. internal::EndsWithMatcher<std::wstring>(suffix));
  4016. }
  4017. #endif // GTEST_HAS_STD_WSTRING
  4018. // Creates a polymorphic matcher that matches a 2-tuple where the
  4019. // first field == the second field.
  4020. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
  4021. // Creates a polymorphic matcher that matches a 2-tuple where the
  4022. // first field >= the second field.
  4023. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
  4024. // Creates a polymorphic matcher that matches a 2-tuple where the
  4025. // first field > the second field.
  4026. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
  4027. // Creates a polymorphic matcher that matches a 2-tuple where the
  4028. // first field <= the second field.
  4029. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
  4030. // Creates a polymorphic matcher that matches a 2-tuple where the
  4031. // first field < the second field.
  4032. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
  4033. // Creates a polymorphic matcher that matches a 2-tuple where the
  4034. // first field != the second field.
  4035. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
  4036. // Creates a polymorphic matcher that matches a 2-tuple where
  4037. // FloatEq(first field) matches the second field.
  4038. inline internal::FloatingEq2Matcher<float> FloatEq() {
  4039. return internal::FloatingEq2Matcher<float>();
  4040. }
  4041. // Creates a polymorphic matcher that matches a 2-tuple where
  4042. // DoubleEq(first field) matches the second field.
  4043. inline internal::FloatingEq2Matcher<double> DoubleEq() {
  4044. return internal::FloatingEq2Matcher<double>();
  4045. }
  4046. // Creates a polymorphic matcher that matches a 2-tuple where
  4047. // FloatEq(first field) matches the second field with NaN equality.
  4048. inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
  4049. return internal::FloatingEq2Matcher<float>(true);
  4050. }
  4051. // Creates a polymorphic matcher that matches a 2-tuple where
  4052. // DoubleEq(first field) matches the second field with NaN equality.
  4053. inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
  4054. return internal::FloatingEq2Matcher<double>(true);
  4055. }
  4056. // Creates a polymorphic matcher that matches a 2-tuple where
  4057. // FloatNear(first field, max_abs_error) matches the second field.
  4058. inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
  4059. return internal::FloatingEq2Matcher<float>(max_abs_error);
  4060. }
  4061. // Creates a polymorphic matcher that matches a 2-tuple where
  4062. // DoubleNear(first field, max_abs_error) matches the second field.
  4063. inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
  4064. return internal::FloatingEq2Matcher<double>(max_abs_error);
  4065. }
  4066. // Creates a polymorphic matcher that matches a 2-tuple where
  4067. // FloatNear(first field, max_abs_error) matches the second field with NaN
  4068. // equality.
  4069. inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
  4070. float max_abs_error) {
  4071. return internal::FloatingEq2Matcher<float>(max_abs_error, true);
  4072. }
  4073. // Creates a polymorphic matcher that matches a 2-tuple where
  4074. // DoubleNear(first field, max_abs_error) matches the second field with NaN
  4075. // equality.
  4076. inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
  4077. double max_abs_error) {
  4078. return internal::FloatingEq2Matcher<double>(max_abs_error, true);
  4079. }
  4080. // Creates a matcher that matches any value of type T that m doesn't
  4081. // match.
  4082. template <typename InnerMatcher>
  4083. inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
  4084. return internal::NotMatcher<InnerMatcher>(m);
  4085. }
  4086. // Returns a matcher that matches anything that satisfies the given
  4087. // predicate. The predicate can be any unary function or functor
  4088. // whose return type can be implicitly converted to bool.
  4089. template <typename Predicate>
  4090. inline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly(
  4091. Predicate pred) {
  4092. return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
  4093. }
  4094. // Returns a matcher that matches the container size. The container must
  4095. // support both size() and size_type which all STL-like containers provide.
  4096. // Note that the parameter 'size' can be a value of type size_type as well as
  4097. // matcher. For instance:
  4098. // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
  4099. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
  4100. template <typename SizeMatcher>
  4101. inline internal::SizeIsMatcher<SizeMatcher> SizeIs(
  4102. const SizeMatcher& size_matcher) {
  4103. return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
  4104. }
  4105. // Returns a matcher that matches the distance between the container's begin()
  4106. // iterator and its end() iterator, i.e. the size of the container. This matcher
  4107. // can be used instead of SizeIs with containers such as std::forward_list which
  4108. // do not implement size(). The container must provide const_iterator (with
  4109. // valid iterator_traits), begin() and end().
  4110. template <typename DistanceMatcher>
  4111. inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(
  4112. const DistanceMatcher& distance_matcher) {
  4113. return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
  4114. }
  4115. // Returns a matcher that matches an equal container.
  4116. // This matcher behaves like Eq(), but in the event of mismatch lists the
  4117. // values that are included in one container but not the other. (Duplicate
  4118. // values and order differences are not explained.)
  4119. template <typename Container>
  4120. inline PolymorphicMatcher<
  4121. internal::ContainerEqMatcher<typename std::remove_const<Container>::type>>
  4122. ContainerEq(const Container& rhs) {
  4123. return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
  4124. }
  4125. // Returns a matcher that matches a container that, when sorted using
  4126. // the given comparator, matches container_matcher.
  4127. template <typename Comparator, typename ContainerMatcher>
  4128. inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(
  4129. const Comparator& comparator, const ContainerMatcher& container_matcher) {
  4130. return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
  4131. comparator, container_matcher);
  4132. }
  4133. // Returns a matcher that matches a container that, when sorted using
  4134. // the < operator, matches container_matcher.
  4135. template <typename ContainerMatcher>
  4136. inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
  4137. WhenSorted(const ContainerMatcher& container_matcher) {
  4138. return internal::WhenSortedByMatcher<internal::LessComparator,
  4139. ContainerMatcher>(
  4140. internal::LessComparator(), container_matcher);
  4141. }
  4142. // Matches an STL-style container or a native array that contains the
  4143. // same number of elements as in rhs, where its i-th element and rhs's
  4144. // i-th element (as a pair) satisfy the given pair matcher, for all i.
  4145. // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const
  4146. // T1&, const T2&> >, where T1 and T2 are the types of elements in the
  4147. // LHS container and the RHS container respectively.
  4148. template <typename TupleMatcher, typename Container>
  4149. inline internal::PointwiseMatcher<TupleMatcher,
  4150. typename std::remove_const<Container>::type>
  4151. Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
  4152. return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
  4153. rhs);
  4154. }
  4155. // Supports the Pointwise(m, {a, b, c}) syntax.
  4156. template <typename TupleMatcher, typename T>
  4157. inline internal::PointwiseMatcher<TupleMatcher, std::vector<T>> Pointwise(
  4158. const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
  4159. return Pointwise(tuple_matcher, std::vector<T>(rhs));
  4160. }
  4161. // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
  4162. // container or a native array that contains the same number of
  4163. // elements as in rhs, where in some permutation of the container, its
  4164. // i-th element and rhs's i-th element (as a pair) satisfy the given
  4165. // pair matcher, for all i. Tuple2Matcher must be able to be safely
  4166. // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are
  4167. // the types of elements in the LHS container and the RHS container
  4168. // respectively.
  4169. //
  4170. // This is like Pointwise(pair_matcher, rhs), except that the element
  4171. // order doesn't matter.
  4172. template <typename Tuple2Matcher, typename RhsContainer>
  4173. inline internal::UnorderedElementsAreArrayMatcher<
  4174. typename internal::BoundSecondMatcher<
  4175. Tuple2Matcher,
  4176. typename internal::StlContainerView<
  4177. typename std::remove_const<RhsContainer>::type>::type::value_type>>
  4178. UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
  4179. const RhsContainer& rhs_container) {
  4180. // RhsView allows the same code to handle RhsContainer being a
  4181. // STL-style container and it being a native C-style array.
  4182. typedef typename internal::StlContainerView<RhsContainer> RhsView;
  4183. typedef typename RhsView::type RhsStlContainer;
  4184. typedef typename RhsStlContainer::value_type Second;
  4185. const RhsStlContainer& rhs_stl_container =
  4186. RhsView::ConstReference(rhs_container);
  4187. // Create a matcher for each element in rhs_container.
  4188. ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers;
  4189. for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end();
  4190. ++it) {
  4191. matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it));
  4192. }
  4193. // Delegate the work to UnorderedElementsAreArray().
  4194. return UnorderedElementsAreArray(matchers);
  4195. }
  4196. // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
  4197. template <typename Tuple2Matcher, typename T>
  4198. inline internal::UnorderedElementsAreArrayMatcher<
  4199. typename internal::BoundSecondMatcher<Tuple2Matcher, T>>
  4200. UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
  4201. std::initializer_list<T> rhs) {
  4202. return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
  4203. }
  4204. // Matches an STL-style container or a native array that contains at
  4205. // least one element matching the given value or matcher.
  4206. //
  4207. // Examples:
  4208. // ::std::set<int> page_ids;
  4209. // page_ids.insert(3);
  4210. // page_ids.insert(1);
  4211. // EXPECT_THAT(page_ids, Contains(1));
  4212. // EXPECT_THAT(page_ids, Contains(Gt(2)));
  4213. // EXPECT_THAT(page_ids, Not(Contains(4))); // See below for Times(0)
  4214. //
  4215. // ::std::map<int, size_t> page_lengths;
  4216. // page_lengths[1] = 100;
  4217. // EXPECT_THAT(page_lengths,
  4218. // Contains(::std::pair<const int, size_t>(1, 100)));
  4219. //
  4220. // const char* user_ids[] = { "joe", "mike", "tom" };
  4221. // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
  4222. //
  4223. // The matcher supports a modifier `Times` that allows to check for arbitrary
  4224. // occurrences including testing for absence with Times(0).
  4225. //
  4226. // Examples:
  4227. // ::std::vector<int> ids;
  4228. // ids.insert(1);
  4229. // ids.insert(1);
  4230. // ids.insert(3);
  4231. // EXPECT_THAT(ids, Contains(1).Times(2)); // 1 occurs 2 times
  4232. // EXPECT_THAT(ids, Contains(2).Times(0)); // 2 is not present
  4233. // EXPECT_THAT(ids, Contains(3).Times(Ge(1))); // 3 occurs at least once
  4234. template <typename M>
  4235. inline internal::ContainsMatcher<M> Contains(M matcher) {
  4236. return internal::ContainsMatcher<M>(matcher);
  4237. }
  4238. // IsSupersetOf(iterator_first, iterator_last)
  4239. // IsSupersetOf(pointer, count)
  4240. // IsSupersetOf(array)
  4241. // IsSupersetOf(container)
  4242. // IsSupersetOf({e1, e2, ..., en})
  4243. //
  4244. // IsSupersetOf() verifies that a surjective partial mapping onto a collection
  4245. // of matchers exists. In other words, a container matches
  4246. // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
  4247. // {y1, ..., yn} of some of the container's elements where y1 matches e1,
  4248. // ..., and yn matches en. Obviously, the size of the container must be >= n
  4249. // in order to have a match. Examples:
  4250. //
  4251. // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
  4252. // 1 matches Ne(0).
  4253. // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
  4254. // both Eq(1) and Lt(2). The reason is that different matchers must be used
  4255. // for elements in different slots of the container.
  4256. // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
  4257. // Eq(1) and (the second) 1 matches Lt(2).
  4258. // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
  4259. // Gt(1) and 3 matches (the second) Gt(1).
  4260. //
  4261. // The matchers can be specified as an array, a pointer and count, a container,
  4262. // an initializer list, or an STL iterator range. In each of these cases, the
  4263. // underlying matchers can be either values or matchers.
  4264. template <typename Iter>
  4265. inline internal::UnorderedElementsAreArrayMatcher<
  4266. typename ::std::iterator_traits<Iter>::value_type>
  4267. IsSupersetOf(Iter first, Iter last) {
  4268. typedef typename ::std::iterator_traits<Iter>::value_type T;
  4269. return internal::UnorderedElementsAreArrayMatcher<T>(
  4270. internal::UnorderedMatcherRequire::Superset, first, last);
  4271. }
  4272. template <typename T>
  4273. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  4274. const T* pointer, size_t count) {
  4275. return IsSupersetOf(pointer, pointer + count);
  4276. }
  4277. template <typename T, size_t N>
  4278. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  4279. const T (&array)[N]) {
  4280. return IsSupersetOf(array, N);
  4281. }
  4282. template <typename Container>
  4283. inline internal::UnorderedElementsAreArrayMatcher<
  4284. typename Container::value_type>
  4285. IsSupersetOf(const Container& container) {
  4286. return IsSupersetOf(container.begin(), container.end());
  4287. }
  4288. template <typename T>
  4289. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  4290. ::std::initializer_list<T> xs) {
  4291. return IsSupersetOf(xs.begin(), xs.end());
  4292. }
  4293. // IsSubsetOf(iterator_first, iterator_last)
  4294. // IsSubsetOf(pointer, count)
  4295. // IsSubsetOf(array)
  4296. // IsSubsetOf(container)
  4297. // IsSubsetOf({e1, e2, ..., en})
  4298. //
  4299. // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
  4300. // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
  4301. // only if there is a subset of matchers {m1, ..., mk} which would match the
  4302. // container using UnorderedElementsAre. Obviously, the size of the container
  4303. // must be <= n in order to have a match. Examples:
  4304. //
  4305. // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
  4306. // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
  4307. // matches Lt(0).
  4308. // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
  4309. // match Gt(0). The reason is that different matchers must be used for
  4310. // elements in different slots of the container.
  4311. //
  4312. // The matchers can be specified as an array, a pointer and count, a container,
  4313. // an initializer list, or an STL iterator range. In each of these cases, the
  4314. // underlying matchers can be either values or matchers.
  4315. template <typename Iter>
  4316. inline internal::UnorderedElementsAreArrayMatcher<
  4317. typename ::std::iterator_traits<Iter>::value_type>
  4318. IsSubsetOf(Iter first, Iter last) {
  4319. typedef typename ::std::iterator_traits<Iter>::value_type T;
  4320. return internal::UnorderedElementsAreArrayMatcher<T>(
  4321. internal::UnorderedMatcherRequire::Subset, first, last);
  4322. }
  4323. template <typename T>
  4324. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  4325. const T* pointer, size_t count) {
  4326. return IsSubsetOf(pointer, pointer + count);
  4327. }
  4328. template <typename T, size_t N>
  4329. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  4330. const T (&array)[N]) {
  4331. return IsSubsetOf(array, N);
  4332. }
  4333. template <typename Container>
  4334. inline internal::UnorderedElementsAreArrayMatcher<
  4335. typename Container::value_type>
  4336. IsSubsetOf(const Container& container) {
  4337. return IsSubsetOf(container.begin(), container.end());
  4338. }
  4339. template <typename T>
  4340. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  4341. ::std::initializer_list<T> xs) {
  4342. return IsSubsetOf(xs.begin(), xs.end());
  4343. }
  4344. // Matches an STL-style container or a native array that contains only
  4345. // elements matching the given value or matcher.
  4346. //
  4347. // Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only
  4348. // the messages are different.
  4349. //
  4350. // Examples:
  4351. // ::std::set<int> page_ids;
  4352. // // Each(m) matches an empty container, regardless of what m is.
  4353. // EXPECT_THAT(page_ids, Each(Eq(1)));
  4354. // EXPECT_THAT(page_ids, Each(Eq(77)));
  4355. //
  4356. // page_ids.insert(3);
  4357. // EXPECT_THAT(page_ids, Each(Gt(0)));
  4358. // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
  4359. // page_ids.insert(1);
  4360. // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
  4361. //
  4362. // ::std::map<int, size_t> page_lengths;
  4363. // page_lengths[1] = 100;
  4364. // page_lengths[2] = 200;
  4365. // page_lengths[3] = 300;
  4366. // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
  4367. // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
  4368. //
  4369. // const char* user_ids[] = { "joe", "mike", "tom" };
  4370. // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
  4371. template <typename M>
  4372. inline internal::EachMatcher<M> Each(M matcher) {
  4373. return internal::EachMatcher<M>(matcher);
  4374. }
  4375. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  4376. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  4377. // std::map that contains at least one element whose key is >= 5.
  4378. template <typename M>
  4379. inline internal::KeyMatcher<M> Key(M inner_matcher) {
  4380. return internal::KeyMatcher<M>(inner_matcher);
  4381. }
  4382. // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
  4383. // matches first_matcher and whose 'second' field matches second_matcher. For
  4384. // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
  4385. // to match a std::map<int, string> that contains exactly one element whose key
  4386. // is >= 5 and whose value equals "foo".
  4387. template <typename FirstMatcher, typename SecondMatcher>
  4388. inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(
  4389. FirstMatcher first_matcher, SecondMatcher second_matcher) {
  4390. return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher,
  4391. second_matcher);
  4392. }
  4393. namespace no_adl {
  4394. // Conditional() creates a matcher that conditionally uses either the first or
  4395. // second matcher provided. For example, we could create an `equal if, and only
  4396. // if' matcher using the Conditional wrapper as follows:
  4397. //
  4398. // EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected)));
  4399. template <typename MatcherTrue, typename MatcherFalse>
  4400. internal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional(
  4401. bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) {
  4402. return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>(
  4403. condition, std::move(matcher_true), std::move(matcher_false));
  4404. }
  4405. // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
  4406. // These include those that support `get<I>(obj)`, and when structured bindings
  4407. // are enabled any class that supports them.
  4408. // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
  4409. template <typename... M>
  4410. internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
  4411. M&&... matchers) {
  4412. return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
  4413. std::forward<M>(matchers)...);
  4414. }
  4415. // Creates a matcher that matches a pointer (raw or smart) that matches
  4416. // inner_matcher.
  4417. template <typename InnerMatcher>
  4418. inline internal::PointerMatcher<InnerMatcher> Pointer(
  4419. const InnerMatcher& inner_matcher) {
  4420. return internal::PointerMatcher<InnerMatcher>(inner_matcher);
  4421. }
  4422. // Creates a matcher that matches an object that has an address that matches
  4423. // inner_matcher.
  4424. template <typename InnerMatcher>
  4425. inline internal::AddressMatcher<InnerMatcher> Address(
  4426. const InnerMatcher& inner_matcher) {
  4427. return internal::AddressMatcher<InnerMatcher>(inner_matcher);
  4428. }
  4429. // Matches a base64 escaped string, when the unescaped string matches the
  4430. // internal matcher.
  4431. template <typename MatcherType>
  4432. internal::WhenBase64UnescapedMatcher WhenBase64Unescaped(
  4433. const MatcherType& internal_matcher) {
  4434. return internal::WhenBase64UnescapedMatcher(internal_matcher);
  4435. }
  4436. } // namespace no_adl
  4437. // Returns a predicate that is satisfied by anything that matches the
  4438. // given matcher.
  4439. template <typename M>
  4440. inline internal::MatcherAsPredicate<M> Matches(M matcher) {
  4441. return internal::MatcherAsPredicate<M>(matcher);
  4442. }
  4443. // Returns true if and only if the value matches the matcher.
  4444. template <typename T, typename M>
  4445. inline bool Value(const T& value, M matcher) {
  4446. return testing::Matches(matcher)(value);
  4447. }
  4448. // Matches the value against the given matcher and explains the match
  4449. // result to listener.
  4450. template <typename T, typename M>
  4451. inline bool ExplainMatchResult(M matcher, const T& value,
  4452. MatchResultListener* listener) {
  4453. return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
  4454. }
  4455. // Returns a string representation of the given matcher. Useful for description
  4456. // strings of matchers defined using MATCHER_P* macros that accept matchers as
  4457. // their arguments. For example:
  4458. //
  4459. // MATCHER_P(XAndYThat, matcher,
  4460. // "X that " + DescribeMatcher<int>(matcher, negation) +
  4461. // (negation ? " or" : " and") + " Y that " +
  4462. // DescribeMatcher<double>(matcher, negation)) {
  4463. // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
  4464. // ExplainMatchResult(matcher, arg.y(), result_listener);
  4465. // }
  4466. template <typename T, typename M>
  4467. std::string DescribeMatcher(const M& matcher, bool negation = false) {
  4468. ::std::stringstream ss;
  4469. Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
  4470. if (negation) {
  4471. monomorphic_matcher.DescribeNegationTo(&ss);
  4472. } else {
  4473. monomorphic_matcher.DescribeTo(&ss);
  4474. }
  4475. return ss.str();
  4476. }
  4477. template <typename... Args>
  4478. internal::ElementsAreMatcher<
  4479. std::tuple<typename std::decay<const Args&>::type...>>
  4480. ElementsAre(const Args&... matchers) {
  4481. return internal::ElementsAreMatcher<
  4482. std::tuple<typename std::decay<const Args&>::type...>>(
  4483. std::make_tuple(matchers...));
  4484. }
  4485. template <typename... Args>
  4486. internal::UnorderedElementsAreMatcher<
  4487. std::tuple<typename std::decay<const Args&>::type...>>
  4488. UnorderedElementsAre(const Args&... matchers) {
  4489. return internal::UnorderedElementsAreMatcher<
  4490. std::tuple<typename std::decay<const Args&>::type...>>(
  4491. std::make_tuple(matchers...));
  4492. }
  4493. // Define variadic matcher versions.
  4494. template <typename... Args>
  4495. internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
  4496. const Args&... matchers) {
  4497. return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
  4498. matchers...);
  4499. }
  4500. template <typename... Args>
  4501. internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
  4502. const Args&... matchers) {
  4503. return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
  4504. matchers...);
  4505. }
  4506. // AnyOfArray(array)
  4507. // AnyOfArray(pointer, count)
  4508. // AnyOfArray(container)
  4509. // AnyOfArray({ e1, e2, ..., en })
  4510. // AnyOfArray(iterator_first, iterator_last)
  4511. //
  4512. // AnyOfArray() verifies whether a given value matches any member of a
  4513. // collection of matchers.
  4514. //
  4515. // AllOfArray(array)
  4516. // AllOfArray(pointer, count)
  4517. // AllOfArray(container)
  4518. // AllOfArray({ e1, e2, ..., en })
  4519. // AllOfArray(iterator_first, iterator_last)
  4520. //
  4521. // AllOfArray() verifies whether a given value matches all members of a
  4522. // collection of matchers.
  4523. //
  4524. // The matchers can be specified as an array, a pointer and count, a container,
  4525. // an initializer list, or an STL iterator range. In each of these cases, the
  4526. // underlying matchers can be either values or matchers.
  4527. template <typename Iter>
  4528. inline internal::AnyOfArrayMatcher<
  4529. typename ::std::iterator_traits<Iter>::value_type>
  4530. AnyOfArray(Iter first, Iter last) {
  4531. return internal::AnyOfArrayMatcher<
  4532. typename ::std::iterator_traits<Iter>::value_type>(first, last);
  4533. }
  4534. template <typename Iter>
  4535. inline internal::AllOfArrayMatcher<
  4536. typename ::std::iterator_traits<Iter>::value_type>
  4537. AllOfArray(Iter first, Iter last) {
  4538. return internal::AllOfArrayMatcher<
  4539. typename ::std::iterator_traits<Iter>::value_type>(first, last);
  4540. }
  4541. template <typename T>
  4542. inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {
  4543. return AnyOfArray(ptr, ptr + count);
  4544. }
  4545. template <typename T>
  4546. inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {
  4547. return AllOfArray(ptr, ptr + count);
  4548. }
  4549. template <typename T, size_t N>
  4550. inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {
  4551. return AnyOfArray(array, N);
  4552. }
  4553. template <typename T, size_t N>
  4554. inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {
  4555. return AllOfArray(array, N);
  4556. }
  4557. template <typename Container>
  4558. inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(
  4559. const Container& container) {
  4560. return AnyOfArray(container.begin(), container.end());
  4561. }
  4562. template <typename Container>
  4563. inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(
  4564. const Container& container) {
  4565. return AllOfArray(container.begin(), container.end());
  4566. }
  4567. template <typename T>
  4568. inline internal::AnyOfArrayMatcher<T> AnyOfArray(
  4569. ::std::initializer_list<T> xs) {
  4570. return AnyOfArray(xs.begin(), xs.end());
  4571. }
  4572. template <typename T>
  4573. inline internal::AllOfArrayMatcher<T> AllOfArray(
  4574. ::std::initializer_list<T> xs) {
  4575. return AllOfArray(xs.begin(), xs.end());
  4576. }
  4577. // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
  4578. // fields of it matches a_matcher. C++ doesn't support default
  4579. // arguments for function templates, so we have to overload it.
  4580. template <size_t... k, typename InnerMatcher>
  4581. internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
  4582. InnerMatcher&& matcher) {
  4583. return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(
  4584. std::forward<InnerMatcher>(matcher));
  4585. }
  4586. // AllArgs(m) is a synonym of m. This is useful in
  4587. //
  4588. // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
  4589. //
  4590. // which is easier to read than
  4591. //
  4592. // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
  4593. template <typename InnerMatcher>
  4594. inline InnerMatcher AllArgs(const InnerMatcher& matcher) {
  4595. return matcher;
  4596. }
  4597. // Returns a matcher that matches the value of an optional<> type variable.
  4598. // The matcher implementation only uses '!arg' and requires that the optional<>
  4599. // type has a 'value_type' member type and that '*arg' is of type 'value_type'
  4600. // and is printable using 'PrintToString'. It is compatible with
  4601. // std::optional/std::experimental::optional.
  4602. // Note that to compare an optional type variable against nullopt you should
  4603. // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
  4604. // optional value contains an optional itself.
  4605. template <typename ValueMatcher>
  4606. inline internal::OptionalMatcher<ValueMatcher> Optional(
  4607. const ValueMatcher& value_matcher) {
  4608. return internal::OptionalMatcher<ValueMatcher>(value_matcher);
  4609. }
  4610. // Returns a matcher that matches the value of a absl::any type variable.
  4611. template <typename T>
  4612. PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith(
  4613. const Matcher<const T&>& matcher) {
  4614. return MakePolymorphicMatcher(
  4615. internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
  4616. }
  4617. // Returns a matcher that matches the value of a variant<> type variable.
  4618. // The matcher implementation uses ADL to find the holds_alternative and get
  4619. // functions.
  4620. // It is compatible with std::variant.
  4621. template <typename T>
  4622. PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith(
  4623. const Matcher<const T&>& matcher) {
  4624. return MakePolymorphicMatcher(
  4625. internal::variant_matcher::VariantMatcher<T>(matcher));
  4626. }
  4627. #if GTEST_HAS_EXCEPTIONS
  4628. // Anything inside the `internal` namespace is internal to the implementation
  4629. // and must not be used in user code!
  4630. namespace internal {
  4631. class WithWhatMatcherImpl {
  4632. public:
  4633. WithWhatMatcherImpl(Matcher<std::string> matcher)
  4634. : matcher_(std::move(matcher)) {}
  4635. void DescribeTo(std::ostream* os) const {
  4636. *os << "contains .what() that ";
  4637. matcher_.DescribeTo(os);
  4638. }
  4639. void DescribeNegationTo(std::ostream* os) const {
  4640. *os << "contains .what() that does not ";
  4641. matcher_.DescribeTo(os);
  4642. }
  4643. template <typename Err>
  4644. bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
  4645. *listener << "which contains .what() (of value = " << err.what()
  4646. << ") that ";
  4647. return matcher_.MatchAndExplain(err.what(), listener);
  4648. }
  4649. private:
  4650. const Matcher<std::string> matcher_;
  4651. };
  4652. inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
  4653. Matcher<std::string> m) {
  4654. return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
  4655. }
  4656. template <typename Err>
  4657. class ExceptionMatcherImpl {
  4658. class NeverThrown {
  4659. public:
  4660. const char* what() const noexcept {
  4661. return "this exception should never be thrown";
  4662. }
  4663. };
  4664. // If the matchee raises an exception of a wrong type, we'd like to
  4665. // catch it and print its message and type. To do that, we add an additional
  4666. // catch clause:
  4667. //
  4668. // try { ... }
  4669. // catch (const Err&) { /* an expected exception */ }
  4670. // catch (const std::exception&) { /* exception of a wrong type */ }
  4671. //
  4672. // However, if the `Err` itself is `std::exception`, we'd end up with two
  4673. // identical `catch` clauses:
  4674. //
  4675. // try { ... }
  4676. // catch (const std::exception&) { /* an expected exception */ }
  4677. // catch (const std::exception&) { /* exception of a wrong type */ }
  4678. //
  4679. // This can cause a warning or an error in some compilers. To resolve
  4680. // the issue, we use a fake error type whenever `Err` is `std::exception`:
  4681. //
  4682. // try { ... }
  4683. // catch (const std::exception&) { /* an expected exception */ }
  4684. // catch (const NeverThrown&) { /* exception of a wrong type */ }
  4685. using DefaultExceptionType = typename std::conditional<
  4686. std::is_same<typename std::remove_cv<
  4687. typename std::remove_reference<Err>::type>::type,
  4688. std::exception>::value,
  4689. const NeverThrown&, const std::exception&>::type;
  4690. public:
  4691. ExceptionMatcherImpl(Matcher<const Err&> matcher)
  4692. : matcher_(std::move(matcher)) {}
  4693. void DescribeTo(std::ostream* os) const {
  4694. *os << "throws an exception which is a " << GetTypeName<Err>();
  4695. *os << " which ";
  4696. matcher_.DescribeTo(os);
  4697. }
  4698. void DescribeNegationTo(std::ostream* os) const {
  4699. *os << "throws an exception which is not a " << GetTypeName<Err>();
  4700. *os << " which ";
  4701. matcher_.DescribeNegationTo(os);
  4702. }
  4703. template <typename T>
  4704. bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
  4705. try {
  4706. (void)(std::forward<T>(x)());
  4707. } catch (const Err& err) {
  4708. *listener << "throws an exception which is a " << GetTypeName<Err>();
  4709. *listener << " ";
  4710. return matcher_.MatchAndExplain(err, listener);
  4711. } catch (DefaultExceptionType err) {
  4712. #if GTEST_HAS_RTTI
  4713. *listener << "throws an exception of type " << GetTypeName(typeid(err));
  4714. *listener << " ";
  4715. #else
  4716. *listener << "throws an std::exception-derived type ";
  4717. #endif
  4718. *listener << "with description \"" << err.what() << "\"";
  4719. return false;
  4720. } catch (...) {
  4721. *listener << "throws an exception of an unknown type";
  4722. return false;
  4723. }
  4724. *listener << "does not throw any exception";
  4725. return false;
  4726. }
  4727. private:
  4728. const Matcher<const Err&> matcher_;
  4729. };
  4730. } // namespace internal
  4731. // Throws()
  4732. // Throws(exceptionMatcher)
  4733. // ThrowsMessage(messageMatcher)
  4734. //
  4735. // This matcher accepts a callable and verifies that when invoked, it throws
  4736. // an exception with the given type and properties.
  4737. //
  4738. // Examples:
  4739. //
  4740. // EXPECT_THAT(
  4741. // []() { throw std::runtime_error("message"); },
  4742. // Throws<std::runtime_error>());
  4743. //
  4744. // EXPECT_THAT(
  4745. // []() { throw std::runtime_error("message"); },
  4746. // ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  4747. //
  4748. // EXPECT_THAT(
  4749. // []() { throw std::runtime_error("message"); },
  4750. // Throws<std::runtime_error>(
  4751. // Property(&std::runtime_error::what, HasSubstr("message"))));
  4752. template <typename Err>
  4753. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
  4754. return MakePolymorphicMatcher(
  4755. internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
  4756. }
  4757. template <typename Err, typename ExceptionMatcher>
  4758. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
  4759. const ExceptionMatcher& exception_matcher) {
  4760. // Using matcher cast allows users to pass a matcher of a more broad type.
  4761. // For example user may want to pass Matcher<std::exception>
  4762. // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
  4763. return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
  4764. SafeMatcherCast<const Err&>(exception_matcher)));
  4765. }
  4766. template <typename Err, typename MessageMatcher>
  4767. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
  4768. MessageMatcher&& message_matcher) {
  4769. static_assert(std::is_base_of<std::exception, Err>::value,
  4770. "expected an std::exception-derived type");
  4771. return Throws<Err>(internal::WithWhat(
  4772. MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
  4773. }
  4774. #endif // GTEST_HAS_EXCEPTIONS
  4775. // These macros allow using matchers to check values in Google Test
  4776. // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
  4777. // succeed if and only if the value matches the matcher. If the assertion
  4778. // fails, the value and the description of the matcher will be printed.
  4779. #define ASSERT_THAT(value, matcher) \
  4780. ASSERT_PRED_FORMAT1( \
  4781. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  4782. #define EXPECT_THAT(value, matcher) \
  4783. EXPECT_PRED_FORMAT1( \
  4784. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  4785. // MATCHER* macros itself are listed below.
  4786. #define MATCHER(name, description) \
  4787. class name##Matcher \
  4788. : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
  4789. public: \
  4790. template <typename arg_type> \
  4791. class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
  4792. public: \
  4793. gmock_Impl() {} \
  4794. bool MatchAndExplain( \
  4795. const arg_type& arg, \
  4796. ::testing::MatchResultListener* result_listener) const override; \
  4797. void DescribeTo(::std::ostream* gmock_os) const override { \
  4798. *gmock_os << FormatDescription(false); \
  4799. } \
  4800. void DescribeNegationTo(::std::ostream* gmock_os) const override { \
  4801. *gmock_os << FormatDescription(true); \
  4802. } \
  4803. \
  4804. private: \
  4805. ::std::string FormatDescription(bool negation) const { \
  4806. /* NOLINTNEXTLINE readability-redundant-string-init */ \
  4807. ::std::string gmock_description = (description); \
  4808. if (!gmock_description.empty()) { \
  4809. return gmock_description; \
  4810. } \
  4811. return ::testing::internal::FormatMatcherDescription(negation, #name, \
  4812. {}, {}); \
  4813. } \
  4814. }; \
  4815. }; \
  4816. inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \
  4817. GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \
  4818. GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
  4819. name GMOCK_INTERNAL_WARNING_POP()() { \
  4820. return {}; \
  4821. } \
  4822. template <typename arg_type> \
  4823. bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
  4824. const arg_type& arg, \
  4825. ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
  4826. const
  4827. #define MATCHER_P(name, p0, description) \
  4828. GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))
  4829. #define MATCHER_P2(name, p0, p1, description) \
  4830. GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \
  4831. (p0, p1))
  4832. #define MATCHER_P3(name, p0, p1, p2, description) \
  4833. GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \
  4834. (p0, p1, p2))
  4835. #define MATCHER_P4(name, p0, p1, p2, p3, description) \
  4836. GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \
  4837. (#p0, #p1, #p2, #p3), (p0, p1, p2, p3))
  4838. #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
  4839. GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
  4840. (#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4))
  4841. #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
  4842. GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
  4843. (#p0, #p1, #p2, #p3, #p4, #p5), \
  4844. (p0, p1, p2, p3, p4, p5))
  4845. #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
  4846. GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
  4847. (#p0, #p1, #p2, #p3, #p4, #p5, #p6), \
  4848. (p0, p1, p2, p3, p4, p5, p6))
  4849. #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
  4850. GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
  4851. (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7), \
  4852. (p0, p1, p2, p3, p4, p5, p6, p7))
  4853. #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
  4854. GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
  4855. (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8), \
  4856. (p0, p1, p2, p3, p4, p5, p6, p7, p8))
  4857. #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
  4858. GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
  4859. (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9), \
  4860. (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
  4861. #define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args) \
  4862. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  4863. class full_name : public ::testing::internal::MatcherBaseImpl< \
  4864. full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
  4865. public: \
  4866. using full_name::MatcherBaseImpl::MatcherBaseImpl; \
  4867. template <typename arg_type> \
  4868. class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
  4869. public: \
  4870. explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
  4871. : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
  4872. bool MatchAndExplain( \
  4873. const arg_type& arg, \
  4874. ::testing::MatchResultListener* result_listener) const override; \
  4875. void DescribeTo(::std::ostream* gmock_os) const override { \
  4876. *gmock_os << FormatDescription(false); \
  4877. } \
  4878. void DescribeNegationTo(::std::ostream* gmock_os) const override { \
  4879. *gmock_os << FormatDescription(true); \
  4880. } \
  4881. GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
  4882. \
  4883. private: \
  4884. ::std::string FormatDescription(bool negation) const { \
  4885. ::std::string gmock_description; \
  4886. gmock_description = (description); \
  4887. if (!gmock_description.empty()) { \
  4888. return gmock_description; \
  4889. } \
  4890. return ::testing::internal::FormatMatcherDescription( \
  4891. negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)}, \
  4892. ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
  4893. ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
  4894. GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
  4895. } \
  4896. }; \
  4897. }; \
  4898. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  4899. inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
  4900. GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
  4901. return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
  4902. GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
  4903. } \
  4904. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  4905. template <typename arg_type> \
  4906. bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
  4907. arg_type>::MatchAndExplain(const arg_type& arg, \
  4908. ::testing::MatchResultListener* \
  4909. result_listener GTEST_ATTRIBUTE_UNUSED_) \
  4910. const
  4911. #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
  4912. GMOCK_PP_TAIL( \
  4913. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
  4914. #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
  4915. , typename arg##_type
  4916. #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
  4917. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
  4918. #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
  4919. , arg##_type
  4920. #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
  4921. GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
  4922. GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
  4923. #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
  4924. , arg##_type gmock_p##i
  4925. #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
  4926. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
  4927. #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
  4928. , arg(::std::forward<arg##_type>(gmock_p##i))
  4929. #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
  4930. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
  4931. #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
  4932. const arg##_type arg;
  4933. #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
  4934. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
  4935. #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
  4936. #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
  4937. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
  4938. #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
  4939. , gmock_p##i
  4940. // To prevent ADL on certain functions we put them on a separate namespace.
  4941. using namespace no_adl; // NOLINT
  4942. } // namespace testing
  4943. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
  4944. // Include any custom callback matchers added by the local installation.
  4945. // We must include this header at the end to make sure it can use the
  4946. // declarations from this file.
  4947. #include "gmock/internal/custom/gmock-matchers.h"
  4948. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_