gmock-matchers.h 204 KB

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