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