gmock-matchers.h 162 KB

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