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