gmock-matchers-misc_test.cc 62 KB

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