gmock-matchers.h 205 KB

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