gmock-matchers-comparisons_test.cc 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file tests some commonly used argument matchers.
  32. #include <functional>
  33. #include <memory>
  34. #include <string>
  35. #include <tuple>
  36. #include <vector>
  37. #include "test/gmock-matchers_test.h"
  38. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  39. // possible loss of data and C4100, unreferenced local parameter
  40. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
  41. namespace testing {
  42. namespace gmock_matchers_test {
  43. namespace {
  44. INSTANTIATE_GTEST_MATCHER_TEST_P(MonotonicMatcherTest);
  45. TEST_P(MonotonicMatcherTestP, IsPrintable) {
  46. stringstream ss;
  47. ss << GreaterThan(5);
  48. EXPECT_EQ("is > 5", ss.str());
  49. }
  50. TEST(MatchResultListenerTest, StreamingWorks) {
  51. StringMatchResultListener listener;
  52. listener << "hi" << 5;
  53. EXPECT_EQ("hi5", listener.str());
  54. listener.Clear();
  55. EXPECT_EQ("", listener.str());
  56. listener << 42;
  57. EXPECT_EQ("42", listener.str());
  58. // Streaming shouldn't crash when the underlying ostream is NULL.
  59. DummyMatchResultListener dummy;
  60. dummy << "hi" << 5;
  61. }
  62. TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
  63. EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
  64. EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
  65. EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
  66. }
  67. TEST(MatchResultListenerTest, IsInterestedWorks) {
  68. EXPECT_TRUE(StringMatchResultListener().IsInterested());
  69. EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
  70. EXPECT_FALSE(DummyMatchResultListener().IsInterested());
  71. EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
  72. }
  73. // Makes sure that the MatcherInterface<T> interface doesn't
  74. // change.
  75. class EvenMatcherImpl : public MatcherInterface<int> {
  76. public:
  77. bool MatchAndExplain(int x,
  78. MatchResultListener* /* listener */) const override {
  79. return x % 2 == 0;
  80. }
  81. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  82. // We deliberately don't define DescribeNegationTo() and
  83. // ExplainMatchResultTo() here, to make sure the definition of these
  84. // two methods is optional.
  85. };
  86. // Makes sure that the MatcherInterface API doesn't change.
  87. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
  88. EvenMatcherImpl m;
  89. }
  90. // Tests implementing a monomorphic matcher using MatchAndExplain().
  91. class NewEvenMatcherImpl : public MatcherInterface<int> {
  92. public:
  93. bool MatchAndExplain(int x, MatchResultListener* listener) const override {
  94. const bool match = x % 2 == 0;
  95. // Verifies that we can stream to a listener directly.
  96. *listener << "value % " << 2;
  97. if (listener->stream() != nullptr) {
  98. // Verifies that we can stream to a listener's underlying stream
  99. // too.
  100. *listener->stream() << " == " << (x % 2);
  101. }
  102. return match;
  103. }
  104. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  105. };
  106. TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
  107. Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
  108. EXPECT_TRUE(m.Matches(2));
  109. EXPECT_FALSE(m.Matches(3));
  110. EXPECT_EQ("value % 2 == 0", Explain(m, 2));
  111. EXPECT_EQ("value % 2 == 1", Explain(m, 3));
  112. }
  113. INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTest);
  114. // Tests default-constructing a matcher.
  115. TEST(MatcherTest, CanBeDefaultConstructed) { Matcher<double> m; }
  116. // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
  117. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
  118. const MatcherInterface<int>* impl = new EvenMatcherImpl;
  119. Matcher<int> m(impl);
  120. EXPECT_TRUE(m.Matches(4));
  121. EXPECT_FALSE(m.Matches(5));
  122. }
  123. // Tests that value can be used in place of Eq(value).
  124. TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
  125. Matcher<int> m1 = 5;
  126. EXPECT_TRUE(m1.Matches(5));
  127. EXPECT_FALSE(m1.Matches(6));
  128. }
  129. // Tests that NULL can be used in place of Eq(NULL).
  130. TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
  131. Matcher<int*> m1 = nullptr;
  132. EXPECT_TRUE(m1.Matches(nullptr));
  133. int n = 0;
  134. EXPECT_FALSE(m1.Matches(&n));
  135. }
  136. // Tests that matchers can be constructed from a variable that is not properly
  137. // defined. This should be illegal, but many users rely on this accidentally.
  138. struct Undefined {
  139. virtual ~Undefined() = 0;
  140. static const int kInt = 1;
  141. };
  142. TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
  143. Matcher<int> m1 = Undefined::kInt;
  144. EXPECT_TRUE(m1.Matches(1));
  145. EXPECT_FALSE(m1.Matches(2));
  146. }
  147. // Test that a matcher parameterized with an abstract class compiles.
  148. TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
  149. // Tests that matchers are copyable.
  150. TEST(MatcherTest, IsCopyable) {
  151. // Tests the copy constructor.
  152. Matcher<bool> m1 = Eq(false);
  153. EXPECT_TRUE(m1.Matches(false));
  154. EXPECT_FALSE(m1.Matches(true));
  155. // Tests the assignment operator.
  156. m1 = Eq(true);
  157. EXPECT_TRUE(m1.Matches(true));
  158. EXPECT_FALSE(m1.Matches(false));
  159. }
  160. // Tests that Matcher<T>::DescribeTo() calls
  161. // MatcherInterface<T>::DescribeTo().
  162. TEST(MatcherTest, CanDescribeItself) {
  163. EXPECT_EQ("is an even number", Describe(Matcher<int>(new EvenMatcherImpl)));
  164. }
  165. // Tests Matcher<T>::MatchAndExplain().
  166. TEST_P(MatcherTestP, MatchAndExplain) {
  167. Matcher<int> m = GreaterThan(0);
  168. StringMatchResultListener listener1;
  169. EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
  170. EXPECT_EQ("which is 42 more than 0", listener1.str());
  171. StringMatchResultListener listener2;
  172. EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
  173. EXPECT_EQ("which is 9 less than 0", listener2.str());
  174. }
  175. // Tests that a C-string literal can be implicitly converted to a
  176. // Matcher<std::string> or Matcher<const std::string&>.
  177. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  178. Matcher<std::string> m1 = "hi";
  179. EXPECT_TRUE(m1.Matches("hi"));
  180. EXPECT_FALSE(m1.Matches("hello"));
  181. Matcher<const std::string&> m2 = "hi";
  182. EXPECT_TRUE(m2.Matches("hi"));
  183. EXPECT_FALSE(m2.Matches("hello"));
  184. }
  185. // Tests that a string object can be implicitly converted to a
  186. // Matcher<std::string> or Matcher<const std::string&>.
  187. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
  188. Matcher<std::string> m1 = std::string("hi");
  189. EXPECT_TRUE(m1.Matches("hi"));
  190. EXPECT_FALSE(m1.Matches("hello"));
  191. Matcher<const std::string&> m2 = std::string("hi");
  192. EXPECT_TRUE(m2.Matches("hi"));
  193. EXPECT_FALSE(m2.Matches("hello"));
  194. }
  195. #if GTEST_INTERNAL_HAS_STRING_VIEW
  196. // Tests that a C-string literal can be implicitly converted to a
  197. // Matcher<StringView> or Matcher<const StringView&>.
  198. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  199. Matcher<internal::StringView> m1 = "cats";
  200. EXPECT_TRUE(m1.Matches("cats"));
  201. EXPECT_FALSE(m1.Matches("dogs"));
  202. Matcher<const internal::StringView&> m2 = "cats";
  203. EXPECT_TRUE(m2.Matches("cats"));
  204. EXPECT_FALSE(m2.Matches("dogs"));
  205. }
  206. // Tests that a std::string object can be implicitly converted to a
  207. // Matcher<StringView> or Matcher<const StringView&>.
  208. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
  209. Matcher<internal::StringView> m1 = std::string("cats");
  210. EXPECT_TRUE(m1.Matches("cats"));
  211. EXPECT_FALSE(m1.Matches("dogs"));
  212. Matcher<const internal::StringView&> m2 = std::string("cats");
  213. EXPECT_TRUE(m2.Matches("cats"));
  214. EXPECT_FALSE(m2.Matches("dogs"));
  215. }
  216. // Tests that a StringView object can be implicitly converted to a
  217. // Matcher<StringView> or Matcher<const StringView&>.
  218. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
  219. Matcher<internal::StringView> m1 = internal::StringView("cats");
  220. EXPECT_TRUE(m1.Matches("cats"));
  221. EXPECT_FALSE(m1.Matches("dogs"));
  222. Matcher<const internal::StringView&> m2 = internal::StringView("cats");
  223. EXPECT_TRUE(m2.Matches("cats"));
  224. EXPECT_FALSE(m2.Matches("dogs"));
  225. }
  226. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  227. // Tests that a std::reference_wrapper<std::string> object can be implicitly
  228. // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
  229. TEST(StringMatcherTest,
  230. CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
  231. std::string value = "cats";
  232. Matcher<std::string> m1 = Eq(std::ref(value));
  233. EXPECT_TRUE(m1.Matches("cats"));
  234. EXPECT_FALSE(m1.Matches("dogs"));
  235. Matcher<const std::string&> m2 = Eq(std::ref(value));
  236. EXPECT_TRUE(m2.Matches("cats"));
  237. EXPECT_FALSE(m2.Matches("dogs"));
  238. }
  239. // Tests that MakeMatcher() constructs a Matcher<T> from a
  240. // MatcherInterface* without requiring the user to explicitly
  241. // write the type.
  242. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
  243. const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
  244. Matcher<int> m = MakeMatcher(dummy_impl);
  245. }
  246. // Tests that MakePolymorphicMatcher() can construct a polymorphic
  247. // matcher from its implementation using the old API.
  248. const int g_bar = 1;
  249. class ReferencesBarOrIsZeroImpl {
  250. public:
  251. template <typename T>
  252. bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const {
  253. const void* p = &x;
  254. return p == &g_bar || x == 0;
  255. }
  256. void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
  257. void DescribeNegationTo(ostream* os) const {
  258. *os << "doesn't reference g_bar and is not zero";
  259. }
  260. };
  261. // This function verifies that MakePolymorphicMatcher() returns a
  262. // PolymorphicMatcher<T> where T is the argument's type.
  263. PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
  264. return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
  265. }
  266. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
  267. // Using a polymorphic matcher to match a reference type.
  268. Matcher<const int&> m1 = ReferencesBarOrIsZero();
  269. EXPECT_TRUE(m1.Matches(0));
  270. // Verifies that the identity of a by-reference argument is preserved.
  271. EXPECT_TRUE(m1.Matches(g_bar));
  272. EXPECT_FALSE(m1.Matches(1));
  273. EXPECT_EQ("g_bar or zero", Describe(m1));
  274. // Using a polymorphic matcher to match a value type.
  275. Matcher<double> m2 = ReferencesBarOrIsZero();
  276. EXPECT_TRUE(m2.Matches(0.0));
  277. EXPECT_FALSE(m2.Matches(0.1));
  278. EXPECT_EQ("g_bar or zero", Describe(m2));
  279. }
  280. // Tests implementing a polymorphic matcher using MatchAndExplain().
  281. class PolymorphicIsEvenImpl {
  282. public:
  283. void DescribeTo(ostream* os) const { *os << "is even"; }
  284. void DescribeNegationTo(ostream* os) const { *os << "is odd"; }
  285. template <typename T>
  286. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  287. // Verifies that we can stream to the listener directly.
  288. *listener << "% " << 2;
  289. if (listener->stream() != nullptr) {
  290. // Verifies that we can stream to the listener's underlying stream
  291. // too.
  292. *listener->stream() << " == " << (x % 2);
  293. }
  294. return (x % 2) == 0;
  295. }
  296. };
  297. PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
  298. return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
  299. }
  300. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
  301. // Using PolymorphicIsEven() as a Matcher<int>.
  302. const Matcher<int> m1 = PolymorphicIsEven();
  303. EXPECT_TRUE(m1.Matches(42));
  304. EXPECT_FALSE(m1.Matches(43));
  305. EXPECT_EQ("is even", Describe(m1));
  306. const Matcher<int> not_m1 = Not(m1);
  307. EXPECT_EQ("is odd", Describe(not_m1));
  308. EXPECT_EQ("% 2 == 0", Explain(m1, 42));
  309. // Using PolymorphicIsEven() as a Matcher<char>.
  310. const Matcher<char> m2 = PolymorphicIsEven();
  311. EXPECT_TRUE(m2.Matches('\x42'));
  312. EXPECT_FALSE(m2.Matches('\x43'));
  313. EXPECT_EQ("is even", Describe(m2));
  314. const Matcher<char> not_m2 = Not(m2);
  315. EXPECT_EQ("is odd", Describe(not_m2));
  316. EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
  317. }
  318. INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherCastTest);
  319. // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
  320. TEST_P(MatcherCastTestP, FromPolymorphicMatcher) {
  321. Matcher<int16_t> m;
  322. if (use_gtest_matcher_) {
  323. m = MatcherCast<int16_t>(GtestGreaterThan(int64_t{5}));
  324. } else {
  325. m = MatcherCast<int16_t>(Gt(int64_t{5}));
  326. }
  327. EXPECT_TRUE(m.Matches(6));
  328. EXPECT_FALSE(m.Matches(4));
  329. }
  330. // For testing casting matchers between compatible types.
  331. class IntValue {
  332. public:
  333. // An int can be statically (although not implicitly) cast to a
  334. // IntValue.
  335. explicit IntValue(int a_value) : value_(a_value) {}
  336. int value() const { return value_; }
  337. private:
  338. int value_;
  339. };
  340. // For testing casting matchers between compatible types.
  341. bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
  342. // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
  343. // can be statically converted to U.
  344. TEST(MatcherCastTest, FromCompatibleType) {
  345. Matcher<double> m1 = Eq(2.0);
  346. Matcher<int> m2 = MatcherCast<int>(m1);
  347. EXPECT_TRUE(m2.Matches(2));
  348. EXPECT_FALSE(m2.Matches(3));
  349. Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
  350. Matcher<int> m4 = MatcherCast<int>(m3);
  351. // In the following, the arguments 1 and 0 are statically converted
  352. // to IntValue objects, and then tested by the IsPositiveIntValue()
  353. // predicate.
  354. EXPECT_TRUE(m4.Matches(1));
  355. EXPECT_FALSE(m4.Matches(0));
  356. }
  357. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
  358. TEST(MatcherCastTest, FromConstReferenceToNonReference) {
  359. Matcher<const int&> m1 = Eq(0);
  360. Matcher<int> m2 = MatcherCast<int>(m1);
  361. EXPECT_TRUE(m2.Matches(0));
  362. EXPECT_FALSE(m2.Matches(1));
  363. }
  364. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
  365. TEST(MatcherCastTest, FromReferenceToNonReference) {
  366. Matcher<int&> m1 = Eq(0);
  367. Matcher<int> m2 = MatcherCast<int>(m1);
  368. EXPECT_TRUE(m2.Matches(0));
  369. EXPECT_FALSE(m2.Matches(1));
  370. }
  371. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  372. TEST(MatcherCastTest, FromNonReferenceToConstReference) {
  373. Matcher<int> m1 = Eq(0);
  374. Matcher<const int&> m2 = MatcherCast<const int&>(m1);
  375. EXPECT_TRUE(m2.Matches(0));
  376. EXPECT_FALSE(m2.Matches(1));
  377. }
  378. // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
  379. TEST(MatcherCastTest, FromNonReferenceToReference) {
  380. Matcher<int> m1 = Eq(0);
  381. Matcher<int&> m2 = MatcherCast<int&>(m1);
  382. int n = 0;
  383. EXPECT_TRUE(m2.Matches(n));
  384. n = 1;
  385. EXPECT_FALSE(m2.Matches(n));
  386. }
  387. // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
  388. TEST(MatcherCastTest, FromSameType) {
  389. Matcher<int> m1 = Eq(0);
  390. Matcher<int> m2 = MatcherCast<int>(m1);
  391. EXPECT_TRUE(m2.Matches(0));
  392. EXPECT_FALSE(m2.Matches(1));
  393. }
  394. // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
  395. // value type of the Matcher.
  396. TEST(MatcherCastTest, FromAValue) {
  397. Matcher<int> m = MatcherCast<int>(42);
  398. EXPECT_TRUE(m.Matches(42));
  399. EXPECT_FALSE(m.Matches(239));
  400. }
  401. // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
  402. // convertible to the value type of the Matcher.
  403. TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
  404. const int kExpected = 'c';
  405. Matcher<int> m = MatcherCast<int>('c');
  406. EXPECT_TRUE(m.Matches(kExpected));
  407. EXPECT_FALSE(m.Matches(kExpected + 1));
  408. }
  409. struct NonImplicitlyConstructibleTypeWithOperatorEq {
  410. friend bool operator==(
  411. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
  412. int rhs) {
  413. return 42 == rhs;
  414. }
  415. friend bool operator==(
  416. int lhs,
  417. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
  418. return lhs == 42;
  419. }
  420. };
  421. // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
  422. // implicitly convertible to the value type of the Matcher, but the value type
  423. // of the matcher has operator==() overload accepting m.
  424. TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
  425. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
  426. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
  427. EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  428. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
  429. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
  430. EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  431. // When updating the following lines please also change the comment to
  432. // namespace convertible_from_any.
  433. Matcher<int> m3 =
  434. MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
  435. EXPECT_TRUE(m3.Matches(42));
  436. EXPECT_FALSE(m3.Matches(239));
  437. }
  438. // ConvertibleFromAny does not work with MSVC. resulting in
  439. // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
  440. // No constructor could take the source type, or constructor overload
  441. // resolution was ambiguous
  442. #if !defined _MSC_VER
  443. // The below ConvertibleFromAny struct is implicitly constructible from anything
  444. // and when in the same namespace can interact with other tests. In particular,
  445. // if it is in the same namespace as other tests and one removes
  446. // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
  447. // then the corresponding test still compiles (and it should not!) by implicitly
  448. // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
  449. // in m3.Matcher().
  450. namespace convertible_from_any {
  451. // Implicitly convertible from any type.
  452. struct ConvertibleFromAny {
  453. ConvertibleFromAny(int a_value) : value(a_value) {}
  454. template <typename T>
  455. ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
  456. ADD_FAILURE() << "Conversion constructor called";
  457. }
  458. int value;
  459. };
  460. bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
  461. return a.value == b.value;
  462. }
  463. ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
  464. return os << a.value;
  465. }
  466. TEST(MatcherCastTest, ConversionConstructorIsUsed) {
  467. Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
  468. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  469. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  470. }
  471. TEST(MatcherCastTest, FromConvertibleFromAny) {
  472. Matcher<ConvertibleFromAny> m =
  473. MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  474. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  475. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  476. }
  477. } // namespace convertible_from_any
  478. #endif // !defined _MSC_VER
  479. struct IntReferenceWrapper {
  480. IntReferenceWrapper(const int& a_value) : value(&a_value) {}
  481. const int* value;
  482. };
  483. bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
  484. return a.value == b.value;
  485. }
  486. TEST(MatcherCastTest, ValueIsNotCopied) {
  487. int n = 42;
  488. Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
  489. // Verify that the matcher holds a reference to n, not to its temporary copy.
  490. EXPECT_TRUE(m.Matches(n));
  491. }
  492. class Base {
  493. public:
  494. virtual ~Base() = default;
  495. Base() = default;
  496. private:
  497. Base(const Base&) = delete;
  498. Base& operator=(const Base&) = delete;
  499. };
  500. class Derived : public Base {
  501. public:
  502. Derived() : Base() {}
  503. int i;
  504. };
  505. class OtherDerived : public Base {};
  506. INSTANTIATE_GTEST_MATCHER_TEST_P(SafeMatcherCastTest);
  507. // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
  508. TEST_P(SafeMatcherCastTestP, FromPolymorphicMatcher) {
  509. Matcher<char> m2;
  510. if (use_gtest_matcher_) {
  511. m2 = SafeMatcherCast<char>(GtestGreaterThan(32));
  512. } else {
  513. m2 = SafeMatcherCast<char>(Gt(32));
  514. }
  515. EXPECT_TRUE(m2.Matches('A'));
  516. EXPECT_FALSE(m2.Matches('\n'));
  517. }
  518. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
  519. // T and U are arithmetic types and T can be losslessly converted to
  520. // U.
  521. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
  522. Matcher<double> m1 = DoubleEq(1.0);
  523. Matcher<float> m2 = SafeMatcherCast<float>(m1);
  524. EXPECT_TRUE(m2.Matches(1.0f));
  525. EXPECT_FALSE(m2.Matches(2.0f));
  526. Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
  527. EXPECT_TRUE(m3.Matches('a'));
  528. EXPECT_FALSE(m3.Matches('b'));
  529. }
  530. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
  531. // are pointers or references to a derived and a base class, correspondingly.
  532. TEST(SafeMatcherCastTest, FromBaseClass) {
  533. Derived d, d2;
  534. Matcher<Base*> m1 = Eq(&d);
  535. Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
  536. EXPECT_TRUE(m2.Matches(&d));
  537. EXPECT_FALSE(m2.Matches(&d2));
  538. Matcher<Base&> m3 = Ref(d);
  539. Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
  540. EXPECT_TRUE(m4.Matches(d));
  541. EXPECT_FALSE(m4.Matches(d2));
  542. }
  543. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
  544. TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
  545. int n = 0;
  546. Matcher<const int&> m1 = Ref(n);
  547. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  548. int n1 = 0;
  549. EXPECT_TRUE(m2.Matches(n));
  550. EXPECT_FALSE(m2.Matches(n1));
  551. }
  552. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  553. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
  554. Matcher<std::unique_ptr<int>> m1 = IsNull();
  555. Matcher<const std::unique_ptr<int>&> m2 =
  556. SafeMatcherCast<const std::unique_ptr<int>&>(m1);
  557. EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
  558. EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
  559. }
  560. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
  561. TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
  562. Matcher<int> m1 = Eq(0);
  563. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  564. int n = 0;
  565. EXPECT_TRUE(m2.Matches(n));
  566. n = 1;
  567. EXPECT_FALSE(m2.Matches(n));
  568. }
  569. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
  570. TEST(SafeMatcherCastTest, FromSameType) {
  571. Matcher<int> m1 = Eq(0);
  572. Matcher<int> m2 = SafeMatcherCast<int>(m1);
  573. EXPECT_TRUE(m2.Matches(0));
  574. EXPECT_FALSE(m2.Matches(1));
  575. }
  576. #if !defined _MSC_VER
  577. namespace convertible_from_any {
  578. TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
  579. Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
  580. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  581. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  582. }
  583. TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
  584. Matcher<ConvertibleFromAny> m =
  585. SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  586. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  587. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  588. }
  589. } // namespace convertible_from_any
  590. #endif // !defined _MSC_VER
  591. TEST(SafeMatcherCastTest, ValueIsNotCopied) {
  592. int n = 42;
  593. Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
  594. // Verify that the matcher holds a reference to n, not to its temporary copy.
  595. EXPECT_TRUE(m.Matches(n));
  596. }
  597. TEST(ExpectThat, TakesLiterals) {
  598. EXPECT_THAT(1, 1);
  599. EXPECT_THAT(1.0, 1.0);
  600. EXPECT_THAT(std::string(), "");
  601. }
  602. TEST(ExpectThat, TakesFunctions) {
  603. struct Helper {
  604. static void Func() {}
  605. };
  606. void (*func)() = Helper::Func;
  607. EXPECT_THAT(func, Helper::Func);
  608. EXPECT_THAT(func, &Helper::Func);
  609. }
  610. // Tests that A<T>() matches any value of type T.
  611. TEST(ATest, MatchesAnyValue) {
  612. // Tests a matcher for a value type.
  613. Matcher<double> m1 = A<double>();
  614. EXPECT_TRUE(m1.Matches(91.43));
  615. EXPECT_TRUE(m1.Matches(-15.32));
  616. // Tests a matcher for a reference type.
  617. int a = 2;
  618. int b = -6;
  619. Matcher<int&> m2 = A<int&>();
  620. EXPECT_TRUE(m2.Matches(a));
  621. EXPECT_TRUE(m2.Matches(b));
  622. }
  623. TEST(ATest, WorksForDerivedClass) {
  624. Base base;
  625. Derived derived;
  626. EXPECT_THAT(&base, A<Base*>());
  627. // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
  628. EXPECT_THAT(&derived, A<Base*>());
  629. EXPECT_THAT(&derived, A<Derived*>());
  630. }
  631. // Tests that A<T>() describes itself properly.
  632. TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A<bool>())); }
  633. // Tests that An<T>() matches any value of type T.
  634. TEST(AnTest, MatchesAnyValue) {
  635. // Tests a matcher for a value type.
  636. Matcher<int> m1 = An<int>();
  637. EXPECT_TRUE(m1.Matches(9143));
  638. EXPECT_TRUE(m1.Matches(-1532));
  639. // Tests a matcher for a reference type.
  640. int a = 2;
  641. int b = -6;
  642. Matcher<int&> m2 = An<int&>();
  643. EXPECT_TRUE(m2.Matches(a));
  644. EXPECT_TRUE(m2.Matches(b));
  645. }
  646. // Tests that An<T>() describes itself properly.
  647. TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An<int>())); }
  648. // Tests that _ can be used as a matcher for any type and matches any
  649. // value of that type.
  650. TEST(UnderscoreTest, MatchesAnyValue) {
  651. // Uses _ as a matcher for a value type.
  652. Matcher<int> m1 = _;
  653. EXPECT_TRUE(m1.Matches(123));
  654. EXPECT_TRUE(m1.Matches(-242));
  655. // Uses _ as a matcher for a reference type.
  656. bool a = false;
  657. const bool b = true;
  658. Matcher<const bool&> m2 = _;
  659. EXPECT_TRUE(m2.Matches(a));
  660. EXPECT_TRUE(m2.Matches(b));
  661. }
  662. // Tests that _ describes itself properly.
  663. TEST(UnderscoreTest, CanDescribeSelf) {
  664. Matcher<int> m = _;
  665. EXPECT_EQ("is anything", Describe(m));
  666. }
  667. // Tests that Eq(x) matches any value equal to x.
  668. TEST(EqTest, MatchesEqualValue) {
  669. // 2 C-strings with same content but different addresses.
  670. const char a1[] = "hi";
  671. const char a2[] = "hi";
  672. Matcher<const char*> m1 = Eq(a1);
  673. EXPECT_TRUE(m1.Matches(a1));
  674. EXPECT_FALSE(m1.Matches(a2));
  675. }
  676. // Tests that Eq(v) describes itself properly.
  677. class Unprintable {
  678. public:
  679. Unprintable() : c_('a') {}
  680. bool operator==(const Unprintable& /* rhs */) const { return true; }
  681. // -Wunused-private-field: dummy accessor for `c_`.
  682. char dummy_c() { return c_; }
  683. private:
  684. char c_;
  685. };
  686. TEST(EqTest, CanDescribeSelf) {
  687. Matcher<Unprintable> m = Eq(Unprintable());
  688. EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
  689. }
  690. // Tests that Eq(v) can be used to match any type that supports
  691. // comparing with type T, where T is v's type.
  692. TEST(EqTest, IsPolymorphic) {
  693. Matcher<int> m1 = Eq(1);
  694. EXPECT_TRUE(m1.Matches(1));
  695. EXPECT_FALSE(m1.Matches(2));
  696. Matcher<char> m2 = Eq(1);
  697. EXPECT_TRUE(m2.Matches('\1'));
  698. EXPECT_FALSE(m2.Matches('a'));
  699. }
  700. // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
  701. TEST(TypedEqTest, ChecksEqualityForGivenType) {
  702. Matcher<char> m1 = TypedEq<char>('a');
  703. EXPECT_TRUE(m1.Matches('a'));
  704. EXPECT_FALSE(m1.Matches('b'));
  705. Matcher<int> m2 = TypedEq<int>(6);
  706. EXPECT_TRUE(m2.Matches(6));
  707. EXPECT_FALSE(m2.Matches(7));
  708. }
  709. // Tests that TypedEq(v) describes itself properly.
  710. TEST(TypedEqTest, CanDescribeSelf) {
  711. EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
  712. }
  713. // Tests that TypedEq<T>(v) has type Matcher<T>.
  714. // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
  715. // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
  716. // not T, the compiler will generate a message about "undefined reference".
  717. template <typename T>
  718. struct Type {
  719. static bool IsTypeOf(const T& /* v */) { return true; }
  720. template <typename T2>
  721. static void IsTypeOf(T2 v);
  722. };
  723. TEST(TypedEqTest, HasSpecifiedType) {
  724. // Verifies that the type of TypedEq<T>(v) is Matcher<T>.
  725. Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
  726. Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
  727. }
  728. // Tests that Ge(v) matches anything >= v.
  729. TEST(GeTest, ImplementsGreaterThanOrEqual) {
  730. Matcher<int> m1 = Ge(0);
  731. EXPECT_TRUE(m1.Matches(1));
  732. EXPECT_TRUE(m1.Matches(0));
  733. EXPECT_FALSE(m1.Matches(-1));
  734. }
  735. // Tests that Ge(v) describes itself properly.
  736. TEST(GeTest, CanDescribeSelf) {
  737. Matcher<int> m = Ge(5);
  738. EXPECT_EQ("is >= 5", Describe(m));
  739. }
  740. // Tests that Gt(v) matches anything > v.
  741. TEST(GtTest, ImplementsGreaterThan) {
  742. Matcher<double> m1 = Gt(0);
  743. EXPECT_TRUE(m1.Matches(1.0));
  744. EXPECT_FALSE(m1.Matches(0.0));
  745. EXPECT_FALSE(m1.Matches(-1.0));
  746. }
  747. // Tests that Gt(v) describes itself properly.
  748. TEST(GtTest, CanDescribeSelf) {
  749. Matcher<int> m = Gt(5);
  750. EXPECT_EQ("is > 5", Describe(m));
  751. }
  752. // Tests that Le(v) matches anything <= v.
  753. TEST(LeTest, ImplementsLessThanOrEqual) {
  754. Matcher<char> m1 = Le('b');
  755. EXPECT_TRUE(m1.Matches('a'));
  756. EXPECT_TRUE(m1.Matches('b'));
  757. EXPECT_FALSE(m1.Matches('c'));
  758. }
  759. // Tests that Le(v) describes itself properly.
  760. TEST(LeTest, CanDescribeSelf) {
  761. Matcher<int> m = Le(5);
  762. EXPECT_EQ("is <= 5", Describe(m));
  763. }
  764. // Tests that Lt(v) matches anything < v.
  765. TEST(LtTest, ImplementsLessThan) {
  766. Matcher<const std::string&> m1 = Lt("Hello");
  767. EXPECT_TRUE(m1.Matches("Abc"));
  768. EXPECT_FALSE(m1.Matches("Hello"));
  769. EXPECT_FALSE(m1.Matches("Hello, world!"));
  770. }
  771. // Tests that Lt(v) describes itself properly.
  772. TEST(LtTest, CanDescribeSelf) {
  773. Matcher<int> m = Lt(5);
  774. EXPECT_EQ("is < 5", Describe(m));
  775. }
  776. // Tests that Ne(v) matches anything != v.
  777. TEST(NeTest, ImplementsNotEqual) {
  778. Matcher<int> m1 = Ne(0);
  779. EXPECT_TRUE(m1.Matches(1));
  780. EXPECT_TRUE(m1.Matches(-1));
  781. EXPECT_FALSE(m1.Matches(0));
  782. }
  783. // Tests that Ne(v) describes itself properly.
  784. TEST(NeTest, CanDescribeSelf) {
  785. Matcher<int> m = Ne(5);
  786. EXPECT_EQ("isn't equal to 5", Describe(m));
  787. }
  788. class MoveOnly {
  789. public:
  790. explicit MoveOnly(int i) : i_(i) {}
  791. MoveOnly(const MoveOnly&) = delete;
  792. MoveOnly(MoveOnly&&) = default;
  793. MoveOnly& operator=(const MoveOnly&) = delete;
  794. MoveOnly& operator=(MoveOnly&&) = default;
  795. bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
  796. bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
  797. bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
  798. bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
  799. bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
  800. bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
  801. private:
  802. int i_;
  803. };
  804. struct MoveHelper {
  805. MOCK_METHOD1(Call, void(MoveOnly));
  806. };
  807. // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
  808. #if defined(_MSC_VER) && (_MSC_VER < 1910)
  809. TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
  810. #else
  811. TEST(ComparisonBaseTest, WorksWithMoveOnly) {
  812. #endif
  813. MoveOnly m{0};
  814. MoveHelper helper;
  815. EXPECT_CALL(helper, Call(Eq(ByRef(m))));
  816. helper.Call(MoveOnly(0));
  817. EXPECT_CALL(helper, Call(Ne(ByRef(m))));
  818. helper.Call(MoveOnly(1));
  819. EXPECT_CALL(helper, Call(Le(ByRef(m))));
  820. helper.Call(MoveOnly(0));
  821. EXPECT_CALL(helper, Call(Lt(ByRef(m))));
  822. helper.Call(MoveOnly(-1));
  823. EXPECT_CALL(helper, Call(Ge(ByRef(m))));
  824. helper.Call(MoveOnly(0));
  825. EXPECT_CALL(helper, Call(Gt(ByRef(m))));
  826. helper.Call(MoveOnly(1));
  827. }
  828. TEST(IsEmptyTest, MatchesContainer) {
  829. const Matcher<std::vector<int>> m = IsEmpty();
  830. std::vector<int> a = {};
  831. std::vector<int> b = {1};
  832. EXPECT_TRUE(m.Matches(a));
  833. EXPECT_FALSE(m.Matches(b));
  834. }
  835. TEST(IsEmptyTest, MatchesStdString) {
  836. const Matcher<std::string> m = IsEmpty();
  837. std::string a = "z";
  838. std::string b = "";
  839. EXPECT_FALSE(m.Matches(a));
  840. EXPECT_TRUE(m.Matches(b));
  841. }
  842. TEST(IsEmptyTest, MatchesCString) {
  843. const Matcher<const char*> m = IsEmpty();
  844. const char a[] = "";
  845. const char b[] = "x";
  846. EXPECT_TRUE(m.Matches(a));
  847. EXPECT_FALSE(m.Matches(b));
  848. }
  849. // Tests that IsNull() matches any NULL pointer of any type.
  850. TEST(IsNullTest, MatchesNullPointer) {
  851. Matcher<int*> m1 = IsNull();
  852. int* p1 = nullptr;
  853. int n = 0;
  854. EXPECT_TRUE(m1.Matches(p1));
  855. EXPECT_FALSE(m1.Matches(&n));
  856. Matcher<const char*> m2 = IsNull();
  857. const char* p2 = nullptr;
  858. EXPECT_TRUE(m2.Matches(p2));
  859. EXPECT_FALSE(m2.Matches("hi"));
  860. Matcher<void*> m3 = IsNull();
  861. void* p3 = nullptr;
  862. EXPECT_TRUE(m3.Matches(p3));
  863. EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
  864. }
  865. TEST(IsNullTest, StdFunction) {
  866. const Matcher<std::function<void()>> m = IsNull();
  867. EXPECT_TRUE(m.Matches(std::function<void()>()));
  868. EXPECT_FALSE(m.Matches([] {}));
  869. }
  870. // Tests that IsNull() describes itself properly.
  871. TEST(IsNullTest, CanDescribeSelf) {
  872. Matcher<int*> m = IsNull();
  873. EXPECT_EQ("is NULL", Describe(m));
  874. EXPECT_EQ("isn't NULL", DescribeNegation(m));
  875. }
  876. // Tests that NotNull() matches any non-NULL pointer of any type.
  877. TEST(NotNullTest, MatchesNonNullPointer) {
  878. Matcher<int*> m1 = NotNull();
  879. int* p1 = nullptr;
  880. int n = 0;
  881. EXPECT_FALSE(m1.Matches(p1));
  882. EXPECT_TRUE(m1.Matches(&n));
  883. Matcher<const char*> m2 = NotNull();
  884. const char* p2 = nullptr;
  885. EXPECT_FALSE(m2.Matches(p2));
  886. EXPECT_TRUE(m2.Matches("hi"));
  887. }
  888. TEST(NotNullTest, LinkedPtr) {
  889. const Matcher<std::shared_ptr<int>> m = NotNull();
  890. const std::shared_ptr<int> null_p;
  891. const std::shared_ptr<int> non_null_p(new int);
  892. EXPECT_FALSE(m.Matches(null_p));
  893. EXPECT_TRUE(m.Matches(non_null_p));
  894. }
  895. TEST(NotNullTest, ReferenceToConstLinkedPtr) {
  896. const Matcher<const std::shared_ptr<double>&> m = NotNull();
  897. const std::shared_ptr<double> null_p;
  898. const std::shared_ptr<double> non_null_p(new double);
  899. EXPECT_FALSE(m.Matches(null_p));
  900. EXPECT_TRUE(m.Matches(non_null_p));
  901. }
  902. TEST(NotNullTest, StdFunction) {
  903. const Matcher<std::function<void()>> m = NotNull();
  904. EXPECT_TRUE(m.Matches([] {}));
  905. EXPECT_FALSE(m.Matches(std::function<void()>()));
  906. }
  907. // Tests that NotNull() describes itself properly.
  908. TEST(NotNullTest, CanDescribeSelf) {
  909. Matcher<int*> m = NotNull();
  910. EXPECT_EQ("isn't NULL", Describe(m));
  911. }
  912. // Tests that Ref(variable) matches an argument that references
  913. // 'variable'.
  914. TEST(RefTest, MatchesSameVariable) {
  915. int a = 0;
  916. int b = 0;
  917. Matcher<int&> m = Ref(a);
  918. EXPECT_TRUE(m.Matches(a));
  919. EXPECT_FALSE(m.Matches(b));
  920. }
  921. // Tests that Ref(variable) describes itself properly.
  922. TEST(RefTest, CanDescribeSelf) {
  923. int n = 5;
  924. Matcher<int&> m = Ref(n);
  925. stringstream ss;
  926. ss << "references the variable @" << &n << " 5";
  927. EXPECT_EQ(ss.str(), Describe(m));
  928. }
  929. // Test that Ref(non_const_varialbe) can be used as a matcher for a
  930. // const reference.
  931. TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
  932. int a = 0;
  933. int b = 0;
  934. Matcher<const int&> m = Ref(a);
  935. EXPECT_TRUE(m.Matches(a));
  936. EXPECT_FALSE(m.Matches(b));
  937. }
  938. // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
  939. // used wherever Ref(base) can be used (Ref(derived) is a sub-type
  940. // of Ref(base), but not vice versa.
  941. TEST(RefTest, IsCovariant) {
  942. Base base, base2;
  943. Derived derived;
  944. Matcher<const Base&> m1 = Ref(base);
  945. EXPECT_TRUE(m1.Matches(base));
  946. EXPECT_FALSE(m1.Matches(base2));
  947. EXPECT_FALSE(m1.Matches(derived));
  948. m1 = Ref(derived);
  949. EXPECT_TRUE(m1.Matches(derived));
  950. EXPECT_FALSE(m1.Matches(base));
  951. EXPECT_FALSE(m1.Matches(base2));
  952. }
  953. TEST(RefTest, ExplainsResult) {
  954. int n = 0;
  955. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
  956. StartsWith("which is located @"));
  957. int m = 0;
  958. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
  959. StartsWith("which is located @"));
  960. }
  961. // Tests string comparison matchers.
  962. template <typename T = std::string>
  963. std::string FromStringLike(internal::StringLike<T> str) {
  964. return std::string(str);
  965. }
  966. TEST(StringLike, TestConversions) {
  967. EXPECT_EQ("foo", FromStringLike("foo"));
  968. EXPECT_EQ("foo", FromStringLike(std::string("foo")));
  969. #if GTEST_INTERNAL_HAS_STRING_VIEW
  970. EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
  971. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  972. // Non deducible types.
  973. EXPECT_EQ("", FromStringLike({}));
  974. EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
  975. const char buf[] = "foo";
  976. EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
  977. }
  978. TEST(StrEqTest, MatchesEqualString) {
  979. Matcher<const char*> m = StrEq(std::string("Hello"));
  980. EXPECT_TRUE(m.Matches("Hello"));
  981. EXPECT_FALSE(m.Matches("hello"));
  982. EXPECT_FALSE(m.Matches(nullptr));
  983. Matcher<const std::string&> m2 = StrEq("Hello");
  984. EXPECT_TRUE(m2.Matches("Hello"));
  985. EXPECT_FALSE(m2.Matches("Hi"));
  986. #if GTEST_INTERNAL_HAS_STRING_VIEW
  987. Matcher<const internal::StringView&> m3 =
  988. StrEq(internal::StringView("Hello"));
  989. EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
  990. EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
  991. EXPECT_FALSE(m3.Matches(internal::StringView()));
  992. Matcher<const internal::StringView&> m_empty = StrEq("");
  993. EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
  994. EXPECT_TRUE(m_empty.Matches(internal::StringView()));
  995. EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
  996. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  997. }
  998. TEST(StrEqTest, CanDescribeSelf) {
  999. Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
  1000. EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
  1001. Describe(m));
  1002. std::string str("01204500800");
  1003. str[3] = '\0';
  1004. Matcher<std::string> m2 = StrEq(str);
  1005. EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
  1006. str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
  1007. Matcher<std::string> m3 = StrEq(str);
  1008. EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
  1009. }
  1010. TEST(StrNeTest, MatchesUnequalString) {
  1011. Matcher<const char*> m = StrNe("Hello");
  1012. EXPECT_TRUE(m.Matches(""));
  1013. EXPECT_TRUE(m.Matches(nullptr));
  1014. EXPECT_FALSE(m.Matches("Hello"));
  1015. Matcher<std::string> m2 = StrNe(std::string("Hello"));
  1016. EXPECT_TRUE(m2.Matches("hello"));
  1017. EXPECT_FALSE(m2.Matches("Hello"));
  1018. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1019. Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
  1020. EXPECT_TRUE(m3.Matches(internal::StringView("")));
  1021. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1022. EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
  1023. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1024. }
  1025. TEST(StrNeTest, CanDescribeSelf) {
  1026. Matcher<const char*> m = StrNe("Hi");
  1027. EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
  1028. }
  1029. TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1030. Matcher<const char*> m = StrCaseEq(std::string("Hello"));
  1031. EXPECT_TRUE(m.Matches("Hello"));
  1032. EXPECT_TRUE(m.Matches("hello"));
  1033. EXPECT_FALSE(m.Matches("Hi"));
  1034. EXPECT_FALSE(m.Matches(nullptr));
  1035. Matcher<const std::string&> m2 = StrCaseEq("Hello");
  1036. EXPECT_TRUE(m2.Matches("hello"));
  1037. EXPECT_FALSE(m2.Matches("Hi"));
  1038. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1039. Matcher<const internal::StringView&> m3 =
  1040. StrCaseEq(internal::StringView("Hello"));
  1041. EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
  1042. EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
  1043. EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
  1044. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1045. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1046. }
  1047. TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1048. std::string str1("oabocdooeoo");
  1049. std::string str2("OABOCDOOEOO");
  1050. Matcher<const std::string&> m0 = StrCaseEq(str1);
  1051. EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
  1052. str1[3] = str2[3] = '\0';
  1053. Matcher<const std::string&> m1 = StrCaseEq(str1);
  1054. EXPECT_TRUE(m1.Matches(str2));
  1055. str1[0] = str1[6] = str1[7] = str1[10] = '\0';
  1056. str2[0] = str2[6] = str2[7] = str2[10] = '\0';
  1057. Matcher<const std::string&> m2 = StrCaseEq(str1);
  1058. str1[9] = str2[9] = '\0';
  1059. EXPECT_FALSE(m2.Matches(str2));
  1060. Matcher<const std::string&> m3 = StrCaseEq(str1);
  1061. EXPECT_TRUE(m3.Matches(str2));
  1062. EXPECT_FALSE(m3.Matches(str2 + "x"));
  1063. str2.append(1, '\0');
  1064. EXPECT_FALSE(m3.Matches(str2));
  1065. EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
  1066. }
  1067. TEST(StrCaseEqTest, CanDescribeSelf) {
  1068. Matcher<std::string> m = StrCaseEq("Hi");
  1069. EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
  1070. }
  1071. TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1072. Matcher<const char*> m = StrCaseNe("Hello");
  1073. EXPECT_TRUE(m.Matches("Hi"));
  1074. EXPECT_TRUE(m.Matches(nullptr));
  1075. EXPECT_FALSE(m.Matches("Hello"));
  1076. EXPECT_FALSE(m.Matches("hello"));
  1077. Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
  1078. EXPECT_TRUE(m2.Matches(""));
  1079. EXPECT_FALSE(m2.Matches("Hello"));
  1080. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1081. Matcher<const internal::StringView> m3 =
  1082. StrCaseNe(internal::StringView("Hello"));
  1083. EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
  1084. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1085. EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
  1086. EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
  1087. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1088. }
  1089. TEST(StrCaseNeTest, CanDescribeSelf) {
  1090. Matcher<const char*> m = StrCaseNe("Hi");
  1091. EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
  1092. }
  1093. // Tests that HasSubstr() works for matching string-typed values.
  1094. TEST(HasSubstrTest, WorksForStringClasses) {
  1095. const Matcher<std::string> m1 = HasSubstr("foo");
  1096. EXPECT_TRUE(m1.Matches(std::string("I love food.")));
  1097. EXPECT_FALSE(m1.Matches(std::string("tofo")));
  1098. const Matcher<const std::string&> m2 = HasSubstr("foo");
  1099. EXPECT_TRUE(m2.Matches(std::string("I love food.")));
  1100. EXPECT_FALSE(m2.Matches(std::string("tofo")));
  1101. const Matcher<std::string> m_empty = HasSubstr("");
  1102. EXPECT_TRUE(m_empty.Matches(std::string()));
  1103. EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
  1104. }
  1105. // Tests that HasSubstr() works for matching C-string-typed values.
  1106. TEST(HasSubstrTest, WorksForCStrings) {
  1107. const Matcher<char*> m1 = HasSubstr("foo");
  1108. EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
  1109. EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
  1110. EXPECT_FALSE(m1.Matches(nullptr));
  1111. const Matcher<const char*> m2 = HasSubstr("foo");
  1112. EXPECT_TRUE(m2.Matches("I love food."));
  1113. EXPECT_FALSE(m2.Matches("tofo"));
  1114. EXPECT_FALSE(m2.Matches(nullptr));
  1115. const Matcher<const char*> m_empty = HasSubstr("");
  1116. EXPECT_TRUE(m_empty.Matches("not empty"));
  1117. EXPECT_TRUE(m_empty.Matches(""));
  1118. EXPECT_FALSE(m_empty.Matches(nullptr));
  1119. }
  1120. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1121. // Tests that HasSubstr() works for matching StringView-typed values.
  1122. TEST(HasSubstrTest, WorksForStringViewClasses) {
  1123. const Matcher<internal::StringView> m1 =
  1124. HasSubstr(internal::StringView("foo"));
  1125. EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
  1126. EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
  1127. EXPECT_FALSE(m1.Matches(internal::StringView()));
  1128. const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
  1129. EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
  1130. EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
  1131. EXPECT_FALSE(m2.Matches(internal::StringView()));
  1132. const Matcher<const internal::StringView&> m3 = HasSubstr("");
  1133. EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
  1134. EXPECT_TRUE(m3.Matches(internal::StringView("")));
  1135. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1136. }
  1137. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1138. // Tests that HasSubstr(s) describes itself properly.
  1139. TEST(HasSubstrTest, CanDescribeSelf) {
  1140. Matcher<std::string> m = HasSubstr("foo\n\"");
  1141. EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
  1142. }
  1143. INSTANTIATE_GTEST_MATCHER_TEST_P(KeyTest);
  1144. TEST(KeyTest, CanDescribeSelf) {
  1145. Matcher<const pair<std::string, int>&> m = Key("foo");
  1146. EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
  1147. EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
  1148. }
  1149. TEST_P(KeyTestP, ExplainsResult) {
  1150. Matcher<pair<int, bool>> m = Key(GreaterThan(10));
  1151. EXPECT_EQ("whose first field is a value which is 5 less than 10",
  1152. Explain(m, make_pair(5, true)));
  1153. EXPECT_EQ("whose first field is a value which is 5 more than 10",
  1154. Explain(m, make_pair(15, true)));
  1155. }
  1156. TEST(KeyTest, MatchesCorrectly) {
  1157. pair<int, std::string> p(25, "foo");
  1158. EXPECT_THAT(p, Key(25));
  1159. EXPECT_THAT(p, Not(Key(42)));
  1160. EXPECT_THAT(p, Key(Ge(20)));
  1161. EXPECT_THAT(p, Not(Key(Lt(25))));
  1162. }
  1163. TEST(KeyTest, WorksWithMoveOnly) {
  1164. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1165. EXPECT_THAT(p, Key(Eq(nullptr)));
  1166. }
  1167. INSTANTIATE_GTEST_MATCHER_TEST_P(PairTest);
  1168. template <size_t I>
  1169. struct Tag {};
  1170. struct PairWithGet {
  1171. int member_1;
  1172. std::string member_2;
  1173. using first_type = int;
  1174. using second_type = std::string;
  1175. const int& GetImpl(Tag<0>) const { return member_1; }
  1176. const std::string& GetImpl(Tag<1>) const { return member_2; }
  1177. };
  1178. template <size_t I>
  1179. auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
  1180. return value.GetImpl(Tag<I>());
  1181. }
  1182. TEST(PairTest, MatchesPairWithGetCorrectly) {
  1183. PairWithGet p{25, "foo"};
  1184. EXPECT_THAT(p, Key(25));
  1185. EXPECT_THAT(p, Not(Key(42)));
  1186. EXPECT_THAT(p, Key(Ge(20)));
  1187. EXPECT_THAT(p, Not(Key(Lt(25))));
  1188. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1189. EXPECT_THAT(v, Contains(Key(29)));
  1190. }
  1191. TEST(KeyTest, SafelyCastsInnerMatcher) {
  1192. Matcher<int> is_positive = Gt(0);
  1193. Matcher<int> is_negative = Lt(0);
  1194. pair<char, bool> p('a', true);
  1195. EXPECT_THAT(p, Key(is_positive));
  1196. EXPECT_THAT(p, Not(Key(is_negative)));
  1197. }
  1198. TEST(KeyTest, InsideContainsUsingMap) {
  1199. map<int, char> container;
  1200. container.insert(make_pair(1, 'a'));
  1201. container.insert(make_pair(2, 'b'));
  1202. container.insert(make_pair(4, 'c'));
  1203. EXPECT_THAT(container, Contains(Key(1)));
  1204. EXPECT_THAT(container, Not(Contains(Key(3))));
  1205. }
  1206. TEST(KeyTest, InsideContainsUsingMultimap) {
  1207. multimap<int, char> container;
  1208. container.insert(make_pair(1, 'a'));
  1209. container.insert(make_pair(2, 'b'));
  1210. container.insert(make_pair(4, 'c'));
  1211. EXPECT_THAT(container, Not(Contains(Key(25))));
  1212. container.insert(make_pair(25, 'd'));
  1213. EXPECT_THAT(container, Contains(Key(25)));
  1214. container.insert(make_pair(25, 'e'));
  1215. EXPECT_THAT(container, Contains(Key(25)));
  1216. EXPECT_THAT(container, Contains(Key(1)));
  1217. EXPECT_THAT(container, Not(Contains(Key(3))));
  1218. }
  1219. TEST(PairTest, Typing) {
  1220. // Test verifies the following type conversions can be compiled.
  1221. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
  1222. Matcher<const pair<const char*, int>> m2 = Pair("foo", 42);
  1223. Matcher<pair<const char*, int>> m3 = Pair("foo", 42);
  1224. Matcher<pair<int, const std::string>> m4 = Pair(25, "42");
  1225. Matcher<pair<const std::string, int>> m5 = Pair("25", 42);
  1226. }
  1227. TEST(PairTest, CanDescribeSelf) {
  1228. Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
  1229. EXPECT_EQ(
  1230. "has a first field that is equal to \"foo\""
  1231. ", and has a second field that is equal to 42",
  1232. Describe(m1));
  1233. EXPECT_EQ(
  1234. "has a first field that isn't equal to \"foo\""
  1235. ", or has a second field that isn't equal to 42",
  1236. DescribeNegation(m1));
  1237. // Double and triple negation (1 or 2 times not and description of negation).
  1238. Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
  1239. EXPECT_EQ(
  1240. "has a first field that isn't equal to 13"
  1241. ", and has a second field that is equal to 42",
  1242. DescribeNegation(m2));
  1243. }
  1244. TEST_P(PairTestP, CanExplainMatchResultTo) {
  1245. // If neither field matches, Pair() should explain about the first
  1246. // field.
  1247. const Matcher<pair<int, int>> m = Pair(GreaterThan(0), GreaterThan(0));
  1248. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1249. Explain(m, make_pair(-1, -2)));
  1250. // If the first field matches but the second doesn't, Pair() should
  1251. // explain about the second field.
  1252. EXPECT_EQ("whose second field does not match, which is 2 less than 0",
  1253. Explain(m, make_pair(1, -2)));
  1254. // If the first field doesn't match but the second does, Pair()
  1255. // should explain about the first field.
  1256. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1257. Explain(m, make_pair(-1, 2)));
  1258. // If both fields match, Pair() should explain about them both.
  1259. EXPECT_EQ(
  1260. "whose both fields match, where the first field is a value "
  1261. "which is 1 more than 0, and the second field is a value "
  1262. "which is 2 more than 0",
  1263. Explain(m, make_pair(1, 2)));
  1264. // If only the first match has an explanation, only this explanation should
  1265. // be printed.
  1266. const Matcher<pair<int, int>> explain_first = Pair(GreaterThan(0), 0);
  1267. EXPECT_EQ(
  1268. "whose both fields match, where the first field is a value "
  1269. "which is 1 more than 0",
  1270. Explain(explain_first, make_pair(1, 0)));
  1271. // If only the second match has an explanation, only this explanation should
  1272. // be printed.
  1273. const Matcher<pair<int, int>> explain_second = Pair(0, GreaterThan(0));
  1274. EXPECT_EQ(
  1275. "whose both fields match, where the second field is a value "
  1276. "which is 1 more than 0",
  1277. Explain(explain_second, make_pair(0, 1)));
  1278. }
  1279. TEST(PairTest, MatchesCorrectly) {
  1280. pair<int, std::string> p(25, "foo");
  1281. // Both fields match.
  1282. EXPECT_THAT(p, Pair(25, "foo"));
  1283. EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
  1284. // 'first' doesn't match, but 'second' matches.
  1285. EXPECT_THAT(p, Not(Pair(42, "foo")));
  1286. EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
  1287. // 'first' matches, but 'second' doesn't match.
  1288. EXPECT_THAT(p, Not(Pair(25, "bar")));
  1289. EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
  1290. // Neither field matches.
  1291. EXPECT_THAT(p, Not(Pair(13, "bar")));
  1292. EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
  1293. }
  1294. TEST(PairTest, WorksWithMoveOnly) {
  1295. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1296. p.second = std::make_unique<int>(7);
  1297. EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
  1298. }
  1299. TEST(PairTest, SafelyCastsInnerMatchers) {
  1300. Matcher<int> is_positive = Gt(0);
  1301. Matcher<int> is_negative = Lt(0);
  1302. pair<char, bool> p('a', true);
  1303. EXPECT_THAT(p, Pair(is_positive, _));
  1304. EXPECT_THAT(p, Not(Pair(is_negative, _)));
  1305. EXPECT_THAT(p, Pair(_, is_positive));
  1306. EXPECT_THAT(p, Not(Pair(_, is_negative)));
  1307. }
  1308. TEST(PairTest, InsideContainsUsingMap) {
  1309. map<int, char> container;
  1310. container.insert(make_pair(1, 'a'));
  1311. container.insert(make_pair(2, 'b'));
  1312. container.insert(make_pair(4, 'c'));
  1313. EXPECT_THAT(container, Contains(Pair(1, 'a')));
  1314. EXPECT_THAT(container, Contains(Pair(1, _)));
  1315. EXPECT_THAT(container, Contains(Pair(_, 'a')));
  1316. EXPECT_THAT(container, Not(Contains(Pair(3, _))));
  1317. }
  1318. INSTANTIATE_GTEST_MATCHER_TEST_P(FieldsAreTest);
  1319. TEST(FieldsAreTest, MatchesCorrectly) {
  1320. std::tuple<int, std::string, double> p(25, "foo", .5);
  1321. // All fields match.
  1322. EXPECT_THAT(p, FieldsAre(25, "foo", .5));
  1323. EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
  1324. // Some don't match.
  1325. EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
  1326. EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
  1327. EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
  1328. }
  1329. TEST(FieldsAreTest, CanDescribeSelf) {
  1330. Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
  1331. EXPECT_EQ(
  1332. "has field #0 that is equal to \"foo\""
  1333. ", and has field #1 that is equal to 42",
  1334. Describe(m1));
  1335. EXPECT_EQ(
  1336. "has field #0 that isn't equal to \"foo\""
  1337. ", or has field #1 that isn't equal to 42",
  1338. DescribeNegation(m1));
  1339. }
  1340. TEST_P(FieldsAreTestP, CanExplainMatchResultTo) {
  1341. // The first one that fails is the one that gives the error.
  1342. Matcher<std::tuple<int, int, int>> m =
  1343. FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
  1344. EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
  1345. Explain(m, std::make_tuple(-1, -2, -3)));
  1346. EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
  1347. Explain(m, std::make_tuple(1, -2, -3)));
  1348. EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
  1349. Explain(m, std::make_tuple(1, 2, -3)));
  1350. // If they all match, we get a long explanation of success.
  1351. EXPECT_EQ(
  1352. "whose all elements match, "
  1353. "where field #0 is a value which is 1 more than 0"
  1354. ", and field #1 is a value which is 2 more than 0"
  1355. ", and field #2 is a value which is 3 more than 0",
  1356. Explain(m, std::make_tuple(1, 2, 3)));
  1357. // Only print those that have an explanation.
  1358. m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
  1359. EXPECT_EQ(
  1360. "whose all elements match, "
  1361. "where field #0 is a value which is 1 more than 0"
  1362. ", and field #2 is a value which is 3 more than 0",
  1363. Explain(m, std::make_tuple(1, 0, 3)));
  1364. // If only one has an explanation, then print that one.
  1365. m = FieldsAre(0, GreaterThan(0), 0);
  1366. EXPECT_EQ(
  1367. "whose all elements match, "
  1368. "where field #1 is a value which is 1 more than 0",
  1369. Explain(m, std::make_tuple(0, 1, 0)));
  1370. }
  1371. #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
  1372. TEST(FieldsAreTest, StructuredBindings) {
  1373. // testing::FieldsAre can also match aggregates and such with C++17 and up.
  1374. struct MyType {
  1375. int i;
  1376. std::string str;
  1377. };
  1378. EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
  1379. // Test all the supported arities.
  1380. struct MyVarType1 {
  1381. int a;
  1382. };
  1383. EXPECT_THAT(MyVarType1{}, FieldsAre(0));
  1384. struct MyVarType2 {
  1385. int a, b;
  1386. };
  1387. EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
  1388. struct MyVarType3 {
  1389. int a, b, c;
  1390. };
  1391. EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
  1392. struct MyVarType4 {
  1393. int a, b, c, d;
  1394. };
  1395. EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
  1396. struct MyVarType5 {
  1397. int a, b, c, d, e;
  1398. };
  1399. EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
  1400. struct MyVarType6 {
  1401. int a, b, c, d, e, f;
  1402. };
  1403. EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
  1404. struct MyVarType7 {
  1405. int a, b, c, d, e, f, g;
  1406. };
  1407. EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
  1408. struct MyVarType8 {
  1409. int a, b, c, d, e, f, g, h;
  1410. };
  1411. EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
  1412. struct MyVarType9 {
  1413. int a, b, c, d, e, f, g, h, i;
  1414. };
  1415. EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
  1416. struct MyVarType10 {
  1417. int a, b, c, d, e, f, g, h, i, j;
  1418. };
  1419. EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1420. struct MyVarType11 {
  1421. int a, b, c, d, e, f, g, h, i, j, k;
  1422. };
  1423. EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1424. struct MyVarType12 {
  1425. int a, b, c, d, e, f, g, h, i, j, k, l;
  1426. };
  1427. EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1428. struct MyVarType13 {
  1429. int a, b, c, d, e, f, g, h, i, j, k, l, m;
  1430. };
  1431. EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1432. struct MyVarType14 {
  1433. int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
  1434. };
  1435. EXPECT_THAT(MyVarType14{},
  1436. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1437. struct MyVarType15 {
  1438. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
  1439. };
  1440. EXPECT_THAT(MyVarType15{},
  1441. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1442. struct MyVarType16 {
  1443. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
  1444. };
  1445. EXPECT_THAT(MyVarType16{},
  1446. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1447. struct MyVarType17 {
  1448. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q;
  1449. };
  1450. EXPECT_THAT(MyVarType17{},
  1451. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1452. struct MyVarType18 {
  1453. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r;
  1454. };
  1455. EXPECT_THAT(MyVarType18{},
  1456. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1457. struct MyVarType19 {
  1458. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s;
  1459. };
  1460. EXPECT_THAT(MyVarType19{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1461. 0, 0, 0, 0, 0));
  1462. }
  1463. #endif
  1464. TEST(PairTest, UseGetInsteadOfMembers) {
  1465. PairWithGet pair{7, "ABC"};
  1466. EXPECT_THAT(pair, Pair(7, "ABC"));
  1467. EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
  1468. EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
  1469. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1470. EXPECT_THAT(v,
  1471. ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
  1472. }
  1473. // Tests StartsWith(s).
  1474. TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
  1475. const Matcher<const char*> m1 = StartsWith(std::string(""));
  1476. EXPECT_TRUE(m1.Matches("Hi"));
  1477. EXPECT_TRUE(m1.Matches(""));
  1478. EXPECT_FALSE(m1.Matches(nullptr));
  1479. const Matcher<const std::string&> m2 = StartsWith("Hi");
  1480. EXPECT_TRUE(m2.Matches("Hi"));
  1481. EXPECT_TRUE(m2.Matches("Hi Hi!"));
  1482. EXPECT_TRUE(m2.Matches("High"));
  1483. EXPECT_FALSE(m2.Matches("H"));
  1484. EXPECT_FALSE(m2.Matches(" Hi"));
  1485. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1486. const Matcher<internal::StringView> m_empty =
  1487. StartsWith(internal::StringView(""));
  1488. EXPECT_TRUE(m_empty.Matches(internal::StringView()));
  1489. EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
  1490. EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
  1491. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1492. }
  1493. TEST(StartsWithTest, CanDescribeSelf) {
  1494. Matcher<const std::string> m = StartsWith("Hi");
  1495. EXPECT_EQ("starts with \"Hi\"", Describe(m));
  1496. }
  1497. // Tests EndsWith(s).
  1498. TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
  1499. const Matcher<const char*> m1 = EndsWith("");
  1500. EXPECT_TRUE(m1.Matches("Hi"));
  1501. EXPECT_TRUE(m1.Matches(""));
  1502. EXPECT_FALSE(m1.Matches(nullptr));
  1503. const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
  1504. EXPECT_TRUE(m2.Matches("Hi"));
  1505. EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
  1506. EXPECT_TRUE(m2.Matches("Super Hi"));
  1507. EXPECT_FALSE(m2.Matches("i"));
  1508. EXPECT_FALSE(m2.Matches("Hi "));
  1509. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1510. const Matcher<const internal::StringView&> m4 =
  1511. EndsWith(internal::StringView(""));
  1512. EXPECT_TRUE(m4.Matches("Hi"));
  1513. EXPECT_TRUE(m4.Matches(""));
  1514. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1515. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1516. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1517. }
  1518. TEST(EndsWithTest, CanDescribeSelf) {
  1519. Matcher<const std::string> m = EndsWith("Hi");
  1520. EXPECT_EQ("ends with \"Hi\"", Describe(m));
  1521. }
  1522. // Tests WhenBase64Unescaped.
  1523. TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
  1524. const Matcher<const char*> m1 = WhenBase64Unescaped(EndsWith("!"));
  1525. EXPECT_FALSE(m1.Matches("invalid base64"));
  1526. EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world
  1527. EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world!
  1528. EXPECT_TRUE(m1.Matches("+/-_IQ")); // \xfb\xff\xbf!
  1529. const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
  1530. EXPECT_FALSE(m2.Matches("invalid base64"));
  1531. EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world
  1532. EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world!
  1533. EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
  1534. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1535. const Matcher<const internal::StringView&> m3 =
  1536. WhenBase64Unescaped(EndsWith("!"));
  1537. EXPECT_FALSE(m3.Matches("invalid base64"));
  1538. EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world
  1539. EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world!
  1540. EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
  1541. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1542. }
  1543. TEST(WhenBase64UnescapedTest, CanDescribeSelf) {
  1544. const Matcher<const char*> m = WhenBase64Unescaped(EndsWith("!"));
  1545. EXPECT_EQ("matches after Base64Unescape ends with \"!\"", Describe(m));
  1546. }
  1547. // Tests MatchesRegex().
  1548. TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
  1549. const Matcher<const char*> m1 = MatchesRegex("a.*z");
  1550. EXPECT_TRUE(m1.Matches("az"));
  1551. EXPECT_TRUE(m1.Matches("abcz"));
  1552. EXPECT_FALSE(m1.Matches(nullptr));
  1553. const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
  1554. EXPECT_TRUE(m2.Matches("azbz"));
  1555. EXPECT_FALSE(m2.Matches("az1"));
  1556. EXPECT_FALSE(m2.Matches("1az"));
  1557. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1558. const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
  1559. EXPECT_TRUE(m3.Matches(internal::StringView("az")));
  1560. EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
  1561. EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
  1562. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1563. const Matcher<const internal::StringView&> m4 =
  1564. MatchesRegex(internal::StringView(""));
  1565. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1566. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1567. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1568. }
  1569. TEST(MatchesRegexTest, CanDescribeSelf) {
  1570. Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
  1571. EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
  1572. Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
  1573. EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
  1574. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1575. Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
  1576. EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
  1577. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1578. }
  1579. // Tests ContainsRegex().
  1580. TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
  1581. const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
  1582. EXPECT_TRUE(m1.Matches("az"));
  1583. EXPECT_TRUE(m1.Matches("0abcz1"));
  1584. EXPECT_FALSE(m1.Matches(nullptr));
  1585. const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
  1586. EXPECT_TRUE(m2.Matches("azbz"));
  1587. EXPECT_TRUE(m2.Matches("az1"));
  1588. EXPECT_FALSE(m2.Matches("1a"));
  1589. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1590. const Matcher<const internal::StringView&> m3 = ContainsRegex(new RE("a.*z"));
  1591. EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
  1592. EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
  1593. EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
  1594. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1595. const Matcher<const internal::StringView&> m4 =
  1596. ContainsRegex(internal::StringView(""));
  1597. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1598. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1599. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1600. }
  1601. TEST(ContainsRegexTest, CanDescribeSelf) {
  1602. Matcher<const std::string> m1 = ContainsRegex("Hi.*");
  1603. EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
  1604. Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
  1605. EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
  1606. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1607. Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
  1608. EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
  1609. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1610. }
  1611. // Tests for wide strings.
  1612. #if GTEST_HAS_STD_WSTRING
  1613. TEST(StdWideStrEqTest, MatchesEqual) {
  1614. Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
  1615. EXPECT_TRUE(m.Matches(L"Hello"));
  1616. EXPECT_FALSE(m.Matches(L"hello"));
  1617. EXPECT_FALSE(m.Matches(nullptr));
  1618. Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
  1619. EXPECT_TRUE(m2.Matches(L"Hello"));
  1620. EXPECT_FALSE(m2.Matches(L"Hi"));
  1621. Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1622. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1623. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1624. ::std::wstring str(L"01204500800");
  1625. str[3] = L'\0';
  1626. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1627. EXPECT_TRUE(m4.Matches(str));
  1628. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1629. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1630. EXPECT_TRUE(m5.Matches(str));
  1631. }
  1632. TEST(StdWideStrEqTest, CanDescribeSelf) {
  1633. Matcher<::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1634. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1635. Describe(m));
  1636. Matcher<::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1637. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2));
  1638. ::std::wstring str(L"01204500800");
  1639. str[3] = L'\0';
  1640. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1641. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1642. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1643. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1644. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1645. }
  1646. TEST(StdWideStrNeTest, MatchesUnequalString) {
  1647. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1648. EXPECT_TRUE(m.Matches(L""));
  1649. EXPECT_TRUE(m.Matches(nullptr));
  1650. EXPECT_FALSE(m.Matches(L"Hello"));
  1651. Matcher<::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
  1652. EXPECT_TRUE(m2.Matches(L"hello"));
  1653. EXPECT_FALSE(m2.Matches(L"Hello"));
  1654. }
  1655. TEST(StdWideStrNeTest, CanDescribeSelf) {
  1656. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1657. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1658. }
  1659. TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1660. Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
  1661. EXPECT_TRUE(m.Matches(L"Hello"));
  1662. EXPECT_TRUE(m.Matches(L"hello"));
  1663. EXPECT_FALSE(m.Matches(L"Hi"));
  1664. EXPECT_FALSE(m.Matches(nullptr));
  1665. Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
  1666. EXPECT_TRUE(m2.Matches(L"hello"));
  1667. EXPECT_FALSE(m2.Matches(L"Hi"));
  1668. }
  1669. TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1670. ::std::wstring str1(L"oabocdooeoo");
  1671. ::std::wstring str2(L"OABOCDOOEOO");
  1672. Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
  1673. EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
  1674. str1[3] = str2[3] = L'\0';
  1675. Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
  1676. EXPECT_TRUE(m1.Matches(str2));
  1677. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1678. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1679. Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
  1680. str1[9] = str2[9] = L'\0';
  1681. EXPECT_FALSE(m2.Matches(str2));
  1682. Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
  1683. EXPECT_TRUE(m3.Matches(str2));
  1684. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1685. str2.append(1, L'\0');
  1686. EXPECT_FALSE(m3.Matches(str2));
  1687. EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
  1688. }
  1689. TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
  1690. Matcher<::std::wstring> m = StrCaseEq(L"Hi");
  1691. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1692. }
  1693. TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1694. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1695. EXPECT_TRUE(m.Matches(L"Hi"));
  1696. EXPECT_TRUE(m.Matches(nullptr));
  1697. EXPECT_FALSE(m.Matches(L"Hello"));
  1698. EXPECT_FALSE(m.Matches(L"hello"));
  1699. Matcher<::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
  1700. EXPECT_TRUE(m2.Matches(L""));
  1701. EXPECT_FALSE(m2.Matches(L"Hello"));
  1702. }
  1703. TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
  1704. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1705. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1706. }
  1707. // Tests that HasSubstr() works for matching wstring-typed values.
  1708. TEST(StdWideHasSubstrTest, WorksForStringClasses) {
  1709. const Matcher<::std::wstring> m1 = HasSubstr(L"foo");
  1710. EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
  1711. EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
  1712. const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
  1713. EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
  1714. EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
  1715. }
  1716. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1717. TEST(StdWideHasSubstrTest, WorksForCStrings) {
  1718. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1719. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1720. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1721. EXPECT_FALSE(m1.Matches(nullptr));
  1722. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1723. EXPECT_TRUE(m2.Matches(L"I love food."));
  1724. EXPECT_FALSE(m2.Matches(L"tofo"));
  1725. EXPECT_FALSE(m2.Matches(nullptr));
  1726. }
  1727. // Tests that HasSubstr(s) describes itself properly.
  1728. TEST(StdWideHasSubstrTest, CanDescribeSelf) {
  1729. Matcher<::std::wstring> m = HasSubstr(L"foo\n\"");
  1730. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1731. }
  1732. // Tests StartsWith(s).
  1733. TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1734. const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
  1735. EXPECT_TRUE(m1.Matches(L"Hi"));
  1736. EXPECT_TRUE(m1.Matches(L""));
  1737. EXPECT_FALSE(m1.Matches(nullptr));
  1738. const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
  1739. EXPECT_TRUE(m2.Matches(L"Hi"));
  1740. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1741. EXPECT_TRUE(m2.Matches(L"High"));
  1742. EXPECT_FALSE(m2.Matches(L"H"));
  1743. EXPECT_FALSE(m2.Matches(L" Hi"));
  1744. }
  1745. TEST(StdWideStartsWithTest, CanDescribeSelf) {
  1746. Matcher<const ::std::wstring> m = StartsWith(L"Hi");
  1747. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1748. }
  1749. // Tests EndsWith(s).
  1750. TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1751. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1752. EXPECT_TRUE(m1.Matches(L"Hi"));
  1753. EXPECT_TRUE(m1.Matches(L""));
  1754. EXPECT_FALSE(m1.Matches(nullptr));
  1755. const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
  1756. EXPECT_TRUE(m2.Matches(L"Hi"));
  1757. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1758. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1759. EXPECT_FALSE(m2.Matches(L"i"));
  1760. EXPECT_FALSE(m2.Matches(L"Hi "));
  1761. }
  1762. TEST(StdWideEndsWithTest, CanDescribeSelf) {
  1763. Matcher<const ::std::wstring> m = EndsWith(L"Hi");
  1764. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1765. }
  1766. #endif // GTEST_HAS_STD_WSTRING
  1767. TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
  1768. StringMatchResultListener listener1;
  1769. EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
  1770. EXPECT_EQ("% 2 == 0", listener1.str());
  1771. StringMatchResultListener listener2;
  1772. EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
  1773. EXPECT_EQ("", listener2.str());
  1774. }
  1775. TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
  1776. const Matcher<int> is_even = PolymorphicIsEven();
  1777. StringMatchResultListener listener1;
  1778. EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
  1779. EXPECT_EQ("% 2 == 0", listener1.str());
  1780. const Matcher<const double&> is_zero = Eq(0);
  1781. StringMatchResultListener listener2;
  1782. EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
  1783. EXPECT_EQ("", listener2.str());
  1784. }
  1785. MATCHER(ConstructNoArg, "") { return true; }
  1786. MATCHER_P(Construct1Arg, arg1, "") { return true; }
  1787. MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
  1788. TEST(MatcherConstruct, ExplicitVsImplicit) {
  1789. {
  1790. // No arg constructor can be constructed with empty brace.
  1791. ConstructNoArgMatcher m = {};
  1792. (void)m;
  1793. // And with no args
  1794. ConstructNoArgMatcher m2;
  1795. (void)m2;
  1796. }
  1797. {
  1798. // The one arg constructor has an explicit constructor.
  1799. // This is to prevent the implicit conversion.
  1800. using M = Construct1ArgMatcherP<int>;
  1801. EXPECT_TRUE((std::is_constructible<M, int>::value));
  1802. EXPECT_FALSE((std::is_convertible<int, M>::value));
  1803. }
  1804. {
  1805. // Multiple arg matchers can be constructed with an implicit construction.
  1806. Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
  1807. (void)m;
  1808. }
  1809. }
  1810. MATCHER_P(Really, inner_matcher, "") {
  1811. return ExplainMatchResult(inner_matcher, arg, result_listener);
  1812. }
  1813. TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
  1814. EXPECT_THAT(0, Really(Eq(0)));
  1815. }
  1816. TEST(DescribeMatcherTest, WorksWithValue) {
  1817. EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
  1818. EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
  1819. }
  1820. TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
  1821. const Matcher<int> monomorphic = Le(0);
  1822. EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
  1823. EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
  1824. }
  1825. TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
  1826. EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
  1827. EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
  1828. }
  1829. MATCHER_P(FieldIIs, inner_matcher, "") {
  1830. return ExplainMatchResult(inner_matcher, arg.i, result_listener);
  1831. }
  1832. #if GTEST_HAS_RTTI
  1833. TEST(WhenDynamicCastToTest, SameType) {
  1834. Derived derived;
  1835. derived.i = 4;
  1836. // Right type. A pointer is passed down.
  1837. Base* as_base_ptr = &derived;
  1838. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
  1839. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
  1840. EXPECT_THAT(as_base_ptr,
  1841. Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
  1842. }
  1843. TEST(WhenDynamicCastToTest, WrongTypes) {
  1844. Base base;
  1845. Derived derived;
  1846. OtherDerived other_derived;
  1847. // Wrong types. NULL is passed.
  1848. EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  1849. EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
  1850. Base* as_base_ptr = &derived;
  1851. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
  1852. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
  1853. as_base_ptr = &other_derived;
  1854. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  1855. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  1856. }
  1857. TEST(WhenDynamicCastToTest, AlreadyNull) {
  1858. // Already NULL.
  1859. Base* as_base_ptr = nullptr;
  1860. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  1861. }
  1862. struct AmbiguousCastTypes {
  1863. class VirtualDerived : public virtual Base {};
  1864. class DerivedSub1 : public VirtualDerived {};
  1865. class DerivedSub2 : public VirtualDerived {};
  1866. class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
  1867. };
  1868. TEST(WhenDynamicCastToTest, AmbiguousCast) {
  1869. AmbiguousCastTypes::DerivedSub1 sub1;
  1870. AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
  1871. // Multiply derived from Base. dynamic_cast<> returns NULL.
  1872. Base* as_base_ptr =
  1873. static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
  1874. EXPECT_THAT(as_base_ptr,
  1875. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
  1876. as_base_ptr = &sub1;
  1877. EXPECT_THAT(
  1878. as_base_ptr,
  1879. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
  1880. }
  1881. TEST(WhenDynamicCastToTest, Describe) {
  1882. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  1883. const std::string prefix =
  1884. "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
  1885. EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
  1886. EXPECT_EQ(prefix + "does not point to a value that is anything",
  1887. DescribeNegation(matcher));
  1888. }
  1889. TEST(WhenDynamicCastToTest, Explain) {
  1890. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  1891. Base* null = nullptr;
  1892. EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
  1893. Derived derived;
  1894. EXPECT_TRUE(matcher.Matches(&derived));
  1895. EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
  1896. // With references, the matcher itself can fail. Test for that one.
  1897. Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
  1898. EXPECT_THAT(Explain(ref_matcher, derived),
  1899. HasSubstr("which cannot be dynamic_cast"));
  1900. }
  1901. TEST(WhenDynamicCastToTest, GoodReference) {
  1902. Derived derived;
  1903. derived.i = 4;
  1904. Base& as_base_ref = derived;
  1905. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
  1906. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
  1907. }
  1908. TEST(WhenDynamicCastToTest, BadReference) {
  1909. Derived derived;
  1910. Base& as_base_ref = derived;
  1911. EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
  1912. }
  1913. #endif // GTEST_HAS_RTTI
  1914. class DivisibleByImpl {
  1915. public:
  1916. explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
  1917. // For testing using ExplainMatchResultTo() with polymorphic matchers.
  1918. template <typename T>
  1919. bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
  1920. *listener << "which is " << (n % divider_) << " modulo " << divider_;
  1921. return (n % divider_) == 0;
  1922. }
  1923. void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; }
  1924. void DescribeNegationTo(ostream* os) const {
  1925. *os << "is not divisible by " << divider_;
  1926. }
  1927. void set_divider(int a_divider) { divider_ = a_divider; }
  1928. int divider() const { return divider_; }
  1929. private:
  1930. int divider_;
  1931. };
  1932. PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
  1933. return MakePolymorphicMatcher(DivisibleByImpl(n));
  1934. }
  1935. // Tests that when AllOf() fails, only the first failing matcher is
  1936. // asked to explain why.
  1937. TEST(ExplainMatchResultTest, AllOf_False_False) {
  1938. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  1939. EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
  1940. }
  1941. // Tests that when AllOf() fails, only the first failing matcher is
  1942. // asked to explain why.
  1943. TEST(ExplainMatchResultTest, AllOf_False_True) {
  1944. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  1945. EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
  1946. }
  1947. // Tests that when AllOf() fails, only the first failing matcher is
  1948. // asked to explain why.
  1949. TEST(ExplainMatchResultTest, AllOf_True_False) {
  1950. const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
  1951. EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
  1952. }
  1953. // Tests that when AllOf() succeeds, all matchers are asked to explain
  1954. // why.
  1955. TEST(ExplainMatchResultTest, AllOf_True_True) {
  1956. const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
  1957. EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
  1958. }
  1959. TEST(ExplainMatchResultTest, AllOf_True_True_2) {
  1960. const Matcher<int> m = AllOf(Ge(2), Le(3));
  1961. EXPECT_EQ("", Explain(m, 2));
  1962. }
  1963. INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);
  1964. TEST_P(ExplainmatcherResultTestP, MonomorphicMatcher) {
  1965. const Matcher<int> m = GreaterThan(5);
  1966. EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
  1967. }
  1968. // Tests PolymorphicMatcher::mutable_impl().
  1969. TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
  1970. PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  1971. DivisibleByImpl& impl = m.mutable_impl();
  1972. EXPECT_EQ(42, impl.divider());
  1973. impl.set_divider(0);
  1974. EXPECT_EQ(0, m.mutable_impl().divider());
  1975. }
  1976. // Tests PolymorphicMatcher::impl().
  1977. TEST(PolymorphicMatcherTest, CanAccessImpl) {
  1978. const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  1979. const DivisibleByImpl& impl = m.impl();
  1980. EXPECT_EQ(42, impl.divider());
  1981. }
  1982. } // namespace
  1983. } // namespace gmock_matchers_test
  1984. } // namespace testing
  1985. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100