gmock-matchers.h 204 KB

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