gmock-generated-matchers_test.cc 41 KB

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