2
0

gmock-matchers.h 195 KB

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