gmock-matchers.h 206 KB

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