gmock-matchers.h 179 KB

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