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
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file tests some commonly used argument matchers.
34
35 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
36 // possible loss of data and C4100, unreferenced local parameter
37 #ifdef _MSC_VER
38 # pragma warning(push)
39 # pragma warning(disable:4244)
40 # pragma warning(disable:4100)
41 #endif
42
43 #include "gmock/gmock-matchers.h"
44 #include "gmock/gmock-more-matchers.h"
45
46 #include <string.h>
47 #include <time.h>
48 #include <deque>
49 #include <forward_list>
50 #include <functional>
51 #include <iostream>
52 #include <iterator>
53 #include <limits>
54 #include <list>
55 #include <map>
56 #include <memory>
57 #include <set>
58 #include <sstream>
59 #include <string>
60 #include <type_traits>
61 #include <utility>
62 #include <vector>
63 #include "gmock/gmock.h"
64 #include "gtest/gtest.h"
65 #include "gtest/gtest-spi.h"
66
67 namespace testing {
68 namespace gmock_matchers_test {
69 namespace {
70
71 using std::greater;
72 using std::less;
73 using std::list;
74 using std::make_pair;
75 using std::map;
76 using std::multimap;
77 using std::multiset;
78 using std::ostream;
79 using std::pair;
80 using std::set;
81 using std::stringstream;
82 using std::vector;
83 using testing::internal::DummyMatchResultListener;
84 using testing::internal::ElementMatcherPair;
85 using testing::internal::ElementMatcherPairs;
86 using testing::internal::ExplainMatchFailureTupleTo;
87 using testing::internal::FloatingEqMatcher;
88 using testing::internal::FormatMatcherDescription;
89 using testing::internal::IsReadableTypeName;
90 using testing::internal::MatchMatrix;
91 using testing::internal::PredicateFormatterFromMatcher;
92 using testing::internal::RE;
93 using testing::internal::StreamMatchResultListener;
94 using testing::internal::Strings;
95
96 // Helper for testing container-valued matchers in mock method context. It is
97 // important to test matchers in this context, since it requires additional type
98 // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
99 struct ContainerHelper {
100 MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
101 };
102
MakeUniquePtrs(const std::vector<int> & ints)103 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
104 std::vector<std::unique_ptr<int>> pointers;
105 for (int i : ints) pointers.emplace_back(new int(i));
106 return pointers;
107 }
108
109 // For testing ExplainMatchResultTo().
110 class GreaterThanMatcher : public MatcherInterface<int> {
111 public:
GreaterThanMatcher(int rhs)112 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
113
DescribeTo(ostream * os) const114 void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
115
MatchAndExplain(int lhs,MatchResultListener * listener) const116 bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
117 const int diff = lhs - rhs_;
118 if (diff > 0) {
119 *listener << "which is " << diff << " more than " << rhs_;
120 } else if (diff == 0) {
121 *listener << "which is the same as " << rhs_;
122 } else {
123 *listener << "which is " << -diff << " less than " << rhs_;
124 }
125
126 return lhs > rhs_;
127 }
128
129 private:
130 int rhs_;
131 };
132
GreaterThan(int n)133 Matcher<int> GreaterThan(int n) {
134 return MakeMatcher(new GreaterThanMatcher(n));
135 }
136
OfType(const std::string & type_name)137 std::string OfType(const std::string& type_name) {
138 #if GTEST_HAS_RTTI
139 return " (of type " + type_name + ")";
140 #else
141 return "";
142 #endif
143 }
144
145 // Returns the description of the given matcher.
146 template <typename T>
Describe(const Matcher<T> & m)147 std::string Describe(const Matcher<T>& m) {
148 return DescribeMatcher<T>(m);
149 }
150
151 // Returns the description of the negation of the given matcher.
152 template <typename T>
DescribeNegation(const Matcher<T> & m)153 std::string DescribeNegation(const Matcher<T>& m) {
154 return DescribeMatcher<T>(m, true);
155 }
156
157 // Returns the reason why x matches, or doesn't match, m.
158 template <typename MatcherType, typename Value>
Explain(const MatcherType & m,const Value & x)159 std::string Explain(const MatcherType& m, const Value& x) {
160 StringMatchResultListener listener;
161 ExplainMatchResult(m, x, &listener);
162 return listener.str();
163 }
164
TEST(MonotonicMatcherTest,IsPrintable)165 TEST(MonotonicMatcherTest, IsPrintable) {
166 stringstream ss;
167 ss << GreaterThan(5);
168 EXPECT_EQ("is > 5", ss.str());
169 }
170
TEST(MatchResultListenerTest,StreamingWorks)171 TEST(MatchResultListenerTest, StreamingWorks) {
172 StringMatchResultListener listener;
173 listener << "hi" << 5;
174 EXPECT_EQ("hi5", listener.str());
175
176 listener.Clear();
177 EXPECT_EQ("", listener.str());
178
179 listener << 42;
180 EXPECT_EQ("42", listener.str());
181
182 // Streaming shouldn't crash when the underlying ostream is NULL.
183 DummyMatchResultListener dummy;
184 dummy << "hi" << 5;
185 }
186
TEST(MatchResultListenerTest,CanAccessUnderlyingStream)187 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
188 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
189 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
190
191 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
192 }
193
TEST(MatchResultListenerTest,IsInterestedWorks)194 TEST(MatchResultListenerTest, IsInterestedWorks) {
195 EXPECT_TRUE(StringMatchResultListener().IsInterested());
196 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
197
198 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
199 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
200 }
201
202 // Makes sure that the MatcherInterface<T> interface doesn't
203 // change.
204 class EvenMatcherImpl : public MatcherInterface<int> {
205 public:
MatchAndExplain(int x,MatchResultListener *) const206 bool MatchAndExplain(int x,
207 MatchResultListener* /* listener */) const override {
208 return x % 2 == 0;
209 }
210
DescribeTo(ostream * os) const211 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
212
213 // We deliberately don't define DescribeNegationTo() and
214 // ExplainMatchResultTo() here, to make sure the definition of these
215 // two methods is optional.
216 };
217
218 // Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest,CanBeImplementedUsingPublishedAPI)219 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
220 EvenMatcherImpl m;
221 }
222
223 // Tests implementing a monomorphic matcher using MatchAndExplain().
224
225 class NewEvenMatcherImpl : public MatcherInterface<int> {
226 public:
MatchAndExplain(int x,MatchResultListener * listener) const227 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
228 const bool match = x % 2 == 0;
229 // Verifies that we can stream to a listener directly.
230 *listener << "value % " << 2;
231 if (listener->stream() != nullptr) {
232 // Verifies that we can stream to a listener's underlying stream
233 // too.
234 *listener->stream() << " == " << (x % 2);
235 }
236 return match;
237 }
238
DescribeTo(ostream * os) const239 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
240 };
241
TEST(MatcherInterfaceTest,CanBeImplementedUsingNewAPI)242 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
243 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
244 EXPECT_TRUE(m.Matches(2));
245 EXPECT_FALSE(m.Matches(3));
246 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
247 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
248 }
249
250 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)251 TEST(MatcherTest, CanBeDefaultConstructed) {
252 Matcher<double> m;
253 }
254
255 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)256 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
257 const MatcherInterface<int>* impl = new EvenMatcherImpl;
258 Matcher<int> m(impl);
259 EXPECT_TRUE(m.Matches(4));
260 EXPECT_FALSE(m.Matches(5));
261 }
262
263 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)264 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
265 Matcher<int> m1 = 5;
266 EXPECT_TRUE(m1.Matches(5));
267 EXPECT_FALSE(m1.Matches(6));
268 }
269
270 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)271 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
272 Matcher<int*> m1 = nullptr;
273 EXPECT_TRUE(m1.Matches(nullptr));
274 int n = 0;
275 EXPECT_FALSE(m1.Matches(&n));
276 }
277
278 // Tests that matchers can be constructed from a variable that is not properly
279 // defined. This should be illegal, but many users rely on this accidentally.
280 struct Undefined {
281 virtual ~Undefined() = 0;
282 static const int kInt = 1;
283 };
284
TEST(MatcherTest,CanBeConstructedFromUndefinedVariable)285 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
286 Matcher<int> m1 = Undefined::kInt;
287 EXPECT_TRUE(m1.Matches(1));
288 EXPECT_FALSE(m1.Matches(2));
289 }
290
291 // Test that a matcher parameterized with an abstract class compiles.
TEST(MatcherTest,CanAcceptAbstractClass)292 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
293
294 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)295 TEST(MatcherTest, IsCopyable) {
296 // Tests the copy constructor.
297 Matcher<bool> m1 = Eq(false);
298 EXPECT_TRUE(m1.Matches(false));
299 EXPECT_FALSE(m1.Matches(true));
300
301 // Tests the assignment operator.
302 m1 = Eq(true);
303 EXPECT_TRUE(m1.Matches(true));
304 EXPECT_FALSE(m1.Matches(false));
305 }
306
307 // Tests that Matcher<T>::DescribeTo() calls
308 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)309 TEST(MatcherTest, CanDescribeItself) {
310 EXPECT_EQ("is an even number",
311 Describe(Matcher<int>(new EvenMatcherImpl)));
312 }
313
314 // Tests Matcher<T>::MatchAndExplain().
TEST(MatcherTest,MatchAndExplain)315 TEST(MatcherTest, MatchAndExplain) {
316 Matcher<int> m = GreaterThan(0);
317 StringMatchResultListener listener1;
318 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
319 EXPECT_EQ("which is 42 more than 0", listener1.str());
320
321 StringMatchResultListener listener2;
322 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
323 EXPECT_EQ("which is 9 less than 0", listener2.str());
324 }
325
326 // Tests that a C-string literal can be implicitly converted to a
327 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)328 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
329 Matcher<std::string> m1 = "hi";
330 EXPECT_TRUE(m1.Matches("hi"));
331 EXPECT_FALSE(m1.Matches("hello"));
332
333 Matcher<const std::string&> m2 = "hi";
334 EXPECT_TRUE(m2.Matches("hi"));
335 EXPECT_FALSE(m2.Matches("hello"));
336 }
337
338 // Tests that a string object can be implicitly converted to a
339 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)340 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
341 Matcher<std::string> m1 = std::string("hi");
342 EXPECT_TRUE(m1.Matches("hi"));
343 EXPECT_FALSE(m1.Matches("hello"));
344
345 Matcher<const std::string&> m2 = std::string("hi");
346 EXPECT_TRUE(m2.Matches("hi"));
347 EXPECT_FALSE(m2.Matches("hello"));
348 }
349
350 #if GTEST_HAS_ABSL
351 // Tests that a C-string literal can be implicitly converted to a
352 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)353 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
354 Matcher<absl::string_view> m1 = "cats";
355 EXPECT_TRUE(m1.Matches("cats"));
356 EXPECT_FALSE(m1.Matches("dogs"));
357
358 Matcher<const absl::string_view&> m2 = "cats";
359 EXPECT_TRUE(m2.Matches("cats"));
360 EXPECT_FALSE(m2.Matches("dogs"));
361 }
362
363 // Tests that a std::string object can be implicitly converted to a
364 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromString)365 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
366 Matcher<absl::string_view> m1 = std::string("cats");
367 EXPECT_TRUE(m1.Matches("cats"));
368 EXPECT_FALSE(m1.Matches("dogs"));
369
370 Matcher<const absl::string_view&> m2 = std::string("cats");
371 EXPECT_TRUE(m2.Matches("cats"));
372 EXPECT_FALSE(m2.Matches("dogs"));
373 }
374
375 // Tests that a absl::string_view object can be implicitly converted to a
376 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromStringView)377 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
378 Matcher<absl::string_view> m1 = absl::string_view("cats");
379 EXPECT_TRUE(m1.Matches("cats"));
380 EXPECT_FALSE(m1.Matches("dogs"));
381
382 Matcher<const absl::string_view&> m2 = absl::string_view("cats");
383 EXPECT_TRUE(m2.Matches("cats"));
384 EXPECT_FALSE(m2.Matches("dogs"));
385 }
386 #endif // GTEST_HAS_ABSL
387
388 // Tests that a std::reference_wrapper<std::string> object can be implicitly
389 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromEqReferenceWrapperString)390 TEST(StringMatcherTest,
391 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
392 std::string value = "cats";
393 Matcher<std::string> m1 = Eq(std::ref(value));
394 EXPECT_TRUE(m1.Matches("cats"));
395 EXPECT_FALSE(m1.Matches("dogs"));
396
397 Matcher<const std::string&> m2 = Eq(std::ref(value));
398 EXPECT_TRUE(m2.Matches("cats"));
399 EXPECT_FALSE(m2.Matches("dogs"));
400 }
401
402 // Tests that MakeMatcher() constructs a Matcher<T> from a
403 // MatcherInterface* without requiring the user to explicitly
404 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)405 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
406 const MatcherInterface<int>* dummy_impl = nullptr;
407 Matcher<int> m = MakeMatcher(dummy_impl);
408 }
409
410 // Tests that MakePolymorphicMatcher() can construct a polymorphic
411 // matcher from its implementation using the old API.
412 const int g_bar = 1;
413 class ReferencesBarOrIsZeroImpl {
414 public:
415 template <typename T>
MatchAndExplain(const T & x,MatchResultListener *) const416 bool MatchAndExplain(const T& x,
417 MatchResultListener* /* listener */) const {
418 const void* p = &x;
419 return p == &g_bar || x == 0;
420 }
421
DescribeTo(ostream * os) const422 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
423
DescribeNegationTo(ostream * os) const424 void DescribeNegationTo(ostream* os) const {
425 *os << "doesn't reference g_bar and is not zero";
426 }
427 };
428
429 // This function verifies that MakePolymorphicMatcher() returns a
430 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()431 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
432 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
433 }
434
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingOldAPI)435 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
436 // Using a polymorphic matcher to match a reference type.
437 Matcher<const int&> m1 = ReferencesBarOrIsZero();
438 EXPECT_TRUE(m1.Matches(0));
439 // Verifies that the identity of a by-reference argument is preserved.
440 EXPECT_TRUE(m1.Matches(g_bar));
441 EXPECT_FALSE(m1.Matches(1));
442 EXPECT_EQ("g_bar or zero", Describe(m1));
443
444 // Using a polymorphic matcher to match a value type.
445 Matcher<double> m2 = ReferencesBarOrIsZero();
446 EXPECT_TRUE(m2.Matches(0.0));
447 EXPECT_FALSE(m2.Matches(0.1));
448 EXPECT_EQ("g_bar or zero", Describe(m2));
449 }
450
451 // Tests implementing a polymorphic matcher using MatchAndExplain().
452
453 class PolymorphicIsEvenImpl {
454 public:
DescribeTo(ostream * os) const455 void DescribeTo(ostream* os) const { *os << "is even"; }
456
DescribeNegationTo(ostream * os) const457 void DescribeNegationTo(ostream* os) const {
458 *os << "is odd";
459 }
460
461 template <typename T>
MatchAndExplain(const T & x,MatchResultListener * listener) const462 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
463 // Verifies that we can stream to the listener directly.
464 *listener << "% " << 2;
465 if (listener->stream() != nullptr) {
466 // Verifies that we can stream to the listener's underlying stream
467 // too.
468 *listener->stream() << " == " << (x % 2);
469 }
470 return (x % 2) == 0;
471 }
472 };
473
PolymorphicIsEven()474 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
475 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
476 }
477
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingNewAPI)478 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
479 // Using PolymorphicIsEven() as a Matcher<int>.
480 const Matcher<int> m1 = PolymorphicIsEven();
481 EXPECT_TRUE(m1.Matches(42));
482 EXPECT_FALSE(m1.Matches(43));
483 EXPECT_EQ("is even", Describe(m1));
484
485 const Matcher<int> not_m1 = Not(m1);
486 EXPECT_EQ("is odd", Describe(not_m1));
487
488 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
489
490 // Using PolymorphicIsEven() as a Matcher<char>.
491 const Matcher<char> m2 = PolymorphicIsEven();
492 EXPECT_TRUE(m2.Matches('\x42'));
493 EXPECT_FALSE(m2.Matches('\x43'));
494 EXPECT_EQ("is even", Describe(m2));
495
496 const Matcher<char> not_m2 = Not(m2);
497 EXPECT_EQ("is odd", Describe(not_m2));
498
499 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
500 }
501
502 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest,FromPolymorphicMatcher)503 TEST(MatcherCastTest, FromPolymorphicMatcher) {
504 Matcher<int> m = MatcherCast<int>(Eq(5));
505 EXPECT_TRUE(m.Matches(5));
506 EXPECT_FALSE(m.Matches(6));
507 }
508
509 // For testing casting matchers between compatible types.
510 class IntValue {
511 public:
512 // An int can be statically (although not implicitly) cast to a
513 // IntValue.
IntValue(int a_value)514 explicit IntValue(int a_value) : value_(a_value) {}
515
value() const516 int value() const { return value_; }
517 private:
518 int value_;
519 };
520
521 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)522 bool IsPositiveIntValue(const IntValue& foo) {
523 return foo.value() > 0;
524 }
525
526 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
527 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)528 TEST(MatcherCastTest, FromCompatibleType) {
529 Matcher<double> m1 = Eq(2.0);
530 Matcher<int> m2 = MatcherCast<int>(m1);
531 EXPECT_TRUE(m2.Matches(2));
532 EXPECT_FALSE(m2.Matches(3));
533
534 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
535 Matcher<int> m4 = MatcherCast<int>(m3);
536 // In the following, the arguments 1 and 0 are statically converted
537 // to IntValue objects, and then tested by the IsPositiveIntValue()
538 // predicate.
539 EXPECT_TRUE(m4.Matches(1));
540 EXPECT_FALSE(m4.Matches(0));
541 }
542
543 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)544 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
545 Matcher<const int&> m1 = Eq(0);
546 Matcher<int> m2 = MatcherCast<int>(m1);
547 EXPECT_TRUE(m2.Matches(0));
548 EXPECT_FALSE(m2.Matches(1));
549 }
550
551 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)552 TEST(MatcherCastTest, FromReferenceToNonReference) {
553 Matcher<int&> m1 = Eq(0);
554 Matcher<int> m2 = MatcherCast<int>(m1);
555 EXPECT_TRUE(m2.Matches(0));
556 EXPECT_FALSE(m2.Matches(1));
557 }
558
559 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)560 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
561 Matcher<int> m1 = Eq(0);
562 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
563 EXPECT_TRUE(m2.Matches(0));
564 EXPECT_FALSE(m2.Matches(1));
565 }
566
567 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)568 TEST(MatcherCastTest, FromNonReferenceToReference) {
569 Matcher<int> m1 = Eq(0);
570 Matcher<int&> m2 = MatcherCast<int&>(m1);
571 int n = 0;
572 EXPECT_TRUE(m2.Matches(n));
573 n = 1;
574 EXPECT_FALSE(m2.Matches(n));
575 }
576
577 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)578 TEST(MatcherCastTest, FromSameType) {
579 Matcher<int> m1 = Eq(0);
580 Matcher<int> m2 = MatcherCast<int>(m1);
581 EXPECT_TRUE(m2.Matches(0));
582 EXPECT_FALSE(m2.Matches(1));
583 }
584
585 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
586 // value type of the Matcher.
TEST(MatcherCastTest,FromAValue)587 TEST(MatcherCastTest, FromAValue) {
588 Matcher<int> m = MatcherCast<int>(42);
589 EXPECT_TRUE(m.Matches(42));
590 EXPECT_FALSE(m.Matches(239));
591 }
592
593 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
594 // convertible to the value type of the Matcher.
TEST(MatcherCastTest,FromAnImplicitlyConvertibleValue)595 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
596 const int kExpected = 'c';
597 Matcher<int> m = MatcherCast<int>('c');
598 EXPECT_TRUE(m.Matches(kExpected));
599 EXPECT_FALSE(m.Matches(kExpected + 1));
600 }
601
602 struct NonImplicitlyConstructibleTypeWithOperatorEq {
operator ==(const NonImplicitlyConstructibleTypeWithOperatorEq &,int rhs)603 friend bool operator==(
604 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
605 int rhs) {
606 return 42 == rhs;
607 }
operator ==(int lhs,const NonImplicitlyConstructibleTypeWithOperatorEq &)608 friend bool operator==(
609 int lhs,
610 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
611 return lhs == 42;
612 }
613 };
614
615 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
616 // implicitly convertible to the value type of the Matcher, but the value type
617 // of the matcher has operator==() overload accepting m.
TEST(MatcherCastTest,NonImplicitlyConstructibleTypeWithOperatorEq)618 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
619 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
620 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
621 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
622
623 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
624 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
625 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
626
627 // When updating the following lines please also change the comment to
628 // namespace convertible_from_any.
629 Matcher<int> m3 =
630 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
631 EXPECT_TRUE(m3.Matches(42));
632 EXPECT_FALSE(m3.Matches(239));
633 }
634
635 // ConvertibleFromAny does not work with MSVC. resulting in
636 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
637 // No constructor could take the source type, or constructor overload
638 // resolution was ambiguous
639
640 #if !defined _MSC_VER
641
642 // The below ConvertibleFromAny struct is implicitly constructible from anything
643 // and when in the same namespace can interact with other tests. In particular,
644 // if it is in the same namespace as other tests and one removes
645 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
646 // then the corresponding test still compiles (and it should not!) by implicitly
647 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
648 // in m3.Matcher().
649 namespace convertible_from_any {
650 // Implicitly convertible from any type.
651 struct ConvertibleFromAny {
ConvertibleFromAnytesting::gmock_matchers_test::__anon3596cc380111::convertible_from_any::ConvertibleFromAny652 ConvertibleFromAny(int a_value) : value(a_value) {}
653 template <typename T>
ConvertibleFromAnytesting::gmock_matchers_test::__anon3596cc380111::convertible_from_any::ConvertibleFromAny654 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
655 ADD_FAILURE() << "Conversion constructor called";
656 }
657 int value;
658 };
659
operator ==(const ConvertibleFromAny & a,const ConvertibleFromAny & b)660 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
661 return a.value == b.value;
662 }
663
operator <<(ostream & os,const ConvertibleFromAny & a)664 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
665 return os << a.value;
666 }
667
TEST(MatcherCastTest,ConversionConstructorIsUsed)668 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
669 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
670 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
671 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
672 }
673
TEST(MatcherCastTest,FromConvertibleFromAny)674 TEST(MatcherCastTest, FromConvertibleFromAny) {
675 Matcher<ConvertibleFromAny> m =
676 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
677 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
678 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
679 }
680 } // namespace convertible_from_any
681
682 #endif // !defined _MSC_VER
683
684 struct IntReferenceWrapper {
IntReferenceWrappertesting::gmock_matchers_test::__anon3596cc380111::IntReferenceWrapper685 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
686 const int* value;
687 };
688
operator ==(const IntReferenceWrapper & a,const IntReferenceWrapper & b)689 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
690 return a.value == b.value;
691 }
692
TEST(MatcherCastTest,ValueIsNotCopied)693 TEST(MatcherCastTest, ValueIsNotCopied) {
694 int n = 42;
695 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
696 // Verify that the matcher holds a reference to n, not to its temporary copy.
697 EXPECT_TRUE(m.Matches(n));
698 }
699
700 class Base {
701 public:
~Base()702 virtual ~Base() {}
Base()703 Base() {}
704 private:
705 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
706 };
707
708 class Derived : public Base {
709 public:
Derived()710 Derived() : Base() {}
711 int i;
712 };
713
714 class OtherDerived : public Base {};
715
716 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest,FromPolymorphicMatcher)717 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
718 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
719 EXPECT_TRUE(m2.Matches(' '));
720 EXPECT_FALSE(m2.Matches('\n'));
721 }
722
723 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
724 // T and U are arithmetic types and T can be losslessly converted to
725 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)726 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
727 Matcher<double> m1 = DoubleEq(1.0);
728 Matcher<float> m2 = SafeMatcherCast<float>(m1);
729 EXPECT_TRUE(m2.Matches(1.0f));
730 EXPECT_FALSE(m2.Matches(2.0f));
731
732 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
733 EXPECT_TRUE(m3.Matches('a'));
734 EXPECT_FALSE(m3.Matches('b'));
735 }
736
737 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
738 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)739 TEST(SafeMatcherCastTest, FromBaseClass) {
740 Derived d, d2;
741 Matcher<Base*> m1 = Eq(&d);
742 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
743 EXPECT_TRUE(m2.Matches(&d));
744 EXPECT_FALSE(m2.Matches(&d2));
745
746 Matcher<Base&> m3 = Ref(d);
747 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
748 EXPECT_TRUE(m4.Matches(d));
749 EXPECT_FALSE(m4.Matches(d2));
750 }
751
752 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)753 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
754 int n = 0;
755 Matcher<const int&> m1 = Ref(n);
756 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
757 int n1 = 0;
758 EXPECT_TRUE(m2.Matches(n));
759 EXPECT_FALSE(m2.Matches(n1));
760 }
761
762 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)763 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
764 Matcher<int> m1 = Eq(0);
765 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
766 EXPECT_TRUE(m2.Matches(0));
767 EXPECT_FALSE(m2.Matches(1));
768 }
769
770 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)771 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
772 Matcher<int> m1 = Eq(0);
773 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
774 int n = 0;
775 EXPECT_TRUE(m2.Matches(n));
776 n = 1;
777 EXPECT_FALSE(m2.Matches(n));
778 }
779
780 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)781 TEST(SafeMatcherCastTest, FromSameType) {
782 Matcher<int> m1 = Eq(0);
783 Matcher<int> m2 = SafeMatcherCast<int>(m1);
784 EXPECT_TRUE(m2.Matches(0));
785 EXPECT_FALSE(m2.Matches(1));
786 }
787
788 #if !defined _MSC_VER
789
790 namespace convertible_from_any {
TEST(SafeMatcherCastTest,ConversionConstructorIsUsed)791 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
792 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
793 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
794 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
795 }
796
TEST(SafeMatcherCastTest,FromConvertibleFromAny)797 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
798 Matcher<ConvertibleFromAny> m =
799 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
800 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
801 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
802 }
803 } // namespace convertible_from_any
804
805 #endif // !defined _MSC_VER
806
TEST(SafeMatcherCastTest,ValueIsNotCopied)807 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
808 int n = 42;
809 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
810 // Verify that the matcher holds a reference to n, not to its temporary copy.
811 EXPECT_TRUE(m.Matches(n));
812 }
813
TEST(ExpectThat,TakesLiterals)814 TEST(ExpectThat, TakesLiterals) {
815 EXPECT_THAT(1, 1);
816 EXPECT_THAT(1.0, 1.0);
817 EXPECT_THAT(std::string(), "");
818 }
819
TEST(ExpectThat,TakesFunctions)820 TEST(ExpectThat, TakesFunctions) {
821 struct Helper {
822 static void Func() {}
823 };
824 void (*func)() = Helper::Func;
825 EXPECT_THAT(func, Helper::Func);
826 EXPECT_THAT(func, &Helper::Func);
827 }
828
829 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)830 TEST(ATest, MatchesAnyValue) {
831 // Tests a matcher for a value type.
832 Matcher<double> m1 = A<double>();
833 EXPECT_TRUE(m1.Matches(91.43));
834 EXPECT_TRUE(m1.Matches(-15.32));
835
836 // Tests a matcher for a reference type.
837 int a = 2;
838 int b = -6;
839 Matcher<int&> m2 = A<int&>();
840 EXPECT_TRUE(m2.Matches(a));
841 EXPECT_TRUE(m2.Matches(b));
842 }
843
TEST(ATest,WorksForDerivedClass)844 TEST(ATest, WorksForDerivedClass) {
845 Base base;
846 Derived derived;
847 EXPECT_THAT(&base, A<Base*>());
848 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
849 EXPECT_THAT(&derived, A<Base*>());
850 EXPECT_THAT(&derived, A<Derived*>());
851 }
852
853 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)854 TEST(ATest, CanDescribeSelf) {
855 EXPECT_EQ("is anything", Describe(A<bool>()));
856 }
857
858 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)859 TEST(AnTest, MatchesAnyValue) {
860 // Tests a matcher for a value type.
861 Matcher<int> m1 = An<int>();
862 EXPECT_TRUE(m1.Matches(9143));
863 EXPECT_TRUE(m1.Matches(-1532));
864
865 // Tests a matcher for a reference type.
866 int a = 2;
867 int b = -6;
868 Matcher<int&> m2 = An<int&>();
869 EXPECT_TRUE(m2.Matches(a));
870 EXPECT_TRUE(m2.Matches(b));
871 }
872
873 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)874 TEST(AnTest, CanDescribeSelf) {
875 EXPECT_EQ("is anything", Describe(An<int>()));
876 }
877
878 // Tests that _ can be used as a matcher for any type and matches any
879 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)880 TEST(UnderscoreTest, MatchesAnyValue) {
881 // Uses _ as a matcher for a value type.
882 Matcher<int> m1 = _;
883 EXPECT_TRUE(m1.Matches(123));
884 EXPECT_TRUE(m1.Matches(-242));
885
886 // Uses _ as a matcher for a reference type.
887 bool a = false;
888 const bool b = true;
889 Matcher<const bool&> m2 = _;
890 EXPECT_TRUE(m2.Matches(a));
891 EXPECT_TRUE(m2.Matches(b));
892 }
893
894 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)895 TEST(UnderscoreTest, CanDescribeSelf) {
896 Matcher<int> m = _;
897 EXPECT_EQ("is anything", Describe(m));
898 }
899
900 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)901 TEST(EqTest, MatchesEqualValue) {
902 // 2 C-strings with same content but different addresses.
903 const char a1[] = "hi";
904 const char a2[] = "hi";
905
906 Matcher<const char*> m1 = Eq(a1);
907 EXPECT_TRUE(m1.Matches(a1));
908 EXPECT_FALSE(m1.Matches(a2));
909 }
910
911 // Tests that Eq(v) describes itself properly.
912
913 class Unprintable {
914 public:
Unprintable()915 Unprintable() : c_('a') {}
916
operator ==(const Unprintable &) const917 bool operator==(const Unprintable& /* rhs */) const { return true; }
918 // -Wunused-private-field: dummy accessor for `c_`.
dummy_c()919 char dummy_c() { return c_; }
920 private:
921 char c_;
922 };
923
TEST(EqTest,CanDescribeSelf)924 TEST(EqTest, CanDescribeSelf) {
925 Matcher<Unprintable> m = Eq(Unprintable());
926 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
927 }
928
929 // Tests that Eq(v) can be used to match any type that supports
930 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)931 TEST(EqTest, IsPolymorphic) {
932 Matcher<int> m1 = Eq(1);
933 EXPECT_TRUE(m1.Matches(1));
934 EXPECT_FALSE(m1.Matches(2));
935
936 Matcher<char> m2 = Eq(1);
937 EXPECT_TRUE(m2.Matches('\1'));
938 EXPECT_FALSE(m2.Matches('a'));
939 }
940
941 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)942 TEST(TypedEqTest, ChecksEqualityForGivenType) {
943 Matcher<char> m1 = TypedEq<char>('a');
944 EXPECT_TRUE(m1.Matches('a'));
945 EXPECT_FALSE(m1.Matches('b'));
946
947 Matcher<int> m2 = TypedEq<int>(6);
948 EXPECT_TRUE(m2.Matches(6));
949 EXPECT_FALSE(m2.Matches(7));
950 }
951
952 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)953 TEST(TypedEqTest, CanDescribeSelf) {
954 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
955 }
956
957 // Tests that TypedEq<T>(v) has type Matcher<T>.
958
959 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
960 // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
961 // not T, the compiler will generate a message about "undefined reference".
962 template <typename T>
963 struct Type {
IsTypeOftesting::gmock_matchers_test::__anon3596cc380111::Type964 static bool IsTypeOf(const T& /* v */) { return true; }
965
966 template <typename T2>
967 static void IsTypeOf(T2 v);
968 };
969
TEST(TypedEqTest,HasSpecifiedType)970 TEST(TypedEqTest, HasSpecifiedType) {
971 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
972 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
973 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
974 }
975
976 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)977 TEST(GeTest, ImplementsGreaterThanOrEqual) {
978 Matcher<int> m1 = Ge(0);
979 EXPECT_TRUE(m1.Matches(1));
980 EXPECT_TRUE(m1.Matches(0));
981 EXPECT_FALSE(m1.Matches(-1));
982 }
983
984 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)985 TEST(GeTest, CanDescribeSelf) {
986 Matcher<int> m = Ge(5);
987 EXPECT_EQ("is >= 5", Describe(m));
988 }
989
990 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)991 TEST(GtTest, ImplementsGreaterThan) {
992 Matcher<double> m1 = Gt(0);
993 EXPECT_TRUE(m1.Matches(1.0));
994 EXPECT_FALSE(m1.Matches(0.0));
995 EXPECT_FALSE(m1.Matches(-1.0));
996 }
997
998 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)999 TEST(GtTest, CanDescribeSelf) {
1000 Matcher<int> m = Gt(5);
1001 EXPECT_EQ("is > 5", Describe(m));
1002 }
1003
1004 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)1005 TEST(LeTest, ImplementsLessThanOrEqual) {
1006 Matcher<char> m1 = Le('b');
1007 EXPECT_TRUE(m1.Matches('a'));
1008 EXPECT_TRUE(m1.Matches('b'));
1009 EXPECT_FALSE(m1.Matches('c'));
1010 }
1011
1012 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)1013 TEST(LeTest, CanDescribeSelf) {
1014 Matcher<int> m = Le(5);
1015 EXPECT_EQ("is <= 5", Describe(m));
1016 }
1017
1018 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)1019 TEST(LtTest, ImplementsLessThan) {
1020 Matcher<const std::string&> m1 = Lt("Hello");
1021 EXPECT_TRUE(m1.Matches("Abc"));
1022 EXPECT_FALSE(m1.Matches("Hello"));
1023 EXPECT_FALSE(m1.Matches("Hello, world!"));
1024 }
1025
1026 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)1027 TEST(LtTest, CanDescribeSelf) {
1028 Matcher<int> m = Lt(5);
1029 EXPECT_EQ("is < 5", Describe(m));
1030 }
1031
1032 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)1033 TEST(NeTest, ImplementsNotEqual) {
1034 Matcher<int> m1 = Ne(0);
1035 EXPECT_TRUE(m1.Matches(1));
1036 EXPECT_TRUE(m1.Matches(-1));
1037 EXPECT_FALSE(m1.Matches(0));
1038 }
1039
1040 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)1041 TEST(NeTest, CanDescribeSelf) {
1042 Matcher<int> m = Ne(5);
1043 EXPECT_EQ("isn't equal to 5", Describe(m));
1044 }
1045
1046 class MoveOnly {
1047 public:
MoveOnly(int i)1048 explicit MoveOnly(int i) : i_(i) {}
1049 MoveOnly(const MoveOnly&) = delete;
1050 MoveOnly(MoveOnly&&) = default;
1051 MoveOnly& operator=(const MoveOnly&) = delete;
1052 MoveOnly& operator=(MoveOnly&&) = default;
1053
operator ==(const MoveOnly & other) const1054 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
operator !=(const MoveOnly & other) const1055 bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
operator <(const MoveOnly & other) const1056 bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
operator <=(const MoveOnly & other) const1057 bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
operator >(const MoveOnly & other) const1058 bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
operator >=(const MoveOnly & other) const1059 bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
1060
1061 private:
1062 int i_;
1063 };
1064
1065 struct MoveHelper {
1066 MOCK_METHOD1(Call, void(MoveOnly));
1067 };
1068
TEST(ComparisonBaseTest,WorksWithMoveOnly)1069 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1070 MoveOnly m{0};
1071 MoveHelper helper;
1072
1073 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1074 helper.Call(MoveOnly(0));
1075 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1076 helper.Call(MoveOnly(1));
1077 EXPECT_CALL(helper, Call(Le(ByRef(m))));
1078 helper.Call(MoveOnly(0));
1079 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1080 helper.Call(MoveOnly(-1));
1081 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1082 helper.Call(MoveOnly(0));
1083 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1084 helper.Call(MoveOnly(1));
1085 }
1086
1087 // Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest,MatchesNullPointer)1088 TEST(IsNullTest, MatchesNullPointer) {
1089 Matcher<int*> m1 = IsNull();
1090 int* p1 = nullptr;
1091 int n = 0;
1092 EXPECT_TRUE(m1.Matches(p1));
1093 EXPECT_FALSE(m1.Matches(&n));
1094
1095 Matcher<const char*> m2 = IsNull();
1096 const char* p2 = nullptr;
1097 EXPECT_TRUE(m2.Matches(p2));
1098 EXPECT_FALSE(m2.Matches("hi"));
1099
1100 Matcher<void*> m3 = IsNull();
1101 void* p3 = nullptr;
1102 EXPECT_TRUE(m3.Matches(p3));
1103 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1104 }
1105
TEST(IsNullTest,StdFunction)1106 TEST(IsNullTest, StdFunction) {
1107 const Matcher<std::function<void()>> m = IsNull();
1108
1109 EXPECT_TRUE(m.Matches(std::function<void()>()));
1110 EXPECT_FALSE(m.Matches([]{}));
1111 }
1112
1113 // Tests that IsNull() describes itself properly.
TEST(IsNullTest,CanDescribeSelf)1114 TEST(IsNullTest, CanDescribeSelf) {
1115 Matcher<int*> m = IsNull();
1116 EXPECT_EQ("is NULL", Describe(m));
1117 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1118 }
1119
1120 // Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest,MatchesNonNullPointer)1121 TEST(NotNullTest, MatchesNonNullPointer) {
1122 Matcher<int*> m1 = NotNull();
1123 int* p1 = nullptr;
1124 int n = 0;
1125 EXPECT_FALSE(m1.Matches(p1));
1126 EXPECT_TRUE(m1.Matches(&n));
1127
1128 Matcher<const char*> m2 = NotNull();
1129 const char* p2 = nullptr;
1130 EXPECT_FALSE(m2.Matches(p2));
1131 EXPECT_TRUE(m2.Matches("hi"));
1132 }
1133
TEST(NotNullTest,LinkedPtr)1134 TEST(NotNullTest, LinkedPtr) {
1135 const Matcher<std::shared_ptr<int>> m = NotNull();
1136 const std::shared_ptr<int> null_p;
1137 const std::shared_ptr<int> non_null_p(new int);
1138
1139 EXPECT_FALSE(m.Matches(null_p));
1140 EXPECT_TRUE(m.Matches(non_null_p));
1141 }
1142
TEST(NotNullTest,ReferenceToConstLinkedPtr)1143 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1144 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1145 const std::shared_ptr<double> null_p;
1146 const std::shared_ptr<double> non_null_p(new double);
1147
1148 EXPECT_FALSE(m.Matches(null_p));
1149 EXPECT_TRUE(m.Matches(non_null_p));
1150 }
1151
TEST(NotNullTest,StdFunction)1152 TEST(NotNullTest, StdFunction) {
1153 const Matcher<std::function<void()>> m = NotNull();
1154
1155 EXPECT_TRUE(m.Matches([]{}));
1156 EXPECT_FALSE(m.Matches(std::function<void()>()));
1157 }
1158
1159 // Tests that NotNull() describes itself properly.
TEST(NotNullTest,CanDescribeSelf)1160 TEST(NotNullTest, CanDescribeSelf) {
1161 Matcher<int*> m = NotNull();
1162 EXPECT_EQ("isn't NULL", Describe(m));
1163 }
1164
1165 // Tests that Ref(variable) matches an argument that references
1166 // 'variable'.
TEST(RefTest,MatchesSameVariable)1167 TEST(RefTest, MatchesSameVariable) {
1168 int a = 0;
1169 int b = 0;
1170 Matcher<int&> m = Ref(a);
1171 EXPECT_TRUE(m.Matches(a));
1172 EXPECT_FALSE(m.Matches(b));
1173 }
1174
1175 // Tests that Ref(variable) describes itself properly.
TEST(RefTest,CanDescribeSelf)1176 TEST(RefTest, CanDescribeSelf) {
1177 int n = 5;
1178 Matcher<int&> m = Ref(n);
1179 stringstream ss;
1180 ss << "references the variable @" << &n << " 5";
1181 EXPECT_EQ(ss.str(), Describe(m));
1182 }
1183
1184 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1185 // const reference.
TEST(RefTest,CanBeUsedAsMatcherForConstReference)1186 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1187 int a = 0;
1188 int b = 0;
1189 Matcher<const int&> m = Ref(a);
1190 EXPECT_TRUE(m.Matches(a));
1191 EXPECT_FALSE(m.Matches(b));
1192 }
1193
1194 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1195 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1196 // of Ref(base), but not vice versa.
1197
TEST(RefTest,IsCovariant)1198 TEST(RefTest, IsCovariant) {
1199 Base base, base2;
1200 Derived derived;
1201 Matcher<const Base&> m1 = Ref(base);
1202 EXPECT_TRUE(m1.Matches(base));
1203 EXPECT_FALSE(m1.Matches(base2));
1204 EXPECT_FALSE(m1.Matches(derived));
1205
1206 m1 = Ref(derived);
1207 EXPECT_TRUE(m1.Matches(derived));
1208 EXPECT_FALSE(m1.Matches(base));
1209 EXPECT_FALSE(m1.Matches(base2));
1210 }
1211
TEST(RefTest,ExplainsResult)1212 TEST(RefTest, ExplainsResult) {
1213 int n = 0;
1214 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1215 StartsWith("which is located @"));
1216
1217 int m = 0;
1218 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1219 StartsWith("which is located @"));
1220 }
1221
1222 // Tests string comparison matchers.
1223
TEST(StrEqTest,MatchesEqualString)1224 TEST(StrEqTest, MatchesEqualString) {
1225 Matcher<const char*> m = StrEq(std::string("Hello"));
1226 EXPECT_TRUE(m.Matches("Hello"));
1227 EXPECT_FALSE(m.Matches("hello"));
1228 EXPECT_FALSE(m.Matches(nullptr));
1229
1230 Matcher<const std::string&> m2 = StrEq("Hello");
1231 EXPECT_TRUE(m2.Matches("Hello"));
1232 EXPECT_FALSE(m2.Matches("Hi"));
1233
1234 #if GTEST_HAS_ABSL
1235 Matcher<const absl::string_view&> m3 = StrEq("Hello");
1236 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1237 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1238 EXPECT_FALSE(m3.Matches(absl::string_view()));
1239
1240 Matcher<const absl::string_view&> m_empty = StrEq("");
1241 EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1242 EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1243 EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
1244 #endif // GTEST_HAS_ABSL
1245 }
1246
TEST(StrEqTest,CanDescribeSelf)1247 TEST(StrEqTest, CanDescribeSelf) {
1248 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1249 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1250 Describe(m));
1251
1252 std::string str("01204500800");
1253 str[3] = '\0';
1254 Matcher<std::string> m2 = StrEq(str);
1255 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1256 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1257 Matcher<std::string> m3 = StrEq(str);
1258 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1259 }
1260
TEST(StrNeTest,MatchesUnequalString)1261 TEST(StrNeTest, MatchesUnequalString) {
1262 Matcher<const char*> m = StrNe("Hello");
1263 EXPECT_TRUE(m.Matches(""));
1264 EXPECT_TRUE(m.Matches(nullptr));
1265 EXPECT_FALSE(m.Matches("Hello"));
1266
1267 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1268 EXPECT_TRUE(m2.Matches("hello"));
1269 EXPECT_FALSE(m2.Matches("Hello"));
1270
1271 #if GTEST_HAS_ABSL
1272 Matcher<const absl::string_view> m3 = StrNe("Hello");
1273 EXPECT_TRUE(m3.Matches(absl::string_view("")));
1274 EXPECT_TRUE(m3.Matches(absl::string_view()));
1275 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1276 #endif // GTEST_HAS_ABSL
1277 }
1278
TEST(StrNeTest,CanDescribeSelf)1279 TEST(StrNeTest, CanDescribeSelf) {
1280 Matcher<const char*> m = StrNe("Hi");
1281 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1282 }
1283
TEST(StrCaseEqTest,MatchesEqualStringIgnoringCase)1284 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1285 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1286 EXPECT_TRUE(m.Matches("Hello"));
1287 EXPECT_TRUE(m.Matches("hello"));
1288 EXPECT_FALSE(m.Matches("Hi"));
1289 EXPECT_FALSE(m.Matches(nullptr));
1290
1291 Matcher<const std::string&> m2 = StrCaseEq("Hello");
1292 EXPECT_TRUE(m2.Matches("hello"));
1293 EXPECT_FALSE(m2.Matches("Hi"));
1294
1295 #if GTEST_HAS_ABSL
1296 Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
1297 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1298 EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
1299 EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
1300 EXPECT_FALSE(m3.Matches(absl::string_view()));
1301 #endif // GTEST_HAS_ABSL
1302 }
1303
TEST(StrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1304 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1305 std::string str1("oabocdooeoo");
1306 std::string str2("OABOCDOOEOO");
1307 Matcher<const std::string&> m0 = StrCaseEq(str1);
1308 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1309
1310 str1[3] = str2[3] = '\0';
1311 Matcher<const std::string&> m1 = StrCaseEq(str1);
1312 EXPECT_TRUE(m1.Matches(str2));
1313
1314 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1315 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1316 Matcher<const std::string&> m2 = StrCaseEq(str1);
1317 str1[9] = str2[9] = '\0';
1318 EXPECT_FALSE(m2.Matches(str2));
1319
1320 Matcher<const std::string&> m3 = StrCaseEq(str1);
1321 EXPECT_TRUE(m3.Matches(str2));
1322
1323 EXPECT_FALSE(m3.Matches(str2 + "x"));
1324 str2.append(1, '\0');
1325 EXPECT_FALSE(m3.Matches(str2));
1326 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1327 }
1328
TEST(StrCaseEqTest,CanDescribeSelf)1329 TEST(StrCaseEqTest, CanDescribeSelf) {
1330 Matcher<std::string> m = StrCaseEq("Hi");
1331 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1332 }
1333
TEST(StrCaseNeTest,MatchesUnequalStringIgnoringCase)1334 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1335 Matcher<const char*> m = StrCaseNe("Hello");
1336 EXPECT_TRUE(m.Matches("Hi"));
1337 EXPECT_TRUE(m.Matches(nullptr));
1338 EXPECT_FALSE(m.Matches("Hello"));
1339 EXPECT_FALSE(m.Matches("hello"));
1340
1341 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1342 EXPECT_TRUE(m2.Matches(""));
1343 EXPECT_FALSE(m2.Matches("Hello"));
1344
1345 #if GTEST_HAS_ABSL
1346 Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
1347 EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
1348 EXPECT_TRUE(m3.Matches(absl::string_view()));
1349 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1350 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1351 #endif // GTEST_HAS_ABSL
1352 }
1353
TEST(StrCaseNeTest,CanDescribeSelf)1354 TEST(StrCaseNeTest, CanDescribeSelf) {
1355 Matcher<const char*> m = StrCaseNe("Hi");
1356 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1357 }
1358
1359 // Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest,WorksForStringClasses)1360 TEST(HasSubstrTest, WorksForStringClasses) {
1361 const Matcher<std::string> m1 = HasSubstr("foo");
1362 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1363 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1364
1365 const Matcher<const std::string&> m2 = HasSubstr("foo");
1366 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1367 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1368
1369 const Matcher<std::string> m_empty = HasSubstr("");
1370 EXPECT_TRUE(m_empty.Matches(std::string()));
1371 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1372 }
1373
1374 // Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest,WorksForCStrings)1375 TEST(HasSubstrTest, WorksForCStrings) {
1376 const Matcher<char*> m1 = HasSubstr("foo");
1377 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1378 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1379 EXPECT_FALSE(m1.Matches(nullptr));
1380
1381 const Matcher<const char*> m2 = HasSubstr("foo");
1382 EXPECT_TRUE(m2.Matches("I love food."));
1383 EXPECT_FALSE(m2.Matches("tofo"));
1384 EXPECT_FALSE(m2.Matches(nullptr));
1385
1386 const Matcher<const char*> m_empty = HasSubstr("");
1387 EXPECT_TRUE(m_empty.Matches("not empty"));
1388 EXPECT_TRUE(m_empty.Matches(""));
1389 EXPECT_FALSE(m_empty.Matches(nullptr));
1390 }
1391
1392 #if GTEST_HAS_ABSL
1393 // Tests that HasSubstr() works for matching absl::string_view-typed values.
TEST(HasSubstrTest,WorksForStringViewClasses)1394 TEST(HasSubstrTest, WorksForStringViewClasses) {
1395 const Matcher<absl::string_view> m1 = HasSubstr("foo");
1396 EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
1397 EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
1398 EXPECT_FALSE(m1.Matches(absl::string_view()));
1399
1400 const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
1401 EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
1402 EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
1403 EXPECT_FALSE(m2.Matches(absl::string_view()));
1404
1405 const Matcher<const absl::string_view&> m3 = HasSubstr("");
1406 EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
1407 EXPECT_TRUE(m3.Matches(absl::string_view("")));
1408 EXPECT_TRUE(m3.Matches(absl::string_view()));
1409 }
1410 #endif // GTEST_HAS_ABSL
1411
1412 // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest,CanDescribeSelf)1413 TEST(HasSubstrTest, CanDescribeSelf) {
1414 Matcher<std::string> m = HasSubstr("foo\n\"");
1415 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1416 }
1417
TEST(KeyTest,CanDescribeSelf)1418 TEST(KeyTest, CanDescribeSelf) {
1419 Matcher<const pair<std::string, int>&> m = Key("foo");
1420 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1421 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1422 }
1423
TEST(KeyTest,ExplainsResult)1424 TEST(KeyTest, ExplainsResult) {
1425 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1426 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1427 Explain(m, make_pair(5, true)));
1428 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1429 Explain(m, make_pair(15, true)));
1430 }
1431
TEST(KeyTest,MatchesCorrectly)1432 TEST(KeyTest, MatchesCorrectly) {
1433 pair<int, std::string> p(25, "foo");
1434 EXPECT_THAT(p, Key(25));
1435 EXPECT_THAT(p, Not(Key(42)));
1436 EXPECT_THAT(p, Key(Ge(20)));
1437 EXPECT_THAT(p, Not(Key(Lt(25))));
1438 }
1439
TEST(KeyTest,WorksWithMoveOnly)1440 TEST(KeyTest, WorksWithMoveOnly) {
1441 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1442 EXPECT_THAT(p, Key(Eq(nullptr)));
1443 }
1444
1445 template <size_t I>
1446 struct Tag {};
1447
1448 struct PairWithGet {
1449 int member_1;
1450 std::string member_2;
1451 using first_type = int;
1452 using second_type = std::string;
1453
GetImpltesting::gmock_matchers_test::__anon3596cc380111::PairWithGet1454 const int& GetImpl(Tag<0>) const { return member_1; }
GetImpltesting::gmock_matchers_test::__anon3596cc380111::PairWithGet1455 const std::string& GetImpl(Tag<1>) const { return member_2; }
1456 };
1457 template <size_t I>
get(const PairWithGet & value)1458 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1459 return value.GetImpl(Tag<I>());
1460 }
TEST(PairTest,MatchesPairWithGetCorrectly)1461 TEST(PairTest, MatchesPairWithGetCorrectly) {
1462 PairWithGet p{25, "foo"};
1463 EXPECT_THAT(p, Key(25));
1464 EXPECT_THAT(p, Not(Key(42)));
1465 EXPECT_THAT(p, Key(Ge(20)));
1466 EXPECT_THAT(p, Not(Key(Lt(25))));
1467
1468 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1469 EXPECT_THAT(v, Contains(Key(29)));
1470 }
1471
TEST(KeyTest,SafelyCastsInnerMatcher)1472 TEST(KeyTest, SafelyCastsInnerMatcher) {
1473 Matcher<int> is_positive = Gt(0);
1474 Matcher<int> is_negative = Lt(0);
1475 pair<char, bool> p('a', true);
1476 EXPECT_THAT(p, Key(is_positive));
1477 EXPECT_THAT(p, Not(Key(is_negative)));
1478 }
1479
TEST(KeyTest,InsideContainsUsingMap)1480 TEST(KeyTest, InsideContainsUsingMap) {
1481 map<int, char> container;
1482 container.insert(make_pair(1, 'a'));
1483 container.insert(make_pair(2, 'b'));
1484 container.insert(make_pair(4, 'c'));
1485 EXPECT_THAT(container, Contains(Key(1)));
1486 EXPECT_THAT(container, Not(Contains(Key(3))));
1487 }
1488
TEST(KeyTest,InsideContainsUsingMultimap)1489 TEST(KeyTest, InsideContainsUsingMultimap) {
1490 multimap<int, char> container;
1491 container.insert(make_pair(1, 'a'));
1492 container.insert(make_pair(2, 'b'));
1493 container.insert(make_pair(4, 'c'));
1494
1495 EXPECT_THAT(container, Not(Contains(Key(25))));
1496 container.insert(make_pair(25, 'd'));
1497 EXPECT_THAT(container, Contains(Key(25)));
1498 container.insert(make_pair(25, 'e'));
1499 EXPECT_THAT(container, Contains(Key(25)));
1500
1501 EXPECT_THAT(container, Contains(Key(1)));
1502 EXPECT_THAT(container, Not(Contains(Key(3))));
1503 }
1504
TEST(PairTest,Typing)1505 TEST(PairTest, Typing) {
1506 // Test verifies the following type conversions can be compiled.
1507 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1508 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1509 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1510
1511 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1512 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1513 }
1514
TEST(PairTest,CanDescribeSelf)1515 TEST(PairTest, CanDescribeSelf) {
1516 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1517 EXPECT_EQ("has a first field that is equal to \"foo\""
1518 ", and has a second field that is equal to 42",
1519 Describe(m1));
1520 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1521 ", or has a second field that isn't equal to 42",
1522 DescribeNegation(m1));
1523 // Double and triple negation (1 or 2 times not and description of negation).
1524 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1525 EXPECT_EQ("has a first field that isn't equal to 13"
1526 ", and has a second field that is equal to 42",
1527 DescribeNegation(m2));
1528 }
1529
TEST(PairTest,CanExplainMatchResultTo)1530 TEST(PairTest, CanExplainMatchResultTo) {
1531 // If neither field matches, Pair() should explain about the first
1532 // field.
1533 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1534 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1535 Explain(m, make_pair(-1, -2)));
1536
1537 // If the first field matches but the second doesn't, Pair() should
1538 // explain about the second field.
1539 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1540 Explain(m, make_pair(1, -2)));
1541
1542 // If the first field doesn't match but the second does, Pair()
1543 // should explain about the first field.
1544 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1545 Explain(m, make_pair(-1, 2)));
1546
1547 // If both fields match, Pair() should explain about them both.
1548 EXPECT_EQ("whose both fields match, where the first field is a value "
1549 "which is 1 more than 0, and the second field is a value "
1550 "which is 2 more than 0",
1551 Explain(m, make_pair(1, 2)));
1552
1553 // If only the first match has an explanation, only this explanation should
1554 // be printed.
1555 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1556 EXPECT_EQ("whose both fields match, where the first field is a value "
1557 "which is 1 more than 0",
1558 Explain(explain_first, make_pair(1, 0)));
1559
1560 // If only the second match has an explanation, only this explanation should
1561 // be printed.
1562 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1563 EXPECT_EQ("whose both fields match, where the second field is a value "
1564 "which is 1 more than 0",
1565 Explain(explain_second, make_pair(0, 1)));
1566 }
1567
TEST(PairTest,MatchesCorrectly)1568 TEST(PairTest, MatchesCorrectly) {
1569 pair<int, std::string> p(25, "foo");
1570
1571 // Both fields match.
1572 EXPECT_THAT(p, Pair(25, "foo"));
1573 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1574
1575 // 'first' doesnt' match, but 'second' matches.
1576 EXPECT_THAT(p, Not(Pair(42, "foo")));
1577 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1578
1579 // 'first' matches, but 'second' doesn't match.
1580 EXPECT_THAT(p, Not(Pair(25, "bar")));
1581 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1582
1583 // Neither field matches.
1584 EXPECT_THAT(p, Not(Pair(13, "bar")));
1585 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1586 }
1587
TEST(PairTest,WorksWithMoveOnly)1588 TEST(PairTest, WorksWithMoveOnly) {
1589 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1590 p.second.reset(new int(7));
1591 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1592 }
1593
TEST(PairTest,SafelyCastsInnerMatchers)1594 TEST(PairTest, SafelyCastsInnerMatchers) {
1595 Matcher<int> is_positive = Gt(0);
1596 Matcher<int> is_negative = Lt(0);
1597 pair<char, bool> p('a', true);
1598 EXPECT_THAT(p, Pair(is_positive, _));
1599 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1600 EXPECT_THAT(p, Pair(_, is_positive));
1601 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1602 }
1603
TEST(PairTest,InsideContainsUsingMap)1604 TEST(PairTest, InsideContainsUsingMap) {
1605 map<int, char> container;
1606 container.insert(make_pair(1, 'a'));
1607 container.insert(make_pair(2, 'b'));
1608 container.insert(make_pair(4, 'c'));
1609 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1610 EXPECT_THAT(container, Contains(Pair(1, _)));
1611 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1612 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1613 }
1614
TEST(ContainsTest,WorksWithMoveOnly)1615 TEST(ContainsTest, WorksWithMoveOnly) {
1616 ContainerHelper helper;
1617 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1618 helper.Call(MakeUniquePtrs({1, 2}));
1619 }
1620
TEST(PairTest,UseGetInsteadOfMembers)1621 TEST(PairTest, UseGetInsteadOfMembers) {
1622 PairWithGet pair{7, "ABC"};
1623 EXPECT_THAT(pair, Pair(7, "ABC"));
1624 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1625 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1626
1627 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1628 EXPECT_THAT(v,
1629 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1630 }
1631
1632 // Tests StartsWith(s).
1633
TEST(StartsWithTest,MatchesStringWithGivenPrefix)1634 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1635 const Matcher<const char*> m1 = StartsWith(std::string(""));
1636 EXPECT_TRUE(m1.Matches("Hi"));
1637 EXPECT_TRUE(m1.Matches(""));
1638 EXPECT_FALSE(m1.Matches(nullptr));
1639
1640 const Matcher<const std::string&> m2 = StartsWith("Hi");
1641 EXPECT_TRUE(m2.Matches("Hi"));
1642 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1643 EXPECT_TRUE(m2.Matches("High"));
1644 EXPECT_FALSE(m2.Matches("H"));
1645 EXPECT_FALSE(m2.Matches(" Hi"));
1646
1647 #if GTEST_HAS_ABSL
1648 const Matcher<absl::string_view> m_empty = StartsWith("");
1649 EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1650 EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1651 EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
1652 #endif // GTEST_HAS_ABSL
1653 }
1654
TEST(StartsWithTest,CanDescribeSelf)1655 TEST(StartsWithTest, CanDescribeSelf) {
1656 Matcher<const std::string> m = StartsWith("Hi");
1657 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1658 }
1659
1660 // Tests EndsWith(s).
1661
TEST(EndsWithTest,MatchesStringWithGivenSuffix)1662 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1663 const Matcher<const char*> m1 = EndsWith("");
1664 EXPECT_TRUE(m1.Matches("Hi"));
1665 EXPECT_TRUE(m1.Matches(""));
1666 EXPECT_FALSE(m1.Matches(nullptr));
1667
1668 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1669 EXPECT_TRUE(m2.Matches("Hi"));
1670 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1671 EXPECT_TRUE(m2.Matches("Super Hi"));
1672 EXPECT_FALSE(m2.Matches("i"));
1673 EXPECT_FALSE(m2.Matches("Hi "));
1674
1675 #if GTEST_HAS_ABSL
1676 const Matcher<const absl::string_view&> m4 = EndsWith("");
1677 EXPECT_TRUE(m4.Matches("Hi"));
1678 EXPECT_TRUE(m4.Matches(""));
1679 EXPECT_TRUE(m4.Matches(absl::string_view()));
1680 EXPECT_TRUE(m4.Matches(absl::string_view("")));
1681 #endif // GTEST_HAS_ABSL
1682 }
1683
TEST(EndsWithTest,CanDescribeSelf)1684 TEST(EndsWithTest, CanDescribeSelf) {
1685 Matcher<const std::string> m = EndsWith("Hi");
1686 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1687 }
1688
1689 // Tests MatchesRegex().
1690
TEST(MatchesRegexTest,MatchesStringMatchingGivenRegex)1691 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1692 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1693 EXPECT_TRUE(m1.Matches("az"));
1694 EXPECT_TRUE(m1.Matches("abcz"));
1695 EXPECT_FALSE(m1.Matches(nullptr));
1696
1697 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1698 EXPECT_TRUE(m2.Matches("azbz"));
1699 EXPECT_FALSE(m2.Matches("az1"));
1700 EXPECT_FALSE(m2.Matches("1az"));
1701
1702 #if GTEST_HAS_ABSL
1703 const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
1704 EXPECT_TRUE(m3.Matches(absl::string_view("az")));
1705 EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
1706 EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
1707 EXPECT_FALSE(m3.Matches(absl::string_view()));
1708 const Matcher<const absl::string_view&> m4 = MatchesRegex("");
1709 EXPECT_TRUE(m4.Matches(absl::string_view("")));
1710 EXPECT_TRUE(m4.Matches(absl::string_view()));
1711 #endif // GTEST_HAS_ABSL
1712 }
1713
TEST(MatchesRegexTest,CanDescribeSelf)1714 TEST(MatchesRegexTest, CanDescribeSelf) {
1715 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1716 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1717
1718 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1719 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1720
1721 #if GTEST_HAS_ABSL
1722 Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
1723 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1724 #endif // GTEST_HAS_ABSL
1725 }
1726
1727 // Tests ContainsRegex().
1728
TEST(ContainsRegexTest,MatchesStringContainingGivenRegex)1729 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1730 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1731 EXPECT_TRUE(m1.Matches("az"));
1732 EXPECT_TRUE(m1.Matches("0abcz1"));
1733 EXPECT_FALSE(m1.Matches(nullptr));
1734
1735 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1736 EXPECT_TRUE(m2.Matches("azbz"));
1737 EXPECT_TRUE(m2.Matches("az1"));
1738 EXPECT_FALSE(m2.Matches("1a"));
1739
1740 #if GTEST_HAS_ABSL
1741 const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
1742 EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
1743 EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
1744 EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
1745 EXPECT_FALSE(m3.Matches(absl::string_view()));
1746 const Matcher<const absl::string_view&> m4 = ContainsRegex("");
1747 EXPECT_TRUE(m4.Matches(absl::string_view("")));
1748 EXPECT_TRUE(m4.Matches(absl::string_view()));
1749 #endif // GTEST_HAS_ABSL
1750 }
1751
TEST(ContainsRegexTest,CanDescribeSelf)1752 TEST(ContainsRegexTest, CanDescribeSelf) {
1753 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1754 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1755
1756 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1757 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1758
1759 #if GTEST_HAS_ABSL
1760 Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
1761 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1762 #endif // GTEST_HAS_ABSL
1763 }
1764
1765 // Tests for wide strings.
1766 #if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest,MatchesEqual)1767 TEST(StdWideStrEqTest, MatchesEqual) {
1768 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1769 EXPECT_TRUE(m.Matches(L"Hello"));
1770 EXPECT_FALSE(m.Matches(L"hello"));
1771 EXPECT_FALSE(m.Matches(nullptr));
1772
1773 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1774 EXPECT_TRUE(m2.Matches(L"Hello"));
1775 EXPECT_FALSE(m2.Matches(L"Hi"));
1776
1777 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1778 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1779 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1780
1781 ::std::wstring str(L"01204500800");
1782 str[3] = L'\0';
1783 Matcher<const ::std::wstring&> m4 = StrEq(str);
1784 EXPECT_TRUE(m4.Matches(str));
1785 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1786 Matcher<const ::std::wstring&> m5 = StrEq(str);
1787 EXPECT_TRUE(m5.Matches(str));
1788 }
1789
TEST(StdWideStrEqTest,CanDescribeSelf)1790 TEST(StdWideStrEqTest, CanDescribeSelf) {
1791 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1792 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1793 Describe(m));
1794
1795 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1796 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1797 Describe(m2));
1798
1799 ::std::wstring str(L"01204500800");
1800 str[3] = L'\0';
1801 Matcher<const ::std::wstring&> m4 = StrEq(str);
1802 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1803 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1804 Matcher<const ::std::wstring&> m5 = StrEq(str);
1805 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1806 }
1807
TEST(StdWideStrNeTest,MatchesUnequalString)1808 TEST(StdWideStrNeTest, MatchesUnequalString) {
1809 Matcher<const wchar_t*> m = StrNe(L"Hello");
1810 EXPECT_TRUE(m.Matches(L""));
1811 EXPECT_TRUE(m.Matches(nullptr));
1812 EXPECT_FALSE(m.Matches(L"Hello"));
1813
1814 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1815 EXPECT_TRUE(m2.Matches(L"hello"));
1816 EXPECT_FALSE(m2.Matches(L"Hello"));
1817 }
1818
TEST(StdWideStrNeTest,CanDescribeSelf)1819 TEST(StdWideStrNeTest, CanDescribeSelf) {
1820 Matcher<const wchar_t*> m = StrNe(L"Hi");
1821 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1822 }
1823
TEST(StdWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1824 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1825 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1826 EXPECT_TRUE(m.Matches(L"Hello"));
1827 EXPECT_TRUE(m.Matches(L"hello"));
1828 EXPECT_FALSE(m.Matches(L"Hi"));
1829 EXPECT_FALSE(m.Matches(nullptr));
1830
1831 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1832 EXPECT_TRUE(m2.Matches(L"hello"));
1833 EXPECT_FALSE(m2.Matches(L"Hi"));
1834 }
1835
TEST(StdWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1836 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1837 ::std::wstring str1(L"oabocdooeoo");
1838 ::std::wstring str2(L"OABOCDOOEOO");
1839 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1840 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1841
1842 str1[3] = str2[3] = L'\0';
1843 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1844 EXPECT_TRUE(m1.Matches(str2));
1845
1846 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1847 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1848 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1849 str1[9] = str2[9] = L'\0';
1850 EXPECT_FALSE(m2.Matches(str2));
1851
1852 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1853 EXPECT_TRUE(m3.Matches(str2));
1854
1855 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1856 str2.append(1, L'\0');
1857 EXPECT_FALSE(m3.Matches(str2));
1858 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1859 }
1860
TEST(StdWideStrCaseEqTest,CanDescribeSelf)1861 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1862 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1863 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1864 }
1865
TEST(StdWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1866 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1867 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1868 EXPECT_TRUE(m.Matches(L"Hi"));
1869 EXPECT_TRUE(m.Matches(nullptr));
1870 EXPECT_FALSE(m.Matches(L"Hello"));
1871 EXPECT_FALSE(m.Matches(L"hello"));
1872
1873 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1874 EXPECT_TRUE(m2.Matches(L""));
1875 EXPECT_FALSE(m2.Matches(L"Hello"));
1876 }
1877
TEST(StdWideStrCaseNeTest,CanDescribeSelf)1878 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1879 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1880 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1881 }
1882
1883 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest,WorksForStringClasses)1884 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1885 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1886 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1887 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1888
1889 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1890 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1891 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1892 }
1893
1894 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest,WorksForCStrings)1895 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1896 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1897 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1898 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1899 EXPECT_FALSE(m1.Matches(nullptr));
1900
1901 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1902 EXPECT_TRUE(m2.Matches(L"I love food."));
1903 EXPECT_FALSE(m2.Matches(L"tofo"));
1904 EXPECT_FALSE(m2.Matches(nullptr));
1905 }
1906
1907 // Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest,CanDescribeSelf)1908 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1909 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1910 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1911 }
1912
1913 // Tests StartsWith(s).
1914
TEST(StdWideStartsWithTest,MatchesStringWithGivenPrefix)1915 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1916 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1917 EXPECT_TRUE(m1.Matches(L"Hi"));
1918 EXPECT_TRUE(m1.Matches(L""));
1919 EXPECT_FALSE(m1.Matches(nullptr));
1920
1921 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1922 EXPECT_TRUE(m2.Matches(L"Hi"));
1923 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1924 EXPECT_TRUE(m2.Matches(L"High"));
1925 EXPECT_FALSE(m2.Matches(L"H"));
1926 EXPECT_FALSE(m2.Matches(L" Hi"));
1927 }
1928
TEST(StdWideStartsWithTest,CanDescribeSelf)1929 TEST(StdWideStartsWithTest, CanDescribeSelf) {
1930 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1931 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1932 }
1933
1934 // Tests EndsWith(s).
1935
TEST(StdWideEndsWithTest,MatchesStringWithGivenSuffix)1936 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1937 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1938 EXPECT_TRUE(m1.Matches(L"Hi"));
1939 EXPECT_TRUE(m1.Matches(L""));
1940 EXPECT_FALSE(m1.Matches(nullptr));
1941
1942 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1943 EXPECT_TRUE(m2.Matches(L"Hi"));
1944 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1945 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1946 EXPECT_FALSE(m2.Matches(L"i"));
1947 EXPECT_FALSE(m2.Matches(L"Hi "));
1948 }
1949
TEST(StdWideEndsWithTest,CanDescribeSelf)1950 TEST(StdWideEndsWithTest, CanDescribeSelf) {
1951 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1952 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1953 }
1954
1955 #endif // GTEST_HAS_STD_WSTRING
1956
1957 typedef ::std::tuple<long, int> Tuple2; // NOLINT
1958
1959 // Tests that Eq() matches a 2-tuple where the first field == the
1960 // second field.
TEST(Eq2Test,MatchesEqualArguments)1961 TEST(Eq2Test, MatchesEqualArguments) {
1962 Matcher<const Tuple2&> m = Eq();
1963 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1964 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1965 }
1966
1967 // Tests that Eq() describes itself properly.
TEST(Eq2Test,CanDescribeSelf)1968 TEST(Eq2Test, CanDescribeSelf) {
1969 Matcher<const Tuple2&> m = Eq();
1970 EXPECT_EQ("are an equal pair", Describe(m));
1971 }
1972
1973 // Tests that Ge() matches a 2-tuple where the first field >= the
1974 // second field.
TEST(Ge2Test,MatchesGreaterThanOrEqualArguments)1975 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1976 Matcher<const Tuple2&> m = Ge();
1977 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1978 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1979 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1980 }
1981
1982 // Tests that Ge() describes itself properly.
TEST(Ge2Test,CanDescribeSelf)1983 TEST(Ge2Test, CanDescribeSelf) {
1984 Matcher<const Tuple2&> m = Ge();
1985 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1986 }
1987
1988 // Tests that Gt() matches a 2-tuple where the first field > the
1989 // second field.
TEST(Gt2Test,MatchesGreaterThanArguments)1990 TEST(Gt2Test, MatchesGreaterThanArguments) {
1991 Matcher<const Tuple2&> m = Gt();
1992 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1993 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1994 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1995 }
1996
1997 // Tests that Gt() describes itself properly.
TEST(Gt2Test,CanDescribeSelf)1998 TEST(Gt2Test, CanDescribeSelf) {
1999 Matcher<const Tuple2&> m = Gt();
2000 EXPECT_EQ("are a pair where the first > the second", Describe(m));
2001 }
2002
2003 // Tests that Le() matches a 2-tuple where the first field <= the
2004 // second field.
TEST(Le2Test,MatchesLessThanOrEqualArguments)2005 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2006 Matcher<const Tuple2&> m = Le();
2007 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2008 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2009 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2010 }
2011
2012 // Tests that Le() describes itself properly.
TEST(Le2Test,CanDescribeSelf)2013 TEST(Le2Test, CanDescribeSelf) {
2014 Matcher<const Tuple2&> m = Le();
2015 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2016 }
2017
2018 // Tests that Lt() matches a 2-tuple where the first field < the
2019 // second field.
TEST(Lt2Test,MatchesLessThanArguments)2020 TEST(Lt2Test, MatchesLessThanArguments) {
2021 Matcher<const Tuple2&> m = Lt();
2022 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2023 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2024 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2025 }
2026
2027 // Tests that Lt() describes itself properly.
TEST(Lt2Test,CanDescribeSelf)2028 TEST(Lt2Test, CanDescribeSelf) {
2029 Matcher<const Tuple2&> m = Lt();
2030 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2031 }
2032
2033 // Tests that Ne() matches a 2-tuple where the first field != the
2034 // second field.
TEST(Ne2Test,MatchesUnequalArguments)2035 TEST(Ne2Test, MatchesUnequalArguments) {
2036 Matcher<const Tuple2&> m = Ne();
2037 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2038 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2039 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2040 }
2041
2042 // Tests that Ne() describes itself properly.
TEST(Ne2Test,CanDescribeSelf)2043 TEST(Ne2Test, CanDescribeSelf) {
2044 Matcher<const Tuple2&> m = Ne();
2045 EXPECT_EQ("are an unequal pair", Describe(m));
2046 }
2047
TEST(PairMatchBaseTest,WorksWithMoveOnly)2048 TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2049 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2050 Matcher<Pointers> matcher = Eq();
2051 Pointers pointers;
2052 // Tested values don't matter; the point is that matcher does not copy the
2053 // matched values.
2054 EXPECT_TRUE(matcher.Matches(pointers));
2055 }
2056
2057 // Tests that FloatEq() matches a 2-tuple where
2058 // FloatEq(first field) matches the second field.
TEST(FloatEq2Test,MatchesEqualArguments)2059 TEST(FloatEq2Test, MatchesEqualArguments) {
2060 typedef ::std::tuple<float, float> Tpl;
2061 Matcher<const Tpl&> m = FloatEq();
2062 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2063 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2064 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2065 }
2066
2067 // Tests that FloatEq() describes itself properly.
TEST(FloatEq2Test,CanDescribeSelf)2068 TEST(FloatEq2Test, CanDescribeSelf) {
2069 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2070 EXPECT_EQ("are an almost-equal pair", Describe(m));
2071 }
2072
2073 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2074 // NanSensitiveFloatEq(first field) matches the second field.
TEST(NanSensitiveFloatEqTest,MatchesEqualArgumentsWithNaN)2075 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2076 typedef ::std::tuple<float, float> Tpl;
2077 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2078 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2079 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2080 std::numeric_limits<float>::quiet_NaN())));
2081 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2082 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2083 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2084 }
2085
2086 // Tests that NanSensitiveFloatEq() describes itself properly.
TEST(NanSensitiveFloatEqTest,CanDescribeSelfWithNaNs)2087 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2088 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2089 EXPECT_EQ("are an almost-equal pair", Describe(m));
2090 }
2091
2092 // Tests that DoubleEq() matches a 2-tuple where
2093 // DoubleEq(first field) matches the second field.
TEST(DoubleEq2Test,MatchesEqualArguments)2094 TEST(DoubleEq2Test, MatchesEqualArguments) {
2095 typedef ::std::tuple<double, double> Tpl;
2096 Matcher<const Tpl&> m = DoubleEq();
2097 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2098 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2099 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2100 }
2101
2102 // Tests that DoubleEq() describes itself properly.
TEST(DoubleEq2Test,CanDescribeSelf)2103 TEST(DoubleEq2Test, CanDescribeSelf) {
2104 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2105 EXPECT_EQ("are an almost-equal pair", Describe(m));
2106 }
2107
2108 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2109 // NanSensitiveDoubleEq(first field) matches the second field.
TEST(NanSensitiveDoubleEqTest,MatchesEqualArgumentsWithNaN)2110 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2111 typedef ::std::tuple<double, double> Tpl;
2112 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2113 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2114 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2115 std::numeric_limits<double>::quiet_NaN())));
2116 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2117 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2118 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2119 }
2120
2121 // Tests that DoubleEq() describes itself properly.
TEST(NanSensitiveDoubleEqTest,CanDescribeSelfWithNaNs)2122 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2123 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2124 EXPECT_EQ("are an almost-equal pair", Describe(m));
2125 }
2126
2127 // Tests that FloatEq() matches a 2-tuple where
2128 // FloatNear(first field, max_abs_error) matches the second field.
TEST(FloatNear2Test,MatchesEqualArguments)2129 TEST(FloatNear2Test, MatchesEqualArguments) {
2130 typedef ::std::tuple<float, float> Tpl;
2131 Matcher<const Tpl&> m = FloatNear(0.5f);
2132 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2133 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2134 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2135 }
2136
2137 // Tests that FloatNear() describes itself properly.
TEST(FloatNear2Test,CanDescribeSelf)2138 TEST(FloatNear2Test, CanDescribeSelf) {
2139 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2140 EXPECT_EQ("are an almost-equal pair", Describe(m));
2141 }
2142
2143 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2144 // NanSensitiveFloatNear(first field) matches the second field.
TEST(NanSensitiveFloatNearTest,MatchesNearbyArgumentsWithNaN)2145 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2146 typedef ::std::tuple<float, float> Tpl;
2147 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2148 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2149 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2150 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2151 std::numeric_limits<float>::quiet_NaN())));
2152 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2153 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2154 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2155 }
2156
2157 // Tests that NanSensitiveFloatNear() describes itself properly.
TEST(NanSensitiveFloatNearTest,CanDescribeSelfWithNaNs)2158 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2159 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2160 EXPECT_EQ("are an almost-equal pair", Describe(m));
2161 }
2162
2163 // Tests that FloatEq() matches a 2-tuple where
2164 // DoubleNear(first field, max_abs_error) matches the second field.
TEST(DoubleNear2Test,MatchesEqualArguments)2165 TEST(DoubleNear2Test, MatchesEqualArguments) {
2166 typedef ::std::tuple<double, double> Tpl;
2167 Matcher<const Tpl&> m = DoubleNear(0.5);
2168 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2169 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2170 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2171 }
2172
2173 // Tests that DoubleNear() describes itself properly.
TEST(DoubleNear2Test,CanDescribeSelf)2174 TEST(DoubleNear2Test, CanDescribeSelf) {
2175 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2176 EXPECT_EQ("are an almost-equal pair", Describe(m));
2177 }
2178
2179 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2180 // NanSensitiveDoubleNear(first field) matches the second field.
TEST(NanSensitiveDoubleNearTest,MatchesNearbyArgumentsWithNaN)2181 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2182 typedef ::std::tuple<double, double> Tpl;
2183 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2184 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2185 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2186 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2187 std::numeric_limits<double>::quiet_NaN())));
2188 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2189 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2190 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2191 }
2192
2193 // Tests that NanSensitiveDoubleNear() describes itself properly.
TEST(NanSensitiveDoubleNearTest,CanDescribeSelfWithNaNs)2194 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2195 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2196 EXPECT_EQ("are an almost-equal pair", Describe(m));
2197 }
2198
2199 // Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest,NegatesMatcher)2200 TEST(NotTest, NegatesMatcher) {
2201 Matcher<int> m;
2202 m = Not(Eq(2));
2203 EXPECT_TRUE(m.Matches(3));
2204 EXPECT_FALSE(m.Matches(2));
2205 }
2206
2207 // Tests that Not(m) describes itself properly.
TEST(NotTest,CanDescribeSelf)2208 TEST(NotTest, CanDescribeSelf) {
2209 Matcher<int> m = Not(Eq(5));
2210 EXPECT_EQ("isn't equal to 5", Describe(m));
2211 }
2212
2213 // Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest,NotMatcherSafelyCastsMonomorphicMatchers)2214 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2215 // greater_than_5 is a monomorphic matcher.
2216 Matcher<int> greater_than_5 = Gt(5);
2217
2218 Matcher<const int&> m = Not(greater_than_5);
2219 Matcher<int&> m2 = Not(greater_than_5);
2220 Matcher<int&> m3 = Not(m);
2221 }
2222
2223 // Helper to allow easy testing of AllOf matchers with num parameters.
AllOfMatches(int num,const Matcher<int> & m)2224 void AllOfMatches(int num, const Matcher<int>& m) {
2225 SCOPED_TRACE(Describe(m));
2226 EXPECT_TRUE(m.Matches(0));
2227 for (int i = 1; i <= num; ++i) {
2228 EXPECT_FALSE(m.Matches(i));
2229 }
2230 EXPECT_TRUE(m.Matches(num + 1));
2231 }
2232
2233 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2234 // the given matchers.
TEST(AllOfTest,MatchesWhenAllMatch)2235 TEST(AllOfTest, MatchesWhenAllMatch) {
2236 Matcher<int> m;
2237 m = AllOf(Le(2), Ge(1));
2238 EXPECT_TRUE(m.Matches(1));
2239 EXPECT_TRUE(m.Matches(2));
2240 EXPECT_FALSE(m.Matches(0));
2241 EXPECT_FALSE(m.Matches(3));
2242
2243 m = AllOf(Gt(0), Ne(1), Ne(2));
2244 EXPECT_TRUE(m.Matches(3));
2245 EXPECT_FALSE(m.Matches(2));
2246 EXPECT_FALSE(m.Matches(1));
2247 EXPECT_FALSE(m.Matches(0));
2248
2249 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2250 EXPECT_TRUE(m.Matches(4));
2251 EXPECT_FALSE(m.Matches(3));
2252 EXPECT_FALSE(m.Matches(2));
2253 EXPECT_FALSE(m.Matches(1));
2254 EXPECT_FALSE(m.Matches(0));
2255
2256 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2257 EXPECT_TRUE(m.Matches(0));
2258 EXPECT_TRUE(m.Matches(1));
2259 EXPECT_FALSE(m.Matches(3));
2260
2261 // The following tests for varying number of sub-matchers. Due to the way
2262 // the sub-matchers are handled it is enough to test every sub-matcher once
2263 // with sub-matchers using the same matcher type. Varying matcher types are
2264 // checked for above.
2265 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2266 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2267 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2268 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2269 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2270 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2271 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2272 Ne(8)));
2273 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2274 Ne(8), Ne(9)));
2275 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2276 Ne(9), Ne(10)));
2277 AllOfMatches(
2278 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2279 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2280 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2281 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2282 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2283 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2284 Ne(50)));
2285 }
2286
2287
2288 // Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest,CanDescribeSelf)2289 TEST(AllOfTest, CanDescribeSelf) {
2290 Matcher<int> m;
2291 m = AllOf(Le(2), Ge(1));
2292 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2293
2294 m = AllOf(Gt(0), Ne(1), Ne(2));
2295 std::string expected_descr1 =
2296 "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2297 EXPECT_EQ(expected_descr1, Describe(m));
2298
2299 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2300 std::string expected_descr2 =
2301 "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2302 "to 3)";
2303 EXPECT_EQ(expected_descr2, Describe(m));
2304
2305 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2306 std::string expected_descr3 =
2307 "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2308 "and (isn't equal to 7)";
2309 EXPECT_EQ(expected_descr3, Describe(m));
2310 }
2311
2312 // Tests that AllOf(m1, ..., mn) describes its negation properly.
TEST(AllOfTest,CanDescribeNegation)2313 TEST(AllOfTest, CanDescribeNegation) {
2314 Matcher<int> m;
2315 m = AllOf(Le(2), Ge(1));
2316 std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2317 EXPECT_EQ(expected_descr4, DescribeNegation(m));
2318
2319 m = AllOf(Gt(0), Ne(1), Ne(2));
2320 std::string expected_descr5 =
2321 "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2322 EXPECT_EQ(expected_descr5, DescribeNegation(m));
2323
2324 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2325 std::string expected_descr6 =
2326 "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2327 EXPECT_EQ(expected_descr6, DescribeNegation(m));
2328
2329 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2330 std::string expected_desr7 =
2331 "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2332 "(is equal to 7)";
2333 EXPECT_EQ(expected_desr7, DescribeNegation(m));
2334
2335 m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2336 Ne(10), Ne(11));
2337 AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2338 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2339 AllOfMatches(11, m);
2340 }
2341
2342 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest,AllOfMatcherSafelyCastsMonomorphicMatchers)2343 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2344 // greater_than_5 and less_than_10 are monomorphic matchers.
2345 Matcher<int> greater_than_5 = Gt(5);
2346 Matcher<int> less_than_10 = Lt(10);
2347
2348 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2349 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2350 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2351
2352 // Tests that BothOf works when composing itself.
2353 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2354 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2355 }
2356
TEST(AllOfTest,ExplainsResult)2357 TEST(AllOfTest, ExplainsResult) {
2358 Matcher<int> m;
2359
2360 // Successful match. Both matchers need to explain. The second
2361 // matcher doesn't give an explanation, so only the first matcher's
2362 // explanation is printed.
2363 m = AllOf(GreaterThan(10), Lt(30));
2364 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2365
2366 // Successful match. Both matchers need to explain.
2367 m = AllOf(GreaterThan(10), GreaterThan(20));
2368 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2369 Explain(m, 30));
2370
2371 // Successful match. All matchers need to explain. The second
2372 // matcher doesn't given an explanation.
2373 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2374 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2375 Explain(m, 25));
2376
2377 // Successful match. All matchers need to explain.
2378 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2379 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2380 "and which is 10 more than 30",
2381 Explain(m, 40));
2382
2383 // Failed match. The first matcher, which failed, needs to
2384 // explain.
2385 m = AllOf(GreaterThan(10), GreaterThan(20));
2386 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2387
2388 // Failed match. The second matcher, which failed, needs to
2389 // explain. Since it doesn't given an explanation, nothing is
2390 // printed.
2391 m = AllOf(GreaterThan(10), Lt(30));
2392 EXPECT_EQ("", Explain(m, 40));
2393
2394 // Failed match. The second matcher, which failed, needs to
2395 // explain.
2396 m = AllOf(GreaterThan(10), GreaterThan(20));
2397 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2398 }
2399
2400 // Helper to allow easy testing of AnyOf matchers with num parameters.
AnyOfMatches(int num,const Matcher<int> & m)2401 static void AnyOfMatches(int num, const Matcher<int>& m) {
2402 SCOPED_TRACE(Describe(m));
2403 EXPECT_FALSE(m.Matches(0));
2404 for (int i = 1; i <= num; ++i) {
2405 EXPECT_TRUE(m.Matches(i));
2406 }
2407 EXPECT_FALSE(m.Matches(num + 1));
2408 }
2409
AnyOfStringMatches(int num,const Matcher<std::string> & m)2410 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2411 SCOPED_TRACE(Describe(m));
2412 EXPECT_FALSE(m.Matches(std::to_string(0)));
2413
2414 for (int i = 1; i <= num; ++i) {
2415 EXPECT_TRUE(m.Matches(std::to_string(i)));
2416 }
2417 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2418 }
2419
2420 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2421 // least one of the given matchers.
TEST(AnyOfTest,MatchesWhenAnyMatches)2422 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2423 Matcher<int> m;
2424 m = AnyOf(Le(1), Ge(3));
2425 EXPECT_TRUE(m.Matches(1));
2426 EXPECT_TRUE(m.Matches(4));
2427 EXPECT_FALSE(m.Matches(2));
2428
2429 m = AnyOf(Lt(0), Eq(1), Eq(2));
2430 EXPECT_TRUE(m.Matches(-1));
2431 EXPECT_TRUE(m.Matches(1));
2432 EXPECT_TRUE(m.Matches(2));
2433 EXPECT_FALSE(m.Matches(0));
2434
2435 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2436 EXPECT_TRUE(m.Matches(-1));
2437 EXPECT_TRUE(m.Matches(1));
2438 EXPECT_TRUE(m.Matches(2));
2439 EXPECT_TRUE(m.Matches(3));
2440 EXPECT_FALSE(m.Matches(0));
2441
2442 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2443 EXPECT_TRUE(m.Matches(0));
2444 EXPECT_TRUE(m.Matches(11));
2445 EXPECT_TRUE(m.Matches(3));
2446 EXPECT_FALSE(m.Matches(2));
2447
2448 // The following tests for varying number of sub-matchers. Due to the way
2449 // the sub-matchers are handled it is enough to test every sub-matcher once
2450 // with sub-matchers using the same matcher type. Varying matcher types are
2451 // checked for above.
2452 AnyOfMatches(2, AnyOf(1, 2));
2453 AnyOfMatches(3, AnyOf(1, 2, 3));
2454 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2455 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2456 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2457 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2458 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2459 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2460 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2461 }
2462
2463 // Tests the variadic version of the AnyOfMatcher.
TEST(AnyOfTest,VariadicMatchesWhenAnyMatches)2464 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2465 // Also make sure AnyOf is defined in the right namespace and does not depend
2466 // on ADL.
2467 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2468
2469 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2470 AnyOfMatches(11, m);
2471 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2472 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2473 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2474 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2475 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2476 AnyOfStringMatches(
2477 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2478 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2479 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2480 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2481 "43", "44", "45", "46", "47", "48", "49", "50"));
2482 }
2483
2484 // Tests the variadic version of the ElementsAreMatcher
TEST(ElementsAreTest,HugeMatcher)2485 TEST(ElementsAreTest, HugeMatcher) {
2486 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2487
2488 EXPECT_THAT(test_vector,
2489 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2490 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2491 }
2492
2493 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherStr)2494 TEST(ElementsAreTest, HugeMatcherStr) {
2495 vector<std::string> test_vector{
2496 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2497
2498 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2499 _, _, _, _, _, _));
2500 }
2501
2502 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherUnordered)2503 TEST(ElementsAreTest, HugeMatcherUnordered) {
2504 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2505
2506 EXPECT_THAT(test_vector, UnorderedElementsAre(
2507 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2508 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2509 }
2510
2511
2512 // Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest,CanDescribeSelf)2513 TEST(AnyOfTest, CanDescribeSelf) {
2514 Matcher<int> m;
2515 m = AnyOf(Le(1), Ge(3));
2516
2517 EXPECT_EQ("(is <= 1) or (is >= 3)",
2518 Describe(m));
2519
2520 m = AnyOf(Lt(0), Eq(1), Eq(2));
2521 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
2522
2523 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2524 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
2525 Describe(m));
2526
2527 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2528 EXPECT_EQ(
2529 "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2530 "equal to 7)",
2531 Describe(m));
2532 }
2533
2534 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
TEST(AnyOfTest,CanDescribeNegation)2535 TEST(AnyOfTest, CanDescribeNegation) {
2536 Matcher<int> m;
2537 m = AnyOf(Le(1), Ge(3));
2538 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2539 DescribeNegation(m));
2540
2541 m = AnyOf(Lt(0), Eq(1), Eq(2));
2542 EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
2543 DescribeNegation(m));
2544
2545 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2546 EXPECT_EQ(
2547 "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2548 "equal to 3)",
2549 DescribeNegation(m));
2550
2551 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2552 EXPECT_EQ(
2553 "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2554 "to 5) and (isn't equal to 7)",
2555 DescribeNegation(m));
2556 }
2557
2558 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest,AnyOfMatcherSafelyCastsMonomorphicMatchers)2559 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2560 // greater_than_5 and less_than_10 are monomorphic matchers.
2561 Matcher<int> greater_than_5 = Gt(5);
2562 Matcher<int> less_than_10 = Lt(10);
2563
2564 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2565 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2566 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2567
2568 // Tests that EitherOf works when composing itself.
2569 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2570 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2571 }
2572
TEST(AnyOfTest,ExplainsResult)2573 TEST(AnyOfTest, ExplainsResult) {
2574 Matcher<int> m;
2575
2576 // Failed match. Both matchers need to explain. The second
2577 // matcher doesn't give an explanation, so only the first matcher's
2578 // explanation is printed.
2579 m = AnyOf(GreaterThan(10), Lt(0));
2580 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2581
2582 // Failed match. Both matchers need to explain.
2583 m = AnyOf(GreaterThan(10), GreaterThan(20));
2584 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2585 Explain(m, 5));
2586
2587 // Failed match. All matchers need to explain. The second
2588 // matcher doesn't given an explanation.
2589 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2590 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2591 Explain(m, 5));
2592
2593 // Failed match. All matchers need to explain.
2594 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2595 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2596 "and which is 25 less than 30",
2597 Explain(m, 5));
2598
2599 // Successful match. The first matcher, which succeeded, needs to
2600 // explain.
2601 m = AnyOf(GreaterThan(10), GreaterThan(20));
2602 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2603
2604 // Successful match. The second matcher, which succeeded, needs to
2605 // explain. Since it doesn't given an explanation, nothing is
2606 // printed.
2607 m = AnyOf(GreaterThan(10), Lt(30));
2608 EXPECT_EQ("", Explain(m, 0));
2609
2610 // Successful match. The second matcher, which succeeded, needs to
2611 // explain.
2612 m = AnyOf(GreaterThan(30), GreaterThan(20));
2613 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2614 }
2615
2616 // The following predicate function and predicate functor are for
2617 // testing the Truly(predicate) matcher.
2618
2619 // Returns non-zero if the input is positive. Note that the return
2620 // type of this function is not bool. It's OK as Truly() accepts any
2621 // unary function or functor whose return type can be implicitly
2622 // converted to bool.
IsPositive(double x)2623 int IsPositive(double x) {
2624 return x > 0 ? 1 : 0;
2625 }
2626
2627 // This functor returns true if the input is greater than the given
2628 // number.
2629 class IsGreaterThan {
2630 public:
IsGreaterThan(int threshold)2631 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2632
operator ()(int n) const2633 bool operator()(int n) const { return n > threshold_; }
2634
2635 private:
2636 int threshold_;
2637 };
2638
2639 // For testing Truly().
2640 const int foo = 0;
2641
2642 // This predicate returns true if and only if the argument references foo and
2643 // has a zero value.
ReferencesFooAndIsZero(const int & n)2644 bool ReferencesFooAndIsZero(const int& n) {
2645 return (&n == &foo) && (n == 0);
2646 }
2647
2648 // Tests that Truly(predicate) matches what satisfies the given
2649 // predicate.
TEST(TrulyTest,MatchesWhatSatisfiesThePredicate)2650 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2651 Matcher<double> m = Truly(IsPositive);
2652 EXPECT_TRUE(m.Matches(2.0));
2653 EXPECT_FALSE(m.Matches(-1.5));
2654 }
2655
2656 // Tests that Truly(predicate_functor) works too.
TEST(TrulyTest,CanBeUsedWithFunctor)2657 TEST(TrulyTest, CanBeUsedWithFunctor) {
2658 Matcher<int> m = Truly(IsGreaterThan(5));
2659 EXPECT_TRUE(m.Matches(6));
2660 EXPECT_FALSE(m.Matches(4));
2661 }
2662
2663 // A class that can be implicitly converted to bool.
2664 class ConvertibleToBool {
2665 public:
ConvertibleToBool(int number)2666 explicit ConvertibleToBool(int number) : number_(number) {}
operator bool() const2667 operator bool() const { return number_ != 0; }
2668
2669 private:
2670 int number_;
2671 };
2672
IsNotZero(int number)2673 ConvertibleToBool IsNotZero(int number) {
2674 return ConvertibleToBool(number);
2675 }
2676
2677 // Tests that the predicate used in Truly() may return a class that's
2678 // implicitly convertible to bool, even when the class has no
2679 // operator!().
TEST(TrulyTest,PredicateCanReturnAClassConvertibleToBool)2680 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2681 Matcher<int> m = Truly(IsNotZero);
2682 EXPECT_TRUE(m.Matches(1));
2683 EXPECT_FALSE(m.Matches(0));
2684 }
2685
2686 // Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest,CanDescribeSelf)2687 TEST(TrulyTest, CanDescribeSelf) {
2688 Matcher<double> m = Truly(IsPositive);
2689 EXPECT_EQ("satisfies the given predicate",
2690 Describe(m));
2691 }
2692
2693 // Tests that Truly(predicate) works when the matcher takes its
2694 // argument by reference.
TEST(TrulyTest,WorksForByRefArguments)2695 TEST(TrulyTest, WorksForByRefArguments) {
2696 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2697 EXPECT_TRUE(m.Matches(foo));
2698 int n = 0;
2699 EXPECT_FALSE(m.Matches(n));
2700 }
2701
2702 // Tests that Matches(m) is a predicate satisfied by whatever that
2703 // matches matcher m.
TEST(MatchesTest,IsSatisfiedByWhatMatchesTheMatcher)2704 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2705 EXPECT_TRUE(Matches(Ge(0))(1));
2706 EXPECT_FALSE(Matches(Eq('a'))('b'));
2707 }
2708
2709 // Tests that Matches(m) works when the matcher takes its argument by
2710 // reference.
TEST(MatchesTest,WorksOnByRefArguments)2711 TEST(MatchesTest, WorksOnByRefArguments) {
2712 int m = 0, n = 0;
2713 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2714 EXPECT_FALSE(Matches(Ref(m))(n));
2715 }
2716
2717 // Tests that a Matcher on non-reference type can be used in
2718 // Matches().
TEST(MatchesTest,WorksWithMatcherOnNonRefType)2719 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2720 Matcher<int> eq5 = Eq(5);
2721 EXPECT_TRUE(Matches(eq5)(5));
2722 EXPECT_FALSE(Matches(eq5)(2));
2723 }
2724
2725 // Tests Value(value, matcher). Since Value() is a simple wrapper for
2726 // Matches(), which has been tested already, we don't spend a lot of
2727 // effort on testing Value().
TEST(ValueTest,WorksWithPolymorphicMatcher)2728 TEST(ValueTest, WorksWithPolymorphicMatcher) {
2729 EXPECT_TRUE(Value("hi", StartsWith("h")));
2730 EXPECT_FALSE(Value(5, Gt(10)));
2731 }
2732
TEST(ValueTest,WorksWithMonomorphicMatcher)2733 TEST(ValueTest, WorksWithMonomorphicMatcher) {
2734 const Matcher<int> is_zero = Eq(0);
2735 EXPECT_TRUE(Value(0, is_zero));
2736 EXPECT_FALSE(Value('a', is_zero));
2737
2738 int n = 0;
2739 const Matcher<const int&> ref_n = Ref(n);
2740 EXPECT_TRUE(Value(n, ref_n));
2741 EXPECT_FALSE(Value(1, ref_n));
2742 }
2743
TEST(ExplainMatchResultTest,WorksWithPolymorphicMatcher)2744 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2745 StringMatchResultListener listener1;
2746 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2747 EXPECT_EQ("% 2 == 0", listener1.str());
2748
2749 StringMatchResultListener listener2;
2750 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2751 EXPECT_EQ("", listener2.str());
2752 }
2753
TEST(ExplainMatchResultTest,WorksWithMonomorphicMatcher)2754 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2755 const Matcher<int> is_even = PolymorphicIsEven();
2756 StringMatchResultListener listener1;
2757 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2758 EXPECT_EQ("% 2 == 0", listener1.str());
2759
2760 const Matcher<const double&> is_zero = Eq(0);
2761 StringMatchResultListener listener2;
2762 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2763 EXPECT_EQ("", listener2.str());
2764 }
2765
2766 MATCHER_P(Really, inner_matcher, "") {
2767 return ExplainMatchResult(inner_matcher, arg, result_listener);
2768 }
2769
TEST(ExplainMatchResultTest,WorksInsideMATCHER)2770 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2771 EXPECT_THAT(0, Really(Eq(0)));
2772 }
2773
TEST(DescribeMatcherTest,WorksWithValue)2774 TEST(DescribeMatcherTest, WorksWithValue) {
2775 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
2776 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
2777 }
2778
TEST(DescribeMatcherTest,WorksWithMonomorphicMatcher)2779 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
2780 const Matcher<int> monomorphic = Le(0);
2781 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
2782 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
2783 }
2784
TEST(DescribeMatcherTest,WorksWithPolymorphicMatcher)2785 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
2786 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
2787 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
2788 }
2789
TEST(AllArgsTest,WorksForTuple)2790 TEST(AllArgsTest, WorksForTuple) {
2791 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
2792 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
2793 }
2794
TEST(AllArgsTest,WorksForNonTuple)2795 TEST(AllArgsTest, WorksForNonTuple) {
2796 EXPECT_THAT(42, AllArgs(Gt(0)));
2797 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2798 }
2799
2800 class AllArgsHelper {
2801 public:
AllArgsHelper()2802 AllArgsHelper() {}
2803
2804 MOCK_METHOD2(Helper, int(char x, int y));
2805
2806 private:
2807 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2808 };
2809
TEST(AllArgsTest,WorksInWithClause)2810 TEST(AllArgsTest, WorksInWithClause) {
2811 AllArgsHelper helper;
2812 ON_CALL(helper, Helper(_, _))
2813 .With(AllArgs(Lt()))
2814 .WillByDefault(Return(1));
2815 EXPECT_CALL(helper, Helper(_, _));
2816 EXPECT_CALL(helper, Helper(_, _))
2817 .With(AllArgs(Gt()))
2818 .WillOnce(Return(2));
2819
2820 EXPECT_EQ(1, helper.Helper('\1', 2));
2821 EXPECT_EQ(2, helper.Helper('a', 1));
2822 }
2823
2824 class OptionalMatchersHelper {
2825 public:
OptionalMatchersHelper()2826 OptionalMatchersHelper() {}
2827
2828 MOCK_METHOD0(NoArgs, int());
2829
2830 MOCK_METHOD1(OneArg, int(int y));
2831
2832 MOCK_METHOD2(TwoArgs, int(char x, int y));
2833
2834 MOCK_METHOD1(Overloaded, int(char x));
2835 MOCK_METHOD2(Overloaded, int(char x, int y));
2836
2837 private:
2838 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
2839 };
2840
TEST(AllArgsTest,WorksWithoutMatchers)2841 TEST(AllArgsTest, WorksWithoutMatchers) {
2842 OptionalMatchersHelper helper;
2843
2844 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
2845 ON_CALL(helper, OneArg).WillByDefault(Return(20));
2846 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
2847
2848 EXPECT_EQ(10, helper.NoArgs());
2849 EXPECT_EQ(20, helper.OneArg(1));
2850 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
2851
2852 EXPECT_CALL(helper, NoArgs).Times(1);
2853 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
2854 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
2855 EXPECT_CALL(helper, TwoArgs).Times(0);
2856
2857 EXPECT_EQ(10, helper.NoArgs());
2858 EXPECT_EQ(100, helper.OneArg(1));
2859 EXPECT_EQ(200, helper.OneArg(17));
2860 }
2861
2862 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2863 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)2864 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2865 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2866 ASSERT_THAT("Foo", EndsWith("oo"));
2867 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2868 EXPECT_THAT("Hello", StartsWith("Hell"));
2869 }
2870
2871 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2872 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)2873 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2874 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2875 // which cannot reference auto variables.
2876 static unsigned short n; // NOLINT
2877 n = 5;
2878
2879 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2880 // functions declared in the namespace scope from within nested classes.
2881 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2882 // namespace-level functions invoked inside them need to be explicitly
2883 // resolved.
2884 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
2885 "Value of: n\n"
2886 "Expected: is > 10\n"
2887 " Actual: 5" + OfType("unsigned short"));
2888 n = 0;
2889 EXPECT_NONFATAL_FAILURE(
2890 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2891 "Value of: n\n"
2892 "Expected: (is <= 7) and (is >= 5)\n"
2893 " Actual: 0" + OfType("unsigned short"));
2894 }
2895
2896 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2897 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)2898 TEST(MatcherAssertionTest, WorksForByRefArguments) {
2899 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2900 // reference auto variables.
2901 static int n;
2902 n = 0;
2903 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
2904 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2905 "Value of: n\n"
2906 "Expected: does not reference the variable @");
2907 // Tests the "Actual" part.
2908 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2909 "Actual: 0" + OfType("int") + ", which is located @");
2910 }
2911
2912 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2913 // monomorphic.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)2914 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2915 Matcher<const char*> starts_with_he = StartsWith("he");
2916 ASSERT_THAT("hello", starts_with_he);
2917
2918 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
2919 ASSERT_THAT("book", ends_with_ok);
2920 const std::string bad = "bad";
2921 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2922 "Value of: bad\n"
2923 "Expected: ends with \"ok\"\n"
2924 " Actual: \"bad\"");
2925 Matcher<int> is_greater_than_5 = Gt(5);
2926 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2927 "Value of: 5\n"
2928 "Expected: is > 5\n"
2929 " Actual: 5" + OfType("int"));
2930 }
2931
2932 // Tests floating-point matchers.
2933 template <typename RawType>
2934 class FloatingPointTest : public testing::Test {
2935 protected:
2936 typedef testing::internal::FloatingPoint<RawType> Floating;
2937 typedef typename Floating::Bits Bits;
2938
FloatingPointTest()2939 FloatingPointTest()
2940 : max_ulps_(Floating::kMaxUlps),
2941 zero_bits_(Floating(0).bits()),
2942 one_bits_(Floating(1).bits()),
2943 infinity_bits_(Floating(Floating::Infinity()).bits()),
2944 close_to_positive_zero_(
2945 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2946 close_to_negative_zero_(
2947 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2948 further_from_negative_zero_(-Floating::ReinterpretBits(
2949 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2950 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2951 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2952 infinity_(Floating::Infinity()),
2953 close_to_infinity_(
2954 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2955 further_from_infinity_(
2956 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2957 max_(Floating::Max()),
2958 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2959 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
2960 }
2961
TestSize()2962 void TestSize() {
2963 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2964 }
2965
2966 // A battery of tests for FloatingEqMatcher::Matches.
2967 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType))2968 void TestMatches(
2969 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2970 Matcher<RawType> m1 = matcher_maker(0.0);
2971 EXPECT_TRUE(m1.Matches(-0.0));
2972 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2973 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2974 EXPECT_FALSE(m1.Matches(1.0));
2975
2976 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2977 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2978
2979 Matcher<RawType> m3 = matcher_maker(1.0);
2980 EXPECT_TRUE(m3.Matches(close_to_one_));
2981 EXPECT_FALSE(m3.Matches(further_from_one_));
2982
2983 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2984 EXPECT_FALSE(m3.Matches(0.0));
2985
2986 Matcher<RawType> m4 = matcher_maker(-infinity_);
2987 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2988
2989 Matcher<RawType> m5 = matcher_maker(infinity_);
2990 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2991
2992 // This is interesting as the representations of infinity_ and nan1_
2993 // are only 1 DLP apart.
2994 EXPECT_FALSE(m5.Matches(nan1_));
2995
2996 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2997 // some cases.
2998 Matcher<const RawType&> m6 = matcher_maker(0.0);
2999 EXPECT_TRUE(m6.Matches(-0.0));
3000 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3001 EXPECT_FALSE(m6.Matches(1.0));
3002
3003 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3004 // cases.
3005 Matcher<RawType&> m7 = matcher_maker(0.0);
3006 RawType x = 0.0;
3007 EXPECT_TRUE(m7.Matches(x));
3008 x = 0.01f;
3009 EXPECT_FALSE(m7.Matches(x));
3010 }
3011
3012 // Pre-calculated numbers to be used by the tests.
3013
3014 const Bits max_ulps_;
3015
3016 const Bits zero_bits_; // The bits that represent 0.0.
3017 const Bits one_bits_; // The bits that represent 1.0.
3018 const Bits infinity_bits_; // The bits that represent +infinity.
3019
3020 // Some numbers close to 0.0.
3021 const RawType close_to_positive_zero_;
3022 const RawType close_to_negative_zero_;
3023 const RawType further_from_negative_zero_;
3024
3025 // Some numbers close to 1.0.
3026 const RawType close_to_one_;
3027 const RawType further_from_one_;
3028
3029 // Some numbers close to +infinity.
3030 const RawType infinity_;
3031 const RawType close_to_infinity_;
3032 const RawType further_from_infinity_;
3033
3034 // Maximum representable value that's not infinity.
3035 const RawType max_;
3036
3037 // Some NaNs.
3038 const RawType nan1_;
3039 const RawType nan2_;
3040 };
3041
3042 // Tests floating-point matchers with fixed epsilons.
3043 template <typename RawType>
3044 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3045 protected:
3046 typedef FloatingPointTest<RawType> ParentType;
3047
3048 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3049 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestNearMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType,RawType))3050 void TestNearMatches(
3051 testing::internal::FloatingEqMatcher<RawType>
3052 (*matcher_maker)(RawType, RawType)) {
3053 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3054 EXPECT_TRUE(m1.Matches(0.0));
3055 EXPECT_TRUE(m1.Matches(-0.0));
3056 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3057 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3058 EXPECT_FALSE(m1.Matches(1.0));
3059
3060 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3061 EXPECT_TRUE(m2.Matches(0.0));
3062 EXPECT_TRUE(m2.Matches(-0.0));
3063 EXPECT_TRUE(m2.Matches(1.0));
3064 EXPECT_TRUE(m2.Matches(-1.0));
3065 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3066 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3067
3068 // Check that inf matches inf, regardless of the of the specified max
3069 // absolute error.
3070 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3071 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3072 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3073 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3074
3075 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3076 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3077 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3078 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3079
3080 // Test various overflow scenarios.
3081 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3082 EXPECT_TRUE(m5.Matches(ParentType::max_));
3083 EXPECT_FALSE(m5.Matches(-ParentType::max_));
3084
3085 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3086 EXPECT_FALSE(m6.Matches(ParentType::max_));
3087 EXPECT_TRUE(m6.Matches(-ParentType::max_));
3088
3089 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3090 EXPECT_TRUE(m7.Matches(ParentType::max_));
3091 EXPECT_FALSE(m7.Matches(-ParentType::max_));
3092
3093 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3094 EXPECT_FALSE(m8.Matches(ParentType::max_));
3095 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3096
3097 // The difference between max() and -max() normally overflows to infinity,
3098 // but it should still match if the max_abs_error is also infinity.
3099 Matcher<RawType> m9 = matcher_maker(
3100 ParentType::max_, ParentType::infinity_);
3101 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3102
3103 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3104 // some cases.
3105 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3106 EXPECT_TRUE(m10.Matches(-0.0));
3107 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3108 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3109
3110 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3111 // cases.
3112 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3113 RawType x = 0.0;
3114 EXPECT_TRUE(m11.Matches(x));
3115 x = 1.0f;
3116 EXPECT_TRUE(m11.Matches(x));
3117 x = -1.0f;
3118 EXPECT_TRUE(m11.Matches(x));
3119 x = 1.1f;
3120 EXPECT_FALSE(m11.Matches(x));
3121 x = -1.1f;
3122 EXPECT_FALSE(m11.Matches(x));
3123 }
3124 };
3125
3126 // Instantiate FloatingPointTest for testing floats.
3127 typedef FloatingPointTest<float> FloatTest;
3128
TEST_F(FloatTest,FloatEqApproximatelyMatchesFloats)3129 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3130 TestMatches(&FloatEq);
3131 }
3132
TEST_F(FloatTest,NanSensitiveFloatEqApproximatelyMatchesFloats)3133 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3134 TestMatches(&NanSensitiveFloatEq);
3135 }
3136
TEST_F(FloatTest,FloatEqCannotMatchNaN)3137 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3138 // FloatEq never matches NaN.
3139 Matcher<float> m = FloatEq(nan1_);
3140 EXPECT_FALSE(m.Matches(nan1_));
3141 EXPECT_FALSE(m.Matches(nan2_));
3142 EXPECT_FALSE(m.Matches(1.0));
3143 }
3144
TEST_F(FloatTest,NanSensitiveFloatEqCanMatchNaN)3145 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3146 // NanSensitiveFloatEq will match NaN.
3147 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3148 EXPECT_TRUE(m.Matches(nan1_));
3149 EXPECT_TRUE(m.Matches(nan2_));
3150 EXPECT_FALSE(m.Matches(1.0));
3151 }
3152
TEST_F(FloatTest,FloatEqCanDescribeSelf)3153 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3154 Matcher<float> m1 = FloatEq(2.0f);
3155 EXPECT_EQ("is approximately 2", Describe(m1));
3156 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3157
3158 Matcher<float> m2 = FloatEq(0.5f);
3159 EXPECT_EQ("is approximately 0.5", Describe(m2));
3160 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3161
3162 Matcher<float> m3 = FloatEq(nan1_);
3163 EXPECT_EQ("never matches", Describe(m3));
3164 EXPECT_EQ("is anything", DescribeNegation(m3));
3165 }
3166
TEST_F(FloatTest,NanSensitiveFloatEqCanDescribeSelf)3167 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3168 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3169 EXPECT_EQ("is approximately 2", Describe(m1));
3170 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3171
3172 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3173 EXPECT_EQ("is approximately 0.5", Describe(m2));
3174 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3175
3176 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3177 EXPECT_EQ("is NaN", Describe(m3));
3178 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3179 }
3180
3181 // Instantiate FloatingPointTest for testing floats with a user-specified
3182 // max absolute error.
3183 typedef FloatingPointNearTest<float> FloatNearTest;
3184
TEST_F(FloatNearTest,FloatNearMatches)3185 TEST_F(FloatNearTest, FloatNearMatches) {
3186 TestNearMatches(&FloatNear);
3187 }
3188
TEST_F(FloatNearTest,NanSensitiveFloatNearApproximatelyMatchesFloats)3189 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3190 TestNearMatches(&NanSensitiveFloatNear);
3191 }
3192
TEST_F(FloatNearTest,FloatNearCanDescribeSelf)3193 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3194 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3195 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3196 EXPECT_EQ(
3197 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3198
3199 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3200 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3201 EXPECT_EQ(
3202 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3203
3204 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3205 EXPECT_EQ("never matches", Describe(m3));
3206 EXPECT_EQ("is anything", DescribeNegation(m3));
3207 }
3208
TEST_F(FloatNearTest,NanSensitiveFloatNearCanDescribeSelf)3209 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3210 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3211 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3212 EXPECT_EQ(
3213 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3214
3215 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3216 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3217 EXPECT_EQ(
3218 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3219
3220 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3221 EXPECT_EQ("is NaN", Describe(m3));
3222 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3223 }
3224
TEST_F(FloatNearTest,FloatNearCannotMatchNaN)3225 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3226 // FloatNear never matches NaN.
3227 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3228 EXPECT_FALSE(m.Matches(nan1_));
3229 EXPECT_FALSE(m.Matches(nan2_));
3230 EXPECT_FALSE(m.Matches(1.0));
3231 }
3232
TEST_F(FloatNearTest,NanSensitiveFloatNearCanMatchNaN)3233 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3234 // NanSensitiveFloatNear will match NaN.
3235 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3236 EXPECT_TRUE(m.Matches(nan1_));
3237 EXPECT_TRUE(m.Matches(nan2_));
3238 EXPECT_FALSE(m.Matches(1.0));
3239 }
3240
3241 // Instantiate FloatingPointTest for testing doubles.
3242 typedef FloatingPointTest<double> DoubleTest;
3243
TEST_F(DoubleTest,DoubleEqApproximatelyMatchesDoubles)3244 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3245 TestMatches(&DoubleEq);
3246 }
3247
TEST_F(DoubleTest,NanSensitiveDoubleEqApproximatelyMatchesDoubles)3248 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3249 TestMatches(&NanSensitiveDoubleEq);
3250 }
3251
TEST_F(DoubleTest,DoubleEqCannotMatchNaN)3252 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3253 // DoubleEq never matches NaN.
3254 Matcher<double> m = DoubleEq(nan1_);
3255 EXPECT_FALSE(m.Matches(nan1_));
3256 EXPECT_FALSE(m.Matches(nan2_));
3257 EXPECT_FALSE(m.Matches(1.0));
3258 }
3259
TEST_F(DoubleTest,NanSensitiveDoubleEqCanMatchNaN)3260 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3261 // NanSensitiveDoubleEq will match NaN.
3262 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3263 EXPECT_TRUE(m.Matches(nan1_));
3264 EXPECT_TRUE(m.Matches(nan2_));
3265 EXPECT_FALSE(m.Matches(1.0));
3266 }
3267
TEST_F(DoubleTest,DoubleEqCanDescribeSelf)3268 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3269 Matcher<double> m1 = DoubleEq(2.0);
3270 EXPECT_EQ("is approximately 2", Describe(m1));
3271 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3272
3273 Matcher<double> m2 = DoubleEq(0.5);
3274 EXPECT_EQ("is approximately 0.5", Describe(m2));
3275 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3276
3277 Matcher<double> m3 = DoubleEq(nan1_);
3278 EXPECT_EQ("never matches", Describe(m3));
3279 EXPECT_EQ("is anything", DescribeNegation(m3));
3280 }
3281
TEST_F(DoubleTest,NanSensitiveDoubleEqCanDescribeSelf)3282 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3283 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3284 EXPECT_EQ("is approximately 2", Describe(m1));
3285 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3286
3287 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3288 EXPECT_EQ("is approximately 0.5", Describe(m2));
3289 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3290
3291 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3292 EXPECT_EQ("is NaN", Describe(m3));
3293 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3294 }
3295
3296 // Instantiate FloatingPointTest for testing floats with a user-specified
3297 // max absolute error.
3298 typedef FloatingPointNearTest<double> DoubleNearTest;
3299
TEST_F(DoubleNearTest,DoubleNearMatches)3300 TEST_F(DoubleNearTest, DoubleNearMatches) {
3301 TestNearMatches(&DoubleNear);
3302 }
3303
TEST_F(DoubleNearTest,NanSensitiveDoubleNearApproximatelyMatchesDoubles)3304 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3305 TestNearMatches(&NanSensitiveDoubleNear);
3306 }
3307
TEST_F(DoubleNearTest,DoubleNearCanDescribeSelf)3308 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3309 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3310 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3311 EXPECT_EQ(
3312 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3313
3314 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3315 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3316 EXPECT_EQ(
3317 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3318
3319 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3320 EXPECT_EQ("never matches", Describe(m3));
3321 EXPECT_EQ("is anything", DescribeNegation(m3));
3322 }
3323
TEST_F(DoubleNearTest,ExplainsResultWhenMatchFails)3324 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3325 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3326 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3327 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3328
3329 const std::string explanation =
3330 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3331 // Different C++ implementations may print floating-point numbers
3332 // slightly differently.
3333 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3334 explanation == "which is 1.2e-010 from 2.1") // MSVC
3335 << " where explanation is \"" << explanation << "\".";
3336 }
3337
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanDescribeSelf)3338 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3339 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3340 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3341 EXPECT_EQ(
3342 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3343
3344 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3345 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3346 EXPECT_EQ(
3347 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3348
3349 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3350 EXPECT_EQ("is NaN", Describe(m3));
3351 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3352 }
3353
TEST_F(DoubleNearTest,DoubleNearCannotMatchNaN)3354 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3355 // DoubleNear never matches NaN.
3356 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3357 EXPECT_FALSE(m.Matches(nan1_));
3358 EXPECT_FALSE(m.Matches(nan2_));
3359 EXPECT_FALSE(m.Matches(1.0));
3360 }
3361
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanMatchNaN)3362 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3363 // NanSensitiveDoubleNear will match NaN.
3364 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3365 EXPECT_TRUE(m.Matches(nan1_));
3366 EXPECT_TRUE(m.Matches(nan2_));
3367 EXPECT_FALSE(m.Matches(1.0));
3368 }
3369
TEST(PointeeTest,RawPointer)3370 TEST(PointeeTest, RawPointer) {
3371 const Matcher<int*> m = Pointee(Ge(0));
3372
3373 int n = 1;
3374 EXPECT_TRUE(m.Matches(&n));
3375 n = -1;
3376 EXPECT_FALSE(m.Matches(&n));
3377 EXPECT_FALSE(m.Matches(nullptr));
3378 }
3379
TEST(PointeeTest,RawPointerToConst)3380 TEST(PointeeTest, RawPointerToConst) {
3381 const Matcher<const double*> m = Pointee(Ge(0));
3382
3383 double x = 1;
3384 EXPECT_TRUE(m.Matches(&x));
3385 x = -1;
3386 EXPECT_FALSE(m.Matches(&x));
3387 EXPECT_FALSE(m.Matches(nullptr));
3388 }
3389
TEST(PointeeTest,ReferenceToConstRawPointer)3390 TEST(PointeeTest, ReferenceToConstRawPointer) {
3391 const Matcher<int* const &> m = Pointee(Ge(0));
3392
3393 int n = 1;
3394 EXPECT_TRUE(m.Matches(&n));
3395 n = -1;
3396 EXPECT_FALSE(m.Matches(&n));
3397 EXPECT_FALSE(m.Matches(nullptr));
3398 }
3399
TEST(PointeeTest,ReferenceToNonConstRawPointer)3400 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3401 const Matcher<double* &> m = Pointee(Ge(0));
3402
3403 double x = 1.0;
3404 double* p = &x;
3405 EXPECT_TRUE(m.Matches(p));
3406 x = -1;
3407 EXPECT_FALSE(m.Matches(p));
3408 p = nullptr;
3409 EXPECT_FALSE(m.Matches(p));
3410 }
3411
3412 MATCHER_P(FieldIIs, inner_matcher, "") {
3413 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3414 }
3415
3416 #if GTEST_HAS_RTTI
TEST(WhenDynamicCastToTest,SameType)3417 TEST(WhenDynamicCastToTest, SameType) {
3418 Derived derived;
3419 derived.i = 4;
3420
3421 // Right type. A pointer is passed down.
3422 Base* as_base_ptr = &derived;
3423 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3424 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3425 EXPECT_THAT(as_base_ptr,
3426 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3427 }
3428
TEST(WhenDynamicCastToTest,WrongTypes)3429 TEST(WhenDynamicCastToTest, WrongTypes) {
3430 Base base;
3431 Derived derived;
3432 OtherDerived other_derived;
3433
3434 // Wrong types. NULL is passed.
3435 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3436 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3437 Base* as_base_ptr = &derived;
3438 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3439 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3440 as_base_ptr = &other_derived;
3441 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3442 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3443 }
3444
TEST(WhenDynamicCastToTest,AlreadyNull)3445 TEST(WhenDynamicCastToTest, AlreadyNull) {
3446 // Already NULL.
3447 Base* as_base_ptr = nullptr;
3448 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3449 }
3450
3451 struct AmbiguousCastTypes {
3452 class VirtualDerived : public virtual Base {};
3453 class DerivedSub1 : public VirtualDerived {};
3454 class DerivedSub2 : public VirtualDerived {};
3455 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3456 };
3457
TEST(WhenDynamicCastToTest,AmbiguousCast)3458 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3459 AmbiguousCastTypes::DerivedSub1 sub1;
3460 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3461 // Multiply derived from Base. dynamic_cast<> returns NULL.
3462 Base* as_base_ptr =
3463 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3464 EXPECT_THAT(as_base_ptr,
3465 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3466 as_base_ptr = &sub1;
3467 EXPECT_THAT(
3468 as_base_ptr,
3469 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3470 }
3471
TEST(WhenDynamicCastToTest,Describe)3472 TEST(WhenDynamicCastToTest, Describe) {
3473 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3474 const std::string prefix =
3475 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3476 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3477 EXPECT_EQ(prefix + "does not point to a value that is anything",
3478 DescribeNegation(matcher));
3479 }
3480
TEST(WhenDynamicCastToTest,Explain)3481 TEST(WhenDynamicCastToTest, Explain) {
3482 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3483 Base* null = nullptr;
3484 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3485 Derived derived;
3486 EXPECT_TRUE(matcher.Matches(&derived));
3487 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3488
3489 // With references, the matcher itself can fail. Test for that one.
3490 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3491 EXPECT_THAT(Explain(ref_matcher, derived),
3492 HasSubstr("which cannot be dynamic_cast"));
3493 }
3494
TEST(WhenDynamicCastToTest,GoodReference)3495 TEST(WhenDynamicCastToTest, GoodReference) {
3496 Derived derived;
3497 derived.i = 4;
3498 Base& as_base_ref = derived;
3499 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3500 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3501 }
3502
TEST(WhenDynamicCastToTest,BadReference)3503 TEST(WhenDynamicCastToTest, BadReference) {
3504 Derived derived;
3505 Base& as_base_ref = derived;
3506 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3507 }
3508 #endif // GTEST_HAS_RTTI
3509
3510 // Minimal const-propagating pointer.
3511 template <typename T>
3512 class ConstPropagatingPtr {
3513 public:
3514 typedef T element_type;
3515
ConstPropagatingPtr()3516 ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)3517 explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)3518 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3519
get()3520 T* get() { return val_; }
operator *()3521 T& operator*() { return *val_; }
3522 // Most smart pointers return non-const T* and T& from the next methods.
get() const3523 const T* get() const { return val_; }
operator *() const3524 const T& operator*() const { return *val_; }
3525
3526 private:
3527 T* val_;
3528 };
3529
TEST(PointeeTest,WorksWithConstPropagatingPointers)3530 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3531 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3532 int three = 3;
3533 const ConstPropagatingPtr<int> co(&three);
3534 ConstPropagatingPtr<int> o(&three);
3535 EXPECT_TRUE(m.Matches(o));
3536 EXPECT_TRUE(m.Matches(co));
3537 *o = 6;
3538 EXPECT_FALSE(m.Matches(o));
3539 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3540 }
3541
TEST(PointeeTest,NeverMatchesNull)3542 TEST(PointeeTest, NeverMatchesNull) {
3543 const Matcher<const char*> m = Pointee(_);
3544 EXPECT_FALSE(m.Matches(nullptr));
3545 }
3546
3547 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)3548 TEST(PointeeTest, MatchesAgainstAValue) {
3549 const Matcher<int*> m = Pointee(5);
3550
3551 int n = 5;
3552 EXPECT_TRUE(m.Matches(&n));
3553 n = -1;
3554 EXPECT_FALSE(m.Matches(&n));
3555 EXPECT_FALSE(m.Matches(nullptr));
3556 }
3557
TEST(PointeeTest,CanDescribeSelf)3558 TEST(PointeeTest, CanDescribeSelf) {
3559 const Matcher<int*> m = Pointee(Gt(3));
3560 EXPECT_EQ("points to a value that is > 3", Describe(m));
3561 EXPECT_EQ("does not point to a value that is > 3",
3562 DescribeNegation(m));
3563 }
3564
TEST(PointeeTest,CanExplainMatchResult)3565 TEST(PointeeTest, CanExplainMatchResult) {
3566 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3567
3568 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
3569
3570 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3571 long n = 3; // NOLINT
3572 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3573 Explain(m2, &n));
3574 }
3575
TEST(PointeeTest,AlwaysExplainsPointee)3576 TEST(PointeeTest, AlwaysExplainsPointee) {
3577 const Matcher<int*> m = Pointee(0);
3578 int n = 42;
3579 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3580 }
3581
3582 // An uncopyable class.
3583 class Uncopyable {
3584 public:
Uncopyable()3585 Uncopyable() : value_(-1) {}
Uncopyable(int a_value)3586 explicit Uncopyable(int a_value) : value_(a_value) {}
3587
value() const3588 int value() const { return value_; }
set_value(int i)3589 void set_value(int i) { value_ = i; }
3590
3591 private:
3592 int value_;
3593 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3594 };
3595
3596 // Returns true if and only if x.value() is positive.
ValueIsPositive(const Uncopyable & x)3597 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3598
3599 MATCHER_P(UncopyableIs, inner_matcher, "") {
3600 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3601 }
3602
3603 // A user-defined struct for testing Field().
3604 struct AStruct {
AStructtesting::gmock_matchers_test::__anon3596cc380111::AStruct3605 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
AStructtesting::gmock_matchers_test::__anon3596cc380111::AStruct3606 AStruct(const AStruct& rhs)
3607 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3608
3609 int x; // A non-const field.
3610 const double y; // A const field.
3611 Uncopyable z; // An uncopyable field.
3612 const char* p; // A pointer field.
3613
3614 private:
3615 GTEST_DISALLOW_ASSIGN_(AStruct);
3616 };
3617
3618 // A derived struct for testing Field().
3619 struct DerivedStruct : public AStruct {
3620 char ch;
3621
3622 private:
3623 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3624 };
3625
3626 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)3627 TEST(FieldTest, WorksForNonConstField) {
3628 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3629 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
3630
3631 AStruct a;
3632 EXPECT_TRUE(m.Matches(a));
3633 EXPECT_TRUE(m_with_name.Matches(a));
3634 a.x = -1;
3635 EXPECT_FALSE(m.Matches(a));
3636 EXPECT_FALSE(m_with_name.Matches(a));
3637 }
3638
3639 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)3640 TEST(FieldTest, WorksForConstField) {
3641 AStruct a;
3642
3643 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3644 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
3645 EXPECT_TRUE(m.Matches(a));
3646 EXPECT_TRUE(m_with_name.Matches(a));
3647 m = Field(&AStruct::y, Le(0.0));
3648 m_with_name = Field("y", &AStruct::y, Le(0.0));
3649 EXPECT_FALSE(m.Matches(a));
3650 EXPECT_FALSE(m_with_name.Matches(a));
3651 }
3652
3653 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)3654 TEST(FieldTest, WorksForUncopyableField) {
3655 AStruct a;
3656
3657 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3658 EXPECT_TRUE(m.Matches(a));
3659 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3660 EXPECT_FALSE(m.Matches(a));
3661 }
3662
3663 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)3664 TEST(FieldTest, WorksForPointerField) {
3665 // Matching against NULL.
3666 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
3667 AStruct a;
3668 EXPECT_TRUE(m.Matches(a));
3669 a.p = "hi";
3670 EXPECT_FALSE(m.Matches(a));
3671
3672 // Matching a pointer that is not NULL.
3673 m = Field(&AStruct::p, StartsWith("hi"));
3674 a.p = "hill";
3675 EXPECT_TRUE(m.Matches(a));
3676 a.p = "hole";
3677 EXPECT_FALSE(m.Matches(a));
3678 }
3679
3680 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)3681 TEST(FieldTest, WorksForByRefArgument) {
3682 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3683
3684 AStruct a;
3685 EXPECT_TRUE(m.Matches(a));
3686 a.x = -1;
3687 EXPECT_FALSE(m.Matches(a));
3688 }
3689
3690 // Tests that Field(&Foo::field, ...) works when the argument's type
3691 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)3692 TEST(FieldTest, WorksForArgumentOfSubType) {
3693 // Note that the matcher expects DerivedStruct but we say AStruct
3694 // inside Field().
3695 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3696
3697 DerivedStruct d;
3698 EXPECT_TRUE(m.Matches(d));
3699 d.x = -1;
3700 EXPECT_FALSE(m.Matches(d));
3701 }
3702
3703 // Tests that Field(&Foo::field, m) works when field's type and m's
3704 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)3705 TEST(FieldTest, WorksForCompatibleMatcherType) {
3706 // The field is an int, but the inner matcher expects a signed char.
3707 Matcher<const AStruct&> m = Field(&AStruct::x,
3708 Matcher<signed char>(Ge(0)));
3709
3710 AStruct a;
3711 EXPECT_TRUE(m.Matches(a));
3712 a.x = -1;
3713 EXPECT_FALSE(m.Matches(a));
3714 }
3715
3716 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)3717 TEST(FieldTest, CanDescribeSelf) {
3718 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3719
3720 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3721 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3722 }
3723
TEST(FieldTest,CanDescribeSelfWithFieldName)3724 TEST(FieldTest, CanDescribeSelfWithFieldName) {
3725 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3726
3727 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3728 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3729 DescribeNegation(m));
3730 }
3731
3732 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)3733 TEST(FieldTest, CanExplainMatchResult) {
3734 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3735
3736 AStruct a;
3737 a.x = 1;
3738 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3739
3740 m = Field(&AStruct::x, GreaterThan(0));
3741 EXPECT_EQ(
3742 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3743 Explain(m, a));
3744 }
3745
TEST(FieldTest,CanExplainMatchResultWithFieldName)3746 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
3747 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3748
3749 AStruct a;
3750 a.x = 1;
3751 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
3752
3753 m = Field("field_name", &AStruct::x, GreaterThan(0));
3754 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
3755 ", which is 1 more than 0",
3756 Explain(m, a));
3757 }
3758
3759 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)3760 TEST(FieldForPointerTest, WorksForPointerToConst) {
3761 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3762
3763 AStruct a;
3764 EXPECT_TRUE(m.Matches(&a));
3765 a.x = -1;
3766 EXPECT_FALSE(m.Matches(&a));
3767 }
3768
3769 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)3770 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3771 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3772
3773 AStruct a;
3774 EXPECT_TRUE(m.Matches(&a));
3775 a.x = -1;
3776 EXPECT_FALSE(m.Matches(&a));
3777 }
3778
3779 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)3780 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3781 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3782
3783 AStruct a;
3784 EXPECT_TRUE(m.Matches(&a));
3785 a.x = -1;
3786 EXPECT_FALSE(m.Matches(&a));
3787 }
3788
3789 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)3790 TEST(FieldForPointerTest, DoesNotMatchNull) {
3791 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3792 EXPECT_FALSE(m.Matches(nullptr));
3793 }
3794
3795 // Tests that Field(&Foo::field, ...) works when the argument's type
3796 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)3797 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3798 // Note that the matcher expects DerivedStruct but we say AStruct
3799 // inside Field().
3800 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3801
3802 DerivedStruct d;
3803 EXPECT_TRUE(m.Matches(&d));
3804 d.x = -1;
3805 EXPECT_FALSE(m.Matches(&d));
3806 }
3807
3808 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)3809 TEST(FieldForPointerTest, CanDescribeSelf) {
3810 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3811
3812 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3813 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3814 }
3815
TEST(FieldForPointerTest,CanDescribeSelfWithFieldName)3816 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
3817 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3818
3819 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3820 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3821 DescribeNegation(m));
3822 }
3823
3824 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)3825 TEST(FieldForPointerTest, CanExplainMatchResult) {
3826 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3827
3828 AStruct a;
3829 a.x = 1;
3830 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
3831 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3832 Explain(m, &a));
3833
3834 m = Field(&AStruct::x, GreaterThan(0));
3835 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3836 ", which is 1 more than 0", Explain(m, &a));
3837 }
3838
TEST(FieldForPointerTest,CanExplainMatchResultWithFieldName)3839 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
3840 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3841
3842 AStruct a;
3843 a.x = 1;
3844 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
3845 EXPECT_EQ(
3846 "which points to an object whose field `field_name` is 1" + OfType("int"),
3847 Explain(m, &a));
3848
3849 m = Field("field_name", &AStruct::x, GreaterThan(0));
3850 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
3851 OfType("int") + ", which is 1 more than 0",
3852 Explain(m, &a));
3853 }
3854
3855 // A user-defined class for testing Property().
3856 class AClass {
3857 public:
AClass()3858 AClass() : n_(0) {}
3859
3860 // A getter that returns a non-reference.
n() const3861 int n() const { return n_; }
3862
set_n(int new_n)3863 void set_n(int new_n) { n_ = new_n; }
3864
3865 // A getter that returns a reference to const.
s() const3866 const std::string& s() const { return s_; }
3867
s_ref() const3868 const std::string& s_ref() const & { return s_; }
3869
set_s(const std::string & new_s)3870 void set_s(const std::string& new_s) { s_ = new_s; }
3871
3872 // A getter that returns a reference to non-const.
x() const3873 double& x() const { return x_; }
3874
3875 private:
3876 int n_;
3877 std::string s_;
3878
3879 static double x_;
3880 };
3881
3882 double AClass::x_ = 0.0;
3883
3884 // A derived class for testing Property().
3885 class DerivedClass : public AClass {
3886 public:
k() const3887 int k() const { return k_; }
3888 private:
3889 int k_;
3890 };
3891
3892 // Tests that Property(&Foo::property, ...) works when property()
3893 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)3894 TEST(PropertyTest, WorksForNonReferenceProperty) {
3895 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3896 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
3897
3898 AClass a;
3899 a.set_n(1);
3900 EXPECT_TRUE(m.Matches(a));
3901 EXPECT_TRUE(m_with_name.Matches(a));
3902
3903 a.set_n(-1);
3904 EXPECT_FALSE(m.Matches(a));
3905 EXPECT_FALSE(m_with_name.Matches(a));
3906 }
3907
3908 // Tests that Property(&Foo::property, ...) works when property()
3909 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)3910 TEST(PropertyTest, WorksForReferenceToConstProperty) {
3911 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3912 Matcher<const AClass&> m_with_name =
3913 Property("s", &AClass::s, StartsWith("hi"));
3914
3915 AClass a;
3916 a.set_s("hill");
3917 EXPECT_TRUE(m.Matches(a));
3918 EXPECT_TRUE(m_with_name.Matches(a));
3919
3920 a.set_s("hole");
3921 EXPECT_FALSE(m.Matches(a));
3922 EXPECT_FALSE(m_with_name.Matches(a));
3923 }
3924
3925 // Tests that Property(&Foo::property, ...) works when property() is
3926 // ref-qualified.
TEST(PropertyTest,WorksForRefQualifiedProperty)3927 TEST(PropertyTest, WorksForRefQualifiedProperty) {
3928 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
3929 Matcher<const AClass&> m_with_name =
3930 Property("s", &AClass::s_ref, StartsWith("hi"));
3931
3932 AClass a;
3933 a.set_s("hill");
3934 EXPECT_TRUE(m.Matches(a));
3935 EXPECT_TRUE(m_with_name.Matches(a));
3936
3937 a.set_s("hole");
3938 EXPECT_FALSE(m.Matches(a));
3939 EXPECT_FALSE(m_with_name.Matches(a));
3940 }
3941
3942 // Tests that Property(&Foo::property, ...) works when property()
3943 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)3944 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3945 double x = 0.0;
3946 AClass a;
3947
3948 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3949 EXPECT_FALSE(m.Matches(a));
3950
3951 m = Property(&AClass::x, Not(Ref(x)));
3952 EXPECT_TRUE(m.Matches(a));
3953 }
3954
3955 // Tests that Property(&Foo::property, ...) works when the argument is
3956 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)3957 TEST(PropertyTest, WorksForByValueArgument) {
3958 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3959
3960 AClass a;
3961 a.set_s("hill");
3962 EXPECT_TRUE(m.Matches(a));
3963
3964 a.set_s("hole");
3965 EXPECT_FALSE(m.Matches(a));
3966 }
3967
3968 // Tests that Property(&Foo::property, ...) works when the argument's
3969 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)3970 TEST(PropertyTest, WorksForArgumentOfSubType) {
3971 // The matcher expects a DerivedClass, but inside the Property() we
3972 // say AClass.
3973 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3974
3975 DerivedClass d;
3976 d.set_n(1);
3977 EXPECT_TRUE(m.Matches(d));
3978
3979 d.set_n(-1);
3980 EXPECT_FALSE(m.Matches(d));
3981 }
3982
3983 // Tests that Property(&Foo::property, m) works when property()'s type
3984 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)3985 TEST(PropertyTest, WorksForCompatibleMatcherType) {
3986 // n() returns an int but the inner matcher expects a signed char.
3987 Matcher<const AClass&> m = Property(&AClass::n,
3988 Matcher<signed char>(Ge(0)));
3989
3990 Matcher<const AClass&> m_with_name =
3991 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
3992
3993 AClass a;
3994 EXPECT_TRUE(m.Matches(a));
3995 EXPECT_TRUE(m_with_name.Matches(a));
3996 a.set_n(-1);
3997 EXPECT_FALSE(m.Matches(a));
3998 EXPECT_FALSE(m_with_name.Matches(a));
3999 }
4000
4001 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)4002 TEST(PropertyTest, CanDescribeSelf) {
4003 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4004
4005 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4006 EXPECT_EQ("is an object whose given property isn't >= 0",
4007 DescribeNegation(m));
4008 }
4009
TEST(PropertyTest,CanDescribeSelfWithPropertyName)4010 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4011 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4012
4013 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4014 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4015 DescribeNegation(m));
4016 }
4017
4018 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)4019 TEST(PropertyTest, CanExplainMatchResult) {
4020 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4021
4022 AClass a;
4023 a.set_n(1);
4024 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4025
4026 m = Property(&AClass::n, GreaterThan(0));
4027 EXPECT_EQ(
4028 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4029 Explain(m, a));
4030 }
4031
TEST(PropertyTest,CanExplainMatchResultWithPropertyName)4032 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4033 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4034
4035 AClass a;
4036 a.set_n(1);
4037 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4038
4039 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4040 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4041 ", which is 1 more than 0",
4042 Explain(m, a));
4043 }
4044
4045 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)4046 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4047 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4048
4049 AClass a;
4050 a.set_n(1);
4051 EXPECT_TRUE(m.Matches(&a));
4052
4053 a.set_n(-1);
4054 EXPECT_FALSE(m.Matches(&a));
4055 }
4056
4057 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)4058 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4059 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4060
4061 AClass a;
4062 a.set_s("hill");
4063 EXPECT_TRUE(m.Matches(&a));
4064
4065 a.set_s("hole");
4066 EXPECT_FALSE(m.Matches(&a));
4067 }
4068
4069 // Tests that Property() works when the argument is a reference to a
4070 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)4071 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4072 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4073
4074 AClass a;
4075 a.set_s("hill");
4076 EXPECT_TRUE(m.Matches(&a));
4077
4078 a.set_s("hole");
4079 EXPECT_FALSE(m.Matches(&a));
4080 }
4081
4082 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)4083 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4084 Matcher<const AClass*> m = Property(&AClass::x, _);
4085 EXPECT_FALSE(m.Matches(nullptr));
4086 }
4087
4088 // Tests that Property(&Foo::property, ...) works when the argument's
4089 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)4090 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4091 // The matcher expects a DerivedClass, but inside the Property() we
4092 // say AClass.
4093 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4094
4095 DerivedClass d;
4096 d.set_n(1);
4097 EXPECT_TRUE(m.Matches(&d));
4098
4099 d.set_n(-1);
4100 EXPECT_FALSE(m.Matches(&d));
4101 }
4102
4103 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)4104 TEST(PropertyForPointerTest, CanDescribeSelf) {
4105 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4106
4107 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4108 EXPECT_EQ("is an object whose given property isn't >= 0",
4109 DescribeNegation(m));
4110 }
4111
TEST(PropertyForPointerTest,CanDescribeSelfWithPropertyDescription)4112 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4113 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4114
4115 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4116 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4117 DescribeNegation(m));
4118 }
4119
4120 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)4121 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4122 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4123
4124 AClass a;
4125 a.set_n(1);
4126 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4127 EXPECT_EQ(
4128 "which points to an object whose given property is 1" + OfType("int"),
4129 Explain(m, &a));
4130
4131 m = Property(&AClass::n, GreaterThan(0));
4132 EXPECT_EQ("which points to an object whose given property is 1" +
4133 OfType("int") + ", which is 1 more than 0",
4134 Explain(m, &a));
4135 }
4136
TEST(PropertyForPointerTest,CanExplainMatchResultWithPropertyName)4137 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4138 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4139
4140 AClass a;
4141 a.set_n(1);
4142 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4143 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4144 OfType("int"),
4145 Explain(m, &a));
4146
4147 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4148 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4149 OfType("int") + ", which is 1 more than 0",
4150 Explain(m, &a));
4151 }
4152
4153 // Tests ResultOf.
4154
4155 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4156 // function pointer.
IntToStringFunction(int input)4157 std::string IntToStringFunction(int input) {
4158 return input == 1 ? "foo" : "bar";
4159 }
4160
TEST(ResultOfTest,WorksForFunctionPointers)4161 TEST(ResultOfTest, WorksForFunctionPointers) {
4162 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4163
4164 EXPECT_TRUE(matcher.Matches(1));
4165 EXPECT_FALSE(matcher.Matches(2));
4166 }
4167
4168 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)4169 TEST(ResultOfTest, CanDescribeItself) {
4170 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4171
4172 EXPECT_EQ("is mapped by the given callable to a value that "
4173 "is equal to \"foo\"", Describe(matcher));
4174 EXPECT_EQ("is mapped by the given callable to a value that "
4175 "isn't equal to \"foo\"", DescribeNegation(matcher));
4176 }
4177
4178 // Tests that ResultOf() can explain the match result.
IntFunction(int input)4179 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4180
TEST(ResultOfTest,CanExplainMatchResult)4181 TEST(ResultOfTest, CanExplainMatchResult) {
4182 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4183 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4184 Explain(matcher, 36));
4185
4186 matcher = ResultOf(&IntFunction, GreaterThan(85));
4187 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4188 ", which is 5 more than 85", Explain(matcher, 36));
4189 }
4190
4191 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4192 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)4193 TEST(ResultOfTest, WorksForNonReferenceResults) {
4194 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4195
4196 EXPECT_TRUE(matcher.Matches(42));
4197 EXPECT_FALSE(matcher.Matches(36));
4198 }
4199
4200 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4201 // returns a reference to non-const.
DoubleFunction(double & input)4202 double& DoubleFunction(double& input) { return input; } // NOLINT
4203
RefUncopyableFunction(Uncopyable & obj)4204 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
4205 return obj;
4206 }
4207
TEST(ResultOfTest,WorksForReferenceToNonConstResults)4208 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4209 double x = 3.14;
4210 double x2 = x;
4211 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4212
4213 EXPECT_TRUE(matcher.Matches(x));
4214 EXPECT_FALSE(matcher.Matches(x2));
4215
4216 // Test that ResultOf works with uncopyable objects
4217 Uncopyable obj(0);
4218 Uncopyable obj2(0);
4219 Matcher<Uncopyable&> matcher2 =
4220 ResultOf(&RefUncopyableFunction, Ref(obj));
4221
4222 EXPECT_TRUE(matcher2.Matches(obj));
4223 EXPECT_FALSE(matcher2.Matches(obj2));
4224 }
4225
4226 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4227 // returns a reference to const.
StringFunction(const std::string & input)4228 const std::string& StringFunction(const std::string& input) { return input; }
4229
TEST(ResultOfTest,WorksForReferenceToConstResults)4230 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4231 std::string s = "foo";
4232 std::string s2 = s;
4233 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4234
4235 EXPECT_TRUE(matcher.Matches(s));
4236 EXPECT_FALSE(matcher.Matches(s2));
4237 }
4238
4239 // Tests that ResultOf(f, m) works when f(x) and m's
4240 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)4241 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4242 // IntFunction() returns int but the inner matcher expects a signed char.
4243 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4244
4245 EXPECT_TRUE(matcher.Matches(36));
4246 EXPECT_FALSE(matcher.Matches(42));
4247 }
4248
4249 // Tests that the program aborts when ResultOf is passed
4250 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)4251 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4252 EXPECT_DEATH_IF_SUPPORTED(
4253 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4254 Eq(std::string("foo"))),
4255 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4256 }
4257
4258 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4259 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)4260 TEST(ResultOfTest, WorksForFunctionReferences) {
4261 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4262 EXPECT_TRUE(matcher.Matches(1));
4263 EXPECT_FALSE(matcher.Matches(2));
4264 }
4265
4266 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4267 // function object.
4268 struct Functor {
operator ()testing::gmock_matchers_test::__anon3596cc380111::Functor4269 std::string operator()(int input) const {
4270 return IntToStringFunction(input);
4271 }
4272 };
4273
TEST(ResultOfTest,WorksForFunctors)4274 TEST(ResultOfTest, WorksForFunctors) {
4275 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4276
4277 EXPECT_TRUE(matcher.Matches(1));
4278 EXPECT_FALSE(matcher.Matches(2));
4279 }
4280
4281 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4282 // functor with more than one operator() defined. ResultOf() must work
4283 // for each defined operator().
4284 struct PolymorphicFunctor {
4285 typedef int result_type;
operator ()testing::gmock_matchers_test::__anon3596cc380111::PolymorphicFunctor4286 int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::__anon3596cc380111::PolymorphicFunctor4287 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
operator ()testing::gmock_matchers_test::__anon3596cc380111::PolymorphicFunctor4288 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4289 };
4290
TEST(ResultOfTest,WorksForPolymorphicFunctors)4291 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4292 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4293
4294 EXPECT_TRUE(matcher_int.Matches(10));
4295 EXPECT_FALSE(matcher_int.Matches(2));
4296
4297 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4298
4299 EXPECT_TRUE(matcher_string.Matches("long string"));
4300 EXPECT_FALSE(matcher_string.Matches("shrt"));
4301 }
4302
TEST(ResultOfTest,WorksForPolymorphicFunctorsIgnoringResultType)4303 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4304 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4305
4306 int n = 0;
4307 EXPECT_TRUE(matcher.Matches(&n));
4308 EXPECT_FALSE(matcher.Matches(nullptr));
4309 }
4310
TEST(ResultOfTest,WorksForLambdas)4311 TEST(ResultOfTest, WorksForLambdas) {
4312 Matcher<int> matcher = ResultOf(
4313 [](int str_len) {
4314 return std::string(static_cast<size_t>(str_len), 'x');
4315 },
4316 "xxx");
4317 EXPECT_TRUE(matcher.Matches(3));
4318 EXPECT_FALSE(matcher.Matches(1));
4319 }
4320
TEST(ResultOfTest,WorksForNonCopyableArguments)4321 TEST(ResultOfTest, WorksForNonCopyableArguments) {
4322 Matcher<std::unique_ptr<int>> matcher = ResultOf(
4323 [](const std::unique_ptr<int>& str_len) {
4324 return std::string(static_cast<size_t>(*str_len), 'x');
4325 },
4326 "xxx");
4327 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4328 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4329 }
4330
ReferencingFunction(const int & n)4331 const int* ReferencingFunction(const int& n) { return &n; }
4332
4333 struct ReferencingFunctor {
4334 typedef const int* result_type;
operator ()testing::gmock_matchers_test::__anon3596cc380111::ReferencingFunctor4335 result_type operator()(const int& n) { return &n; }
4336 };
4337
TEST(ResultOfTest,WorksForReferencingCallables)4338 TEST(ResultOfTest, WorksForReferencingCallables) {
4339 const int n = 1;
4340 const int n2 = 1;
4341 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4342 EXPECT_TRUE(matcher2.Matches(n));
4343 EXPECT_FALSE(matcher2.Matches(n2));
4344
4345 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4346 EXPECT_TRUE(matcher3.Matches(n));
4347 EXPECT_FALSE(matcher3.Matches(n2));
4348 }
4349
4350 class DivisibleByImpl {
4351 public:
DivisibleByImpl(int a_divider)4352 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4353
4354 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4355 template <typename T>
MatchAndExplain(const T & n,MatchResultListener * listener) const4356 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4357 *listener << "which is " << (n % divider_) << " modulo "
4358 << divider_;
4359 return (n % divider_) == 0;
4360 }
4361
DescribeTo(ostream * os) const4362 void DescribeTo(ostream* os) const {
4363 *os << "is divisible by " << divider_;
4364 }
4365
DescribeNegationTo(ostream * os) const4366 void DescribeNegationTo(ostream* os) const {
4367 *os << "is not divisible by " << divider_;
4368 }
4369
set_divider(int a_divider)4370 void set_divider(int a_divider) { divider_ = a_divider; }
divider() const4371 int divider() const { return divider_; }
4372
4373 private:
4374 int divider_;
4375 };
4376
DivisibleBy(int n)4377 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4378 return MakePolymorphicMatcher(DivisibleByImpl(n));
4379 }
4380
4381 // Tests that when AllOf() fails, only the first failing matcher is
4382 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_False)4383 TEST(ExplainMatchResultTest, AllOf_False_False) {
4384 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4385 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4386 }
4387
4388 // Tests that when AllOf() fails, only the first failing matcher is
4389 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_True)4390 TEST(ExplainMatchResultTest, AllOf_False_True) {
4391 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4392 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4393 }
4394
4395 // Tests that when AllOf() fails, only the first failing matcher is
4396 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_True_False)4397 TEST(ExplainMatchResultTest, AllOf_True_False) {
4398 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4399 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4400 }
4401
4402 // Tests that when AllOf() succeeds, all matchers are asked to explain
4403 // why.
TEST(ExplainMatchResultTest,AllOf_True_True)4404 TEST(ExplainMatchResultTest, AllOf_True_True) {
4405 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4406 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4407 }
4408
TEST(ExplainMatchResultTest,AllOf_True_True_2)4409 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4410 const Matcher<int> m = AllOf(Ge(2), Le(3));
4411 EXPECT_EQ("", Explain(m, 2));
4412 }
4413
TEST(ExplainmatcherResultTest,MonomorphicMatcher)4414 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4415 const Matcher<int> m = GreaterThan(5);
4416 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4417 }
4418
4419 // The following two tests verify that values without a public copy
4420 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4421 // with the help of ByRef().
4422
4423 class NotCopyable {
4424 public:
NotCopyable(int a_value)4425 explicit NotCopyable(int a_value) : value_(a_value) {}
4426
value() const4427 int value() const { return value_; }
4428
operator ==(const NotCopyable & rhs) const4429 bool operator==(const NotCopyable& rhs) const {
4430 return value() == rhs.value();
4431 }
4432
operator >=(const NotCopyable & rhs) const4433 bool operator>=(const NotCopyable& rhs) const {
4434 return value() >= rhs.value();
4435 }
4436 private:
4437 int value_;
4438
4439 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4440 };
4441
TEST(ByRefTest,AllowsNotCopyableConstValueInMatchers)4442 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4443 const NotCopyable const_value1(1);
4444 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4445
4446 const NotCopyable n1(1), n2(2);
4447 EXPECT_TRUE(m.Matches(n1));
4448 EXPECT_FALSE(m.Matches(n2));
4449 }
4450
TEST(ByRefTest,AllowsNotCopyableValueInMatchers)4451 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4452 NotCopyable value2(2);
4453 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4454
4455 NotCopyable n1(1), n2(2);
4456 EXPECT_FALSE(m.Matches(n1));
4457 EXPECT_TRUE(m.Matches(n2));
4458 }
4459
TEST(IsEmptyTest,ImplementsIsEmpty)4460 TEST(IsEmptyTest, ImplementsIsEmpty) {
4461 vector<int> container;
4462 EXPECT_THAT(container, IsEmpty());
4463 container.push_back(0);
4464 EXPECT_THAT(container, Not(IsEmpty()));
4465 container.push_back(1);
4466 EXPECT_THAT(container, Not(IsEmpty()));
4467 }
4468
TEST(IsEmptyTest,WorksWithString)4469 TEST(IsEmptyTest, WorksWithString) {
4470 std::string text;
4471 EXPECT_THAT(text, IsEmpty());
4472 text = "foo";
4473 EXPECT_THAT(text, Not(IsEmpty()));
4474 text = std::string("\0", 1);
4475 EXPECT_THAT(text, Not(IsEmpty()));
4476 }
4477
TEST(IsEmptyTest,CanDescribeSelf)4478 TEST(IsEmptyTest, CanDescribeSelf) {
4479 Matcher<vector<int> > m = IsEmpty();
4480 EXPECT_EQ("is empty", Describe(m));
4481 EXPECT_EQ("isn't empty", DescribeNegation(m));
4482 }
4483
TEST(IsEmptyTest,ExplainsResult)4484 TEST(IsEmptyTest, ExplainsResult) {
4485 Matcher<vector<int> > m = IsEmpty();
4486 vector<int> container;
4487 EXPECT_EQ("", Explain(m, container));
4488 container.push_back(0);
4489 EXPECT_EQ("whose size is 1", Explain(m, container));
4490 }
4491
TEST(IsEmptyTest,WorksWithMoveOnly)4492 TEST(IsEmptyTest, WorksWithMoveOnly) {
4493 ContainerHelper helper;
4494 EXPECT_CALL(helper, Call(IsEmpty()));
4495 helper.Call({});
4496 }
4497
TEST(IsTrueTest,IsTrueIsFalse)4498 TEST(IsTrueTest, IsTrueIsFalse) {
4499 EXPECT_THAT(true, IsTrue());
4500 EXPECT_THAT(false, IsFalse());
4501 EXPECT_THAT(true, Not(IsFalse()));
4502 EXPECT_THAT(false, Not(IsTrue()));
4503 EXPECT_THAT(0, Not(IsTrue()));
4504 EXPECT_THAT(0, IsFalse());
4505 EXPECT_THAT(nullptr, Not(IsTrue()));
4506 EXPECT_THAT(nullptr, IsFalse());
4507 EXPECT_THAT(-1, IsTrue());
4508 EXPECT_THAT(-1, Not(IsFalse()));
4509 EXPECT_THAT(1, IsTrue());
4510 EXPECT_THAT(1, Not(IsFalse()));
4511 EXPECT_THAT(2, IsTrue());
4512 EXPECT_THAT(2, Not(IsFalse()));
4513 int a = 42;
4514 EXPECT_THAT(a, IsTrue());
4515 EXPECT_THAT(a, Not(IsFalse()));
4516 EXPECT_THAT(&a, IsTrue());
4517 EXPECT_THAT(&a, Not(IsFalse()));
4518 EXPECT_THAT(false, Not(IsTrue()));
4519 EXPECT_THAT(true, Not(IsFalse()));
4520 EXPECT_THAT(std::true_type(), IsTrue());
4521 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4522 EXPECT_THAT(std::false_type(), IsFalse());
4523 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4524 EXPECT_THAT(nullptr, Not(IsTrue()));
4525 EXPECT_THAT(nullptr, IsFalse());
4526 std::unique_ptr<int> null_unique;
4527 std::unique_ptr<int> nonnull_unique(new int(0));
4528 EXPECT_THAT(null_unique, Not(IsTrue()));
4529 EXPECT_THAT(null_unique, IsFalse());
4530 EXPECT_THAT(nonnull_unique, IsTrue());
4531 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4532 }
4533
TEST(SizeIsTest,ImplementsSizeIs)4534 TEST(SizeIsTest, ImplementsSizeIs) {
4535 vector<int> container;
4536 EXPECT_THAT(container, SizeIs(0));
4537 EXPECT_THAT(container, Not(SizeIs(1)));
4538 container.push_back(0);
4539 EXPECT_THAT(container, Not(SizeIs(0)));
4540 EXPECT_THAT(container, SizeIs(1));
4541 container.push_back(0);
4542 EXPECT_THAT(container, Not(SizeIs(0)));
4543 EXPECT_THAT(container, SizeIs(2));
4544 }
4545
TEST(SizeIsTest,WorksWithMap)4546 TEST(SizeIsTest, WorksWithMap) {
4547 map<std::string, int> container;
4548 EXPECT_THAT(container, SizeIs(0));
4549 EXPECT_THAT(container, Not(SizeIs(1)));
4550 container.insert(make_pair("foo", 1));
4551 EXPECT_THAT(container, Not(SizeIs(0)));
4552 EXPECT_THAT(container, SizeIs(1));
4553 container.insert(make_pair("bar", 2));
4554 EXPECT_THAT(container, Not(SizeIs(0)));
4555 EXPECT_THAT(container, SizeIs(2));
4556 }
4557
TEST(SizeIsTest,WorksWithReferences)4558 TEST(SizeIsTest, WorksWithReferences) {
4559 vector<int> container;
4560 Matcher<const vector<int>&> m = SizeIs(1);
4561 EXPECT_THAT(container, Not(m));
4562 container.push_back(0);
4563 EXPECT_THAT(container, m);
4564 }
4565
TEST(SizeIsTest,WorksWithMoveOnly)4566 TEST(SizeIsTest, WorksWithMoveOnly) {
4567 ContainerHelper helper;
4568 EXPECT_CALL(helper, Call(SizeIs(3)));
4569 helper.Call(MakeUniquePtrs({1, 2, 3}));
4570 }
4571
4572 // SizeIs should work for any type that provides a size() member function.
4573 // For example, a size_type member type should not need to be provided.
4574 struct MinimalistCustomType {
sizetesting::gmock_matchers_test::__anon3596cc380111::MinimalistCustomType4575 int size() const { return 1; }
4576 };
TEST(SizeIsTest,WorksWithMinimalistCustomType)4577 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4578 MinimalistCustomType container;
4579 EXPECT_THAT(container, SizeIs(1));
4580 EXPECT_THAT(container, Not(SizeIs(0)));
4581 }
4582
TEST(SizeIsTest,CanDescribeSelf)4583 TEST(SizeIsTest, CanDescribeSelf) {
4584 Matcher<vector<int> > m = SizeIs(2);
4585 EXPECT_EQ("size is equal to 2", Describe(m));
4586 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4587 }
4588
TEST(SizeIsTest,ExplainsResult)4589 TEST(SizeIsTest, ExplainsResult) {
4590 Matcher<vector<int> > m1 = SizeIs(2);
4591 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4592 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4593 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4594 vector<int> container;
4595 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4596 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4597 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4598 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4599 Explain(m4, container));
4600 container.push_back(0);
4601 container.push_back(0);
4602 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4603 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4604 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4605 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4606 Explain(m4, container));
4607 }
4608
4609 #if GTEST_HAS_TYPED_TEST
4610 // Tests ContainerEq with different container types, and
4611 // different element types.
4612
4613 template <typename T>
4614 class ContainerEqTest : public testing::Test {};
4615
4616 typedef testing::Types<
4617 set<int>,
4618 vector<size_t>,
4619 multiset<size_t>,
4620 list<int> >
4621 ContainerEqTestTypes;
4622
4623 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
4624
4625 // Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest,EqualsSelf)4626 TYPED_TEST(ContainerEqTest, EqualsSelf) {
4627 static const int vals[] = {1, 1, 2, 3, 5, 8};
4628 TypeParam my_set(vals, vals + 6);
4629 const Matcher<TypeParam> m = ContainerEq(my_set);
4630 EXPECT_TRUE(m.Matches(my_set));
4631 EXPECT_EQ("", Explain(m, my_set));
4632 }
4633
4634 // Tests that missing values are reported.
TYPED_TEST(ContainerEqTest,ValueMissing)4635 TYPED_TEST(ContainerEqTest, ValueMissing) {
4636 static const int vals[] = {1, 1, 2, 3, 5, 8};
4637 static const int test_vals[] = {2, 1, 8, 5};
4638 TypeParam my_set(vals, vals + 6);
4639 TypeParam test_set(test_vals, test_vals + 4);
4640 const Matcher<TypeParam> m = ContainerEq(my_set);
4641 EXPECT_FALSE(m.Matches(test_set));
4642 EXPECT_EQ("which doesn't have these expected elements: 3",
4643 Explain(m, test_set));
4644 }
4645
4646 // Tests that added values are reported.
TYPED_TEST(ContainerEqTest,ValueAdded)4647 TYPED_TEST(ContainerEqTest, ValueAdded) {
4648 static const int vals[] = {1, 1, 2, 3, 5, 8};
4649 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4650 TypeParam my_set(vals, vals + 6);
4651 TypeParam test_set(test_vals, test_vals + 6);
4652 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4653 EXPECT_FALSE(m.Matches(test_set));
4654 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4655 }
4656
4657 // Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest,ValueAddedAndRemoved)4658 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4659 static const int vals[] = {1, 1, 2, 3, 5, 8};
4660 static const int test_vals[] = {1, 2, 3, 8, 46};
4661 TypeParam my_set(vals, vals + 6);
4662 TypeParam test_set(test_vals, test_vals + 5);
4663 const Matcher<TypeParam> m = ContainerEq(my_set);
4664 EXPECT_FALSE(m.Matches(test_set));
4665 EXPECT_EQ("which has these unexpected elements: 46,\n"
4666 "and doesn't have these expected elements: 5",
4667 Explain(m, test_set));
4668 }
4669
4670 // Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest,DuplicateDifference)4671 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4672 static const int vals[] = {1, 1, 2, 3, 5, 8};
4673 static const int test_vals[] = {1, 2, 3, 5, 8};
4674 TypeParam my_set(vals, vals + 6);
4675 TypeParam test_set(test_vals, test_vals + 5);
4676 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4677 // Depending on the container, match may be true or false
4678 // But in any case there should be no explanation.
4679 EXPECT_EQ("", Explain(m, test_set));
4680 }
4681 #endif // GTEST_HAS_TYPED_TEST
4682
4683 // Tests that multiple missing values are reported.
4684 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesMissing)4685 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4686 static const int vals[] = {1, 1, 2, 3, 5, 8};
4687 static const int test_vals[] = {2, 1, 5};
4688 vector<int> my_set(vals, vals + 6);
4689 vector<int> test_set(test_vals, test_vals + 3);
4690 const Matcher<vector<int> > m = ContainerEq(my_set);
4691 EXPECT_FALSE(m.Matches(test_set));
4692 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4693 Explain(m, test_set));
4694 }
4695
4696 // Tests that added values are reported.
4697 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesAdded)4698 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4699 static const int vals[] = {1, 1, 2, 3, 5, 8};
4700 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4701 list<size_t> my_set(vals, vals + 6);
4702 list<size_t> test_set(test_vals, test_vals + 7);
4703 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4704 EXPECT_FALSE(m.Matches(test_set));
4705 EXPECT_EQ("which has these unexpected elements: 92, 46",
4706 Explain(m, test_set));
4707 }
4708
4709 // Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest,MultipleValuesAddedAndRemoved)4710 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4711 static const int vals[] = {1, 1, 2, 3, 5, 8};
4712 static const int test_vals[] = {1, 2, 3, 92, 46};
4713 list<size_t> my_set(vals, vals + 6);
4714 list<size_t> test_set(test_vals, test_vals + 5);
4715 const Matcher<const list<size_t> > m = ContainerEq(my_set);
4716 EXPECT_FALSE(m.Matches(test_set));
4717 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4718 "and doesn't have these expected elements: 5, 8",
4719 Explain(m, test_set));
4720 }
4721
4722 // Tests to see that duplicate elements are detected,
4723 // but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest,MultiSetOfIntDuplicateDifference)4724 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4725 static const int vals[] = {1, 1, 2, 3, 5, 8};
4726 static const int test_vals[] = {1, 2, 3, 5, 8};
4727 vector<int> my_set(vals, vals + 6);
4728 vector<int> test_set(test_vals, test_vals + 5);
4729 const Matcher<vector<int> > m = ContainerEq(my_set);
4730 EXPECT_TRUE(m.Matches(my_set));
4731 EXPECT_FALSE(m.Matches(test_set));
4732 // There is nothing to report when both sets contain all the same values.
4733 EXPECT_EQ("", Explain(m, test_set));
4734 }
4735
4736 // Tests that ContainerEq works for non-trivial associative containers,
4737 // like maps.
TEST(ContainerEqExtraTest,WorksForMaps)4738 TEST(ContainerEqExtraTest, WorksForMaps) {
4739 map<int, std::string> my_map;
4740 my_map[0] = "a";
4741 my_map[1] = "b";
4742
4743 map<int, std::string> test_map;
4744 test_map[0] = "aa";
4745 test_map[1] = "b";
4746
4747 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
4748 EXPECT_TRUE(m.Matches(my_map));
4749 EXPECT_FALSE(m.Matches(test_map));
4750
4751 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4752 "and doesn't have these expected elements: (0, \"a\")",
4753 Explain(m, test_map));
4754 }
4755
TEST(ContainerEqExtraTest,WorksForNativeArray)4756 TEST(ContainerEqExtraTest, WorksForNativeArray) {
4757 int a1[] = {1, 2, 3};
4758 int a2[] = {1, 2, 3};
4759 int b[] = {1, 2, 4};
4760
4761 EXPECT_THAT(a1, ContainerEq(a2));
4762 EXPECT_THAT(a1, Not(ContainerEq(b)));
4763 }
4764
TEST(ContainerEqExtraTest,WorksForTwoDimensionalNativeArray)4765 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4766 const char a1[][3] = {"hi", "lo"};
4767 const char a2[][3] = {"hi", "lo"};
4768 const char b[][3] = {"lo", "hi"};
4769
4770 // Tests using ContainerEq() in the first dimension.
4771 EXPECT_THAT(a1, ContainerEq(a2));
4772 EXPECT_THAT(a1, Not(ContainerEq(b)));
4773
4774 // Tests using ContainerEq() in the second dimension.
4775 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4776 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4777 }
4778
TEST(ContainerEqExtraTest,WorksForNativeArrayAsTuple)4779 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4780 const int a1[] = {1, 2, 3};
4781 const int a2[] = {1, 2, 3};
4782 const int b[] = {1, 2, 3, 4};
4783
4784 const int* const p1 = a1;
4785 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
4786 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
4787
4788 const int c[] = {1, 3, 2};
4789 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
4790 }
4791
TEST(ContainerEqExtraTest,CopiesNativeArrayParameter)4792 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4793 std::string a1[][3] = {
4794 {"hi", "hello", "ciao"},
4795 {"bye", "see you", "ciao"}
4796 };
4797
4798 std::string a2[][3] = {
4799 {"hi", "hello", "ciao"},
4800 {"bye", "see you", "ciao"}
4801 };
4802
4803 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4804 EXPECT_THAT(a1, m);
4805
4806 a2[0][0] = "ha";
4807 EXPECT_THAT(a1, m);
4808 }
4809
TEST(WhenSortedByTest,WorksForEmptyContainer)4810 TEST(WhenSortedByTest, WorksForEmptyContainer) {
4811 const vector<int> numbers;
4812 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4813 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4814 }
4815
TEST(WhenSortedByTest,WorksForNonEmptyContainer)4816 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4817 vector<unsigned> numbers;
4818 numbers.push_back(3);
4819 numbers.push_back(1);
4820 numbers.push_back(2);
4821 numbers.push_back(2);
4822 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4823 ElementsAre(3, 2, 2, 1)));
4824 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4825 ElementsAre(1, 2, 2, 3))));
4826 }
4827
TEST(WhenSortedByTest,WorksForNonVectorContainer)4828 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4829 list<std::string> words;
4830 words.push_back("say");
4831 words.push_back("hello");
4832 words.push_back("world");
4833 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
4834 ElementsAre("hello", "say", "world")));
4835 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
4836 ElementsAre("say", "hello", "world"))));
4837 }
4838
TEST(WhenSortedByTest,WorksForNativeArray)4839 TEST(WhenSortedByTest, WorksForNativeArray) {
4840 const int numbers[] = {1, 3, 2, 4};
4841 const int sorted_numbers[] = {1, 2, 3, 4};
4842 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4843 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4844 ElementsAreArray(sorted_numbers)));
4845 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4846 }
4847
TEST(WhenSortedByTest,CanDescribeSelf)4848 TEST(WhenSortedByTest, CanDescribeSelf) {
4849 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4850 EXPECT_EQ("(when sorted) has 2 elements where\n"
4851 "element #0 is equal to 1,\n"
4852 "element #1 is equal to 2",
4853 Describe(m));
4854 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4855 "element #0 isn't equal to 1, or\n"
4856 "element #1 isn't equal to 2",
4857 DescribeNegation(m));
4858 }
4859
TEST(WhenSortedByTest,ExplainsMatchResult)4860 TEST(WhenSortedByTest, ExplainsMatchResult) {
4861 const int a[] = {2, 1};
4862 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4863 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4864 EXPECT_EQ("which is { 1, 2 } when sorted",
4865 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4866 }
4867
4868 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4869 // need to test it as exhaustively as we test the latter.
4870
TEST(WhenSortedTest,WorksForEmptyContainer)4871 TEST(WhenSortedTest, WorksForEmptyContainer) {
4872 const vector<int> numbers;
4873 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4874 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4875 }
4876
TEST(WhenSortedTest,WorksForNonEmptyContainer)4877 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4878 list<std::string> words;
4879 words.push_back("3");
4880 words.push_back("1");
4881 words.push_back("2");
4882 words.push_back("2");
4883 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4884 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4885 }
4886
TEST(WhenSortedTest,WorksForMapTypes)4887 TEST(WhenSortedTest, WorksForMapTypes) {
4888 map<std::string, int> word_counts;
4889 word_counts["and"] = 1;
4890 word_counts["the"] = 1;
4891 word_counts["buffalo"] = 2;
4892 EXPECT_THAT(word_counts,
4893 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
4894 Pair("the", 1))));
4895 EXPECT_THAT(word_counts,
4896 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
4897 Pair("buffalo", 2)))));
4898 }
4899
TEST(WhenSortedTest,WorksForMultiMapTypes)4900 TEST(WhenSortedTest, WorksForMultiMapTypes) {
4901 multimap<int, int> ifib;
4902 ifib.insert(make_pair(8, 6));
4903 ifib.insert(make_pair(2, 3));
4904 ifib.insert(make_pair(1, 1));
4905 ifib.insert(make_pair(3, 4));
4906 ifib.insert(make_pair(1, 2));
4907 ifib.insert(make_pair(5, 5));
4908 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4909 Pair(1, 2),
4910 Pair(2, 3),
4911 Pair(3, 4),
4912 Pair(5, 5),
4913 Pair(8, 6))));
4914 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4915 Pair(2, 3),
4916 Pair(1, 1),
4917 Pair(3, 4),
4918 Pair(1, 2),
4919 Pair(5, 5)))));
4920 }
4921
TEST(WhenSortedTest,WorksForPolymorphicMatcher)4922 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4923 std::deque<int> d;
4924 d.push_back(2);
4925 d.push_back(1);
4926 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4927 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4928 }
4929
TEST(WhenSortedTest,WorksForVectorConstRefMatcher)4930 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4931 std::deque<int> d;
4932 d.push_back(2);
4933 d.push_back(1);
4934 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4935 EXPECT_THAT(d, WhenSorted(vector_match));
4936 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4937 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4938 }
4939
4940 // Deliberately bare pseudo-container.
4941 // Offers only begin() and end() accessors, yielding InputIterator.
4942 template <typename T>
4943 class Streamlike {
4944 private:
4945 class ConstIter;
4946 public:
4947 typedef ConstIter const_iterator;
4948 typedef T value_type;
4949
4950 template <typename InIter>
Streamlike(InIter first,InIter last)4951 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4952
begin() const4953 const_iterator begin() const {
4954 return const_iterator(this, remainder_.begin());
4955 }
end() const4956 const_iterator end() const {
4957 return const_iterator(this, remainder_.end());
4958 }
4959
4960 private:
4961 class ConstIter : public std::iterator<std::input_iterator_tag,
4962 value_type,
4963 ptrdiff_t,
4964 const value_type*,
4965 const value_type&> {
4966 public:
ConstIter(const Streamlike * s,typename std::list<value_type>::iterator pos)4967 ConstIter(const Streamlike* s,
4968 typename std::list<value_type>::iterator pos)
4969 : s_(s), pos_(pos) {}
4970
operator *() const4971 const value_type& operator*() const { return *pos_; }
operator ->() const4972 const value_type* operator->() const { return &*pos_; }
operator ++()4973 ConstIter& operator++() {
4974 s_->remainder_.erase(pos_++);
4975 return *this;
4976 }
4977
4978 // *iter++ is required to work (see std::istreambuf_iterator).
4979 // (void)iter++ is also required to work.
4980 class PostIncrProxy {
4981 public:
PostIncrProxy(const value_type & value)4982 explicit PostIncrProxy(const value_type& value) : value_(value) {}
operator *() const4983 value_type operator*() const { return value_; }
4984 private:
4985 value_type value_;
4986 };
operator ++(int)4987 PostIncrProxy operator++(int) {
4988 PostIncrProxy proxy(**this);
4989 ++(*this);
4990 return proxy;
4991 }
4992
operator ==(const ConstIter & a,const ConstIter & b)4993 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4994 return a.s_ == b.s_ && a.pos_ == b.pos_;
4995 }
operator !=(const ConstIter & a,const ConstIter & b)4996 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4997 return !(a == b);
4998 }
4999
5000 private:
5001 const Streamlike* s_;
5002 typename std::list<value_type>::iterator pos_;
5003 };
5004
operator <<(std::ostream & os,const Streamlike & s)5005 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5006 os << "[";
5007 typedef typename std::list<value_type>::const_iterator Iter;
5008 const char* sep = "";
5009 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5010 os << sep << *it;
5011 sep = ",";
5012 }
5013 os << "]";
5014 return os;
5015 }
5016
5017 mutable std::list<value_type> remainder_; // modified by iteration
5018 };
5019
TEST(StreamlikeTest,Iteration)5020 TEST(StreamlikeTest, Iteration) {
5021 const int a[5] = {2, 1, 4, 5, 3};
5022 Streamlike<int> s(a, a + 5);
5023 Streamlike<int>::const_iterator it = s.begin();
5024 const int* ip = a;
5025 while (it != s.end()) {
5026 SCOPED_TRACE(ip - a);
5027 EXPECT_EQ(*ip++, *it++);
5028 }
5029 }
5030
TEST(BeginEndDistanceIsTest,WorksWithForwardList)5031 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5032 std::forward_list<int> container;
5033 EXPECT_THAT(container, BeginEndDistanceIs(0));
5034 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5035 container.push_front(0);
5036 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5037 EXPECT_THAT(container, BeginEndDistanceIs(1));
5038 container.push_front(0);
5039 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5040 EXPECT_THAT(container, BeginEndDistanceIs(2));
5041 }
5042
TEST(BeginEndDistanceIsTest,WorksWithNonStdList)5043 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5044 const int a[5] = {1, 2, 3, 4, 5};
5045 Streamlike<int> s(a, a + 5);
5046 EXPECT_THAT(s, BeginEndDistanceIs(5));
5047 }
5048
TEST(BeginEndDistanceIsTest,CanDescribeSelf)5049 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5050 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5051 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5052 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5053 DescribeNegation(m));
5054 }
5055
TEST(BeginEndDistanceIsTest,WorksWithMoveOnly)5056 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5057 ContainerHelper helper;
5058 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5059 helper.Call(MakeUniquePtrs({1, 2}));
5060 }
5061
TEST(BeginEndDistanceIsTest,ExplainsResult)5062 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5063 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5064 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5065 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5066 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5067 vector<int> container;
5068 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5069 Explain(m1, container));
5070 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5071 Explain(m2, container));
5072 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5073 Explain(m3, container));
5074 EXPECT_EQ(
5075 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5076 "less than 1",
5077 Explain(m4, container));
5078 container.push_back(0);
5079 container.push_back(0);
5080 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5081 Explain(m1, container));
5082 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5083 Explain(m2, container));
5084 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5085 Explain(m3, container));
5086 EXPECT_EQ(
5087 "whose distance between begin() and end() 2 matches, which is 1 more "
5088 "than 1",
5089 Explain(m4, container));
5090 }
5091
TEST(WhenSortedTest,WorksForStreamlike)5092 TEST(WhenSortedTest, WorksForStreamlike) {
5093 // Streamlike 'container' provides only minimal iterator support.
5094 // Its iterators are tagged with input_iterator_tag.
5095 const int a[5] = {2, 1, 4, 5, 3};
5096 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5097 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5098 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5099 }
5100
TEST(WhenSortedTest,WorksForVectorConstRefMatcherOnStreamlike)5101 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5102 const int a[] = {2, 1, 4, 5, 3};
5103 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5104 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5105 EXPECT_THAT(s, WhenSorted(vector_match));
5106 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5107 }
5108
TEST(IsSupersetOfTest,WorksForNativeArray)5109 TEST(IsSupersetOfTest, WorksForNativeArray) {
5110 const int subset[] = {1, 4};
5111 const int superset[] = {1, 2, 4};
5112 const int disjoint[] = {1, 0, 3};
5113 EXPECT_THAT(subset, IsSupersetOf(subset));
5114 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5115 EXPECT_THAT(superset, IsSupersetOf(subset));
5116 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5117 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5118 }
5119
TEST(IsSupersetOfTest,WorksWithDuplicates)5120 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5121 const int not_enough[] = {1, 2};
5122 const int enough[] = {1, 1, 2};
5123 const int expected[] = {1, 1};
5124 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5125 EXPECT_THAT(enough, IsSupersetOf(expected));
5126 }
5127
TEST(IsSupersetOfTest,WorksForEmpty)5128 TEST(IsSupersetOfTest, WorksForEmpty) {
5129 vector<int> numbers;
5130 vector<int> expected;
5131 EXPECT_THAT(numbers, IsSupersetOf(expected));
5132 expected.push_back(1);
5133 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5134 expected.clear();
5135 numbers.push_back(1);
5136 numbers.push_back(2);
5137 EXPECT_THAT(numbers, IsSupersetOf(expected));
5138 expected.push_back(1);
5139 EXPECT_THAT(numbers, IsSupersetOf(expected));
5140 expected.push_back(2);
5141 EXPECT_THAT(numbers, IsSupersetOf(expected));
5142 expected.push_back(3);
5143 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5144 }
5145
TEST(IsSupersetOfTest,WorksForStreamlike)5146 TEST(IsSupersetOfTest, WorksForStreamlike) {
5147 const int a[5] = {1, 2, 3, 4, 5};
5148 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5149
5150 vector<int> expected;
5151 expected.push_back(1);
5152 expected.push_back(2);
5153 expected.push_back(5);
5154 EXPECT_THAT(s, IsSupersetOf(expected));
5155
5156 expected.push_back(0);
5157 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5158 }
5159
TEST(IsSupersetOfTest,TakesStlContainer)5160 TEST(IsSupersetOfTest, TakesStlContainer) {
5161 const int actual[] = {3, 1, 2};
5162
5163 ::std::list<int> expected;
5164 expected.push_back(1);
5165 expected.push_back(3);
5166 EXPECT_THAT(actual, IsSupersetOf(expected));
5167
5168 expected.push_back(4);
5169 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5170 }
5171
TEST(IsSupersetOfTest,Describe)5172 TEST(IsSupersetOfTest, Describe) {
5173 typedef std::vector<int> IntVec;
5174 IntVec expected;
5175 expected.push_back(111);
5176 expected.push_back(222);
5177 expected.push_back(333);
5178 EXPECT_THAT(
5179 Describe<IntVec>(IsSupersetOf(expected)),
5180 Eq("a surjection from elements to requirements exists such that:\n"
5181 " - an element is equal to 111\n"
5182 " - an element is equal to 222\n"
5183 " - an element is equal to 333"));
5184 }
5185
TEST(IsSupersetOfTest,DescribeNegation)5186 TEST(IsSupersetOfTest, DescribeNegation) {
5187 typedef std::vector<int> IntVec;
5188 IntVec expected;
5189 expected.push_back(111);
5190 expected.push_back(222);
5191 expected.push_back(333);
5192 EXPECT_THAT(
5193 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5194 Eq("no surjection from elements to requirements exists such that:\n"
5195 " - an element is equal to 111\n"
5196 " - an element is equal to 222\n"
5197 " - an element is equal to 333"));
5198 }
5199
TEST(IsSupersetOfTest,MatchAndExplain)5200 TEST(IsSupersetOfTest, MatchAndExplain) {
5201 std::vector<int> v;
5202 v.push_back(2);
5203 v.push_back(3);
5204 std::vector<int> expected;
5205 expected.push_back(1);
5206 expected.push_back(2);
5207 StringMatchResultListener listener;
5208 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5209 << listener.str();
5210 EXPECT_THAT(listener.str(),
5211 Eq("where the following matchers don't match any elements:\n"
5212 "matcher #0: is equal to 1"));
5213
5214 v.push_back(1);
5215 listener.Clear();
5216 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5217 << listener.str();
5218 EXPECT_THAT(listener.str(), Eq("where:\n"
5219 " - element #0 is matched by matcher #1,\n"
5220 " - element #2 is matched by matcher #0"));
5221 }
5222
TEST(IsSupersetOfTest,WorksForRhsInitializerList)5223 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5224 const int numbers[] = {1, 3, 6, 2, 4, 5};
5225 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5226 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5227 }
5228
TEST(IsSupersetOfTest,WorksWithMoveOnly)5229 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5230 ContainerHelper helper;
5231 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5232 helper.Call(MakeUniquePtrs({1, 2}));
5233 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5234 helper.Call(MakeUniquePtrs({2}));
5235 }
5236
TEST(IsSubsetOfTest,WorksForNativeArray)5237 TEST(IsSubsetOfTest, WorksForNativeArray) {
5238 const int subset[] = {1, 4};
5239 const int superset[] = {1, 2, 4};
5240 const int disjoint[] = {1, 0, 3};
5241 EXPECT_THAT(subset, IsSubsetOf(subset));
5242 EXPECT_THAT(subset, IsSubsetOf(superset));
5243 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5244 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5245 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5246 }
5247
TEST(IsSubsetOfTest,WorksWithDuplicates)5248 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5249 const int not_enough[] = {1, 2};
5250 const int enough[] = {1, 1, 2};
5251 const int actual[] = {1, 1};
5252 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5253 EXPECT_THAT(actual, IsSubsetOf(enough));
5254 }
5255
TEST(IsSubsetOfTest,WorksForEmpty)5256 TEST(IsSubsetOfTest, WorksForEmpty) {
5257 vector<int> numbers;
5258 vector<int> expected;
5259 EXPECT_THAT(numbers, IsSubsetOf(expected));
5260 expected.push_back(1);
5261 EXPECT_THAT(numbers, IsSubsetOf(expected));
5262 expected.clear();
5263 numbers.push_back(1);
5264 numbers.push_back(2);
5265 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5266 expected.push_back(1);
5267 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5268 expected.push_back(2);
5269 EXPECT_THAT(numbers, IsSubsetOf(expected));
5270 expected.push_back(3);
5271 EXPECT_THAT(numbers, IsSubsetOf(expected));
5272 }
5273
TEST(IsSubsetOfTest,WorksForStreamlike)5274 TEST(IsSubsetOfTest, WorksForStreamlike) {
5275 const int a[5] = {1, 2};
5276 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5277
5278 vector<int> expected;
5279 expected.push_back(1);
5280 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5281 expected.push_back(2);
5282 expected.push_back(5);
5283 EXPECT_THAT(s, IsSubsetOf(expected));
5284 }
5285
TEST(IsSubsetOfTest,TakesStlContainer)5286 TEST(IsSubsetOfTest, TakesStlContainer) {
5287 const int actual[] = {3, 1, 2};
5288
5289 ::std::list<int> expected;
5290 expected.push_back(1);
5291 expected.push_back(3);
5292 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5293
5294 expected.push_back(2);
5295 expected.push_back(4);
5296 EXPECT_THAT(actual, IsSubsetOf(expected));
5297 }
5298
TEST(IsSubsetOfTest,Describe)5299 TEST(IsSubsetOfTest, Describe) {
5300 typedef std::vector<int> IntVec;
5301 IntVec expected;
5302 expected.push_back(111);
5303 expected.push_back(222);
5304 expected.push_back(333);
5305
5306 EXPECT_THAT(
5307 Describe<IntVec>(IsSubsetOf(expected)),
5308 Eq("an injection from elements to requirements exists such that:\n"
5309 " - an element is equal to 111\n"
5310 " - an element is equal to 222\n"
5311 " - an element is equal to 333"));
5312 }
5313
TEST(IsSubsetOfTest,DescribeNegation)5314 TEST(IsSubsetOfTest, DescribeNegation) {
5315 typedef std::vector<int> IntVec;
5316 IntVec expected;
5317 expected.push_back(111);
5318 expected.push_back(222);
5319 expected.push_back(333);
5320 EXPECT_THAT(
5321 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5322 Eq("no injection from elements to requirements exists such that:\n"
5323 " - an element is equal to 111\n"
5324 " - an element is equal to 222\n"
5325 " - an element is equal to 333"));
5326 }
5327
TEST(IsSubsetOfTest,MatchAndExplain)5328 TEST(IsSubsetOfTest, MatchAndExplain) {
5329 std::vector<int> v;
5330 v.push_back(2);
5331 v.push_back(3);
5332 std::vector<int> expected;
5333 expected.push_back(1);
5334 expected.push_back(2);
5335 StringMatchResultListener listener;
5336 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5337 << listener.str();
5338 EXPECT_THAT(listener.str(),
5339 Eq("where the following elements don't match any matchers:\n"
5340 "element #1: 3"));
5341
5342 expected.push_back(3);
5343 listener.Clear();
5344 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5345 << listener.str();
5346 EXPECT_THAT(listener.str(), Eq("where:\n"
5347 " - element #0 is matched by matcher #1,\n"
5348 " - element #1 is matched by matcher #2"));
5349 }
5350
TEST(IsSubsetOfTest,WorksForRhsInitializerList)5351 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5352 const int numbers[] = {1, 2, 3};
5353 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5354 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5355 }
5356
TEST(IsSubsetOfTest,WorksWithMoveOnly)5357 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5358 ContainerHelper helper;
5359 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5360 helper.Call(MakeUniquePtrs({1}));
5361 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5362 helper.Call(MakeUniquePtrs({2}));
5363 }
5364
5365 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5366 // "containers".
5367
TEST(ElemensAreStreamTest,WorksForStreamlike)5368 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5369 const int a[5] = {1, 2, 3, 4, 5};
5370 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5371 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5372 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5373 }
5374
TEST(ElemensAreArrayStreamTest,WorksForStreamlike)5375 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5376 const int a[5] = {1, 2, 3, 4, 5};
5377 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5378
5379 vector<int> expected;
5380 expected.push_back(1);
5381 expected.push_back(2);
5382 expected.push_back(3);
5383 expected.push_back(4);
5384 expected.push_back(5);
5385 EXPECT_THAT(s, ElementsAreArray(expected));
5386
5387 expected[3] = 0;
5388 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5389 }
5390
TEST(ElementsAreTest,WorksWithUncopyable)5391 TEST(ElementsAreTest, WorksWithUncopyable) {
5392 Uncopyable objs[2];
5393 objs[0].set_value(-3);
5394 objs[1].set_value(1);
5395 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5396 }
5397
TEST(ElementsAreTest,WorksWithMoveOnly)5398 TEST(ElementsAreTest, WorksWithMoveOnly) {
5399 ContainerHelper helper;
5400 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5401 helper.Call(MakeUniquePtrs({1, 2}));
5402
5403 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5404 helper.Call(MakeUniquePtrs({3, 4}));
5405 }
5406
TEST(ElementsAreTest,TakesStlContainer)5407 TEST(ElementsAreTest, TakesStlContainer) {
5408 const int actual[] = {3, 1, 2};
5409
5410 ::std::list<int> expected;
5411 expected.push_back(3);
5412 expected.push_back(1);
5413 expected.push_back(2);
5414 EXPECT_THAT(actual, ElementsAreArray(expected));
5415
5416 expected.push_back(4);
5417 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5418 }
5419
5420 // Tests for UnorderedElementsAreArray()
5421
TEST(UnorderedElementsAreArrayTest,SucceedsWhenExpected)5422 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5423 const int a[] = {0, 1, 2, 3, 4};
5424 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5425 do {
5426 StringMatchResultListener listener;
5427 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5428 s, &listener)) << listener.str();
5429 } while (std::next_permutation(s.begin(), s.end()));
5430 }
5431
TEST(UnorderedElementsAreArrayTest,VectorBool)5432 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5433 const bool a[] = {0, 1, 0, 1, 1};
5434 const bool b[] = {1, 0, 1, 1, 0};
5435 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
5436 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
5437 StringMatchResultListener listener;
5438 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5439 actual, &listener)) << listener.str();
5440 }
5441
TEST(UnorderedElementsAreArrayTest,WorksForStreamlike)5442 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5443 // Streamlike 'container' provides only minimal iterator support.
5444 // Its iterators are tagged with input_iterator_tag, and it has no
5445 // size() or empty() methods.
5446 const int a[5] = {2, 1, 4, 5, 3};
5447 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5448
5449 ::std::vector<int> expected;
5450 expected.push_back(1);
5451 expected.push_back(2);
5452 expected.push_back(3);
5453 expected.push_back(4);
5454 expected.push_back(5);
5455 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5456
5457 expected.push_back(6);
5458 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5459 }
5460
TEST(UnorderedElementsAreArrayTest,TakesStlContainer)5461 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5462 const int actual[] = {3, 1, 2};
5463
5464 ::std::list<int> expected;
5465 expected.push_back(1);
5466 expected.push_back(2);
5467 expected.push_back(3);
5468 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5469
5470 expected.push_back(4);
5471 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5472 }
5473
5474
TEST(UnorderedElementsAreArrayTest,TakesInitializerList)5475 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5476 const int a[5] = {2, 1, 4, 5, 3};
5477 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5478 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5479 }
5480
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfCStrings)5481 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5482 const std::string a[5] = {"a", "b", "c", "d", "e"};
5483 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5484 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5485 }
5486
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)5487 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5488 const int a[5] = {2, 1, 4, 5, 3};
5489 EXPECT_THAT(a, UnorderedElementsAreArray(
5490 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5491 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5492 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5493 }
5494
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)5495 TEST(UnorderedElementsAreArrayTest,
5496 TakesInitializerListOfDifferentTypedMatchers) {
5497 const int a[5] = {2, 1, 4, 5, 3};
5498 // The compiler cannot infer the type of the initializer list if its
5499 // elements have different types. We must explicitly specify the
5500 // unified element type in this case.
5501 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5502 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5503 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5504 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5505 }
5506
5507
TEST(UnorderedElementsAreArrayTest,WorksWithMoveOnly)5508 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5509 ContainerHelper helper;
5510 EXPECT_CALL(helper,
5511 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5512 helper.Call(MakeUniquePtrs({2, 1}));
5513 }
5514
5515 class UnorderedElementsAreTest : public testing::Test {
5516 protected:
5517 typedef std::vector<int> IntVec;
5518 };
5519
TEST_F(UnorderedElementsAreTest,WorksWithUncopyable)5520 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5521 Uncopyable objs[2];
5522 objs[0].set_value(-3);
5523 objs[1].set_value(1);
5524 EXPECT_THAT(objs,
5525 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5526 }
5527
TEST_F(UnorderedElementsAreTest,SucceedsWhenExpected)5528 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5529 const int a[] = {1, 2, 3};
5530 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5531 do {
5532 StringMatchResultListener listener;
5533 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5534 s, &listener)) << listener.str();
5535 } while (std::next_permutation(s.begin(), s.end()));
5536 }
5537
TEST_F(UnorderedElementsAreTest,FailsWhenAnElementMatchesNoMatcher)5538 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5539 const int a[] = {1, 2, 3};
5540 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5541 std::vector<Matcher<int> > mv;
5542 mv.push_back(1);
5543 mv.push_back(2);
5544 mv.push_back(2);
5545 // The element with value '3' matches nothing: fail fast.
5546 StringMatchResultListener listener;
5547 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5548 s, &listener)) << listener.str();
5549 }
5550
TEST_F(UnorderedElementsAreTest,WorksForStreamlike)5551 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5552 // Streamlike 'container' provides only minimal iterator support.
5553 // Its iterators are tagged with input_iterator_tag, and it has no
5554 // size() or empty() methods.
5555 const int a[5] = {2, 1, 4, 5, 3};
5556 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5557
5558 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5559 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5560 }
5561
TEST_F(UnorderedElementsAreTest,WorksWithMoveOnly)5562 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5563 ContainerHelper helper;
5564 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5565 helper.Call(MakeUniquePtrs({2, 1}));
5566 }
5567
5568 // One naive implementation of the matcher runs in O(N!) time, which is too
5569 // slow for many real-world inputs. This test shows that our matcher can match
5570 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5571 // iterations and obviously effectively incomputable.
5572 // [ RUN ] UnorderedElementsAreTest.Performance
5573 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
TEST_F(UnorderedElementsAreTest,Performance)5574 TEST_F(UnorderedElementsAreTest, Performance) {
5575 std::vector<int> s;
5576 std::vector<Matcher<int> > mv;
5577 for (int i = 0; i < 100; ++i) {
5578 s.push_back(i);
5579 mv.push_back(_);
5580 }
5581 mv[50] = Eq(0);
5582 StringMatchResultListener listener;
5583 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5584 s, &listener)) << listener.str();
5585 }
5586
5587 // Another variant of 'Performance' with similar expectations.
5588 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5589 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
TEST_F(UnorderedElementsAreTest,PerformanceHalfStrict)5590 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5591 std::vector<int> s;
5592 std::vector<Matcher<int> > mv;
5593 for (int i = 0; i < 100; ++i) {
5594 s.push_back(i);
5595 if (i & 1) {
5596 mv.push_back(_);
5597 } else {
5598 mv.push_back(i);
5599 }
5600 }
5601 StringMatchResultListener listener;
5602 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5603 s, &listener)) << listener.str();
5604 }
5605
TEST_F(UnorderedElementsAreTest,FailMessageCountWrong)5606 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5607 std::vector<int> v;
5608 v.push_back(4);
5609 StringMatchResultListener listener;
5610 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5611 v, &listener)) << listener.str();
5612 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5613 }
5614
TEST_F(UnorderedElementsAreTest,FailMessageCountWrongZero)5615 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5616 std::vector<int> v;
5617 StringMatchResultListener listener;
5618 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5619 v, &listener)) << listener.str();
5620 EXPECT_THAT(listener.str(), Eq(""));
5621 }
5622
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatchers)5623 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5624 std::vector<int> v;
5625 v.push_back(1);
5626 v.push_back(1);
5627 StringMatchResultListener listener;
5628 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5629 v, &listener)) << listener.str();
5630 EXPECT_THAT(
5631 listener.str(),
5632 Eq("where the following matchers don't match any elements:\n"
5633 "matcher #1: is equal to 2"));
5634 }
5635
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedElements)5636 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5637 std::vector<int> v;
5638 v.push_back(1);
5639 v.push_back(2);
5640 StringMatchResultListener listener;
5641 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5642 v, &listener)) << listener.str();
5643 EXPECT_THAT(
5644 listener.str(),
5645 Eq("where the following elements don't match any matchers:\n"
5646 "element #1: 2"));
5647 }
5648
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatcherAndElement)5649 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5650 std::vector<int> v;
5651 v.push_back(2);
5652 v.push_back(3);
5653 StringMatchResultListener listener;
5654 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5655 v, &listener)) << listener.str();
5656 EXPECT_THAT(
5657 listener.str(),
5658 Eq("where"
5659 " the following matchers don't match any elements:\n"
5660 "matcher #0: is equal to 1\n"
5661 "and"
5662 " where"
5663 " the following elements don't match any matchers:\n"
5664 "element #1: 3"));
5665 }
5666
5667 // Test helper for formatting element, matcher index pairs in expectations.
EMString(int element,int matcher)5668 static std::string EMString(int element, int matcher) {
5669 stringstream ss;
5670 ss << "(element #" << element << ", matcher #" << matcher << ")";
5671 return ss.str();
5672 }
5673
TEST_F(UnorderedElementsAreTest,FailMessageImperfectMatchOnly)5674 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
5675 // A situation where all elements and matchers have a match
5676 // associated with them, but the max matching is not perfect.
5677 std::vector<std::string> v;
5678 v.push_back("a");
5679 v.push_back("b");
5680 v.push_back("c");
5681 StringMatchResultListener listener;
5682 EXPECT_FALSE(ExplainMatchResult(
5683 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5684 << listener.str();
5685
5686 std::string prefix =
5687 "where no permutation of the elements can satisfy all matchers, "
5688 "and the closest match is 2 of 3 matchers with the "
5689 "pairings:\n";
5690
5691 // We have to be a bit loose here, because there are 4 valid max matches.
5692 EXPECT_THAT(
5693 listener.str(),
5694 AnyOf(prefix + "{\n " + EMString(0, 0) +
5695 ",\n " + EMString(1, 2) + "\n}",
5696 prefix + "{\n " + EMString(0, 1) +
5697 ",\n " + EMString(1, 2) + "\n}",
5698 prefix + "{\n " + EMString(0, 0) +
5699 ",\n " + EMString(2, 2) + "\n}",
5700 prefix + "{\n " + EMString(0, 1) +
5701 ",\n " + EMString(2, 2) + "\n}"));
5702 }
5703
TEST_F(UnorderedElementsAreTest,Describe)5704 TEST_F(UnorderedElementsAreTest, Describe) {
5705 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5706 Eq("is empty"));
5707 EXPECT_THAT(
5708 Describe<IntVec>(UnorderedElementsAre(345)),
5709 Eq("has 1 element and that element is equal to 345"));
5710 EXPECT_THAT(
5711 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5712 Eq("has 3 elements and there exists some permutation "
5713 "of elements such that:\n"
5714 " - element #0 is equal to 111, and\n"
5715 " - element #1 is equal to 222, and\n"
5716 " - element #2 is equal to 333"));
5717 }
5718
TEST_F(UnorderedElementsAreTest,DescribeNegation)5719 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5720 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5721 Eq("isn't empty"));
5722 EXPECT_THAT(
5723 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5724 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5725 EXPECT_THAT(
5726 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5727 Eq("doesn't have 3 elements, or there exists no permutation "
5728 "of elements such that:\n"
5729 " - element #0 is equal to 123, and\n"
5730 " - element #1 is equal to 234, and\n"
5731 " - element #2 is equal to 345"));
5732 }
5733
5734 namespace {
5735
5736 // Used as a check on the more complex max flow method used in the
5737 // real testing::internal::FindMaxBipartiteMatching. This method is
5738 // compatible but runs in worst-case factorial time, so we only
5739 // use it in testing for small problem sizes.
5740 template <typename Graph>
5741 class BacktrackingMaxBPMState {
5742 public:
5743 // Does not take ownership of 'g'.
BacktrackingMaxBPMState(const Graph * g)5744 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5745
Compute()5746 ElementMatcherPairs Compute() {
5747 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5748 return best_so_far_;
5749 }
5750 lhs_used_.assign(graph_->LhsSize(), kUnused);
5751 rhs_used_.assign(graph_->RhsSize(), kUnused);
5752 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5753 matches_.clear();
5754 RecurseInto(irhs);
5755 if (best_so_far_.size() == graph_->RhsSize())
5756 break;
5757 }
5758 return best_so_far_;
5759 }
5760
5761 private:
5762 static const size_t kUnused = static_cast<size_t>(-1);
5763
PushMatch(size_t lhs,size_t rhs)5764 void PushMatch(size_t lhs, size_t rhs) {
5765 matches_.push_back(ElementMatcherPair(lhs, rhs));
5766 lhs_used_[lhs] = rhs;
5767 rhs_used_[rhs] = lhs;
5768 if (matches_.size() > best_so_far_.size()) {
5769 best_so_far_ = matches_;
5770 }
5771 }
5772
PopMatch()5773 void PopMatch() {
5774 const ElementMatcherPair& back = matches_.back();
5775 lhs_used_[back.first] = kUnused;
5776 rhs_used_[back.second] = kUnused;
5777 matches_.pop_back();
5778 }
5779
RecurseInto(size_t irhs)5780 bool RecurseInto(size_t irhs) {
5781 if (rhs_used_[irhs] != kUnused) {
5782 return true;
5783 }
5784 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5785 if (lhs_used_[ilhs] != kUnused) {
5786 continue;
5787 }
5788 if (!graph_->HasEdge(ilhs, irhs)) {
5789 continue;
5790 }
5791 PushMatch(ilhs, irhs);
5792 if (best_so_far_.size() == graph_->RhsSize()) {
5793 return false;
5794 }
5795 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5796 if (!RecurseInto(mi)) return false;
5797 }
5798 PopMatch();
5799 }
5800 return true;
5801 }
5802
5803 const Graph* graph_; // not owned
5804 std::vector<size_t> lhs_used_;
5805 std::vector<size_t> rhs_used_;
5806 ElementMatcherPairs matches_;
5807 ElementMatcherPairs best_so_far_;
5808 };
5809
5810 template <typename Graph>
5811 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5812
5813 } // namespace
5814
5815 // Implement a simple backtracking algorithm to determine if it is possible
5816 // to find one element per matcher, without reusing elements.
5817 template <typename Graph>
5818 ElementMatcherPairs
FindBacktrackingMaxBPM(const Graph & g)5819 FindBacktrackingMaxBPM(const Graph& g) {
5820 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5821 }
5822
5823 class BacktrackingBPMTest : public ::testing::Test { };
5824
5825 // Tests the MaxBipartiteMatching algorithm with square matrices.
5826 // The single int param is the # of nodes on each of the left and right sides.
5827 class BipartiteTest : public ::testing::TestWithParam<size_t> {};
5828
5829 // Verify all match graphs up to some moderate number of edges.
TEST_P(BipartiteTest,Exhaustive)5830 TEST_P(BipartiteTest, Exhaustive) {
5831 size_t nodes = GetParam();
5832 MatchMatrix graph(nodes, nodes);
5833 do {
5834 ElementMatcherPairs matches =
5835 internal::FindMaxBipartiteMatching(graph);
5836 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5837 << "graph: " << graph.DebugString();
5838 // Check that all elements of matches are in the graph.
5839 // Check that elements of first and second are unique.
5840 std::vector<bool> seen_element(graph.LhsSize());
5841 std::vector<bool> seen_matcher(graph.RhsSize());
5842 SCOPED_TRACE(PrintToString(matches));
5843 for (size_t i = 0; i < matches.size(); ++i) {
5844 size_t ilhs = matches[i].first;
5845 size_t irhs = matches[i].second;
5846 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5847 EXPECT_FALSE(seen_element[ilhs]);
5848 EXPECT_FALSE(seen_matcher[irhs]);
5849 seen_element[ilhs] = true;
5850 seen_matcher[irhs] = true;
5851 }
5852 } while (graph.NextGraph());
5853 }
5854
5855 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
5856 ::testing::Range(size_t{0}, size_t{5}));
5857
5858 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
5859 class BipartiteNonSquareTest
5860 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5861 };
5862
TEST_F(BipartiteNonSquareTest,SimpleBacktracking)5863 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5864 // .......
5865 // 0:-----\ :
5866 // 1:---\ | :
5867 // 2:---\ | :
5868 // 3:-\ | | :
5869 // :.......:
5870 // 0 1 2
5871 MatchMatrix g(4, 3);
5872 static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
5873 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
5874 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5875 }
5876 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5877 ElementsAre(Pair(3, 0),
5878 Pair(AnyOf(1, 2), 1),
5879 Pair(0, 2))) << g.DebugString();
5880 }
5881
5882 // Verify a few nonsquare matrices.
TEST_P(BipartiteNonSquareTest,Exhaustive)5883 TEST_P(BipartiteNonSquareTest, Exhaustive) {
5884 size_t nlhs = GetParam().first;
5885 size_t nrhs = GetParam().second;
5886 MatchMatrix graph(nlhs, nrhs);
5887 do {
5888 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5889 internal::FindMaxBipartiteMatching(graph).size())
5890 << "graph: " << graph.DebugString()
5891 << "\nbacktracking: "
5892 << PrintToString(FindBacktrackingMaxBPM(graph))
5893 << "\nmax flow: "
5894 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5895 } while (graph.NextGraph());
5896 }
5897
5898 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
5899 testing::Values(
5900 std::make_pair(1, 2),
5901 std::make_pair(2, 1),
5902 std::make_pair(3, 2),
5903 std::make_pair(2, 3),
5904 std::make_pair(4, 1),
5905 std::make_pair(1, 4),
5906 std::make_pair(4, 3),
5907 std::make_pair(3, 4)));
5908
5909 class BipartiteRandomTest
5910 : public ::testing::TestWithParam<std::pair<int, int> > {
5911 };
5912
5913 // Verifies a large sample of larger graphs.
TEST_P(BipartiteRandomTest,LargerNets)5914 TEST_P(BipartiteRandomTest, LargerNets) {
5915 int nodes = GetParam().first;
5916 int iters = GetParam().second;
5917 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
5918
5919 auto seed = static_cast<testing::internal::UInt32>(GTEST_FLAG(random_seed));
5920 if (seed == 0) {
5921 seed = static_cast<testing::internal::UInt32>(time(nullptr));
5922 }
5923
5924 for (; iters > 0; --iters, ++seed) {
5925 srand(static_cast<unsigned int>(seed));
5926 graph.Randomize();
5927 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5928 internal::FindMaxBipartiteMatching(graph).size())
5929 << " graph: " << graph.DebugString()
5930 << "\nTo reproduce the failure, rerun the test with the flag"
5931 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5932 }
5933 }
5934
5935 // Test argument is a std::pair<int, int> representing (nodes, iters).
5936 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
5937 testing::Values(
5938 std::make_pair(5, 10000),
5939 std::make_pair(6, 5000),
5940 std::make_pair(7, 2000),
5941 std::make_pair(8, 500),
5942 std::make_pair(9, 100)));
5943
5944 // Tests IsReadableTypeName().
5945
TEST(IsReadableTypeNameTest,ReturnsTrueForShortNames)5946 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5947 EXPECT_TRUE(IsReadableTypeName("int"));
5948 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5949 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5950 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5951 }
5952
TEST(IsReadableTypeNameTest,ReturnsTrueForLongNonTemplateNonFunctionNames)5953 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5954 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5955 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5956 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5957 }
5958
TEST(IsReadableTypeNameTest,ReturnsFalseForLongTemplateNames)5959 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5960 EXPECT_FALSE(
5961 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5962 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5963 }
5964
TEST(IsReadableTypeNameTest,ReturnsFalseForLongFunctionTypeNames)5965 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5966 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5967 }
5968
5969 // Tests FormatMatcherDescription().
5970
TEST(FormatMatcherDescriptionTest,WorksForEmptyDescription)5971 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5972 EXPECT_EQ("is even",
5973 FormatMatcherDescription(false, "IsEven", Strings()));
5974 EXPECT_EQ("not (is even)",
5975 FormatMatcherDescription(true, "IsEven", Strings()));
5976
5977 const char* params[] = {"5"};
5978 EXPECT_EQ("equals 5",
5979 FormatMatcherDescription(false, "Equals",
5980 Strings(params, params + 1)));
5981
5982 const char* params2[] = {"5", "8"};
5983 EXPECT_EQ("is in range (5, 8)",
5984 FormatMatcherDescription(false, "IsInRange",
5985 Strings(params2, params2 + 2)));
5986 }
5987
5988 // Tests PolymorphicMatcher::mutable_impl().
TEST(PolymorphicMatcherTest,CanAccessMutableImpl)5989 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5990 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5991 DivisibleByImpl& impl = m.mutable_impl();
5992 EXPECT_EQ(42, impl.divider());
5993
5994 impl.set_divider(0);
5995 EXPECT_EQ(0, m.mutable_impl().divider());
5996 }
5997
5998 // Tests PolymorphicMatcher::impl().
TEST(PolymorphicMatcherTest,CanAccessImpl)5999 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6000 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6001 const DivisibleByImpl& impl = m.impl();
6002 EXPECT_EQ(42, impl.divider());
6003 }
6004
TEST(MatcherTupleTest,ExplainsMatchFailure)6005 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6006 stringstream ss1;
6007 ExplainMatchFailureTupleTo(
6008 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6009 std::make_tuple('a', 10), &ss1);
6010 EXPECT_EQ("", ss1.str()); // Successful match.
6011
6012 stringstream ss2;
6013 ExplainMatchFailureTupleTo(
6014 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6015 std::make_tuple(2, 'b'), &ss2);
6016 EXPECT_EQ(" Expected arg #0: is > 5\n"
6017 " Actual: 2, which is 3 less than 5\n"
6018 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6019 " Actual: 'b' (98, 0x62)\n",
6020 ss2.str()); // Failed match where both arguments need explanation.
6021
6022 stringstream ss3;
6023 ExplainMatchFailureTupleTo(
6024 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6025 std::make_tuple(2, 'a'), &ss3);
6026 EXPECT_EQ(" Expected arg #0: is > 5\n"
6027 " Actual: 2, which is 3 less than 5\n",
6028 ss3.str()); // Failed match where only one argument needs
6029 // explanation.
6030 }
6031
6032 // Tests Each().
6033
TEST(EachTest,ExplainsMatchResultCorrectly)6034 TEST(EachTest, ExplainsMatchResultCorrectly) {
6035 set<int> a; // empty
6036
6037 Matcher<set<int> > m = Each(2);
6038 EXPECT_EQ("", Explain(m, a));
6039
6040 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6041
6042 const int b[1] = {1};
6043 EXPECT_EQ("", Explain(n, b));
6044
6045 n = Each(3);
6046 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6047
6048 a.insert(1);
6049 a.insert(2);
6050 a.insert(3);
6051 m = Each(GreaterThan(0));
6052 EXPECT_EQ("", Explain(m, a));
6053
6054 m = Each(GreaterThan(10));
6055 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6056 Explain(m, a));
6057 }
6058
TEST(EachTest,DescribesItselfCorrectly)6059 TEST(EachTest, DescribesItselfCorrectly) {
6060 Matcher<vector<int> > m = Each(1);
6061 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6062
6063 Matcher<vector<int> > m2 = Not(m);
6064 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6065 }
6066
TEST(EachTest,MatchesVectorWhenAllElementsMatch)6067 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6068 vector<int> some_vector;
6069 EXPECT_THAT(some_vector, Each(1));
6070 some_vector.push_back(3);
6071 EXPECT_THAT(some_vector, Not(Each(1)));
6072 EXPECT_THAT(some_vector, Each(3));
6073 some_vector.push_back(1);
6074 some_vector.push_back(2);
6075 EXPECT_THAT(some_vector, Not(Each(3)));
6076 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6077
6078 vector<std::string> another_vector;
6079 another_vector.push_back("fee");
6080 EXPECT_THAT(another_vector, Each(std::string("fee")));
6081 another_vector.push_back("fie");
6082 another_vector.push_back("foe");
6083 another_vector.push_back("fum");
6084 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6085 }
6086
TEST(EachTest,MatchesMapWhenAllElementsMatch)6087 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6088 map<const char*, int> my_map;
6089 const char* bar = "a string";
6090 my_map[bar] = 2;
6091 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6092
6093 map<std::string, int> another_map;
6094 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6095 another_map["fee"] = 1;
6096 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6097 another_map["fie"] = 2;
6098 another_map["foe"] = 3;
6099 another_map["fum"] = 4;
6100 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6101 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6102 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6103 }
6104
TEST(EachTest,AcceptsMatcher)6105 TEST(EachTest, AcceptsMatcher) {
6106 const int a[] = {1, 2, 3};
6107 EXPECT_THAT(a, Each(Gt(0)));
6108 EXPECT_THAT(a, Not(Each(Gt(1))));
6109 }
6110
TEST(EachTest,WorksForNativeArrayAsTuple)6111 TEST(EachTest, WorksForNativeArrayAsTuple) {
6112 const int a[] = {1, 2};
6113 const int* const pointer = a;
6114 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6115 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6116 }
6117
TEST(EachTest,WorksWithMoveOnly)6118 TEST(EachTest, WorksWithMoveOnly) {
6119 ContainerHelper helper;
6120 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6121 helper.Call(MakeUniquePtrs({1, 2}));
6122 }
6123
6124 // For testing Pointwise().
6125 class IsHalfOfMatcher {
6126 public:
6127 template <typename T1, typename T2>
MatchAndExplain(const std::tuple<T1,T2> & a_pair,MatchResultListener * listener) const6128 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
6129 MatchResultListener* listener) const {
6130 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6131 *listener << "where the second is " << std::get<1>(a_pair);
6132 return true;
6133 } else {
6134 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
6135 return false;
6136 }
6137 }
6138
DescribeTo(ostream * os) const6139 void DescribeTo(ostream* os) const {
6140 *os << "are a pair where the first is half of the second";
6141 }
6142
DescribeNegationTo(ostream * os) const6143 void DescribeNegationTo(ostream* os) const {
6144 *os << "are a pair where the first isn't half of the second";
6145 }
6146 };
6147
IsHalfOf()6148 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6149 return MakePolymorphicMatcher(IsHalfOfMatcher());
6150 }
6151
TEST(PointwiseTest,DescribesSelf)6152 TEST(PointwiseTest, DescribesSelf) {
6153 vector<int> rhs;
6154 rhs.push_back(1);
6155 rhs.push_back(2);
6156 rhs.push_back(3);
6157 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6158 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6159 "in { 1, 2, 3 } are a pair where the first is half of the second",
6160 Describe(m));
6161 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6162 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6163 "where the first isn't half of the second",
6164 DescribeNegation(m));
6165 }
6166
TEST(PointwiseTest,MakesCopyOfRhs)6167 TEST(PointwiseTest, MakesCopyOfRhs) {
6168 list<signed char> rhs;
6169 rhs.push_back(2);
6170 rhs.push_back(4);
6171
6172 int lhs[] = {1, 2};
6173 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6174 EXPECT_THAT(lhs, m);
6175
6176 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6177 rhs.push_back(6);
6178 EXPECT_THAT(lhs, m);
6179 }
6180
TEST(PointwiseTest,WorksForLhsNativeArray)6181 TEST(PointwiseTest, WorksForLhsNativeArray) {
6182 const int lhs[] = {1, 2, 3};
6183 vector<int> rhs;
6184 rhs.push_back(2);
6185 rhs.push_back(4);
6186 rhs.push_back(6);
6187 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6188 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6189 }
6190
TEST(PointwiseTest,WorksForRhsNativeArray)6191 TEST(PointwiseTest, WorksForRhsNativeArray) {
6192 const int rhs[] = {1, 2, 3};
6193 vector<int> lhs;
6194 lhs.push_back(2);
6195 lhs.push_back(4);
6196 lhs.push_back(6);
6197 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6198 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6199 }
6200
6201 // Test is effective only with sanitizers.
TEST(PointwiseTest,WorksForVectorOfBool)6202 TEST(PointwiseTest, WorksForVectorOfBool) {
6203 vector<bool> rhs(3, false);
6204 rhs[1] = true;
6205 vector<bool> lhs = rhs;
6206 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6207 rhs[0] = true;
6208 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6209 }
6210
6211
TEST(PointwiseTest,WorksForRhsInitializerList)6212 TEST(PointwiseTest, WorksForRhsInitializerList) {
6213 const vector<int> lhs{2, 4, 6};
6214 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6215 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6216 }
6217
6218
TEST(PointwiseTest,RejectsWrongSize)6219 TEST(PointwiseTest, RejectsWrongSize) {
6220 const double lhs[2] = {1, 2};
6221 const int rhs[1] = {0};
6222 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6223 EXPECT_EQ("which contains 2 values",
6224 Explain(Pointwise(Gt(), rhs), lhs));
6225
6226 const int rhs2[3] = {0, 1, 2};
6227 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6228 }
6229
TEST(PointwiseTest,RejectsWrongContent)6230 TEST(PointwiseTest, RejectsWrongContent) {
6231 const double lhs[3] = {1, 2, 3};
6232 const int rhs[3] = {2, 6, 4};
6233 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6234 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6235 "where the second/2 is 3",
6236 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6237 }
6238
TEST(PointwiseTest,AcceptsCorrectContent)6239 TEST(PointwiseTest, AcceptsCorrectContent) {
6240 const double lhs[3] = {1, 2, 3};
6241 const int rhs[3] = {2, 4, 6};
6242 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6243 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6244 }
6245
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)6246 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6247 const double lhs[3] = {1, 2, 3};
6248 const int rhs[3] = {2, 4, 6};
6249 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6250 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6251 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6252
6253 // This type works as a std::tuple<const double&, const int&> can be
6254 // implicitly cast to std::tuple<double, int>.
6255 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6256 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6257 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6258 }
6259
6260 MATCHER(PointeeEquals, "Points to an equal value") {
6261 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6262 ::testing::get<0>(arg), result_listener);
6263 }
6264
TEST(PointwiseTest,WorksWithMoveOnly)6265 TEST(PointwiseTest, WorksWithMoveOnly) {
6266 ContainerHelper helper;
6267 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6268 helper.Call(MakeUniquePtrs({1, 2}));
6269 }
6270
TEST(UnorderedPointwiseTest,DescribesSelf)6271 TEST(UnorderedPointwiseTest, DescribesSelf) {
6272 vector<int> rhs;
6273 rhs.push_back(1);
6274 rhs.push_back(2);
6275 rhs.push_back(3);
6276 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6277 EXPECT_EQ(
6278 "has 3 elements and there exists some permutation of elements such "
6279 "that:\n"
6280 " - element #0 and 1 are a pair where the first is half of the second, "
6281 "and\n"
6282 " - element #1 and 2 are a pair where the first is half of the second, "
6283 "and\n"
6284 " - element #2 and 3 are a pair where the first is half of the second",
6285 Describe(m));
6286 EXPECT_EQ(
6287 "doesn't have 3 elements, or there exists no permutation of elements "
6288 "such that:\n"
6289 " - element #0 and 1 are a pair where the first is half of the second, "
6290 "and\n"
6291 " - element #1 and 2 are a pair where the first is half of the second, "
6292 "and\n"
6293 " - element #2 and 3 are a pair where the first is half of the second",
6294 DescribeNegation(m));
6295 }
6296
TEST(UnorderedPointwiseTest,MakesCopyOfRhs)6297 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6298 list<signed char> rhs;
6299 rhs.push_back(2);
6300 rhs.push_back(4);
6301
6302 int lhs[] = {2, 1};
6303 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6304 EXPECT_THAT(lhs, m);
6305
6306 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6307 rhs.push_back(6);
6308 EXPECT_THAT(lhs, m);
6309 }
6310
TEST(UnorderedPointwiseTest,WorksForLhsNativeArray)6311 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6312 const int lhs[] = {1, 2, 3};
6313 vector<int> rhs;
6314 rhs.push_back(4);
6315 rhs.push_back(6);
6316 rhs.push_back(2);
6317 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6318 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6319 }
6320
TEST(UnorderedPointwiseTest,WorksForRhsNativeArray)6321 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6322 const int rhs[] = {1, 2, 3};
6323 vector<int> lhs;
6324 lhs.push_back(4);
6325 lhs.push_back(2);
6326 lhs.push_back(6);
6327 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6328 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6329 }
6330
6331
TEST(UnorderedPointwiseTest,WorksForRhsInitializerList)6332 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6333 const vector<int> lhs{2, 4, 6};
6334 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6335 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6336 }
6337
6338
TEST(UnorderedPointwiseTest,RejectsWrongSize)6339 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6340 const double lhs[2] = {1, 2};
6341 const int rhs[1] = {0};
6342 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6343 EXPECT_EQ("which has 2 elements",
6344 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6345
6346 const int rhs2[3] = {0, 1, 2};
6347 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6348 }
6349
TEST(UnorderedPointwiseTest,RejectsWrongContent)6350 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6351 const double lhs[3] = {1, 2, 3};
6352 const int rhs[3] = {2, 6, 6};
6353 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6354 EXPECT_EQ("where the following elements don't match any matchers:\n"
6355 "element #1: 2",
6356 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6357 }
6358
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInSameOrder)6359 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6360 const double lhs[3] = {1, 2, 3};
6361 const int rhs[3] = {2, 4, 6};
6362 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6363 }
6364
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInDifferentOrder)6365 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6366 const double lhs[3] = {1, 2, 3};
6367 const int rhs[3] = {6, 4, 2};
6368 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6369 }
6370
TEST(UnorderedPointwiseTest,AllowsMonomorphicInnerMatcher)6371 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6372 const double lhs[3] = {1, 2, 3};
6373 const int rhs[3] = {4, 6, 2};
6374 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6375 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6376
6377 // This type works as a std::tuple<const double&, const int&> can be
6378 // implicitly cast to std::tuple<double, int>.
6379 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6380 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6381 }
6382
TEST(UnorderedPointwiseTest,WorksWithMoveOnly)6383 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6384 ContainerHelper helper;
6385 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6386 std::vector<int>{1, 2})));
6387 helper.Call(MakeUniquePtrs({2, 1}));
6388 }
6389
6390 // Sample optional type implementation with minimal requirements for use with
6391 // Optional matcher.
6392 template <typename T>
6393 class SampleOptional {
6394 public:
6395 using value_type = T;
SampleOptional(T value)6396 explicit SampleOptional(T value)
6397 : value_(std::move(value)), has_value_(true) {}
SampleOptional()6398 SampleOptional() : value_(), has_value_(false) {}
operator bool() const6399 operator bool() const { return has_value_; }
operator *() const6400 const T& operator*() const { return value_; }
6401
6402 private:
6403 T value_;
6404 bool has_value_;
6405 };
6406
TEST(OptionalTest,DescribesSelf)6407 TEST(OptionalTest, DescribesSelf) {
6408 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6409 EXPECT_EQ("value is equal to 1", Describe(m));
6410 }
6411
TEST(OptionalTest,ExplainsSelf)6412 TEST(OptionalTest, ExplainsSelf) {
6413 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6414 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6415 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6416 }
6417
TEST(OptionalTest,MatchesNonEmptyOptional)6418 TEST(OptionalTest, MatchesNonEmptyOptional) {
6419 const Matcher<SampleOptional<int>> m1 = Optional(1);
6420 const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6421 const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6422 SampleOptional<int> opt(1);
6423 EXPECT_TRUE(m1.Matches(opt));
6424 EXPECT_FALSE(m2.Matches(opt));
6425 EXPECT_TRUE(m3.Matches(opt));
6426 }
6427
TEST(OptionalTest,DoesNotMatchNullopt)6428 TEST(OptionalTest, DoesNotMatchNullopt) {
6429 const Matcher<SampleOptional<int>> m = Optional(1);
6430 SampleOptional<int> empty;
6431 EXPECT_FALSE(m.Matches(empty));
6432 }
6433
TEST(OptionalTest,WorksWithMoveOnly)6434 TEST(OptionalTest, WorksWithMoveOnly) {
6435 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6436 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6437 }
6438
6439 class SampleVariantIntString {
6440 public:
SampleVariantIntString(int i)6441 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
SampleVariantIntString(const std::string & s)6442 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6443
6444 template <typename T>
holds_alternative(const SampleVariantIntString & value)6445 friend bool holds_alternative(const SampleVariantIntString& value) {
6446 return value.has_int_ == std::is_same<T, int>::value;
6447 }
6448
6449 template <typename T>
get(const SampleVariantIntString & value)6450 friend const T& get(const SampleVariantIntString& value) {
6451 return value.get_impl(static_cast<T*>(nullptr));
6452 }
6453
6454 private:
get_impl(int *) const6455 const int& get_impl(int*) const { return i_; }
get_impl(std::string *) const6456 const std::string& get_impl(std::string*) const { return s_; }
6457
6458 int i_;
6459 std::string s_;
6460 bool has_int_;
6461 };
6462
TEST(VariantTest,DescribesSelf)6463 TEST(VariantTest, DescribesSelf) {
6464 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6465 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6466 "'.*' and the value is equal to 1"));
6467 }
6468
TEST(VariantTest,ExplainsSelf)6469 TEST(VariantTest, ExplainsSelf) {
6470 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6471 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6472 ContainsRegex("whose value 1"));
6473 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6474 HasSubstr("whose value is not of type '"));
6475 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6476 "whose value 2 doesn't match");
6477 }
6478
TEST(VariantTest,FullMatch)6479 TEST(VariantTest, FullMatch) {
6480 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6481 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6482
6483 m = VariantWith<std::string>(Eq("1"));
6484 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6485 }
6486
TEST(VariantTest,TypeDoesNotMatch)6487 TEST(VariantTest, TypeDoesNotMatch) {
6488 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6489 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6490
6491 m = VariantWith<std::string>(Eq("1"));
6492 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6493 }
6494
TEST(VariantTest,InnerDoesNotMatch)6495 TEST(VariantTest, InnerDoesNotMatch) {
6496 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6497 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6498
6499 m = VariantWith<std::string>(Eq("1"));
6500 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6501 }
6502
6503 class SampleAnyType {
6504 public:
SampleAnyType(int i)6505 explicit SampleAnyType(int i) : index_(0), i_(i) {}
SampleAnyType(const std::string & s)6506 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6507
6508 template <typename T>
any_cast(const SampleAnyType * any)6509 friend const T* any_cast(const SampleAnyType* any) {
6510 return any->get_impl(static_cast<T*>(nullptr));
6511 }
6512
6513 private:
6514 int index_;
6515 int i_;
6516 std::string s_;
6517
get_impl(int *) const6518 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
get_impl(std::string *) const6519 const std::string* get_impl(std::string*) const {
6520 return index_ == 1 ? &s_ : nullptr;
6521 }
6522 };
6523
TEST(AnyWithTest,FullMatch)6524 TEST(AnyWithTest, FullMatch) {
6525 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6526 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6527 }
6528
TEST(AnyWithTest,TestBadCastType)6529 TEST(AnyWithTest, TestBadCastType) {
6530 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6531 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6532 }
6533
TEST(AnyWithTest,TestUseInContainers)6534 TEST(AnyWithTest, TestUseInContainers) {
6535 std::vector<SampleAnyType> a;
6536 a.emplace_back(1);
6537 a.emplace_back(2);
6538 a.emplace_back(3);
6539 EXPECT_THAT(
6540 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6541
6542 std::vector<SampleAnyType> b;
6543 b.emplace_back("hello");
6544 b.emplace_back("merhaba");
6545 b.emplace_back("salut");
6546 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6547 AnyWith<std::string>("merhaba"),
6548 AnyWith<std::string>("salut")}));
6549 }
TEST(AnyWithTest,TestCompare)6550 TEST(AnyWithTest, TestCompare) {
6551 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6552 }
6553
TEST(AnyWithTest,DescribesSelf)6554 TEST(AnyWithTest, DescribesSelf) {
6555 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6556 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6557 "'.*' and the value is equal to 1"));
6558 }
6559
TEST(AnyWithTest,ExplainsSelf)6560 TEST(AnyWithTest, ExplainsSelf) {
6561 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6562
6563 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6564 EXPECT_THAT(Explain(m, SampleAnyType("A")),
6565 HasSubstr("whose value is not of type '"));
6566 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6567 }
6568
TEST(PointeeTest,WorksOnMoveOnlyType)6569 TEST(PointeeTest, WorksOnMoveOnlyType) {
6570 std::unique_ptr<int> p(new int(3));
6571 EXPECT_THAT(p, Pointee(Eq(3)));
6572 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6573 }
6574
TEST(NotTest,WorksOnMoveOnlyType)6575 TEST(NotTest, WorksOnMoveOnlyType) {
6576 std::unique_ptr<int> p(new int(3));
6577 EXPECT_THAT(p, Pointee(Eq(3)));
6578 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6579 }
6580
6581 // Tests Args<k0, ..., kn>(m).
6582
TEST(ArgsTest,AcceptsZeroTemplateArg)6583 TEST(ArgsTest, AcceptsZeroTemplateArg) {
6584 const std::tuple<int, bool> t(5, true);
6585 EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
6586 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
6587 }
6588
TEST(ArgsTest,AcceptsOneTemplateArg)6589 TEST(ArgsTest, AcceptsOneTemplateArg) {
6590 const std::tuple<int, bool> t(5, true);
6591 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
6592 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
6593 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
6594 }
6595
TEST(ArgsTest,AcceptsTwoTemplateArgs)6596 TEST(ArgsTest, AcceptsTwoTemplateArgs) {
6597 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6598
6599 EXPECT_THAT(t, (Args<0, 1>(Lt())));
6600 EXPECT_THAT(t, (Args<1, 2>(Lt())));
6601 EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
6602 }
6603
TEST(ArgsTest,AcceptsRepeatedTemplateArgs)6604 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
6605 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6606 EXPECT_THAT(t, (Args<0, 0>(Eq())));
6607 EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
6608 }
6609
TEST(ArgsTest,AcceptsDecreasingTemplateArgs)6610 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
6611 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6612 EXPECT_THAT(t, (Args<2, 0>(Gt())));
6613 EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
6614 }
6615
6616 MATCHER(SumIsZero, "") {
6617 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
6618 }
6619
TEST(ArgsTest,AcceptsMoreTemplateArgsThanArityOfOriginalTuple)6620 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
6621 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
6622 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
6623 }
6624
TEST(ArgsTest,CanBeNested)6625 TEST(ArgsTest, CanBeNested) {
6626 const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
6627 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
6628 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
6629 }
6630
TEST(ArgsTest,CanMatchTupleByValue)6631 TEST(ArgsTest, CanMatchTupleByValue) {
6632 typedef std::tuple<char, int, int> Tuple3;
6633 const Matcher<Tuple3> m = Args<1, 2>(Lt());
6634 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
6635 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
6636 }
6637
TEST(ArgsTest,CanMatchTupleByReference)6638 TEST(ArgsTest, CanMatchTupleByReference) {
6639 typedef std::tuple<char, char, int> Tuple3;
6640 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
6641 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
6642 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
6643 }
6644
6645 // Validates that arg is printed as str.
6646 MATCHER_P(PrintsAs, str, "") {
6647 return testing::PrintToString(arg) == str;
6648 }
6649
TEST(ArgsTest,AcceptsTenTemplateArgs)6650 TEST(ArgsTest, AcceptsTenTemplateArgs) {
6651 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6652 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6653 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6654 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6655 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6656 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6657 }
6658
TEST(ArgsTest,DescirbesSelfCorrectly)6659 TEST(ArgsTest, DescirbesSelfCorrectly) {
6660 const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
6661 EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
6662 "the first < the second",
6663 Describe(m));
6664 }
6665
TEST(ArgsTest,DescirbesNestedArgsCorrectly)6666 TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
6667 const Matcher<const std::tuple<int, bool, char, int>&> m =
6668 Args<0, 2, 3>(Args<2, 0>(Lt()));
6669 EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
6670 "whose fields (#2, #0) are a pair where the first < the second",
6671 Describe(m));
6672 }
6673
TEST(ArgsTest,DescribesNegationCorrectly)6674 TEST(ArgsTest, DescribesNegationCorrectly) {
6675 const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
6676 EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
6677 "where the first > the second",
6678 DescribeNegation(m));
6679 }
6680
TEST(ArgsTest,ExplainsMatchResultWithoutInnerExplanation)6681 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
6682 const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
6683 EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
6684 Explain(m, std::make_tuple(false, 42, 42)));
6685 EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
6686 Explain(m, std::make_tuple(false, 42, 43)));
6687 }
6688
6689 // For testing Args<>'s explanation.
6690 class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
6691 public:
DescribeTo(::std::ostream *) const6692 void DescribeTo(::std::ostream* /*os*/) const override {}
6693
MatchAndExplain(std::tuple<char,int> value,MatchResultListener * listener) const6694 bool MatchAndExplain(std::tuple<char, int> value,
6695 MatchResultListener* listener) const override {
6696 const int diff = std::get<0>(value) - std::get<1>(value);
6697 if (diff > 0) {
6698 *listener << "where the first value is " << diff
6699 << " more than the second";
6700 }
6701 return diff < 0;
6702 }
6703 };
6704
LessThan()6705 Matcher<std::tuple<char, int> > LessThan() {
6706 return MakeMatcher(new LessThanMatcher);
6707 }
6708
TEST(ArgsTest,ExplainsMatchResultWithInnerExplanation)6709 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
6710 const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
6711 EXPECT_EQ(
6712 "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
6713 "where the first value is 55 more than the second",
6714 Explain(m, std::make_tuple('a', 42, 42)));
6715 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
6716 Explain(m, std::make_tuple('\0', 42, 43)));
6717 }
6718
6719 class PredicateFormatterFromMatcherTest : public ::testing::Test {
6720 protected:
6721 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
6722
6723 // A matcher that can return different results when used multiple times on the
6724 // same input. No real matcher should do this; but this lets us test that we
6725 // detect such behavior and fail appropriately.
6726 class MockMatcher : public MatcherInterface<Behavior> {
6727 public:
MatchAndExplain(Behavior behavior,MatchResultListener * listener) const6728 bool MatchAndExplain(Behavior behavior,
6729 MatchResultListener* listener) const override {
6730 *listener << "[MatchAndExplain]";
6731 switch (behavior) {
6732 case kInitialSuccess:
6733 // The first call to MatchAndExplain should use a "not interested"
6734 // listener; so this is expected to return |true|. There should be no
6735 // subsequent calls.
6736 return !listener->IsInterested();
6737
6738 case kAlwaysFail:
6739 return false;
6740
6741 case kFlaky:
6742 // The first call to MatchAndExplain should use a "not interested"
6743 // listener; so this will return |false|. Subsequent calls should have
6744 // an "interested" listener; so this will return |true|, thus
6745 // simulating a flaky matcher.
6746 return listener->IsInterested();
6747 }
6748
6749 GTEST_LOG_(FATAL) << "This should never be reached";
6750 return false;
6751 }
6752
DescribeTo(ostream * os) const6753 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
6754
DescribeNegationTo(ostream * os) const6755 void DescribeNegationTo(ostream* os) const override {
6756 *os << "[DescribeNegationTo]";
6757 }
6758 };
6759
RunPredicateFormatter(Behavior behavior)6760 AssertionResult RunPredicateFormatter(Behavior behavior) {
6761 auto matcher = MakeMatcher(new MockMatcher);
6762 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
6763 matcher);
6764 return predicate_formatter("dummy-name", behavior);
6765 }
6766 };
6767
TEST_F(PredicateFormatterFromMatcherTest,ShortCircuitOnSuccess)6768 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
6769 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
6770 EXPECT_TRUE(result); // Implicit cast to bool.
6771 std::string expect;
6772 EXPECT_EQ(expect, result.message());
6773 }
6774
TEST_F(PredicateFormatterFromMatcherTest,NoShortCircuitOnFailure)6775 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
6776 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
6777 EXPECT_FALSE(result); // Implicit cast to bool.
6778 std::string expect =
6779 "Value of: dummy-name\nExpected: [DescribeTo]\n"
6780 " Actual: 1, [MatchAndExplain]";
6781 EXPECT_EQ(expect, result.message());
6782 }
6783
TEST_F(PredicateFormatterFromMatcherTest,DetectsFlakyShortCircuit)6784 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
6785 AssertionResult result = RunPredicateFormatter(kFlaky);
6786 EXPECT_FALSE(result); // Implicit cast to bool.
6787 std::string expect =
6788 "Value of: dummy-name\nExpected: [DescribeTo]\n"
6789 " The matcher failed on the initial attempt; but passed when rerun to "
6790 "generate the explanation.\n"
6791 " Actual: 2, [MatchAndExplain]";
6792 EXPECT_EQ(expect, result.message());
6793 }
6794
6795 } // namespace
6796 } // namespace gmock_matchers_test
6797 } // namespace testing
6798
6799 #ifdef _MSC_VER
6800 # pragma warning(pop)
6801 #endif
6802