gmock-matchers-misc_test.cc 60 KB

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