gmock-matchers.h 156 KB

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