gmock-matchers.h 187 KB

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