gmock-matchers-misc_test.cc 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file tests some commonly used argument matchers.
  32. #include <array>
  33. #include <memory>
  34. #include <ostream>
  35. #include <string>
  36. #include <tuple>
  37. #include <utility>
  38. #include <vector>
  39. #include "gtest/gtest.h"
  40. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  41. // possible loss of data and C4100, unreferenced local parameter
  42. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
  43. #include "test/gmock-matchers_test.h"
  44. namespace testing {
  45. namespace gmock_matchers_test {
  46. namespace {
  47. TEST(AddressTest, NonConst) {
  48. int n = 1;
  49. const Matcher<int> m = Address(Eq(&n));
  50. EXPECT_TRUE(m.Matches(n));
  51. int other = 5;
  52. EXPECT_FALSE(m.Matches(other));
  53. int& n_ref = n;
  54. EXPECT_TRUE(m.Matches(n_ref));
  55. }
  56. TEST(AddressTest, Const) {
  57. const int n = 1;
  58. const Matcher<int> m = Address(Eq(&n));
  59. EXPECT_TRUE(m.Matches(n));
  60. int other = 5;
  61. EXPECT_FALSE(m.Matches(other));
  62. }
  63. TEST(AddressTest, MatcherDoesntCopy) {
  64. std::unique_ptr<int> n(new int(1));
  65. const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
  66. EXPECT_TRUE(m.Matches(n));
  67. }
  68. TEST(AddressTest, Describe) {
  69. Matcher<int> matcher = Address(_);
  70. EXPECT_EQ("has address that is anything", Describe(matcher));
  71. EXPECT_EQ("does not have address that is anything",
  72. DescribeNegation(matcher));
  73. }
  74. // The following two tests verify that values without a public copy
  75. // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
  76. // with the help of ByRef().
  77. class NotCopyable {
  78. public:
  79. explicit NotCopyable(int a_value) : value_(a_value) {}
  80. int value() const { return value_; }
  81. bool operator==(const NotCopyable& rhs) const {
  82. return value() == rhs.value();
  83. }
  84. bool operator>=(const NotCopyable& rhs) const {
  85. return value() >= rhs.value();
  86. }
  87. private:
  88. int value_;
  89. NotCopyable(const NotCopyable&) = delete;
  90. NotCopyable& operator=(const NotCopyable&) = delete;
  91. };
  92. TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
  93. const NotCopyable const_value1(1);
  94. const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
  95. const NotCopyable n1(1), n2(2);
  96. EXPECT_TRUE(m.Matches(n1));
  97. EXPECT_FALSE(m.Matches(n2));
  98. }
  99. TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
  100. NotCopyable value2(2);
  101. const Matcher<NotCopyable&> m = Ge(ByRef(value2));
  102. NotCopyable n1(1), n2(2);
  103. EXPECT_FALSE(m.Matches(n1));
  104. EXPECT_TRUE(m.Matches(n2));
  105. }
  106. TEST(IsEmptyTest, ImplementsIsEmpty) {
  107. vector<int> container;
  108. EXPECT_THAT(container, IsEmpty());
  109. container.push_back(0);
  110. EXPECT_THAT(container, Not(IsEmpty()));
  111. container.push_back(1);
  112. EXPECT_THAT(container, Not(IsEmpty()));
  113. }
  114. TEST(IsEmptyTest, WorksWithString) {
  115. std::string text;
  116. EXPECT_THAT(text, IsEmpty());
  117. text = "foo";
  118. EXPECT_THAT(text, Not(IsEmpty()));
  119. text = std::string("\0", 1);
  120. EXPECT_THAT(text, Not(IsEmpty()));
  121. }
  122. TEST(IsEmptyTest, CanDescribeSelf) {
  123. Matcher<vector<int>> m = IsEmpty();
  124. EXPECT_EQ("is empty", Describe(m));
  125. EXPECT_EQ("isn't empty", DescribeNegation(m));
  126. }
  127. TEST(IsEmptyTest, ExplainsResult) {
  128. Matcher<vector<int>> m = IsEmpty();
  129. vector<int> container;
  130. EXPECT_EQ("", Explain(m, container));
  131. container.push_back(0);
  132. EXPECT_EQ("whose size is 1", Explain(m, container));
  133. }
  134. TEST(IsEmptyTest, WorksWithMoveOnly) {
  135. ContainerHelper helper;
  136. EXPECT_CALL(helper, Call(IsEmpty()));
  137. helper.Call({});
  138. }
  139. TEST(IsTrueTest, IsTrueIsFalse) {
  140. EXPECT_THAT(true, IsTrue());
  141. EXPECT_THAT(false, IsFalse());
  142. EXPECT_THAT(true, Not(IsFalse()));
  143. EXPECT_THAT(false, Not(IsTrue()));
  144. EXPECT_THAT(0, Not(IsTrue()));
  145. EXPECT_THAT(0, IsFalse());
  146. EXPECT_THAT(nullptr, Not(IsTrue()));
  147. EXPECT_THAT(nullptr, IsFalse());
  148. EXPECT_THAT(-1, IsTrue());
  149. EXPECT_THAT(-1, Not(IsFalse()));
  150. EXPECT_THAT(1, IsTrue());
  151. EXPECT_THAT(1, Not(IsFalse()));
  152. EXPECT_THAT(2, IsTrue());
  153. EXPECT_THAT(2, Not(IsFalse()));
  154. int a = 42;
  155. EXPECT_THAT(a, IsTrue());
  156. EXPECT_THAT(a, Not(IsFalse()));
  157. EXPECT_THAT(&a, IsTrue());
  158. EXPECT_THAT(&a, Not(IsFalse()));
  159. EXPECT_THAT(false, Not(IsTrue()));
  160. EXPECT_THAT(true, Not(IsFalse()));
  161. EXPECT_THAT(std::true_type(), IsTrue());
  162. EXPECT_THAT(std::true_type(), Not(IsFalse()));
  163. EXPECT_THAT(std::false_type(), IsFalse());
  164. EXPECT_THAT(std::false_type(), Not(IsTrue()));
  165. EXPECT_THAT(nullptr, Not(IsTrue()));
  166. EXPECT_THAT(nullptr, IsFalse());
  167. std::unique_ptr<int> null_unique;
  168. std::unique_ptr<int> nonnull_unique(new int(0));
  169. EXPECT_THAT(null_unique, Not(IsTrue()));
  170. EXPECT_THAT(null_unique, IsFalse());
  171. EXPECT_THAT(nonnull_unique, IsTrue());
  172. EXPECT_THAT(nonnull_unique, Not(IsFalse()));
  173. }
  174. #ifdef GTEST_HAS_TYPED_TEST
  175. // Tests ContainerEq with different container types, and
  176. // different element types.
  177. template <typename T>
  178. class ContainerEqTest : public testing::Test {};
  179. typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>>
  180. ContainerEqTestTypes;
  181. TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
  182. // Tests that the filled container is equal to itself.
  183. TYPED_TEST(ContainerEqTest, EqualsSelf) {
  184. static const int vals[] = {1, 1, 2, 3, 5, 8};
  185. TypeParam my_set(vals, vals + 6);
  186. const Matcher<TypeParam> m = ContainerEq(my_set);
  187. EXPECT_TRUE(m.Matches(my_set));
  188. EXPECT_EQ("", Explain(m, my_set));
  189. }
  190. // Tests that missing values are reported.
  191. TYPED_TEST(ContainerEqTest, ValueMissing) {
  192. static const int vals[] = {1, 1, 2, 3, 5, 8};
  193. static const int test_vals[] = {2, 1, 8, 5};
  194. TypeParam my_set(vals, vals + 6);
  195. TypeParam test_set(test_vals, test_vals + 4);
  196. const Matcher<TypeParam> m = ContainerEq(my_set);
  197. EXPECT_FALSE(m.Matches(test_set));
  198. EXPECT_EQ("which doesn't have these expected elements: 3",
  199. Explain(m, test_set));
  200. }
  201. // Tests that added values are reported.
  202. TYPED_TEST(ContainerEqTest, ValueAdded) {
  203. static const int vals[] = {1, 1, 2, 3, 5, 8};
  204. static const int test_vals[] = {1, 2, 3, 5, 8, 46};
  205. TypeParam my_set(vals, vals + 6);
  206. TypeParam test_set(test_vals, test_vals + 6);
  207. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  208. EXPECT_FALSE(m.Matches(test_set));
  209. EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
  210. }
  211. // Tests that added and missing values are reported together.
  212. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
  213. static const int vals[] = {1, 1, 2, 3, 5, 8};
  214. static const int test_vals[] = {1, 2, 3, 8, 46};
  215. TypeParam my_set(vals, vals + 6);
  216. TypeParam test_set(test_vals, test_vals + 5);
  217. const Matcher<TypeParam> m = ContainerEq(my_set);
  218. EXPECT_FALSE(m.Matches(test_set));
  219. EXPECT_EQ(
  220. "which has these unexpected elements: 46,\n"
  221. "and doesn't have these expected elements: 5",
  222. Explain(m, test_set));
  223. }
  224. // Tests duplicated value -- expect no explanation.
  225. TYPED_TEST(ContainerEqTest, DuplicateDifference) {
  226. static const int vals[] = {1, 1, 2, 3, 5, 8};
  227. static const int test_vals[] = {1, 2, 3, 5, 8};
  228. TypeParam my_set(vals, vals + 6);
  229. TypeParam test_set(test_vals, test_vals + 5);
  230. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  231. // Depending on the container, match may be true or false
  232. // But in any case there should be no explanation.
  233. EXPECT_EQ("", Explain(m, test_set));
  234. }
  235. #endif // GTEST_HAS_TYPED_TEST
  236. // Tests that multiple missing values are reported.
  237. // Using just vector here, so order is predictable.
  238. TEST(ContainerEqExtraTest, MultipleValuesMissing) {
  239. static const int vals[] = {1, 1, 2, 3, 5, 8};
  240. static const int test_vals[] = {2, 1, 5};
  241. vector<int> my_set(vals, vals + 6);
  242. vector<int> test_set(test_vals, test_vals + 3);
  243. const Matcher<vector<int>> m = ContainerEq(my_set);
  244. EXPECT_FALSE(m.Matches(test_set));
  245. EXPECT_EQ("which doesn't have these expected elements: 3, 8",
  246. Explain(m, test_set));
  247. }
  248. // Tests that added values are reported.
  249. // Using just vector here, so order is predictable.
  250. TEST(ContainerEqExtraTest, MultipleValuesAdded) {
  251. static const int vals[] = {1, 1, 2, 3, 5, 8};
  252. static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
  253. list<size_t> my_set(vals, vals + 6);
  254. list<size_t> test_set(test_vals, test_vals + 7);
  255. const Matcher<const list<size_t>&> m = ContainerEq(my_set);
  256. EXPECT_FALSE(m.Matches(test_set));
  257. EXPECT_EQ("which has these unexpected elements: 92, 46",
  258. Explain(m, test_set));
  259. }
  260. // Tests that added and missing values are reported together.
  261. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
  262. static const int vals[] = {1, 1, 2, 3, 5, 8};
  263. static const int test_vals[] = {1, 2, 3, 92, 46};
  264. list<size_t> my_set(vals, vals + 6);
  265. list<size_t> test_set(test_vals, test_vals + 5);
  266. const Matcher<const list<size_t>> m = ContainerEq(my_set);
  267. EXPECT_FALSE(m.Matches(test_set));
  268. EXPECT_EQ(
  269. "which has these unexpected elements: 92, 46,\n"
  270. "and doesn't have these expected elements: 5, 8",
  271. Explain(m, test_set));
  272. }
  273. // Tests to see that duplicate elements are detected,
  274. // but (as above) not reported in the explanation.
  275. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
  276. static const int vals[] = {1, 1, 2, 3, 5, 8};
  277. static const int test_vals[] = {1, 2, 3, 5, 8};
  278. vector<int> my_set(vals, vals + 6);
  279. vector<int> test_set(test_vals, test_vals + 5);
  280. const Matcher<vector<int>> m = ContainerEq(my_set);
  281. EXPECT_TRUE(m.Matches(my_set));
  282. EXPECT_FALSE(m.Matches(test_set));
  283. // There is nothing to report when both sets contain all the same values.
  284. EXPECT_EQ("", Explain(m, test_set));
  285. }
  286. // Tests that ContainerEq works for non-trivial associative containers,
  287. // like maps.
  288. TEST(ContainerEqExtraTest, WorksForMaps) {
  289. map<int, std::string> my_map;
  290. my_map[0] = "a";
  291. my_map[1] = "b";
  292. map<int, std::string> test_map;
  293. test_map[0] = "aa";
  294. test_map[1] = "b";
  295. const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
  296. EXPECT_TRUE(m.Matches(my_map));
  297. EXPECT_FALSE(m.Matches(test_map));
  298. EXPECT_EQ(
  299. "which has these unexpected elements: (0, \"aa\"),\n"
  300. "and doesn't have these expected elements: (0, \"a\")",
  301. Explain(m, test_map));
  302. }
  303. TEST(ContainerEqExtraTest, WorksForNativeArray) {
  304. int a1[] = {1, 2, 3};
  305. int a2[] = {1, 2, 3};
  306. int b[] = {1, 2, 4};
  307. EXPECT_THAT(a1, ContainerEq(a2));
  308. EXPECT_THAT(a1, Not(ContainerEq(b)));
  309. }
  310. TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
  311. const char a1[][3] = {"hi", "lo"};
  312. const char a2[][3] = {"hi", "lo"};
  313. const char b[][3] = {"lo", "hi"};
  314. // Tests using ContainerEq() in the first dimension.
  315. EXPECT_THAT(a1, ContainerEq(a2));
  316. EXPECT_THAT(a1, Not(ContainerEq(b)));
  317. // Tests using ContainerEq() in the second dimension.
  318. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
  319. EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
  320. }
  321. TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
  322. const int a1[] = {1, 2, 3};
  323. const int a2[] = {1, 2, 3};
  324. const int b[] = {1, 2, 3, 4};
  325. const int* const p1 = a1;
  326. EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
  327. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
  328. const int c[] = {1, 3, 2};
  329. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
  330. }
  331. TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
  332. std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};
  333. std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};
  334. const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
  335. EXPECT_THAT(a1, m);
  336. a2[0][0] = "ha";
  337. EXPECT_THAT(a1, m);
  338. }
  339. namespace {
  340. // Used as a check on the more complex max flow method used in the
  341. // real testing::internal::FindMaxBipartiteMatching. This method is
  342. // compatible but runs in worst-case factorial time, so we only
  343. // use it in testing for small problem sizes.
  344. template <typename Graph>
  345. class BacktrackingMaxBPMState {
  346. public:
  347. // Does not take ownership of 'g'.
  348. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {}
  349. ElementMatcherPairs Compute() {
  350. if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
  351. return best_so_far_;
  352. }
  353. lhs_used_.assign(graph_->LhsSize(), kUnused);
  354. rhs_used_.assign(graph_->RhsSize(), kUnused);
  355. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  356. matches_.clear();
  357. RecurseInto(irhs);
  358. if (best_so_far_.size() == graph_->RhsSize()) break;
  359. }
  360. return best_so_far_;
  361. }
  362. private:
  363. static const size_t kUnused = static_cast<size_t>(-1);
  364. void PushMatch(size_t lhs, size_t rhs) {
  365. matches_.push_back(ElementMatcherPair(lhs, rhs));
  366. lhs_used_[lhs] = rhs;
  367. rhs_used_[rhs] = lhs;
  368. if (matches_.size() > best_so_far_.size()) {
  369. best_so_far_ = matches_;
  370. }
  371. }
  372. void PopMatch() {
  373. const ElementMatcherPair& back = matches_.back();
  374. lhs_used_[back.first] = kUnused;
  375. rhs_used_[back.second] = kUnused;
  376. matches_.pop_back();
  377. }
  378. bool RecurseInto(size_t irhs) {
  379. if (rhs_used_[irhs] != kUnused) {
  380. return true;
  381. }
  382. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  383. if (lhs_used_[ilhs] != kUnused) {
  384. continue;
  385. }
  386. if (!graph_->HasEdge(ilhs, irhs)) {
  387. continue;
  388. }
  389. PushMatch(ilhs, irhs);
  390. if (best_so_far_.size() == graph_->RhsSize()) {
  391. return false;
  392. }
  393. for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
  394. if (!RecurseInto(mi)) return false;
  395. }
  396. PopMatch();
  397. }
  398. return true;
  399. }
  400. const Graph* graph_; // not owned
  401. std::vector<size_t> lhs_used_;
  402. std::vector<size_t> rhs_used_;
  403. ElementMatcherPairs matches_;
  404. ElementMatcherPairs best_so_far_;
  405. };
  406. template <typename Graph>
  407. const size_t BacktrackingMaxBPMState<Graph>::kUnused;
  408. } // namespace
  409. // Implement a simple backtracking algorithm to determine if it is possible
  410. // to find one element per matcher, without reusing elements.
  411. template <typename Graph>
  412. ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) {
  413. return BacktrackingMaxBPMState<Graph>(&g).Compute();
  414. }
  415. class BacktrackingBPMTest : public ::testing::Test {};
  416. // Tests the MaxBipartiteMatching algorithm with square matrices.
  417. // The single int param is the # of nodes on each of the left and right sides.
  418. class BipartiteTest : public ::testing::TestWithParam<size_t> {};
  419. // Verify all match graphs up to some moderate number of edges.
  420. TEST_P(BipartiteTest, Exhaustive) {
  421. size_t nodes = GetParam();
  422. MatchMatrix graph(nodes, nodes);
  423. do {
  424. ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph);
  425. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
  426. << "graph: " << graph.DebugString();
  427. // Check that all elements of matches are in the graph.
  428. // Check that elements of first and second are unique.
  429. std::vector<bool> seen_element(graph.LhsSize());
  430. std::vector<bool> seen_matcher(graph.RhsSize());
  431. SCOPED_TRACE(PrintToString(matches));
  432. for (size_t i = 0; i < matches.size(); ++i) {
  433. size_t ilhs = matches[i].first;
  434. size_t irhs = matches[i].second;
  435. EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
  436. EXPECT_FALSE(seen_element[ilhs]);
  437. EXPECT_FALSE(seen_matcher[irhs]);
  438. seen_element[ilhs] = true;
  439. seen_matcher[irhs] = true;
  440. }
  441. } while (graph.NextGraph());
  442. }
  443. INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
  444. ::testing::Range(size_t{0}, size_t{5}));
  445. // Parameterized by a pair interpreted as (LhsSize, RhsSize).
  446. class BipartiteNonSquareTest
  447. : public ::testing::TestWithParam<std::pair<size_t, size_t>> {};
  448. TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
  449. // .......
  450. // 0:-----\ :
  451. // 1:---\ | :
  452. // 2:---\ | :
  453. // 3:-\ | | :
  454. // :.......:
  455. // 0 1 2
  456. MatchMatrix g(4, 3);
  457. constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
  458. {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
  459. for (size_t i = 0; i < kEdges.size(); ++i) {
  460. g.SetEdge(kEdges[i][0], kEdges[i][1], true);
  461. }
  462. EXPECT_THAT(FindBacktrackingMaxBPM(g),
  463. ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2)))
  464. << g.DebugString();
  465. }
  466. // Verify a few nonsquare matrices.
  467. TEST_P(BipartiteNonSquareTest, Exhaustive) {
  468. size_t nlhs = GetParam().first;
  469. size_t nrhs = GetParam().second;
  470. MatchMatrix graph(nlhs, nrhs);
  471. do {
  472. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  473. internal::FindMaxBipartiteMatching(graph).size())
  474. << "graph: " << graph.DebugString()
  475. << "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph))
  476. << "\nmax flow: "
  477. << PrintToString(internal::FindMaxBipartiteMatching(graph));
  478. } while (graph.NextGraph());
  479. }
  480. INSTANTIATE_TEST_SUITE_P(
  481. AllGraphs, BipartiteNonSquareTest,
  482. testing::Values(std::make_pair(1, 2), std::make_pair(2, 1),
  483. std::make_pair(3, 2), std::make_pair(2, 3),
  484. std::make_pair(4, 1), std::make_pair(1, 4),
  485. std::make_pair(4, 3), std::make_pair(3, 4)));
  486. class BipartiteRandomTest
  487. : public ::testing::TestWithParam<std::pair<int, int>> {};
  488. // Verifies a large sample of larger graphs.
  489. TEST_P(BipartiteRandomTest, LargerNets) {
  490. int nodes = GetParam().first;
  491. int iters = GetParam().second;
  492. MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
  493. auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));
  494. if (seed == 0) {
  495. seed = static_cast<uint32_t>(time(nullptr));
  496. }
  497. for (; iters > 0; --iters, ++seed) {
  498. srand(static_cast<unsigned int>(seed));
  499. graph.Randomize();
  500. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  501. internal::FindMaxBipartiteMatching(graph).size())
  502. << " graph: " << graph.DebugString()
  503. << "\nTo reproduce the failure, rerun the test with the flag"
  504. " --"
  505. << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
  506. }
  507. }
  508. // Test argument is a std::pair<int, int> representing (nodes, iters).
  509. INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
  510. testing::Values(std::make_pair(5, 10000),
  511. std::make_pair(6, 5000),
  512. std::make_pair(7, 2000),
  513. std::make_pair(8, 500),
  514. std::make_pair(9, 100)));
  515. // Tests IsReadableTypeName().
  516. TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
  517. EXPECT_TRUE(IsReadableTypeName("int"));
  518. EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
  519. EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
  520. EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
  521. }
  522. TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
  523. EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
  524. EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
  525. EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
  526. }
  527. TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
  528. EXPECT_FALSE(
  529. IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
  530. EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
  531. }
  532. TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
  533. EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
  534. }
  535. // Tests FormatMatcherDescription().
  536. TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
  537. EXPECT_EQ("is even",
  538. FormatMatcherDescription(false, "IsEven", {}, Strings()));
  539. EXPECT_EQ("not (is even)",
  540. FormatMatcherDescription(true, "IsEven", {}, Strings()));
  541. EXPECT_EQ("equals (a: 5)",
  542. FormatMatcherDescription(false, "Equals", {"a"}, {"5"}));
  543. EXPECT_EQ(
  544. "is in range (a: 5, b: 8)",
  545. FormatMatcherDescription(false, "IsInRange", {"a", "b"}, {"5", "8"}));
  546. }
  547. INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest);
  548. TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {
  549. stringstream ss1;
  550. ExplainMatchFailureTupleTo(
  551. std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
  552. std::make_tuple('a', 10), &ss1);
  553. EXPECT_EQ("", ss1.str()); // Successful match.
  554. stringstream ss2;
  555. ExplainMatchFailureTupleTo(
  556. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  557. std::make_tuple(2, 'b'), &ss2);
  558. EXPECT_EQ(
  559. " Expected arg #0: is > 5\n"
  560. " Actual: 2, which is 3 less than 5\n"
  561. " Expected arg #1: is equal to 'a' (97, 0x61)\n"
  562. " Actual: 'b' (98, 0x62)\n",
  563. ss2.str()); // Failed match where both arguments need explanation.
  564. stringstream ss3;
  565. ExplainMatchFailureTupleTo(
  566. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  567. std::make_tuple(2, 'a'), &ss3);
  568. EXPECT_EQ(
  569. " Expected arg #0: is > 5\n"
  570. " Actual: 2, which is 3 less than 5\n",
  571. ss3.str()); // Failed match where only one argument needs
  572. // explanation.
  573. }
  574. // Sample optional type implementation with minimal requirements for use with
  575. // Optional matcher.
  576. template <typename T>
  577. class SampleOptional {
  578. public:
  579. using value_type = T;
  580. explicit SampleOptional(T value)
  581. : value_(std::move(value)), has_value_(true) {}
  582. SampleOptional() : value_(), has_value_(false) {}
  583. operator bool() const { return has_value_; }
  584. const T& operator*() const { return value_; }
  585. private:
  586. T value_;
  587. bool has_value_;
  588. };
  589. TEST(OptionalTest, DescribesSelf) {
  590. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  591. EXPECT_EQ("value is equal to 1", Describe(m));
  592. }
  593. TEST(OptionalTest, ExplainsSelf) {
  594. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  595. EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
  596. EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
  597. }
  598. TEST(OptionalTest, MatchesNonEmptyOptional) {
  599. const Matcher<SampleOptional<int>> m1 = Optional(1);
  600. const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
  601. const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
  602. SampleOptional<int> opt(1);
  603. EXPECT_TRUE(m1.Matches(opt));
  604. EXPECT_FALSE(m2.Matches(opt));
  605. EXPECT_TRUE(m3.Matches(opt));
  606. }
  607. TEST(OptionalTest, DoesNotMatchNullopt) {
  608. const Matcher<SampleOptional<int>> m = Optional(1);
  609. SampleOptional<int> empty;
  610. EXPECT_FALSE(m.Matches(empty));
  611. }
  612. TEST(OptionalTest, WorksWithMoveOnly) {
  613. Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
  614. EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
  615. }
  616. class SampleVariantIntString {
  617. public:
  618. SampleVariantIntString(int i) : i_(i), has_int_(true) {}
  619. SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
  620. template <typename T>
  621. friend bool holds_alternative(const SampleVariantIntString& value) {
  622. return value.has_int_ == std::is_same<T, int>::value;
  623. }
  624. template <typename T>
  625. friend const T& get(const SampleVariantIntString& value) {
  626. return value.get_impl(static_cast<T*>(nullptr));
  627. }
  628. private:
  629. const int& get_impl(int*) const { return i_; }
  630. const std::string& get_impl(std::string*) const { return s_; }
  631. int i_;
  632. std::string s_;
  633. bool has_int_;
  634. };
  635. TEST(VariantTest, DescribesSelf) {
  636. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  637. EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
  638. "'.*' and the value is equal to 1"));
  639. }
  640. TEST(VariantTest, ExplainsSelf) {
  641. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  642. EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
  643. ContainsRegex("whose value 1"));
  644. EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
  645. HasSubstr("whose value is not of type '"));
  646. EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
  647. "whose value 2 doesn't match");
  648. }
  649. TEST(VariantTest, FullMatch) {
  650. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  651. EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
  652. m = VariantWith<std::string>(Eq("1"));
  653. EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
  654. }
  655. TEST(VariantTest, TypeDoesNotMatch) {
  656. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  657. EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
  658. m = VariantWith<std::string>(Eq("1"));
  659. EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
  660. }
  661. TEST(VariantTest, InnerDoesNotMatch) {
  662. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  663. EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
  664. m = VariantWith<std::string>(Eq("1"));
  665. EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
  666. }
  667. class SampleAnyType {
  668. public:
  669. explicit SampleAnyType(int i) : index_(0), i_(i) {}
  670. explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
  671. template <typename T>
  672. friend const T* any_cast(const SampleAnyType* any) {
  673. return any->get_impl(static_cast<T*>(nullptr));
  674. }
  675. private:
  676. int index_;
  677. int i_;
  678. std::string s_;
  679. const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
  680. const std::string* get_impl(std::string*) const {
  681. return index_ == 1 ? &s_ : nullptr;
  682. }
  683. };
  684. TEST(AnyWithTest, FullMatch) {
  685. Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
  686. EXPECT_TRUE(m.Matches(SampleAnyType(1)));
  687. }
  688. TEST(AnyWithTest, TestBadCastType) {
  689. Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
  690. EXPECT_FALSE(m.Matches(SampleAnyType(1)));
  691. }
  692. TEST(AnyWithTest, TestUseInContainers) {
  693. std::vector<SampleAnyType> a;
  694. a.emplace_back(1);
  695. a.emplace_back(2);
  696. a.emplace_back(3);
  697. EXPECT_THAT(
  698. a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
  699. std::vector<SampleAnyType> b;
  700. b.emplace_back("hello");
  701. b.emplace_back("merhaba");
  702. b.emplace_back("salut");
  703. EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
  704. AnyWith<std::string>("merhaba"),
  705. AnyWith<std::string>("salut")}));
  706. }
  707. TEST(AnyWithTest, TestCompare) {
  708. EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
  709. }
  710. TEST(AnyWithTest, DescribesSelf) {
  711. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  712. EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
  713. "'.*' and the value is equal to 1"));
  714. }
  715. TEST(AnyWithTest, ExplainsSelf) {
  716. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  717. EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
  718. EXPECT_THAT(Explain(m, SampleAnyType("A")),
  719. HasSubstr("whose value is not of type '"));
  720. EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
  721. }
  722. // Tests Args<k0, ..., kn>(m).
  723. TEST(ArgsTest, AcceptsZeroTemplateArg) {
  724. const std::tuple<int, bool> t(5, true);
  725. EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
  726. EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
  727. }
  728. TEST(ArgsTest, AcceptsOneTemplateArg) {
  729. const std::tuple<int, bool> t(5, true);
  730. EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
  731. EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
  732. EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
  733. }
  734. TEST(ArgsTest, AcceptsTwoTemplateArgs) {
  735. const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
  736. EXPECT_THAT(t, (Args<0, 1>(Lt())));
  737. EXPECT_THAT(t, (Args<1, 2>(Lt())));
  738. EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
  739. }
  740. TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
  741. const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
  742. EXPECT_THAT(t, (Args<0, 0>(Eq())));
  743. EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
  744. }
  745. TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
  746. const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
  747. EXPECT_THAT(t, (Args<2, 0>(Gt())));
  748. EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
  749. }
  750. MATCHER(SumIsZero, "") {
  751. return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
  752. }
  753. TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
  754. EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
  755. EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
  756. }
  757. TEST(ArgsTest, CanBeNested) {
  758. const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT
  759. EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
  760. EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
  761. }
  762. TEST(ArgsTest, CanMatchTupleByValue) {
  763. typedef std::tuple<char, int, int> Tuple3;
  764. const Matcher<Tuple3> m = Args<1, 2>(Lt());
  765. EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
  766. EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
  767. }
  768. TEST(ArgsTest, CanMatchTupleByReference) {
  769. typedef std::tuple<char, char, int> Tuple3;
  770. const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
  771. EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
  772. EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
  773. }
  774. // Validates that arg is printed as str.
  775. MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; }
  776. TEST(ArgsTest, AcceptsTenTemplateArgs) {
  777. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  778. (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  779. PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  780. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  781. Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  782. PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  783. }
  784. TEST(ArgsTest, DescirbesSelfCorrectly) {
  785. const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt());
  786. EXPECT_EQ(
  787. "are a tuple whose fields (#2, #0) are a pair where "
  788. "the first < the second",
  789. Describe(m));
  790. }
  791. TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
  792. const Matcher<const std::tuple<int, bool, char, int>&> m =
  793. Args<0, 2, 3>(Args<2, 0>(Lt()));
  794. EXPECT_EQ(
  795. "are a tuple whose fields (#0, #2, #3) are a tuple "
  796. "whose fields (#2, #0) are a pair where the first < the second",
  797. Describe(m));
  798. }
  799. TEST(ArgsTest, DescribesNegationCorrectly) {
  800. const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt());
  801. EXPECT_EQ(
  802. "are a tuple whose fields (#1, #0) aren't a pair "
  803. "where the first > the second",
  804. DescribeNegation(m));
  805. }
  806. TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
  807. const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq());
  808. EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
  809. Explain(m, std::make_tuple(false, 42, 42)));
  810. EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
  811. Explain(m, std::make_tuple(false, 42, 43)));
  812. }
  813. // For testing Args<>'s explanation.
  814. class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> {
  815. public:
  816. void DescribeTo(::std::ostream* /*os*/) const override {}
  817. bool MatchAndExplain(std::tuple<char, int> value,
  818. MatchResultListener* listener) const override {
  819. const int diff = std::get<0>(value) - std::get<1>(value);
  820. if (diff > 0) {
  821. *listener << "where the first value is " << diff
  822. << " more than the second";
  823. }
  824. return diff < 0;
  825. }
  826. };
  827. Matcher<std::tuple<char, int>> LessThan() {
  828. return MakeMatcher(new LessThanMatcher);
  829. }
  830. TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
  831. const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan());
  832. EXPECT_EQ(
  833. "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
  834. "where the first value is 55 more than the second",
  835. Explain(m, std::make_tuple('a', 42, 42)));
  836. EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
  837. Explain(m, std::make_tuple('\0', 42, 43)));
  838. }
  839. // Tests for the MATCHER*() macro family.
  840. // Tests that a simple MATCHER() definition works.
  841. MATCHER(IsEven, "") { return (arg % 2) == 0; }
  842. TEST(MatcherMacroTest, Works) {
  843. const Matcher<int> m = IsEven();
  844. EXPECT_TRUE(m.Matches(6));
  845. EXPECT_FALSE(m.Matches(7));
  846. EXPECT_EQ("is even", Describe(m));
  847. EXPECT_EQ("not (is even)", DescribeNegation(m));
  848. EXPECT_EQ("", Explain(m, 6));
  849. EXPECT_EQ("", Explain(m, 7));
  850. }
  851. // This also tests that the description string can reference 'negation'.
  852. MATCHER(IsEven2, negation ? "is odd" : "is even") {
  853. if ((arg % 2) == 0) {
  854. // Verifies that we can stream to result_listener, a listener
  855. // supplied by the MATCHER macro implicitly.
  856. *result_listener << "OK";
  857. return true;
  858. } else {
  859. *result_listener << "% 2 == " << (arg % 2);
  860. return false;
  861. }
  862. }
  863. // This also tests that the description string can reference matcher
  864. // parameters.
  865. MATCHER_P2(EqSumOf, x, y,
  866. std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
  867. PrintToString(x) + " and " + PrintToString(y)) {
  868. if (arg == (x + y)) {
  869. *result_listener << "OK";
  870. return true;
  871. } else {
  872. // Verifies that we can stream to the underlying stream of
  873. // result_listener.
  874. if (result_listener->stream() != nullptr) {
  875. *result_listener->stream() << "diff == " << (x + y - arg);
  876. }
  877. return false;
  878. }
  879. }
  880. // Tests that the matcher description can reference 'negation' and the
  881. // matcher parameters.
  882. TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
  883. const Matcher<int> m1 = IsEven2();
  884. EXPECT_EQ("is even", Describe(m1));
  885. EXPECT_EQ("is odd", DescribeNegation(m1));
  886. const Matcher<int> m2 = EqSumOf(5, 9);
  887. EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
  888. EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
  889. }
  890. // Tests explaining match result in a MATCHER* macro.
  891. TEST(MatcherMacroTest, CanExplainMatchResult) {
  892. const Matcher<int> m1 = IsEven2();
  893. EXPECT_EQ("OK", Explain(m1, 4));
  894. EXPECT_EQ("% 2 == 1", Explain(m1, 5));
  895. const Matcher<int> m2 = EqSumOf(1, 2);
  896. EXPECT_EQ("OK", Explain(m2, 3));
  897. EXPECT_EQ("diff == -1", Explain(m2, 4));
  898. }
  899. // Tests that the body of MATCHER() can reference the type of the
  900. // value being matched.
  901. MATCHER(IsEmptyString, "") {
  902. StaticAssertTypeEq<::std::string, arg_type>();
  903. return arg.empty();
  904. }
  905. MATCHER(IsEmptyStringByRef, "") {
  906. StaticAssertTypeEq<const ::std::string&, arg_type>();
  907. return arg.empty();
  908. }
  909. TEST(MatcherMacroTest, CanReferenceArgType) {
  910. const Matcher<::std::string> m1 = IsEmptyString();
  911. EXPECT_TRUE(m1.Matches(""));
  912. const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
  913. EXPECT_TRUE(m2.Matches(""));
  914. }
  915. // Tests that MATCHER() can be used in a namespace.
  916. namespace matcher_test {
  917. MATCHER(IsOdd, "") { return (arg % 2) != 0; }
  918. } // namespace matcher_test
  919. TEST(MatcherMacroTest, WorksInNamespace) {
  920. Matcher<int> m = matcher_test::IsOdd();
  921. EXPECT_FALSE(m.Matches(4));
  922. EXPECT_TRUE(m.Matches(5));
  923. }
  924. // Tests that Value() can be used to compose matchers.
  925. MATCHER(IsPositiveOdd, "") {
  926. return Value(arg, matcher_test::IsOdd()) && arg > 0;
  927. }
  928. TEST(MatcherMacroTest, CanBeComposedUsingValue) {
  929. EXPECT_THAT(3, IsPositiveOdd());
  930. EXPECT_THAT(4, Not(IsPositiveOdd()));
  931. EXPECT_THAT(-1, Not(IsPositiveOdd()));
  932. }
  933. // Tests that a simple MATCHER_P() definition works.
  934. MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
  935. TEST(MatcherPMacroTest, Works) {
  936. const Matcher<int> m = IsGreaterThan32And(5);
  937. EXPECT_TRUE(m.Matches(36));
  938. EXPECT_FALSE(m.Matches(5));
  939. EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));
  940. EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));
  941. EXPECT_EQ("", Explain(m, 36));
  942. EXPECT_EQ("", Explain(m, 5));
  943. }
  944. // Tests that the description is calculated correctly from the matcher name.
  945. MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
  946. TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
  947. const Matcher<int> m = _is_Greater_Than32and_(5);
  948. EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));
  949. EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));
  950. EXPECT_EQ("", Explain(m, 36));
  951. EXPECT_EQ("", Explain(m, 5));
  952. }
  953. // Tests that a MATCHER_P matcher can be explicitly instantiated with
  954. // a reference parameter type.
  955. class UncopyableFoo {
  956. public:
  957. explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
  958. UncopyableFoo(const UncopyableFoo&) = delete;
  959. void operator=(const UncopyableFoo&) = delete;
  960. private:
  961. char value_;
  962. };
  963. MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
  964. TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
  965. UncopyableFoo foo1('1'), foo2('2');
  966. const Matcher<const UncopyableFoo&> m =
  967. ReferencesUncopyable<const UncopyableFoo&>(foo1);
  968. EXPECT_TRUE(m.Matches(foo1));
  969. EXPECT_FALSE(m.Matches(foo2));
  970. // We don't want the address of the parameter printed, as most
  971. // likely it will just annoy the user. If the address is
  972. // interesting, the user should consider passing the parameter by
  973. // pointer instead.
  974. EXPECT_EQ("references uncopyable (variable: 1-byte object <31>)",
  975. Describe(m));
  976. }
  977. // Tests that the body of MATCHER_Pn() can reference the parameter
  978. // types.
  979. MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
  980. StaticAssertTypeEq<int, foo_type>();
  981. StaticAssertTypeEq<long, bar_type>(); // NOLINT
  982. StaticAssertTypeEq<char, baz_type>();
  983. return arg == 0;
  984. }
  985. TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
  986. EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
  987. }
  988. // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
  989. // reference parameter types.
  990. MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
  991. return &arg == &variable1 || &arg == &variable2;
  992. }
  993. TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
  994. UncopyableFoo foo1('1'), foo2('2'), foo3('3');
  995. const Matcher<const UncopyableFoo&> const_m =
  996. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  997. EXPECT_TRUE(const_m.Matches(foo1));
  998. EXPECT_TRUE(const_m.Matches(foo2));
  999. EXPECT_FALSE(const_m.Matches(foo3));
  1000. const Matcher<UncopyableFoo&> m =
  1001. ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
  1002. EXPECT_TRUE(m.Matches(foo1));
  1003. EXPECT_TRUE(m.Matches(foo2));
  1004. EXPECT_FALSE(m.Matches(foo3));
  1005. }
  1006. TEST(MatcherPnMacroTest,
  1007. GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
  1008. UncopyableFoo foo1('1'), foo2('2');
  1009. const Matcher<const UncopyableFoo&> m =
  1010. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  1011. // We don't want the addresses of the parameters printed, as most
  1012. // likely they will just annoy the user. If the addresses are
  1013. // interesting, the user should consider passing the parameters by
  1014. // pointers instead.
  1015. EXPECT_EQ(
  1016. "references any of (variable1: 1-byte object <31>, variable2: 1-byte "
  1017. "object <32>)",
  1018. Describe(m));
  1019. }
  1020. // Tests that a simple MATCHER_P2() definition works.
  1021. MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
  1022. TEST(MatcherPnMacroTest, Works) {
  1023. const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
  1024. EXPECT_TRUE(m.Matches(36L));
  1025. EXPECT_FALSE(m.Matches(15L));
  1026. EXPECT_EQ("is not in closed range (low: 10, hi: 20)", Describe(m));
  1027. EXPECT_EQ("not (is not in closed range (low: 10, hi: 20))",
  1028. DescribeNegation(m));
  1029. EXPECT_EQ("", Explain(m, 36L));
  1030. EXPECT_EQ("", Explain(m, 15L));
  1031. }
  1032. // Tests that MATCHER*() definitions can be overloaded on the number
  1033. // of parameters; also tests MATCHER_Pn() where n >= 3.
  1034. MATCHER(EqualsSumOf, "") { return arg == 0; }
  1035. MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
  1036. MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
  1037. MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
  1038. MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
  1039. MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
  1040. MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
  1041. return arg == a + b + c + d + e + f;
  1042. }
  1043. MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
  1044. return arg == a + b + c + d + e + f + g;
  1045. }
  1046. MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
  1047. return arg == a + b + c + d + e + f + g + h;
  1048. }
  1049. MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
  1050. return arg == a + b + c + d + e + f + g + h + i;
  1051. }
  1052. MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
  1053. return arg == a + b + c + d + e + f + g + h + i + j;
  1054. }
  1055. TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
  1056. EXPECT_THAT(0, EqualsSumOf());
  1057. EXPECT_THAT(1, EqualsSumOf(1));
  1058. EXPECT_THAT(12, EqualsSumOf(10, 2));
  1059. EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
  1060. EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
  1061. EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
  1062. EXPECT_THAT("abcdef",
  1063. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
  1064. EXPECT_THAT("abcdefg",
  1065. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
  1066. EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
  1067. 'f', 'g', "h"));
  1068. EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
  1069. 'f', 'g', "h", 'i'));
  1070. EXPECT_THAT("abcdefghij",
  1071. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
  1072. 'i', ::std::string("j")));
  1073. EXPECT_THAT(1, Not(EqualsSumOf()));
  1074. EXPECT_THAT(-1, Not(EqualsSumOf(1)));
  1075. EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
  1076. EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
  1077. EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
  1078. EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
  1079. EXPECT_THAT("abcdef ",
  1080. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
  1081. EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  1082. "e", 'f', 'g')));
  1083. EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  1084. "e", 'f', 'g', "h")));
  1085. EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  1086. "e", 'f', 'g', "h", 'i')));
  1087. EXPECT_THAT("abcdefghij ",
  1088. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  1089. "h", 'i', ::std::string("j"))));
  1090. }
  1091. // Tests that a MATCHER_Pn() definition can be instantiated with any
  1092. // compatible parameter types.
  1093. TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
  1094. EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
  1095. EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
  1096. EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
  1097. EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
  1098. }
  1099. // Tests that the matcher body can promote the parameter types.
  1100. MATCHER_P2(EqConcat, prefix, suffix, "") {
  1101. // The following lines promote the two parameters to desired types.
  1102. std::string prefix_str(prefix);
  1103. char suffix_char = static_cast<char>(suffix);
  1104. return arg == prefix_str + suffix_char;
  1105. }
  1106. TEST(MatcherPnMacroTest, SimpleTypePromotion) {
  1107. Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
  1108. Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
  1109. EXPECT_FALSE(no_promo.Matches("fool"));
  1110. EXPECT_FALSE(promo.Matches("fool"));
  1111. EXPECT_TRUE(no_promo.Matches("foot"));
  1112. EXPECT_TRUE(promo.Matches("foot"));
  1113. }
  1114. // Verifies the type of a MATCHER*.
  1115. TEST(MatcherPnMacroTest, TypesAreCorrect) {
  1116. // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
  1117. EqualsSumOfMatcher a0 = EqualsSumOf();
  1118. // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
  1119. EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
  1120. // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
  1121. // variable, and so on.
  1122. EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
  1123. EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
  1124. EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
  1125. EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
  1126. EqualsSumOf(1, 2, 3, 4, '5');
  1127. EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
  1128. EqualsSumOf(1, 2, 3, 4, 5, '6');
  1129. EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
  1130. EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
  1131. EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
  1132. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
  1133. EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
  1134. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
  1135. EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
  1136. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
  1137. // Avoid "unused variable" warnings.
  1138. (void)a0;
  1139. (void)a1;
  1140. (void)a2;
  1141. (void)a3;
  1142. (void)a4;
  1143. (void)a5;
  1144. (void)a6;
  1145. (void)a7;
  1146. (void)a8;
  1147. (void)a9;
  1148. (void)a10;
  1149. }
  1150. // Tests that matcher-typed parameters can be used in Value() inside a
  1151. // MATCHER_Pn definition.
  1152. // Succeeds if arg matches exactly 2 of the 3 matchers.
  1153. MATCHER_P3(TwoOf, m1, m2, m3, "") {
  1154. const int count = static_cast<int>(Value(arg, m1)) +
  1155. static_cast<int>(Value(arg, m2)) +
  1156. static_cast<int>(Value(arg, m3));
  1157. return count == 2;
  1158. }
  1159. TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
  1160. EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
  1161. EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
  1162. }
  1163. // Tests Contains().Times().
  1164. INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes);
  1165. TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {
  1166. list<int> some_list;
  1167. some_list.push_back(3);
  1168. some_list.push_back(1);
  1169. some_list.push_back(2);
  1170. some_list.push_back(3);
  1171. EXPECT_THAT(some_list, Contains(3).Times(2));
  1172. EXPECT_THAT(some_list, Contains(2).Times(1));
  1173. EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));
  1174. EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));
  1175. EXPECT_THAT(some_list, Contains(4).Times(0));
  1176. EXPECT_THAT(some_list, Contains(_).Times(4));
  1177. EXPECT_THAT(some_list, Not(Contains(5).Times(1)));
  1178. EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches
  1179. EXPECT_THAT(some_list, Not(Contains(3).Times(1)));
  1180. EXPECT_THAT(some_list, Contains(3).Times(Not(1)));
  1181. EXPECT_THAT(list<int>{}, Not(Contains(_)));
  1182. }
  1183. TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) {
  1184. const int a[2] = {1, 2};
  1185. Matcher<const int(&)[2]> m = Contains(2).Times(3);
  1186. EXPECT_EQ(
  1187. "whose element #1 matches but whose match quantity of 1 does not match",
  1188. Explain(m, a));
  1189. m = Contains(3).Times(0);
  1190. EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",
  1191. Explain(m, a));
  1192. m = Contains(3).Times(4);
  1193. EXPECT_EQ(
  1194. "has no element that matches and whose match quantity of 0 does not "
  1195. "match",
  1196. Explain(m, a));
  1197. m = Contains(2).Times(4);
  1198. EXPECT_EQ(
  1199. "whose element #1 matches but whose match quantity of 1 does not "
  1200. "match",
  1201. Explain(m, a));
  1202. m = Contains(GreaterThan(0)).Times(2);
  1203. EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",
  1204. Explain(m, a));
  1205. m = Contains(GreaterThan(10)).Times(Gt(1));
  1206. EXPECT_EQ(
  1207. "has no element that matches and whose match quantity of 0 does not "
  1208. "match",
  1209. Explain(m, a));
  1210. m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));
  1211. EXPECT_EQ(
  1212. "whose elements (0, 1) match but whose match quantity of 2 does not "
  1213. "match, which is 3 less than 5",
  1214. Explain(m, a));
  1215. }
  1216. TEST(ContainsTimes, DescribesItselfCorrectly) {
  1217. Matcher<vector<int>> m = Contains(1).Times(2);
  1218. EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",
  1219. Describe(m));
  1220. Matcher<vector<int>> m2 = Not(m);
  1221. EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",
  1222. Describe(m2));
  1223. }
  1224. // Tests AllOfArray()
  1225. TEST(AllOfArrayTest, BasicForms) {
  1226. // Iterator
  1227. std::vector<int> v0{};
  1228. std::vector<int> v1{1};
  1229. std::vector<int> v2{2, 3};
  1230. std::vector<int> v3{4, 4, 4};
  1231. EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
  1232. EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
  1233. EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
  1234. EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
  1235. EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
  1236. // Pointer + size
  1237. int ar[6] = {1, 2, 3, 4, 4, 4};
  1238. EXPECT_THAT(0, AllOfArray(ar, 0));
  1239. EXPECT_THAT(1, AllOfArray(ar, 1));
  1240. EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
  1241. EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
  1242. EXPECT_THAT(4, AllOfArray(ar + 3, 3));
  1243. // Array
  1244. // int ar0[0]; Not usable
  1245. int ar1[1] = {1};
  1246. int ar2[2] = {2, 3};
  1247. int ar3[3] = {4, 4, 4};
  1248. // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
  1249. EXPECT_THAT(1, AllOfArray(ar1));
  1250. EXPECT_THAT(2, Not(AllOfArray(ar1)));
  1251. EXPECT_THAT(3, Not(AllOfArray(ar2)));
  1252. EXPECT_THAT(4, AllOfArray(ar3));
  1253. // Container
  1254. EXPECT_THAT(0, AllOfArray(v0));
  1255. EXPECT_THAT(1, AllOfArray(v1));
  1256. EXPECT_THAT(2, Not(AllOfArray(v1)));
  1257. EXPECT_THAT(3, Not(AllOfArray(v2)));
  1258. EXPECT_THAT(4, AllOfArray(v3));
  1259. // Initializer
  1260. EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
  1261. EXPECT_THAT(1, AllOfArray({1}));
  1262. EXPECT_THAT(2, Not(AllOfArray({1})));
  1263. EXPECT_THAT(3, Not(AllOfArray({2, 3})));
  1264. EXPECT_THAT(4, AllOfArray({4, 4, 4}));
  1265. }
  1266. TEST(AllOfArrayTest, Matchers) {
  1267. // vector
  1268. std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
  1269. EXPECT_THAT(0, Not(AllOfArray(matchers)));
  1270. EXPECT_THAT(1, AllOfArray(matchers));
  1271. EXPECT_THAT(2, Not(AllOfArray(matchers)));
  1272. // initializer_list
  1273. EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
  1274. EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
  1275. }
  1276. INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest);
  1277. TEST(AnyOfArrayTest, BasicForms) {
  1278. // Iterator
  1279. std::vector<int> v0{};
  1280. std::vector<int> v1{1};
  1281. std::vector<int> v2{2, 3};
  1282. EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
  1283. EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
  1284. EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
  1285. EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
  1286. EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
  1287. // Pointer + size
  1288. int ar[3] = {1, 2, 3};
  1289. EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
  1290. EXPECT_THAT(1, AnyOfArray(ar, 1));
  1291. EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
  1292. EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
  1293. EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
  1294. // Array
  1295. // int ar0[0]; Not usable
  1296. int ar1[1] = {1};
  1297. int ar2[2] = {2, 3};
  1298. // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
  1299. EXPECT_THAT(1, AnyOfArray(ar1));
  1300. EXPECT_THAT(2, Not(AnyOfArray(ar1)));
  1301. EXPECT_THAT(3, AnyOfArray(ar2));
  1302. EXPECT_THAT(4, Not(AnyOfArray(ar2)));
  1303. // Container
  1304. EXPECT_THAT(0, Not(AnyOfArray(v0)));
  1305. EXPECT_THAT(1, AnyOfArray(v1));
  1306. EXPECT_THAT(2, Not(AnyOfArray(v1)));
  1307. EXPECT_THAT(3, AnyOfArray(v2));
  1308. EXPECT_THAT(4, Not(AnyOfArray(v2)));
  1309. // Initializer
  1310. EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
  1311. EXPECT_THAT(1, AnyOfArray({1}));
  1312. EXPECT_THAT(2, Not(AnyOfArray({1})));
  1313. EXPECT_THAT(3, AnyOfArray({2, 3}));
  1314. EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
  1315. }
  1316. TEST(AnyOfArrayTest, Matchers) {
  1317. // We negate test AllOfArrayTest.Matchers.
  1318. // vector
  1319. std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
  1320. EXPECT_THAT(0, AnyOfArray(matchers));
  1321. EXPECT_THAT(1, Not(AnyOfArray(matchers)));
  1322. EXPECT_THAT(2, AnyOfArray(matchers));
  1323. // initializer_list
  1324. EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
  1325. EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
  1326. }
  1327. TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
  1328. // AnyOfArray and AllOfArray use the same underlying template-template,
  1329. // thus it is sufficient to test one here.
  1330. const std::vector<int> v0{};
  1331. const std::vector<int> v1{1};
  1332. const std::vector<int> v2{2, 3};
  1333. const Matcher<int> m0 = AnyOfArray(v0);
  1334. const Matcher<int> m1 = AnyOfArray(v1);
  1335. const Matcher<int> m2 = AnyOfArray(v2);
  1336. EXPECT_EQ("", Explain(m0, 0));
  1337. EXPECT_EQ("", Explain(m1, 1));
  1338. EXPECT_EQ("", Explain(m1, 2));
  1339. EXPECT_EQ("", Explain(m2, 3));
  1340. EXPECT_EQ("", Explain(m2, 4));
  1341. EXPECT_EQ("()", Describe(m0));
  1342. EXPECT_EQ("(is equal to 1)", Describe(m1));
  1343. EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
  1344. EXPECT_EQ("()", DescribeNegation(m0));
  1345. EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
  1346. EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
  1347. // Explain with matchers
  1348. const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
  1349. const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
  1350. // Explains the first positive match and all prior negative matches...
  1351. EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
  1352. EXPECT_EQ("which is the same as 1", Explain(g1, 1));
  1353. EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
  1354. EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
  1355. Explain(g2, 0));
  1356. EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
  1357. Explain(g2, 1));
  1358. EXPECT_EQ("which is 1 more than 1", // Only the first
  1359. Explain(g2, 2));
  1360. }
  1361. MATCHER(IsNotNull, "") { return arg != nullptr; }
  1362. // Verifies that a matcher defined using MATCHER() can work on
  1363. // move-only types.
  1364. TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
  1365. std::unique_ptr<int> p(new int(3));
  1366. EXPECT_THAT(p, IsNotNull());
  1367. EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
  1368. }
  1369. MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
  1370. // Verifies that a matcher defined using MATCHER_P*() can work on
  1371. // move-only types.
  1372. TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
  1373. std::unique_ptr<int> p(new int(3));
  1374. EXPECT_THAT(p, UniquePointee(3));
  1375. EXPECT_THAT(p, Not(UniquePointee(2)));
  1376. }
  1377. MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }
  1378. TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {
  1379. #ifdef __clang__
  1380. #pragma clang diagnostic push
  1381. #pragma clang diagnostic error "-Wused-but-marked-unused"
  1382. #endif
  1383. // https://github.com/google/googletest/issues/4055
  1384. EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());
  1385. #ifdef __clang__
  1386. #pragma clang diagnostic pop
  1387. #endif
  1388. }
  1389. #if GTEST_HAS_EXCEPTIONS
  1390. // std::function<void()> is used below for compatibility with older copies of
  1391. // GCC. Normally, a raw lambda is all that is needed.
  1392. // Test that examples from documentation compile
  1393. TEST(ThrowsTest, Examples) {
  1394. EXPECT_THAT(
  1395. std::function<void()>([]() { throw std::runtime_error("message"); }),
  1396. Throws<std::runtime_error>());
  1397. EXPECT_THAT(
  1398. std::function<void()>([]() { throw std::runtime_error("message"); }),
  1399. ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  1400. }
  1401. TEST(ThrowsTest, PrintsExceptionWhat) {
  1402. EXPECT_THAT(
  1403. std::function<void()>([]() { throw std::runtime_error("ABC123XYZ"); }),
  1404. ThrowsMessage<std::runtime_error>(HasSubstr("ABC123XYZ")));
  1405. }
  1406. TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
  1407. EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
  1408. Throws<std::exception>());
  1409. }
  1410. TEST(ThrowsTest, CallableExecutedExactlyOnce) {
  1411. size_t a = 0;
  1412. EXPECT_THAT(std::function<void()>([&a]() {
  1413. a++;
  1414. throw 10;
  1415. }),
  1416. Throws<int>());
  1417. EXPECT_EQ(a, 1u);
  1418. EXPECT_THAT(std::function<void()>([&a]() {
  1419. a++;
  1420. throw std::runtime_error("message");
  1421. }),
  1422. Throws<std::runtime_error>());
  1423. EXPECT_EQ(a, 2u);
  1424. EXPECT_THAT(std::function<void()>([&a]() {
  1425. a++;
  1426. throw std::runtime_error("message");
  1427. }),
  1428. ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  1429. EXPECT_EQ(a, 3u);
  1430. EXPECT_THAT(std::function<void()>([&a]() {
  1431. a++;
  1432. throw std::runtime_error("message");
  1433. }),
  1434. Throws<std::runtime_error>(
  1435. Property(&std::runtime_error::what, HasSubstr("message"))));
  1436. EXPECT_EQ(a, 4u);
  1437. }
  1438. TEST(ThrowsTest, Describe) {
  1439. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  1440. std::stringstream ss;
  1441. matcher.DescribeTo(&ss);
  1442. auto explanation = ss.str();
  1443. EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
  1444. }
  1445. TEST(ThrowsTest, Success) {
  1446. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  1447. StringMatchResultListener listener;
  1448. EXPECT_TRUE(matcher.MatchAndExplain(
  1449. []() { throw std::runtime_error("error message"); }, &listener));
  1450. EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
  1451. }
  1452. TEST(ThrowsTest, FailWrongType) {
  1453. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  1454. StringMatchResultListener listener;
  1455. EXPECT_FALSE(matcher.MatchAndExplain(
  1456. []() { throw std::logic_error("error message"); }, &listener));
  1457. EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
  1458. EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
  1459. }
  1460. TEST(ThrowsTest, FailWrongTypeNonStd) {
  1461. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  1462. StringMatchResultListener listener;
  1463. EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
  1464. EXPECT_THAT(listener.str(),
  1465. HasSubstr("throws an exception of an unknown type"));
  1466. }
  1467. TEST(ThrowsTest, FailNoThrow) {
  1468. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  1469. StringMatchResultListener listener;
  1470. EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
  1471. EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
  1472. }
  1473. class ThrowsPredicateTest
  1474. : public TestWithParam<Matcher<std::function<void()>>> {};
  1475. TEST_P(ThrowsPredicateTest, Describe) {
  1476. Matcher<std::function<void()>> matcher = GetParam();
  1477. std::stringstream ss;
  1478. matcher.DescribeTo(&ss);
  1479. auto explanation = ss.str();
  1480. EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
  1481. EXPECT_THAT(explanation, HasSubstr("error message"));
  1482. }
  1483. TEST_P(ThrowsPredicateTest, Success) {
  1484. Matcher<std::function<void()>> matcher = GetParam();
  1485. StringMatchResultListener listener;
  1486. EXPECT_TRUE(matcher.MatchAndExplain(
  1487. []() { throw std::runtime_error("error message"); }, &listener));
  1488. EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
  1489. }
  1490. TEST_P(ThrowsPredicateTest, FailWrongType) {
  1491. Matcher<std::function<void()>> matcher = GetParam();
  1492. StringMatchResultListener listener;
  1493. EXPECT_FALSE(matcher.MatchAndExplain(
  1494. []() { throw std::logic_error("error message"); }, &listener));
  1495. EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
  1496. EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
  1497. }
  1498. TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
  1499. Matcher<std::function<void()>> matcher = GetParam();
  1500. StringMatchResultListener listener;
  1501. EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
  1502. EXPECT_THAT(listener.str(),
  1503. HasSubstr("throws an exception of an unknown type"));
  1504. }
  1505. TEST_P(ThrowsPredicateTest, FailNoThrow) {
  1506. Matcher<std::function<void()>> matcher = GetParam();
  1507. StringMatchResultListener listener;
  1508. EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
  1509. EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
  1510. }
  1511. INSTANTIATE_TEST_SUITE_P(
  1512. AllMessagePredicates, ThrowsPredicateTest,
  1513. Values(Matcher<std::function<void()>>(
  1514. ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
  1515. // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
  1516. TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
  1517. {
  1518. Matcher<std::function<void()>> matcher =
  1519. ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
  1520. EXPECT_TRUE(
  1521. matcher.Matches([]() { throw std::runtime_error("error message"); }));
  1522. EXPECT_FALSE(
  1523. matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
  1524. }
  1525. {
  1526. Matcher<uint64_t> inner = Eq(10);
  1527. Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
  1528. EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; }));
  1529. EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; }));
  1530. }
  1531. }
  1532. // Tests that ThrowsMessage("message") is equivalent
  1533. // to ThrowsMessage(Eq<std::string>("message")).
  1534. TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
  1535. Matcher<std::function<void()>> matcher =
  1536. ThrowsMessage<std::runtime_error>("error message");
  1537. EXPECT_TRUE(
  1538. matcher.Matches([]() { throw std::runtime_error("error message"); }));
  1539. EXPECT_FALSE(matcher.Matches(
  1540. []() { throw std::runtime_error("wrong error message"); }));
  1541. }
  1542. #endif // GTEST_HAS_EXCEPTIONS
  1543. } // namespace
  1544. } // namespace gmock_matchers_test
  1545. } // namespace testing
  1546. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100