gmock-generated-matchers_test.cc 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. // Copyright 2008, 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 the built-in matchers generated by a script.
  32. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  33. // possible loss of data and C4100, unreferenced local parameter
  34. #ifdef _MSC_VER
  35. # pragma warning(push)
  36. # pragma warning(disable:4244)
  37. # pragma warning(disable:4100)
  38. #endif
  39. #include "gmock/gmock-generated-matchers.h"
  40. #include <list>
  41. #include <map>
  42. #include <memory>
  43. #include <set>
  44. #include <sstream>
  45. #include <string>
  46. #include <utility>
  47. #include <vector>
  48. #include "gmock/gmock.h"
  49. #include "gtest/gtest.h"
  50. #include "gtest/gtest-spi.h"
  51. namespace {
  52. using std::list;
  53. using std::map;
  54. using std::pair;
  55. using std::set;
  56. using std::stringstream;
  57. using std::vector;
  58. using testing::get;
  59. using testing::make_tuple;
  60. using testing::tuple;
  61. using testing::_;
  62. using testing::AllOf;
  63. using testing::AnyOf;
  64. using testing::Args;
  65. using testing::Contains;
  66. using testing::ElementsAre;
  67. using testing::ElementsAreArray;
  68. using testing::Eq;
  69. using testing::Ge;
  70. using testing::Gt;
  71. using testing::Le;
  72. using testing::Lt;
  73. using testing::MakeMatcher;
  74. using testing::Matcher;
  75. using testing::MatcherInterface;
  76. using testing::MatchResultListener;
  77. using testing::Ne;
  78. using testing::Not;
  79. using testing::Pointee;
  80. using testing::PrintToString;
  81. using testing::Ref;
  82. using testing::StaticAssertTypeEq;
  83. using testing::StrEq;
  84. using testing::Value;
  85. using testing::internal::ElementsAreArrayMatcher;
  86. // Returns the description of the given matcher.
  87. template <typename T>
  88. std::string Describe(const Matcher<T>& m) {
  89. stringstream ss;
  90. m.DescribeTo(&ss);
  91. return ss.str();
  92. }
  93. // Returns the description of the negation of the given matcher.
  94. template <typename T>
  95. std::string DescribeNegation(const Matcher<T>& m) {
  96. stringstream ss;
  97. m.DescribeNegationTo(&ss);
  98. return ss.str();
  99. }
  100. // Returns the reason why x matches, or doesn't match, m.
  101. template <typename MatcherType, typename Value>
  102. std::string Explain(const MatcherType& m, const Value& x) {
  103. stringstream ss;
  104. m.ExplainMatchResultTo(x, &ss);
  105. return ss.str();
  106. }
  107. // Tests Args<k0, ..., kn>(m).
  108. TEST(ArgsTest, AcceptsZeroTemplateArg) {
  109. const tuple<int, bool> t(5, true);
  110. EXPECT_THAT(t, Args<>(Eq(tuple<>())));
  111. EXPECT_THAT(t, Not(Args<>(Ne(tuple<>()))));
  112. }
  113. TEST(ArgsTest, AcceptsOneTemplateArg) {
  114. const tuple<int, bool> t(5, true);
  115. EXPECT_THAT(t, Args<0>(Eq(make_tuple(5))));
  116. EXPECT_THAT(t, Args<1>(Eq(make_tuple(true))));
  117. EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false)))));
  118. }
  119. TEST(ArgsTest, AcceptsTwoTemplateArgs) {
  120. const tuple<short, int, long> t(4, 5, 6L); // NOLINT
  121. EXPECT_THAT(t, (Args<0, 1>(Lt())));
  122. EXPECT_THAT(t, (Args<1, 2>(Lt())));
  123. EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
  124. }
  125. TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
  126. const tuple<short, int, long> t(4, 5, 6L); // NOLINT
  127. EXPECT_THAT(t, (Args<0, 0>(Eq())));
  128. EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
  129. }
  130. TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
  131. const tuple<short, int, long> t(4, 5, 6L); // NOLINT
  132. EXPECT_THAT(t, (Args<2, 0>(Gt())));
  133. EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
  134. }
  135. // The MATCHER*() macros trigger warning C4100 (unreferenced formal
  136. // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
  137. // the macro definition, as the warnings are generated when the macro
  138. // is expanded and macro expansion cannot contain #pragma. Therefore
  139. // we suppress them here.
  140. #ifdef _MSC_VER
  141. # pragma warning(push)
  142. # pragma warning(disable:4100)
  143. #endif
  144. MATCHER(SumIsZero, "") {
  145. return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0;
  146. }
  147. TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
  148. EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
  149. EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
  150. }
  151. TEST(ArgsTest, CanBeNested) {
  152. const tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
  153. EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
  154. EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
  155. }
  156. TEST(ArgsTest, CanMatchTupleByValue) {
  157. typedef tuple<char, int, int> Tuple3;
  158. const Matcher<Tuple3> m = Args<1, 2>(Lt());
  159. EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
  160. EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
  161. }
  162. TEST(ArgsTest, CanMatchTupleByReference) {
  163. typedef tuple<char, char, int> Tuple3;
  164. const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
  165. EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
  166. EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
  167. }
  168. // Validates that arg is printed as str.
  169. MATCHER_P(PrintsAs, str, "") {
  170. return testing::PrintToString(arg) == str;
  171. }
  172. TEST(ArgsTest, AcceptsTenTemplateArgs) {
  173. EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  174. (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  175. PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  176. EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  177. Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  178. PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  179. }
  180. TEST(ArgsTest, DescirbesSelfCorrectly) {
  181. const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt());
  182. EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
  183. "the first < the second",
  184. Describe(m));
  185. }
  186. TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
  187. const Matcher<const tuple<int, bool, char, int>&> m =
  188. Args<0, 2, 3>(Args<2, 0>(Lt()));
  189. EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
  190. "whose fields (#2, #0) are a pair where the first < the second",
  191. Describe(m));
  192. }
  193. TEST(ArgsTest, DescribesNegationCorrectly) {
  194. const Matcher<tuple<int, char> > m = Args<1, 0>(Gt());
  195. EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
  196. "where the first > the second",
  197. DescribeNegation(m));
  198. }
  199. TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
  200. const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq());
  201. EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
  202. Explain(m, make_tuple(false, 42, 42)));
  203. EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
  204. Explain(m, make_tuple(false, 42, 43)));
  205. }
  206. // For testing Args<>'s explanation.
  207. class LessThanMatcher : public MatcherInterface<tuple<char, int> > {
  208. public:
  209. virtual void DescribeTo(::std::ostream* os) const {}
  210. virtual bool MatchAndExplain(tuple<char, int> value,
  211. MatchResultListener* listener) const {
  212. const int diff = get<0>(value) - get<1>(value);
  213. if (diff > 0) {
  214. *listener << "where the first value is " << diff
  215. << " more than the second";
  216. }
  217. return diff < 0;
  218. }
  219. };
  220. Matcher<tuple<char, int> > LessThan() {
  221. return MakeMatcher(new LessThanMatcher);
  222. }
  223. TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
  224. const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan());
  225. EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), "
  226. "where the first value is 55 more than the second",
  227. Explain(m, make_tuple('a', 42, 42)));
  228. EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
  229. Explain(m, make_tuple('\0', 42, 43)));
  230. }
  231. // For testing ExplainMatchResultTo().
  232. class GreaterThanMatcher : public MatcherInterface<int> {
  233. public:
  234. explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
  235. virtual void DescribeTo(::std::ostream* os) const {
  236. *os << "is greater than " << rhs_;
  237. }
  238. virtual bool MatchAndExplain(int lhs,
  239. MatchResultListener* listener) const {
  240. const int diff = lhs - rhs_;
  241. if (diff > 0) {
  242. *listener << "which is " << diff << " more than " << rhs_;
  243. } else if (diff == 0) {
  244. *listener << "which is the same as " << rhs_;
  245. } else {
  246. *listener << "which is " << -diff << " less than " << rhs_;
  247. }
  248. return lhs > rhs_;
  249. }
  250. private:
  251. int rhs_;
  252. };
  253. Matcher<int> GreaterThan(int n) {
  254. return MakeMatcher(new GreaterThanMatcher(n));
  255. }
  256. // Tests for ElementsAre().
  257. TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
  258. Matcher<const vector<int>&> m = ElementsAre();
  259. EXPECT_EQ("is empty", Describe(m));
  260. }
  261. TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
  262. Matcher<vector<int> > m = ElementsAre(Gt(5));
  263. EXPECT_EQ("has 1 element that is > 5", Describe(m));
  264. }
  265. TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
  266. Matcher<list<std::string> > m = ElementsAre(StrEq("one"), "two");
  267. EXPECT_EQ("has 2 elements where\n"
  268. "element #0 is equal to \"one\",\n"
  269. "element #1 is equal to \"two\"", Describe(m));
  270. }
  271. TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
  272. Matcher<vector<int> > m = ElementsAre();
  273. EXPECT_EQ("isn't empty", DescribeNegation(m));
  274. }
  275. TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
  276. Matcher<const list<int>& > m = ElementsAre(Gt(5));
  277. EXPECT_EQ("doesn't have 1 element, or\n"
  278. "element #0 isn't > 5", DescribeNegation(m));
  279. }
  280. TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
  281. Matcher<const list<std::string>&> m = ElementsAre("one", "two");
  282. EXPECT_EQ("doesn't have 2 elements, or\n"
  283. "element #0 isn't equal to \"one\", or\n"
  284. "element #1 isn't equal to \"two\"", DescribeNegation(m));
  285. }
  286. TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
  287. Matcher<const list<int>& > m = ElementsAre(1, Ne(2));
  288. list<int> test_list;
  289. test_list.push_back(1);
  290. test_list.push_back(3);
  291. EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
  292. }
  293. TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
  294. Matcher<const vector<int>& > m =
  295. ElementsAre(GreaterThan(1), 0, GreaterThan(2));
  296. const int a[] = { 10, 0, 100 };
  297. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  298. EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
  299. "and whose element #2 matches, which is 98 more than 2",
  300. Explain(m, test_vector));
  301. }
  302. TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
  303. Matcher<const list<int>& > m = ElementsAre(1, 3);
  304. list<int> test_list;
  305. // No need to explain when the container is empty.
  306. EXPECT_EQ("", Explain(m, test_list));
  307. test_list.push_back(1);
  308. EXPECT_EQ("which has 1 element", Explain(m, test_list));
  309. }
  310. TEST(ElementsAreTest, CanExplainMismatchRightSize) {
  311. Matcher<const vector<int>& > m = ElementsAre(1, GreaterThan(5));
  312. vector<int> v;
  313. v.push_back(2);
  314. v.push_back(1);
  315. EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
  316. v[0] = 1;
  317. EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
  318. Explain(m, v));
  319. }
  320. TEST(ElementsAreTest, MatchesOneElementVector) {
  321. vector<std::string> test_vector;
  322. test_vector.push_back("test string");
  323. EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
  324. }
  325. TEST(ElementsAreTest, MatchesOneElementList) {
  326. list<std::string> test_list;
  327. test_list.push_back("test string");
  328. EXPECT_THAT(test_list, ElementsAre("test string"));
  329. }
  330. TEST(ElementsAreTest, MatchesThreeElementVector) {
  331. vector<std::string> test_vector;
  332. test_vector.push_back("one");
  333. test_vector.push_back("two");
  334. test_vector.push_back("three");
  335. EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
  336. }
  337. TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
  338. vector<int> test_vector;
  339. test_vector.push_back(4);
  340. EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
  341. }
  342. TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
  343. vector<int> test_vector;
  344. test_vector.push_back(4);
  345. EXPECT_THAT(test_vector, ElementsAre(_));
  346. }
  347. TEST(ElementsAreTest, MatchesOneElementValue) {
  348. vector<int> test_vector;
  349. test_vector.push_back(4);
  350. EXPECT_THAT(test_vector, ElementsAre(4));
  351. }
  352. TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
  353. vector<int> test_vector;
  354. test_vector.push_back(1);
  355. test_vector.push_back(2);
  356. test_vector.push_back(3);
  357. EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
  358. }
  359. TEST(ElementsAreTest, MatchesTenElementVector) {
  360. const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  361. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  362. EXPECT_THAT(test_vector,
  363. // The element list can contain values and/or matchers
  364. // of different types.
  365. ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
  366. }
  367. TEST(ElementsAreTest, DoesNotMatchWrongSize) {
  368. vector<std::string> test_vector;
  369. test_vector.push_back("test string");
  370. test_vector.push_back("test string");
  371. Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
  372. EXPECT_FALSE(m.Matches(test_vector));
  373. }
  374. TEST(ElementsAreTest, DoesNotMatchWrongValue) {
  375. vector<std::string> test_vector;
  376. test_vector.push_back("other string");
  377. Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
  378. EXPECT_FALSE(m.Matches(test_vector));
  379. }
  380. TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
  381. vector<std::string> test_vector;
  382. test_vector.push_back("one");
  383. test_vector.push_back("three");
  384. test_vector.push_back("two");
  385. Matcher<vector<std::string> > m =
  386. ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
  387. EXPECT_FALSE(m.Matches(test_vector));
  388. }
  389. TEST(ElementsAreTest, WorksForNestedContainer) {
  390. const char* strings[] = {
  391. "Hi",
  392. "world"
  393. };
  394. vector<list<char> > nested;
  395. for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
  396. nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
  397. }
  398. EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
  399. ElementsAre('w', 'o', _, _, 'd')));
  400. EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
  401. ElementsAre('w', 'o', _, _, 'd'))));
  402. }
  403. TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
  404. int a[] = { 0, 1, 2 };
  405. vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
  406. EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
  407. EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
  408. }
  409. TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
  410. int a[] = { 0, 1, 2 };
  411. vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
  412. EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
  413. EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
  414. }
  415. TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
  416. int array[] = { 0, 1, 2 };
  417. EXPECT_THAT(array, ElementsAre(0, 1, _));
  418. EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
  419. EXPECT_THAT(array, Not(ElementsAre(0, _)));
  420. }
  421. class NativeArrayPassedAsPointerAndSize {
  422. public:
  423. NativeArrayPassedAsPointerAndSize() {}
  424. MOCK_METHOD2(Helper, void(int* array, int size));
  425. private:
  426. GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
  427. };
  428. TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
  429. int array[] = { 0, 1 };
  430. ::testing::tuple<int*, size_t> array_as_tuple(array, 2);
  431. EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
  432. EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
  433. NativeArrayPassedAsPointerAndSize helper;
  434. EXPECT_CALL(helper, Helper(_, _))
  435. .With(ElementsAre(0, 1));
  436. helper.Helper(array, 2);
  437. }
  438. TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
  439. const char a2[][3] = { "hi", "lo" };
  440. EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
  441. ElementsAre('l', 'o', '\0')));
  442. EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
  443. EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
  444. ElementsAre('l', 'o', '\0')));
  445. }
  446. TEST(ElementsAreTest, AcceptsStringLiteral) {
  447. std::string array[] = {"hi", "one", "two"};
  448. EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
  449. EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
  450. }
  451. #ifndef _MSC_VER
  452. // The following test passes a value of type const char[] to a
  453. // function template that expects const T&. Some versions of MSVC
  454. // generates a compiler error C2665 for that. We believe it's a bug
  455. // in MSVC. Therefore this test is #if-ed out for MSVC.
  456. // Declared here with the size unknown. Defined AFTER the following test.
  457. extern const char kHi[];
  458. TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
  459. // The size of kHi is not known in this test, but ElementsAre() should
  460. // still accept it.
  461. std::string array1[] = {"hi"};
  462. EXPECT_THAT(array1, ElementsAre(kHi));
  463. std::string array2[] = {"ho"};
  464. EXPECT_THAT(array2, Not(ElementsAre(kHi)));
  465. }
  466. const char kHi[] = "hi";
  467. #endif // _MSC_VER
  468. TEST(ElementsAreTest, MakesCopyOfArguments) {
  469. int x = 1;
  470. int y = 2;
  471. // This should make a copy of x and y.
  472. ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> >
  473. polymorphic_matcher = ElementsAre(x, y);
  474. // Changing x and y now shouldn't affect the meaning of the above matcher.
  475. x = y = 0;
  476. const int array1[] = { 1, 2 };
  477. EXPECT_THAT(array1, polymorphic_matcher);
  478. const int array2[] = { 0, 0 };
  479. EXPECT_THAT(array2, Not(polymorphic_matcher));
  480. }
  481. // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
  482. // of the implementation with ElementsAre(), we don't test it as
  483. // thoroughly here.
  484. TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
  485. const int a[] = { 1, 2, 3 };
  486. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  487. EXPECT_THAT(test_vector, ElementsAreArray(a));
  488. test_vector[2] = 0;
  489. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  490. }
  491. TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
  492. const char* a[] = { "one", "two", "three" };
  493. vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  494. EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
  495. const char** p = a;
  496. test_vector[0] = "1";
  497. EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
  498. }
  499. TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
  500. const char* a[] = { "one", "two", "three" };
  501. vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  502. EXPECT_THAT(test_vector, ElementsAreArray(a));
  503. test_vector[0] = "1";
  504. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  505. }
  506. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
  507. const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
  508. StrEq("three")};
  509. vector<std::string> test_vector;
  510. test_vector.push_back("one");
  511. test_vector.push_back("two");
  512. test_vector.push_back("three");
  513. EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
  514. test_vector.push_back("three");
  515. EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
  516. }
  517. TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
  518. const int a[] = { 1, 2, 3 };
  519. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  520. const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
  521. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  522. test_vector.push_back(4);
  523. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  524. }
  525. #if GTEST_HAS_STD_INITIALIZER_LIST_
  526. TEST(ElementsAreArrayTest, TakesInitializerList) {
  527. const int a[5] = { 1, 2, 3, 4, 5 };
  528. EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
  529. EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
  530. EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
  531. }
  532. TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
  533. const std::string a[5] = {"a", "b", "c", "d", "e"};
  534. EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
  535. EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
  536. EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
  537. }
  538. TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  539. const int a[5] = { 1, 2, 3, 4, 5 };
  540. EXPECT_THAT(a, ElementsAreArray(
  541. { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
  542. EXPECT_THAT(a, Not(ElementsAreArray(
  543. { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
  544. }
  545. TEST(ElementsAreArrayTest,
  546. TakesInitializerListOfDifferentTypedMatchers) {
  547. const int a[5] = { 1, 2, 3, 4, 5 };
  548. // The compiler cannot infer the type of the initializer list if its
  549. // elements have different types. We must explicitly specify the
  550. // unified element type in this case.
  551. EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
  552. { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
  553. EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
  554. { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
  555. }
  556. #endif // GTEST_HAS_STD_INITIALIZER_LIST_
  557. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
  558. const int a[] = { 1, 2, 3 };
  559. const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
  560. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  561. const vector<Matcher<int> > expected(
  562. kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers));
  563. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  564. test_vector.push_back(4);
  565. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  566. }
  567. TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
  568. const int a[] = { 1, 2, 3 };
  569. const vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  570. const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
  571. EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
  572. // Pointers are iterators, too.
  573. EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a)));
  574. // The empty range of NULL pointers should also be okay.
  575. int* const null_int = NULL;
  576. EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
  577. EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
  578. }
  579. // Since ElementsAre() and ElementsAreArray() share much of the
  580. // implementation, we only do a sanity test for native arrays here.
  581. TEST(ElementsAreArrayTest, WorksWithNativeArray) {
  582. ::std::string a[] = { "hi", "ho" };
  583. ::std::string b[] = { "hi", "ho" };
  584. EXPECT_THAT(a, ElementsAreArray(b));
  585. EXPECT_THAT(a, ElementsAreArray(b, 2));
  586. EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
  587. }
  588. TEST(ElementsAreArrayTest, SourceLifeSpan) {
  589. const int a[] = { 1, 2, 3 };
  590. vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
  591. vector<int> expect(a, a + GTEST_ARRAY_SIZE_(a));
  592. ElementsAreArrayMatcher<int> matcher_maker =
  593. ElementsAreArray(expect.begin(), expect.end());
  594. EXPECT_THAT(test_vector, matcher_maker);
  595. // Changing in place the values that initialized matcher_maker should not
  596. // affect matcher_maker anymore. It should have made its own copy of them.
  597. typedef vector<int>::iterator Iter;
  598. for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
  599. EXPECT_THAT(test_vector, matcher_maker);
  600. test_vector.push_back(3);
  601. EXPECT_THAT(test_vector, Not(matcher_maker));
  602. }
  603. // Tests for the MATCHER*() macro family.
  604. // Tests that a simple MATCHER() definition works.
  605. MATCHER(IsEven, "") { return (arg % 2) == 0; }
  606. TEST(MatcherMacroTest, Works) {
  607. const Matcher<int> m = IsEven();
  608. EXPECT_TRUE(m.Matches(6));
  609. EXPECT_FALSE(m.Matches(7));
  610. EXPECT_EQ("is even", Describe(m));
  611. EXPECT_EQ("not (is even)", DescribeNegation(m));
  612. EXPECT_EQ("", Explain(m, 6));
  613. EXPECT_EQ("", Explain(m, 7));
  614. }
  615. // This also tests that the description string can reference 'negation'.
  616. MATCHER(IsEven2, negation ? "is odd" : "is even") {
  617. if ((arg % 2) == 0) {
  618. // Verifies that we can stream to result_listener, a listener
  619. // supplied by the MATCHER macro implicitly.
  620. *result_listener << "OK";
  621. return true;
  622. } else {
  623. *result_listener << "% 2 == " << (arg % 2);
  624. return false;
  625. }
  626. }
  627. // This also tests that the description string can reference matcher
  628. // parameters.
  629. MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") +
  630. " the sum of " + PrintToString(x) + " and " +
  631. PrintToString(y)) {
  632. if (arg == (x + y)) {
  633. *result_listener << "OK";
  634. return true;
  635. } else {
  636. // Verifies that we can stream to the underlying stream of
  637. // result_listener.
  638. if (result_listener->stream() != NULL) {
  639. *result_listener->stream() << "diff == " << (x + y - arg);
  640. }
  641. return false;
  642. }
  643. }
  644. // Tests that the matcher description can reference 'negation' and the
  645. // matcher parameters.
  646. TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
  647. const Matcher<int> m1 = IsEven2();
  648. EXPECT_EQ("is even", Describe(m1));
  649. EXPECT_EQ("is odd", DescribeNegation(m1));
  650. const Matcher<int> m2 = EqSumOf(5, 9);
  651. EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
  652. EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
  653. }
  654. // Tests explaining match result in a MATCHER* macro.
  655. TEST(MatcherMacroTest, CanExplainMatchResult) {
  656. const Matcher<int> m1 = IsEven2();
  657. EXPECT_EQ("OK", Explain(m1, 4));
  658. EXPECT_EQ("% 2 == 1", Explain(m1, 5));
  659. const Matcher<int> m2 = EqSumOf(1, 2);
  660. EXPECT_EQ("OK", Explain(m2, 3));
  661. EXPECT_EQ("diff == -1", Explain(m2, 4));
  662. }
  663. // Tests that the body of MATCHER() can reference the type of the
  664. // value being matched.
  665. MATCHER(IsEmptyString, "") {
  666. StaticAssertTypeEq< ::std::string, arg_type>();
  667. return arg == "";
  668. }
  669. MATCHER(IsEmptyStringByRef, "") {
  670. StaticAssertTypeEq<const ::std::string&, arg_type>();
  671. return arg == "";
  672. }
  673. TEST(MatcherMacroTest, CanReferenceArgType) {
  674. const Matcher< ::std::string> m1 = IsEmptyString();
  675. EXPECT_TRUE(m1.Matches(""));
  676. const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
  677. EXPECT_TRUE(m2.Matches(""));
  678. }
  679. // Tests that MATCHER() can be used in a namespace.
  680. namespace matcher_test {
  681. MATCHER(IsOdd, "") { return (arg % 2) != 0; }
  682. } // namespace matcher_test
  683. TEST(MatcherMacroTest, WorksInNamespace) {
  684. Matcher<int> m = matcher_test::IsOdd();
  685. EXPECT_FALSE(m.Matches(4));
  686. EXPECT_TRUE(m.Matches(5));
  687. }
  688. // Tests that Value() can be used to compose matchers.
  689. MATCHER(IsPositiveOdd, "") {
  690. return Value(arg, matcher_test::IsOdd()) && arg > 0;
  691. }
  692. TEST(MatcherMacroTest, CanBeComposedUsingValue) {
  693. EXPECT_THAT(3, IsPositiveOdd());
  694. EXPECT_THAT(4, Not(IsPositiveOdd()));
  695. EXPECT_THAT(-1, Not(IsPositiveOdd()));
  696. }
  697. // Tests that a simple MATCHER_P() definition works.
  698. MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
  699. TEST(MatcherPMacroTest, Works) {
  700. const Matcher<int> m = IsGreaterThan32And(5);
  701. EXPECT_TRUE(m.Matches(36));
  702. EXPECT_FALSE(m.Matches(5));
  703. EXPECT_EQ("is greater than 32 and 5", Describe(m));
  704. EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
  705. EXPECT_EQ("", Explain(m, 36));
  706. EXPECT_EQ("", Explain(m, 5));
  707. }
  708. // Tests that the description is calculated correctly from the matcher name.
  709. MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
  710. TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
  711. const Matcher<int> m = _is_Greater_Than32and_(5);
  712. EXPECT_EQ("is greater than 32 and 5", Describe(m));
  713. EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
  714. EXPECT_EQ("", Explain(m, 36));
  715. EXPECT_EQ("", Explain(m, 5));
  716. }
  717. // Tests that a MATCHER_P matcher can be explicitly instantiated with
  718. // a reference parameter type.
  719. class UncopyableFoo {
  720. public:
  721. explicit UncopyableFoo(char value) : value_(value) {}
  722. private:
  723. UncopyableFoo(const UncopyableFoo&);
  724. void operator=(const UncopyableFoo&);
  725. char value_;
  726. };
  727. MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
  728. TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
  729. UncopyableFoo foo1('1'), foo2('2');
  730. const Matcher<const UncopyableFoo&> m =
  731. ReferencesUncopyable<const UncopyableFoo&>(foo1);
  732. EXPECT_TRUE(m.Matches(foo1));
  733. EXPECT_FALSE(m.Matches(foo2));
  734. // We don't want the address of the parameter printed, as most
  735. // likely it will just annoy the user. If the address is
  736. // interesting, the user should consider passing the parameter by
  737. // pointer instead.
  738. EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
  739. }
  740. // Tests that the body of MATCHER_Pn() can reference the parameter
  741. // types.
  742. MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
  743. StaticAssertTypeEq<int, foo_type>();
  744. StaticAssertTypeEq<long, bar_type>(); // NOLINT
  745. StaticAssertTypeEq<char, baz_type>();
  746. return arg == 0;
  747. }
  748. TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
  749. EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
  750. }
  751. // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
  752. // reference parameter types.
  753. MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
  754. return &arg == &variable1 || &arg == &variable2;
  755. }
  756. TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
  757. UncopyableFoo foo1('1'), foo2('2'), foo3('3');
  758. const Matcher<const UncopyableFoo&> m =
  759. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  760. EXPECT_TRUE(m.Matches(foo1));
  761. EXPECT_TRUE(m.Matches(foo2));
  762. EXPECT_FALSE(m.Matches(foo3));
  763. }
  764. TEST(MatcherPnMacroTest,
  765. GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
  766. UncopyableFoo foo1('1'), foo2('2');
  767. const Matcher<const UncopyableFoo&> m =
  768. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  769. // We don't want the addresses of the parameters printed, as most
  770. // likely they will just annoy the user. If the addresses are
  771. // interesting, the user should consider passing the parameters by
  772. // pointers instead.
  773. EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
  774. Describe(m));
  775. }
  776. // Tests that a simple MATCHER_P2() definition works.
  777. MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
  778. TEST(MatcherPnMacroTest, Works) {
  779. const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
  780. EXPECT_TRUE(m.Matches(36L));
  781. EXPECT_FALSE(m.Matches(15L));
  782. EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
  783. EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
  784. EXPECT_EQ("", Explain(m, 36L));
  785. EXPECT_EQ("", Explain(m, 15L));
  786. }
  787. // Tests that MATCHER*() definitions can be overloaded on the number
  788. // of parameters; also tests MATCHER_Pn() where n >= 3.
  789. MATCHER(EqualsSumOf, "") { return arg == 0; }
  790. MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
  791. MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
  792. MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
  793. MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
  794. MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
  795. MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
  796. return arg == a + b + c + d + e + f;
  797. }
  798. MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
  799. return arg == a + b + c + d + e + f + g;
  800. }
  801. MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
  802. return arg == a + b + c + d + e + f + g + h;
  803. }
  804. MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
  805. return arg == a + b + c + d + e + f + g + h + i;
  806. }
  807. MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
  808. return arg == a + b + c + d + e + f + g + h + i + j;
  809. }
  810. TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
  811. EXPECT_THAT(0, EqualsSumOf());
  812. EXPECT_THAT(1, EqualsSumOf(1));
  813. EXPECT_THAT(12, EqualsSumOf(10, 2));
  814. EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
  815. EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
  816. EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
  817. EXPECT_THAT("abcdef",
  818. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
  819. EXPECT_THAT("abcdefg",
  820. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
  821. EXPECT_THAT("abcdefgh",
  822. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  823. "h"));
  824. EXPECT_THAT("abcdefghi",
  825. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  826. "h", 'i'));
  827. EXPECT_THAT("abcdefghij",
  828. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  829. "h", 'i', ::std::string("j")));
  830. EXPECT_THAT(1, Not(EqualsSumOf()));
  831. EXPECT_THAT(-1, Not(EqualsSumOf(1)));
  832. EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
  833. EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
  834. EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
  835. EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
  836. EXPECT_THAT("abcdef ",
  837. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
  838. EXPECT_THAT("abcdefg ",
  839. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
  840. 'g')));
  841. EXPECT_THAT("abcdefgh ",
  842. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  843. "h")));
  844. EXPECT_THAT("abcdefghi ",
  845. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  846. "h", 'i')));
  847. EXPECT_THAT("abcdefghij ",
  848. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  849. "h", 'i', ::std::string("j"))));
  850. }
  851. // Tests that a MATCHER_Pn() definition can be instantiated with any
  852. // compatible parameter types.
  853. TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
  854. EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
  855. EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
  856. EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
  857. EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
  858. }
  859. // Tests that the matcher body can promote the parameter types.
  860. MATCHER_P2(EqConcat, prefix, suffix, "") {
  861. // The following lines promote the two parameters to desired types.
  862. std::string prefix_str(prefix);
  863. char suffix_char = static_cast<char>(suffix);
  864. return arg == prefix_str + suffix_char;
  865. }
  866. TEST(MatcherPnMacroTest, SimpleTypePromotion) {
  867. Matcher<std::string> no_promo =
  868. EqConcat(std::string("foo"), 't');
  869. Matcher<const std::string&> promo =
  870. EqConcat("foo", static_cast<int>('t'));
  871. EXPECT_FALSE(no_promo.Matches("fool"));
  872. EXPECT_FALSE(promo.Matches("fool"));
  873. EXPECT_TRUE(no_promo.Matches("foot"));
  874. EXPECT_TRUE(promo.Matches("foot"));
  875. }
  876. // Verifies the type of a MATCHER*.
  877. TEST(MatcherPnMacroTest, TypesAreCorrect) {
  878. // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
  879. EqualsSumOfMatcher a0 = EqualsSumOf();
  880. // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
  881. EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
  882. // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
  883. // variable, and so on.
  884. EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
  885. EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
  886. EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
  887. EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
  888. EqualsSumOf(1, 2, 3, 4, '5');
  889. EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
  890. EqualsSumOf(1, 2, 3, 4, 5, '6');
  891. EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
  892. EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
  893. EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
  894. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
  895. EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
  896. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
  897. EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
  898. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
  899. // Avoid "unused variable" warnings.
  900. (void)a0;
  901. (void)a1;
  902. (void)a2;
  903. (void)a3;
  904. (void)a4;
  905. (void)a5;
  906. (void)a6;
  907. (void)a7;
  908. (void)a8;
  909. (void)a9;
  910. (void)a10;
  911. }
  912. // Tests that matcher-typed parameters can be used in Value() inside a
  913. // MATCHER_Pn definition.
  914. // Succeeds if arg matches exactly 2 of the 3 matchers.
  915. MATCHER_P3(TwoOf, m1, m2, m3, "") {
  916. const int count = static_cast<int>(Value(arg, m1))
  917. + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
  918. return count == 2;
  919. }
  920. TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
  921. EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
  922. EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
  923. }
  924. // Tests Contains().
  925. TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
  926. list<int> some_list;
  927. some_list.push_back(3);
  928. some_list.push_back(1);
  929. some_list.push_back(2);
  930. EXPECT_THAT(some_list, Contains(1));
  931. EXPECT_THAT(some_list, Contains(Gt(2.5)));
  932. EXPECT_THAT(some_list, Contains(Eq(2.0f)));
  933. list<std::string> another_list;
  934. another_list.push_back("fee");
  935. another_list.push_back("fie");
  936. another_list.push_back("foe");
  937. another_list.push_back("fum");
  938. EXPECT_THAT(another_list, Contains(std::string("fee")));
  939. }
  940. TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
  941. list<int> some_list;
  942. some_list.push_back(3);
  943. some_list.push_back(1);
  944. EXPECT_THAT(some_list, Not(Contains(4)));
  945. }
  946. TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
  947. set<int> some_set;
  948. some_set.insert(3);
  949. some_set.insert(1);
  950. some_set.insert(2);
  951. EXPECT_THAT(some_set, Contains(Eq(1.0)));
  952. EXPECT_THAT(some_set, Contains(Eq(3.0f)));
  953. EXPECT_THAT(some_set, Contains(2));
  954. set<const char*> another_set;
  955. another_set.insert("fee");
  956. another_set.insert("fie");
  957. another_set.insert("foe");
  958. another_set.insert("fum");
  959. EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
  960. }
  961. TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
  962. set<int> some_set;
  963. some_set.insert(3);
  964. some_set.insert(1);
  965. EXPECT_THAT(some_set, Not(Contains(4)));
  966. set<const char*> c_string_set;
  967. c_string_set.insert("hello");
  968. EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str())));
  969. }
  970. TEST(ContainsTest, ExplainsMatchResultCorrectly) {
  971. const int a[2] = { 1, 2 };
  972. Matcher<const int (&)[2]> m = Contains(2);
  973. EXPECT_EQ("whose element #1 matches", Explain(m, a));
  974. m = Contains(3);
  975. EXPECT_EQ("", Explain(m, a));
  976. m = Contains(GreaterThan(0));
  977. EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
  978. m = Contains(GreaterThan(10));
  979. EXPECT_EQ("", Explain(m, a));
  980. }
  981. TEST(ContainsTest, DescribesItselfCorrectly) {
  982. Matcher<vector<int> > m = Contains(1);
  983. EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
  984. Matcher<vector<int> > m2 = Not(m);
  985. EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
  986. }
  987. TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
  988. map<const char*, int> my_map;
  989. const char* bar = "a string";
  990. my_map[bar] = 2;
  991. EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
  992. map<std::string, int> another_map;
  993. another_map["fee"] = 1;
  994. another_map["fie"] = 2;
  995. another_map["foe"] = 3;
  996. another_map["fum"] = 4;
  997. EXPECT_THAT(another_map,
  998. Contains(pair<const std::string, int>(std::string("fee"), 1)));
  999. EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
  1000. }
  1001. TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
  1002. map<int, int> some_map;
  1003. some_map[1] = 11;
  1004. some_map[2] = 22;
  1005. EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
  1006. }
  1007. TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
  1008. const char* string_array[] = { "fee", "fie", "foe", "fum" };
  1009. EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
  1010. }
  1011. TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
  1012. int int_array[] = { 1, 2, 3, 4 };
  1013. EXPECT_THAT(int_array, Not(Contains(5)));
  1014. }
  1015. TEST(ContainsTest, AcceptsMatcher) {
  1016. const int a[] = { 1, 2, 3 };
  1017. EXPECT_THAT(a, Contains(Gt(2)));
  1018. EXPECT_THAT(a, Not(Contains(Gt(4))));
  1019. }
  1020. TEST(ContainsTest, WorksForNativeArrayAsTuple) {
  1021. const int a[] = { 1, 2 };
  1022. const int* const pointer = a;
  1023. EXPECT_THAT(make_tuple(pointer, 2), Contains(1));
  1024. EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3))));
  1025. }
  1026. TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
  1027. int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
  1028. EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
  1029. EXPECT_THAT(a, Contains(Contains(5)));
  1030. EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
  1031. EXPECT_THAT(a, Contains(Not(Contains(5))));
  1032. }
  1033. TEST(AllOfTest, HugeMatcher) {
  1034. // Verify that using AllOf with many arguments doesn't cause
  1035. // the compiler to exceed template instantiation depth limit.
  1036. EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
  1037. testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
  1038. }
  1039. TEST(AnyOfTest, HugeMatcher) {
  1040. // Verify that using AnyOf with many arguments doesn't cause
  1041. // the compiler to exceed template instantiation depth limit.
  1042. EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
  1043. testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
  1044. }
  1045. namespace adl_test {
  1046. // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
  1047. // don't issue unqualified recursive calls. If they do, the argument dependent
  1048. // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
  1049. // as a candidate and the compilation will break due to an ambiguous overload.
  1050. // The matcher must be in the same namespace as AllOf/AnyOf to make argument
  1051. // dependent lookup find those.
  1052. MATCHER(M, "") { return true; }
  1053. template <typename T1, typename T2>
  1054. bool AllOf(const T1& t1, const T2& t2) { return true; }
  1055. TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
  1056. EXPECT_THAT(42, testing::AllOf(
  1057. M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
  1058. }
  1059. template <typename T1, typename T2> bool
  1060. AnyOf(const T1& t1, const T2& t2) { return true; }
  1061. TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
  1062. EXPECT_THAT(42, testing::AnyOf(
  1063. M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
  1064. }
  1065. } // namespace adl_test
  1066. #ifdef _MSC_VER
  1067. # pragma warning(pop)
  1068. #endif
  1069. #if GTEST_LANG_CXX11
  1070. TEST(AllOfTest, WorksOnMoveOnlyType) {
  1071. std::unique_ptr<int> p(new int(3));
  1072. EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
  1073. EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
  1074. }
  1075. TEST(AnyOfTest, WorksOnMoveOnlyType) {
  1076. std::unique_ptr<int> p(new int(3));
  1077. EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
  1078. EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
  1079. }
  1080. MATCHER(IsNotNull, "") {
  1081. return arg != nullptr;
  1082. }
  1083. // Verifies that a matcher defined using MATCHER() can work on
  1084. // move-only types.
  1085. TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
  1086. std::unique_ptr<int> p(new int(3));
  1087. EXPECT_THAT(p, IsNotNull());
  1088. EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
  1089. }
  1090. MATCHER_P(UniquePointee, pointee, "") {
  1091. return *arg == pointee;
  1092. }
  1093. // Verifies that a matcher defined using MATCHER_P*() can work on
  1094. // move-only types.
  1095. TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
  1096. std::unique_ptr<int> p(new int(3));
  1097. EXPECT_THAT(p, UniquePointee(3));
  1098. EXPECT_THAT(p, Not(UniquePointee(2)));
  1099. }
  1100. #endif // GTEST_LASNG_CXX11
  1101. } // namespace
  1102. #ifdef _MSC_VER
  1103. # pragma warning(pop)
  1104. #endif