1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This file tests some commonly used argument matchers.
33
34 #include <functional>
35 #include <memory>
36 #include <string>
37 #include <tuple>
38 #include <vector>
39
40 #include "test/gmock-matchers_test.h"
41
42 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
43 // possible loss of data and C4100, unreferenced local parameter
44 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
45
46
47 namespace testing {
48 namespace gmock_matchers_test {
49 namespace {
50
51 INSTANTIATE_GTEST_MATCHER_TEST_P(MonotonicMatcherTest);
52
TEST_P(MonotonicMatcherTestP,IsPrintable)53 TEST_P(MonotonicMatcherTestP, IsPrintable) {
54 stringstream ss;
55 ss << GreaterThan(5);
56 EXPECT_EQ("is > 5", ss.str());
57 }
58
TEST(MatchResultListenerTest,StreamingWorks)59 TEST(MatchResultListenerTest, StreamingWorks) {
60 StringMatchResultListener listener;
61 listener << "hi" << 5;
62 EXPECT_EQ("hi5", listener.str());
63
64 listener.Clear();
65 EXPECT_EQ("", listener.str());
66
67 listener << 42;
68 EXPECT_EQ("42", listener.str());
69
70 // Streaming shouldn't crash when the underlying ostream is NULL.
71 DummyMatchResultListener dummy;
72 dummy << "hi" << 5;
73 }
74
TEST(MatchResultListenerTest,CanAccessUnderlyingStream)75 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
76 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
77 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
78
79 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
80 }
81
TEST(MatchResultListenerTest,IsInterestedWorks)82 TEST(MatchResultListenerTest, IsInterestedWorks) {
83 EXPECT_TRUE(StringMatchResultListener().IsInterested());
84 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
85
86 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
87 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
88 }
89
90 // Makes sure that the MatcherInterface<T> interface doesn't
91 // change.
92 class EvenMatcherImpl : public MatcherInterface<int> {
93 public:
MatchAndExplain(int x,MatchResultListener *) const94 bool MatchAndExplain(int x,
95 MatchResultListener* /* listener */) const override {
96 return x % 2 == 0;
97 }
98
DescribeTo(ostream * os) const99 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
100
101 // We deliberately don't define DescribeNegationTo() and
102 // ExplainMatchResultTo() here, to make sure the definition of these
103 // two methods is optional.
104 };
105
106 // Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest,CanBeImplementedUsingPublishedAPI)107 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
108 EvenMatcherImpl m;
109 }
110
111 // Tests implementing a monomorphic matcher using MatchAndExplain().
112
113 class NewEvenMatcherImpl : public MatcherInterface<int> {
114 public:
MatchAndExplain(int x,MatchResultListener * listener) const115 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
116 const bool match = x % 2 == 0;
117 // Verifies that we can stream to a listener directly.
118 *listener << "value % " << 2;
119 if (listener->stream() != nullptr) {
120 // Verifies that we can stream to a listener's underlying stream
121 // too.
122 *listener->stream() << " == " << (x % 2);
123 }
124 return match;
125 }
126
DescribeTo(ostream * os) const127 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
128 };
129
TEST(MatcherInterfaceTest,CanBeImplementedUsingNewAPI)130 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
131 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
132 EXPECT_TRUE(m.Matches(2));
133 EXPECT_FALSE(m.Matches(3));
134 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
135 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
136 }
137
138 INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTest);
139
140 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)141 TEST(MatcherTest, CanBeDefaultConstructed) { Matcher<double> m; }
142
143 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)144 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
145 const MatcherInterface<int>* impl = new EvenMatcherImpl;
146 Matcher<int> m(impl);
147 EXPECT_TRUE(m.Matches(4));
148 EXPECT_FALSE(m.Matches(5));
149 }
150
151 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)152 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
153 Matcher<int> m1 = 5;
154 EXPECT_TRUE(m1.Matches(5));
155 EXPECT_FALSE(m1.Matches(6));
156 }
157
158 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)159 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
160 Matcher<int*> m1 = nullptr;
161 EXPECT_TRUE(m1.Matches(nullptr));
162 int n = 0;
163 EXPECT_FALSE(m1.Matches(&n));
164 }
165
166 // Tests that matchers can be constructed from a variable that is not properly
167 // defined. This should be illegal, but many users rely on this accidentally.
168 struct Undefined {
169 virtual ~Undefined() = 0;
170 static const int kInt = 1;
171 };
172
TEST(MatcherTest,CanBeConstructedFromUndefinedVariable)173 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
174 Matcher<int> m1 = Undefined::kInt;
175 EXPECT_TRUE(m1.Matches(1));
176 EXPECT_FALSE(m1.Matches(2));
177 }
178
179 // Test that a matcher parameterized with an abstract class compiles.
TEST(MatcherTest,CanAcceptAbstractClass)180 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
181
182 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)183 TEST(MatcherTest, IsCopyable) {
184 // Tests the copy constructor.
185 Matcher<bool> m1 = Eq(false);
186 EXPECT_TRUE(m1.Matches(false));
187 EXPECT_FALSE(m1.Matches(true));
188
189 // Tests the assignment operator.
190 m1 = Eq(true);
191 EXPECT_TRUE(m1.Matches(true));
192 EXPECT_FALSE(m1.Matches(false));
193 }
194
195 // Tests that Matcher<T>::DescribeTo() calls
196 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)197 TEST(MatcherTest, CanDescribeItself) {
198 EXPECT_EQ("is an even number", Describe(Matcher<int>(new EvenMatcherImpl)));
199 }
200
201 // Tests Matcher<T>::MatchAndExplain().
TEST_P(MatcherTestP,MatchAndExplain)202 TEST_P(MatcherTestP, MatchAndExplain) {
203 Matcher<int> m = GreaterThan(0);
204 StringMatchResultListener listener1;
205 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
206 EXPECT_EQ("which is 42 more than 0", listener1.str());
207
208 StringMatchResultListener listener2;
209 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
210 EXPECT_EQ("which is 9 less than 0", listener2.str());
211 }
212
213 // Tests that a C-string literal can be implicitly converted to a
214 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)215 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
216 Matcher<std::string> m1 = "hi";
217 EXPECT_TRUE(m1.Matches("hi"));
218 EXPECT_FALSE(m1.Matches("hello"));
219
220 Matcher<const std::string&> m2 = "hi";
221 EXPECT_TRUE(m2.Matches("hi"));
222 EXPECT_FALSE(m2.Matches("hello"));
223 }
224
225 // Tests that a string object can be implicitly converted to a
226 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)227 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
228 Matcher<std::string> m1 = std::string("hi");
229 EXPECT_TRUE(m1.Matches("hi"));
230 EXPECT_FALSE(m1.Matches("hello"));
231
232 Matcher<const std::string&> m2 = std::string("hi");
233 EXPECT_TRUE(m2.Matches("hi"));
234 EXPECT_FALSE(m2.Matches("hello"));
235 }
236
237 #if GTEST_INTERNAL_HAS_STRING_VIEW
238 // Tests that a C-string literal can be implicitly converted to a
239 // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)240 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
241 Matcher<internal::StringView> m1 = "cats";
242 EXPECT_TRUE(m1.Matches("cats"));
243 EXPECT_FALSE(m1.Matches("dogs"));
244
245 Matcher<const internal::StringView&> m2 = "cats";
246 EXPECT_TRUE(m2.Matches("cats"));
247 EXPECT_FALSE(m2.Matches("dogs"));
248 }
249
250 // Tests that a std::string object can be implicitly converted to a
251 // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromString)252 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
253 Matcher<internal::StringView> m1 = std::string("cats");
254 EXPECT_TRUE(m1.Matches("cats"));
255 EXPECT_FALSE(m1.Matches("dogs"));
256
257 Matcher<const internal::StringView&> m2 = std::string("cats");
258 EXPECT_TRUE(m2.Matches("cats"));
259 EXPECT_FALSE(m2.Matches("dogs"));
260 }
261
262 // Tests that a StringView object can be implicitly converted to a
263 // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromStringView)264 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
265 Matcher<internal::StringView> m1 = internal::StringView("cats");
266 EXPECT_TRUE(m1.Matches("cats"));
267 EXPECT_FALSE(m1.Matches("dogs"));
268
269 Matcher<const internal::StringView&> m2 = internal::StringView("cats");
270 EXPECT_TRUE(m2.Matches("cats"));
271 EXPECT_FALSE(m2.Matches("dogs"));
272 }
273 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
274
275 // Tests that a std::reference_wrapper<std::string> object can be implicitly
276 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromEqReferenceWrapperString)277 TEST(StringMatcherTest,
278 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
279 std::string value = "cats";
280 Matcher<std::string> m1 = Eq(std::ref(value));
281 EXPECT_TRUE(m1.Matches("cats"));
282 EXPECT_FALSE(m1.Matches("dogs"));
283
284 Matcher<const std::string&> m2 = Eq(std::ref(value));
285 EXPECT_TRUE(m2.Matches("cats"));
286 EXPECT_FALSE(m2.Matches("dogs"));
287 }
288
289 // Tests that MakeMatcher() constructs a Matcher<T> from a
290 // MatcherInterface* without requiring the user to explicitly
291 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)292 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
293 const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
294 Matcher<int> m = MakeMatcher(dummy_impl);
295 }
296
297 // Tests that MakePolymorphicMatcher() can construct a polymorphic
298 // matcher from its implementation using the old API.
299 const int g_bar = 1;
300 class ReferencesBarOrIsZeroImpl {
301 public:
302 template <typename T>
MatchAndExplain(const T & x,MatchResultListener *) const303 bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const {
304 const void* p = &x;
305 return p == &g_bar || x == 0;
306 }
307
DescribeTo(ostream * os) const308 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
309
DescribeNegationTo(ostream * os) const310 void DescribeNegationTo(ostream* os) const {
311 *os << "doesn't reference g_bar and is not zero";
312 }
313 };
314
315 // This function verifies that MakePolymorphicMatcher() returns a
316 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()317 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
318 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
319 }
320
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingOldAPI)321 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
322 // Using a polymorphic matcher to match a reference type.
323 Matcher<const int&> m1 = ReferencesBarOrIsZero();
324 EXPECT_TRUE(m1.Matches(0));
325 // Verifies that the identity of a by-reference argument is preserved.
326 EXPECT_TRUE(m1.Matches(g_bar));
327 EXPECT_FALSE(m1.Matches(1));
328 EXPECT_EQ("g_bar or zero", Describe(m1));
329
330 // Using a polymorphic matcher to match a value type.
331 Matcher<double> m2 = ReferencesBarOrIsZero();
332 EXPECT_TRUE(m2.Matches(0.0));
333 EXPECT_FALSE(m2.Matches(0.1));
334 EXPECT_EQ("g_bar or zero", Describe(m2));
335 }
336
337 // Tests implementing a polymorphic matcher using MatchAndExplain().
338
339 class PolymorphicIsEvenImpl {
340 public:
DescribeTo(ostream * os) const341 void DescribeTo(ostream* os) const { *os << "is even"; }
342
DescribeNegationTo(ostream * os) const343 void DescribeNegationTo(ostream* os) const { *os << "is odd"; }
344
345 template <typename T>
MatchAndExplain(const T & x,MatchResultListener * listener) const346 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
347 // Verifies that we can stream to the listener directly.
348 *listener << "% " << 2;
349 if (listener->stream() != nullptr) {
350 // Verifies that we can stream to the listener's underlying stream
351 // too.
352 *listener->stream() << " == " << (x % 2);
353 }
354 return (x % 2) == 0;
355 }
356 };
357
PolymorphicIsEven()358 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
359 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
360 }
361
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingNewAPI)362 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
363 // Using PolymorphicIsEven() as a Matcher<int>.
364 const Matcher<int> m1 = PolymorphicIsEven();
365 EXPECT_TRUE(m1.Matches(42));
366 EXPECT_FALSE(m1.Matches(43));
367 EXPECT_EQ("is even", Describe(m1));
368
369 const Matcher<int> not_m1 = Not(m1);
370 EXPECT_EQ("is odd", Describe(not_m1));
371
372 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
373
374 // Using PolymorphicIsEven() as a Matcher<char>.
375 const Matcher<char> m2 = PolymorphicIsEven();
376 EXPECT_TRUE(m2.Matches('\x42'));
377 EXPECT_FALSE(m2.Matches('\x43'));
378 EXPECT_EQ("is even", Describe(m2));
379
380 const Matcher<char> not_m2 = Not(m2);
381 EXPECT_EQ("is odd", Describe(not_m2));
382
383 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
384 }
385
386 INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherCastTest);
387
388 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST_P(MatcherCastTestP,FromPolymorphicMatcher)389 TEST_P(MatcherCastTestP, FromPolymorphicMatcher) {
390 Matcher<int16_t> m;
391 if (use_gtest_matcher_) {
392 m = MatcherCast<int16_t>(GtestGreaterThan(int64_t{5}));
393 } else {
394 m = MatcherCast<int16_t>(Gt(int64_t{5}));
395 }
396 EXPECT_TRUE(m.Matches(6));
397 EXPECT_FALSE(m.Matches(4));
398 }
399
400 // For testing casting matchers between compatible types.
401 class IntValue {
402 public:
403 // An int can be statically (although not implicitly) cast to a
404 // IntValue.
IntValue(int a_value)405 explicit IntValue(int a_value) : value_(a_value) {}
406
value() const407 int value() const { return value_; }
408
409 private:
410 int value_;
411 };
412
413 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)414 bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
415
416 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
417 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)418 TEST(MatcherCastTest, FromCompatibleType) {
419 Matcher<double> m1 = Eq(2.0);
420 Matcher<int> m2 = MatcherCast<int>(m1);
421 EXPECT_TRUE(m2.Matches(2));
422 EXPECT_FALSE(m2.Matches(3));
423
424 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
425 Matcher<int> m4 = MatcherCast<int>(m3);
426 // In the following, the arguments 1 and 0 are statically converted
427 // to IntValue objects, and then tested by the IsPositiveIntValue()
428 // predicate.
429 EXPECT_TRUE(m4.Matches(1));
430 EXPECT_FALSE(m4.Matches(0));
431 }
432
433 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)434 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
435 Matcher<const int&> m1 = Eq(0);
436 Matcher<int> m2 = MatcherCast<int>(m1);
437 EXPECT_TRUE(m2.Matches(0));
438 EXPECT_FALSE(m2.Matches(1));
439 }
440
441 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)442 TEST(MatcherCastTest, FromReferenceToNonReference) {
443 Matcher<int&> m1 = Eq(0);
444 Matcher<int> m2 = MatcherCast<int>(m1);
445 EXPECT_TRUE(m2.Matches(0));
446 EXPECT_FALSE(m2.Matches(1));
447 }
448
449 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)450 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
451 Matcher<int> m1 = Eq(0);
452 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
453 EXPECT_TRUE(m2.Matches(0));
454 EXPECT_FALSE(m2.Matches(1));
455 }
456
457 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)458 TEST(MatcherCastTest, FromNonReferenceToReference) {
459 Matcher<int> m1 = Eq(0);
460 Matcher<int&> m2 = MatcherCast<int&>(m1);
461 int n = 0;
462 EXPECT_TRUE(m2.Matches(n));
463 n = 1;
464 EXPECT_FALSE(m2.Matches(n));
465 }
466
467 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)468 TEST(MatcherCastTest, FromSameType) {
469 Matcher<int> m1 = Eq(0);
470 Matcher<int> m2 = MatcherCast<int>(m1);
471 EXPECT_TRUE(m2.Matches(0));
472 EXPECT_FALSE(m2.Matches(1));
473 }
474
475 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
476 // value type of the Matcher.
TEST(MatcherCastTest,FromAValue)477 TEST(MatcherCastTest, FromAValue) {
478 Matcher<int> m = MatcherCast<int>(42);
479 EXPECT_TRUE(m.Matches(42));
480 EXPECT_FALSE(m.Matches(239));
481 }
482
483 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
484 // convertible to the value type of the Matcher.
TEST(MatcherCastTest,FromAnImplicitlyConvertibleValue)485 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
486 const int kExpected = 'c';
487 Matcher<int> m = MatcherCast<int>('c');
488 EXPECT_TRUE(m.Matches(kExpected));
489 EXPECT_FALSE(m.Matches(kExpected + 1));
490 }
491
492 struct NonImplicitlyConstructibleTypeWithOperatorEq {
operator ==(const NonImplicitlyConstructibleTypeWithOperatorEq &,int rhs)493 friend bool operator==(
494 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
495 int rhs) {
496 return 42 == rhs;
497 }
operator ==(int lhs,const NonImplicitlyConstructibleTypeWithOperatorEq &)498 friend bool operator==(
499 int lhs,
500 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
501 return lhs == 42;
502 }
503 };
504
505 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
506 // implicitly convertible to the value type of the Matcher, but the value type
507 // of the matcher has operator==() overload accepting m.
TEST(MatcherCastTest,NonImplicitlyConstructibleTypeWithOperatorEq)508 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
509 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
510 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
511 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
512
513 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
514 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
515 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
516
517 // When updating the following lines please also change the comment to
518 // namespace convertible_from_any.
519 Matcher<int> m3 =
520 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
521 EXPECT_TRUE(m3.Matches(42));
522 EXPECT_FALSE(m3.Matches(239));
523 }
524
525 // ConvertibleFromAny does not work with MSVC. resulting in
526 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
527 // No constructor could take the source type, or constructor overload
528 // resolution was ambiguous
529
530 #if !defined _MSC_VER
531
532 // The below ConvertibleFromAny struct is implicitly constructible from anything
533 // and when in the same namespace can interact with other tests. In particular,
534 // if it is in the same namespace as other tests and one removes
535 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
536 // then the corresponding test still compiles (and it should not!) by implicitly
537 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
538 // in m3.Matcher().
539 namespace convertible_from_any {
540 // Implicitly convertible from any type.
541 struct ConvertibleFromAny {
ConvertibleFromAnytesting::gmock_matchers_test::__anon74f0a33d0111::convertible_from_any::ConvertibleFromAny542 ConvertibleFromAny(int a_value) : value(a_value) {}
543 template <typename T>
ConvertibleFromAnytesting::gmock_matchers_test::__anon74f0a33d0111::convertible_from_any::ConvertibleFromAny544 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
545 ADD_FAILURE() << "Conversion constructor called";
546 }
547 int value;
548 };
549
operator ==(const ConvertibleFromAny & a,const ConvertibleFromAny & b)550 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
551 return a.value == b.value;
552 }
553
operator <<(ostream & os,const ConvertibleFromAny & a)554 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
555 return os << a.value;
556 }
557
TEST(MatcherCastTest,ConversionConstructorIsUsed)558 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
559 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
560 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
561 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
562 }
563
TEST(MatcherCastTest,FromConvertibleFromAny)564 TEST(MatcherCastTest, FromConvertibleFromAny) {
565 Matcher<ConvertibleFromAny> m =
566 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
567 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
568 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
569 }
570 } // namespace convertible_from_any
571
572 #endif // !defined _MSC_VER
573
574 struct IntReferenceWrapper {
IntReferenceWrappertesting::gmock_matchers_test::__anon74f0a33d0111::IntReferenceWrapper575 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
576 const int* value;
577 };
578
operator ==(const IntReferenceWrapper & a,const IntReferenceWrapper & b)579 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
580 return a.value == b.value;
581 }
582
TEST(MatcherCastTest,ValueIsNotCopied)583 TEST(MatcherCastTest, ValueIsNotCopied) {
584 int n = 42;
585 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
586 // Verify that the matcher holds a reference to n, not to its temporary copy.
587 EXPECT_TRUE(m.Matches(n));
588 }
589
590 class Base {
591 public:
592 virtual ~Base() = default;
593 Base() = default;
594
595 private:
596 Base(const Base&) = delete;
597 Base& operator=(const Base&) = delete;
598 };
599
600 class Derived : public Base {
601 public:
Derived()602 Derived() : Base() {}
603 int i;
604 };
605
606 class OtherDerived : public Base {};
607
608 INSTANTIATE_GTEST_MATCHER_TEST_P(SafeMatcherCastTest);
609
610 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST_P(SafeMatcherCastTestP,FromPolymorphicMatcher)611 TEST_P(SafeMatcherCastTestP, FromPolymorphicMatcher) {
612 Matcher<char> m2;
613 if (use_gtest_matcher_) {
614 m2 = SafeMatcherCast<char>(GtestGreaterThan(32));
615 } else {
616 m2 = SafeMatcherCast<char>(Gt(32));
617 }
618 EXPECT_TRUE(m2.Matches('A'));
619 EXPECT_FALSE(m2.Matches('\n'));
620 }
621
622 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
623 // T and U are arithmetic types and T can be losslessly converted to
624 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)625 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
626 Matcher<double> m1 = DoubleEq(1.0);
627 Matcher<float> m2 = SafeMatcherCast<float>(m1);
628 EXPECT_TRUE(m2.Matches(1.0f));
629 EXPECT_FALSE(m2.Matches(2.0f));
630
631 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
632 EXPECT_TRUE(m3.Matches('a'));
633 EXPECT_FALSE(m3.Matches('b'));
634 }
635
636 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
637 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)638 TEST(SafeMatcherCastTest, FromBaseClass) {
639 Derived d, d2;
640 Matcher<Base*> m1 = Eq(&d);
641 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
642 EXPECT_TRUE(m2.Matches(&d));
643 EXPECT_FALSE(m2.Matches(&d2));
644
645 Matcher<Base&> m3 = Ref(d);
646 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
647 EXPECT_TRUE(m4.Matches(d));
648 EXPECT_FALSE(m4.Matches(d2));
649 }
650
651 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)652 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
653 int n = 0;
654 Matcher<const int&> m1 = Ref(n);
655 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
656 int n1 = 0;
657 EXPECT_TRUE(m2.Matches(n));
658 EXPECT_FALSE(m2.Matches(n1));
659 }
660
661 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)662 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
663 Matcher<std::unique_ptr<int>> m1 = IsNull();
664 Matcher<const std::unique_ptr<int>&> m2 =
665 SafeMatcherCast<const std::unique_ptr<int>&>(m1);
666 EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
667 EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
668 }
669
670 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)671 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
672 Matcher<int> m1 = Eq(0);
673 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
674 int n = 0;
675 EXPECT_TRUE(m2.Matches(n));
676 n = 1;
677 EXPECT_FALSE(m2.Matches(n));
678 }
679
680 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)681 TEST(SafeMatcherCastTest, FromSameType) {
682 Matcher<int> m1 = Eq(0);
683 Matcher<int> m2 = SafeMatcherCast<int>(m1);
684 EXPECT_TRUE(m2.Matches(0));
685 EXPECT_FALSE(m2.Matches(1));
686 }
687
688 #if !defined _MSC_VER
689
690 namespace convertible_from_any {
TEST(SafeMatcherCastTest,ConversionConstructorIsUsed)691 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
692 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
693 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
694 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
695 }
696
TEST(SafeMatcherCastTest,FromConvertibleFromAny)697 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
698 Matcher<ConvertibleFromAny> m =
699 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
700 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
701 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
702 }
703 } // namespace convertible_from_any
704
705 #endif // !defined _MSC_VER
706
TEST(SafeMatcherCastTest,ValueIsNotCopied)707 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
708 int n = 42;
709 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
710 // Verify that the matcher holds a reference to n, not to its temporary copy.
711 EXPECT_TRUE(m.Matches(n));
712 }
713
TEST(ExpectThat,TakesLiterals)714 TEST(ExpectThat, TakesLiterals) {
715 EXPECT_THAT(1, 1);
716 EXPECT_THAT(1.0, 1.0);
717 EXPECT_THAT(std::string(), "");
718 }
719
TEST(ExpectThat,TakesFunctions)720 TEST(ExpectThat, TakesFunctions) {
721 struct Helper {
722 static void Func() {}
723 };
724 void (*func)() = Helper::Func;
725 EXPECT_THAT(func, Helper::Func);
726 EXPECT_THAT(func, &Helper::Func);
727 }
728
729 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)730 TEST(ATest, MatchesAnyValue) {
731 // Tests a matcher for a value type.
732 Matcher<double> m1 = A<double>();
733 EXPECT_TRUE(m1.Matches(91.43));
734 EXPECT_TRUE(m1.Matches(-15.32));
735
736 // Tests a matcher for a reference type.
737 int a = 2;
738 int b = -6;
739 Matcher<int&> m2 = A<int&>();
740 EXPECT_TRUE(m2.Matches(a));
741 EXPECT_TRUE(m2.Matches(b));
742 }
743
TEST(ATest,WorksForDerivedClass)744 TEST(ATest, WorksForDerivedClass) {
745 Base base;
746 Derived derived;
747 EXPECT_THAT(&base, A<Base*>());
748 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
749 EXPECT_THAT(&derived, A<Base*>());
750 EXPECT_THAT(&derived, A<Derived*>());
751 }
752
753 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)754 TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A<bool>())); }
755
756 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)757 TEST(AnTest, MatchesAnyValue) {
758 // Tests a matcher for a value type.
759 Matcher<int> m1 = An<int>();
760 EXPECT_TRUE(m1.Matches(9143));
761 EXPECT_TRUE(m1.Matches(-1532));
762
763 // Tests a matcher for a reference type.
764 int a = 2;
765 int b = -6;
766 Matcher<int&> m2 = An<int&>();
767 EXPECT_TRUE(m2.Matches(a));
768 EXPECT_TRUE(m2.Matches(b));
769 }
770
771 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)772 TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An<int>())); }
773
774 // Tests that _ can be used as a matcher for any type and matches any
775 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)776 TEST(UnderscoreTest, MatchesAnyValue) {
777 // Uses _ as a matcher for a value type.
778 Matcher<int> m1 = _;
779 EXPECT_TRUE(m1.Matches(123));
780 EXPECT_TRUE(m1.Matches(-242));
781
782 // Uses _ as a matcher for a reference type.
783 bool a = false;
784 const bool b = true;
785 Matcher<const bool&> m2 = _;
786 EXPECT_TRUE(m2.Matches(a));
787 EXPECT_TRUE(m2.Matches(b));
788 }
789
790 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)791 TEST(UnderscoreTest, CanDescribeSelf) {
792 Matcher<int> m = _;
793 EXPECT_EQ("is anything", Describe(m));
794 }
795
796 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)797 TEST(EqTest, MatchesEqualValue) {
798 // 2 C-strings with same content but different addresses.
799 const char a1[] = "hi";
800 const char a2[] = "hi";
801
802 Matcher<const char*> m1 = Eq(a1);
803 EXPECT_TRUE(m1.Matches(a1));
804 EXPECT_FALSE(m1.Matches(a2));
805 }
806
807 // Tests that Eq(v) describes itself properly.
808
809 class Unprintable {
810 public:
Unprintable()811 Unprintable() : c_('a') {}
812
operator ==(const Unprintable &) const813 bool operator==(const Unprintable& /* rhs */) const { return true; }
814 // -Wunused-private-field: dummy accessor for `c_`.
dummy_c()815 char dummy_c() { return c_; }
816
817 private:
818 char c_;
819 };
820
TEST(EqTest,CanDescribeSelf)821 TEST(EqTest, CanDescribeSelf) {
822 Matcher<Unprintable> m = Eq(Unprintable());
823 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
824 }
825
826 // Tests that Eq(v) can be used to match any type that supports
827 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)828 TEST(EqTest, IsPolymorphic) {
829 Matcher<int> m1 = Eq(1);
830 EXPECT_TRUE(m1.Matches(1));
831 EXPECT_FALSE(m1.Matches(2));
832
833 Matcher<char> m2 = Eq(1);
834 EXPECT_TRUE(m2.Matches('\1'));
835 EXPECT_FALSE(m2.Matches('a'));
836 }
837
838 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)839 TEST(TypedEqTest, ChecksEqualityForGivenType) {
840 Matcher<char> m1 = TypedEq<char>('a');
841 EXPECT_TRUE(m1.Matches('a'));
842 EXPECT_FALSE(m1.Matches('b'));
843
844 Matcher<int> m2 = TypedEq<int>(6);
845 EXPECT_TRUE(m2.Matches(6));
846 EXPECT_FALSE(m2.Matches(7));
847 }
848
849 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)850 TEST(TypedEqTest, CanDescribeSelf) {
851 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
852 }
853
854 // Tests that TypedEq<T>(v) has type Matcher<T>.
855
856 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
857 // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
858 // not T, the compiler will generate a message about "undefined reference".
859 template <typename T>
860 struct Type {
IsTypeOftesting::gmock_matchers_test::__anon74f0a33d0111::Type861 static bool IsTypeOf(const T& /* v */) { return true; }
862
863 template <typename T2>
864 static void IsTypeOf(T2 v);
865 };
866
TEST(TypedEqTest,HasSpecifiedType)867 TEST(TypedEqTest, HasSpecifiedType) {
868 // Verifies that the type of TypedEq<T>(v) is Matcher<T>.
869 Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
870 Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
871 }
872
873 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)874 TEST(GeTest, ImplementsGreaterThanOrEqual) {
875 Matcher<int> m1 = Ge(0);
876 EXPECT_TRUE(m1.Matches(1));
877 EXPECT_TRUE(m1.Matches(0));
878 EXPECT_FALSE(m1.Matches(-1));
879 }
880
881 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)882 TEST(GeTest, CanDescribeSelf) {
883 Matcher<int> m = Ge(5);
884 EXPECT_EQ("is >= 5", Describe(m));
885 }
886
887 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)888 TEST(GtTest, ImplementsGreaterThan) {
889 Matcher<double> m1 = Gt(0);
890 EXPECT_TRUE(m1.Matches(1.0));
891 EXPECT_FALSE(m1.Matches(0.0));
892 EXPECT_FALSE(m1.Matches(-1.0));
893 }
894
895 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)896 TEST(GtTest, CanDescribeSelf) {
897 Matcher<int> m = Gt(5);
898 EXPECT_EQ("is > 5", Describe(m));
899 }
900
901 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)902 TEST(LeTest, ImplementsLessThanOrEqual) {
903 Matcher<char> m1 = Le('b');
904 EXPECT_TRUE(m1.Matches('a'));
905 EXPECT_TRUE(m1.Matches('b'));
906 EXPECT_FALSE(m1.Matches('c'));
907 }
908
909 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)910 TEST(LeTest, CanDescribeSelf) {
911 Matcher<int> m = Le(5);
912 EXPECT_EQ("is <= 5", Describe(m));
913 }
914
915 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)916 TEST(LtTest, ImplementsLessThan) {
917 Matcher<const std::string&> m1 = Lt("Hello");
918 EXPECT_TRUE(m1.Matches("Abc"));
919 EXPECT_FALSE(m1.Matches("Hello"));
920 EXPECT_FALSE(m1.Matches("Hello, world!"));
921 }
922
923 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)924 TEST(LtTest, CanDescribeSelf) {
925 Matcher<int> m = Lt(5);
926 EXPECT_EQ("is < 5", Describe(m));
927 }
928
929 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)930 TEST(NeTest, ImplementsNotEqual) {
931 Matcher<int> m1 = Ne(0);
932 EXPECT_TRUE(m1.Matches(1));
933 EXPECT_TRUE(m1.Matches(-1));
934 EXPECT_FALSE(m1.Matches(0));
935 }
936
937 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)938 TEST(NeTest, CanDescribeSelf) {
939 Matcher<int> m = Ne(5);
940 EXPECT_EQ("isn't equal to 5", Describe(m));
941 }
942
943 class MoveOnly {
944 public:
MoveOnly(int i)945 explicit MoveOnly(int i) : i_(i) {}
946 MoveOnly(const MoveOnly&) = delete;
947 MoveOnly(MoveOnly&&) = default;
948 MoveOnly& operator=(const MoveOnly&) = delete;
949 MoveOnly& operator=(MoveOnly&&) = default;
950
operator ==(const MoveOnly & other) const951 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
operator !=(const MoveOnly & other) const952 bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
operator <(const MoveOnly & other) const953 bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
operator <=(const MoveOnly & other) const954 bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
operator >(const MoveOnly & other) const955 bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
operator >=(const MoveOnly & other) const956 bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
957
958 private:
959 int i_;
960 };
961
962 struct MoveHelper {
963 MOCK_METHOD1(Call, void(MoveOnly));
964 };
965
966 // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
967 #if defined(_MSC_VER) && (_MSC_VER < 1910)
TEST(ComparisonBaseTest,DISABLED_WorksWithMoveOnly)968 TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
969 #else
970 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
971 #endif
972 MoveOnly m{0};
973 MoveHelper helper;
974
975 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
976 helper.Call(MoveOnly(0));
977 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
978 helper.Call(MoveOnly(1));
979 EXPECT_CALL(helper, Call(Le(ByRef(m))));
980 helper.Call(MoveOnly(0));
981 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
982 helper.Call(MoveOnly(-1));
983 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
984 helper.Call(MoveOnly(0));
985 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
986 helper.Call(MoveOnly(1));
987 }
988
989 TEST(IsEmptyTest, MatchesContainer) {
990 const Matcher<std::vector<int>> m = IsEmpty();
991 std::vector<int> a = {};
992 std::vector<int> b = {1};
993 EXPECT_TRUE(m.Matches(a));
994 EXPECT_FALSE(m.Matches(b));
995 }
996
997 TEST(IsEmptyTest, MatchesStdString) {
998 const Matcher<std::string> m = IsEmpty();
999 std::string a = "z";
1000 std::string b = "";
1001 EXPECT_FALSE(m.Matches(a));
1002 EXPECT_TRUE(m.Matches(b));
1003 }
1004
1005 TEST(IsEmptyTest, MatchesCString) {
1006 const Matcher<const char*> m = IsEmpty();
1007 const char a[] = "";
1008 const char b[] = "x";
1009 EXPECT_TRUE(m.Matches(a));
1010 EXPECT_FALSE(m.Matches(b));
1011 }
1012
1013 // Tests that IsNull() matches any NULL pointer of any type.
1014 TEST(IsNullTest, MatchesNullPointer) {
1015 Matcher<int*> m1 = IsNull();
1016 int* p1 = nullptr;
1017 int n = 0;
1018 EXPECT_TRUE(m1.Matches(p1));
1019 EXPECT_FALSE(m1.Matches(&n));
1020
1021 Matcher<const char*> m2 = IsNull();
1022 const char* p2 = nullptr;
1023 EXPECT_TRUE(m2.Matches(p2));
1024 EXPECT_FALSE(m2.Matches("hi"));
1025
1026 Matcher<void*> m3 = IsNull();
1027 void* p3 = nullptr;
1028 EXPECT_TRUE(m3.Matches(p3));
1029 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1030 }
1031
1032 TEST(IsNullTest, StdFunction) {
1033 const Matcher<std::function<void()>> m = IsNull();
1034
1035 EXPECT_TRUE(m.Matches(std::function<void()>()));
1036 EXPECT_FALSE(m.Matches([] {}));
1037 }
1038
1039 // Tests that IsNull() describes itself properly.
1040 TEST(IsNullTest, CanDescribeSelf) {
1041 Matcher<int*> m = IsNull();
1042 EXPECT_EQ("is NULL", Describe(m));
1043 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1044 }
1045
1046 // Tests that NotNull() matches any non-NULL pointer of any type.
1047 TEST(NotNullTest, MatchesNonNullPointer) {
1048 Matcher<int*> m1 = NotNull();
1049 int* p1 = nullptr;
1050 int n = 0;
1051 EXPECT_FALSE(m1.Matches(p1));
1052 EXPECT_TRUE(m1.Matches(&n));
1053
1054 Matcher<const char*> m2 = NotNull();
1055 const char* p2 = nullptr;
1056 EXPECT_FALSE(m2.Matches(p2));
1057 EXPECT_TRUE(m2.Matches("hi"));
1058 }
1059
1060 TEST(NotNullTest, LinkedPtr) {
1061 const Matcher<std::shared_ptr<int>> m = NotNull();
1062 const std::shared_ptr<int> null_p;
1063 const std::shared_ptr<int> non_null_p(new int);
1064
1065 EXPECT_FALSE(m.Matches(null_p));
1066 EXPECT_TRUE(m.Matches(non_null_p));
1067 }
1068
1069 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1070 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1071 const std::shared_ptr<double> null_p;
1072 const std::shared_ptr<double> non_null_p(new double);
1073
1074 EXPECT_FALSE(m.Matches(null_p));
1075 EXPECT_TRUE(m.Matches(non_null_p));
1076 }
1077
1078 TEST(NotNullTest, StdFunction) {
1079 const Matcher<std::function<void()>> m = NotNull();
1080
1081 EXPECT_TRUE(m.Matches([] {}));
1082 EXPECT_FALSE(m.Matches(std::function<void()>()));
1083 }
1084
1085 // Tests that NotNull() describes itself properly.
1086 TEST(NotNullTest, CanDescribeSelf) {
1087 Matcher<int*> m = NotNull();
1088 EXPECT_EQ("isn't NULL", Describe(m));
1089 }
1090
1091 // Tests that Ref(variable) matches an argument that references
1092 // 'variable'.
1093 TEST(RefTest, MatchesSameVariable) {
1094 int a = 0;
1095 int b = 0;
1096 Matcher<int&> m = Ref(a);
1097 EXPECT_TRUE(m.Matches(a));
1098 EXPECT_FALSE(m.Matches(b));
1099 }
1100
1101 // Tests that Ref(variable) describes itself properly.
1102 TEST(RefTest, CanDescribeSelf) {
1103 int n = 5;
1104 Matcher<int&> m = Ref(n);
1105 stringstream ss;
1106 ss << "references the variable @" << &n << " 5";
1107 EXPECT_EQ(ss.str(), Describe(m));
1108 }
1109
1110 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1111 // const reference.
1112 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1113 int a = 0;
1114 int b = 0;
1115 Matcher<const int&> m = Ref(a);
1116 EXPECT_TRUE(m.Matches(a));
1117 EXPECT_FALSE(m.Matches(b));
1118 }
1119
1120 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1121 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1122 // of Ref(base), but not vice versa.
1123
1124 TEST(RefTest, IsCovariant) {
1125 Base base, base2;
1126 Derived derived;
1127 Matcher<const Base&> m1 = Ref(base);
1128 EXPECT_TRUE(m1.Matches(base));
1129 EXPECT_FALSE(m1.Matches(base2));
1130 EXPECT_FALSE(m1.Matches(derived));
1131
1132 m1 = Ref(derived);
1133 EXPECT_TRUE(m1.Matches(derived));
1134 EXPECT_FALSE(m1.Matches(base));
1135 EXPECT_FALSE(m1.Matches(base2));
1136 }
1137
1138 TEST(RefTest, ExplainsResult) {
1139 int n = 0;
1140 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1141 StartsWith("which is located @"));
1142
1143 int m = 0;
1144 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1145 StartsWith("which is located @"));
1146 }
1147
1148 // Tests string comparison matchers.
1149
1150 template <typename T = std::string>
1151 std::string FromStringLike(internal::StringLike<T> str) {
1152 return std::string(str);
1153 }
1154
1155 TEST(StringLike, TestConversions) {
1156 EXPECT_EQ("foo", FromStringLike("foo"));
1157 EXPECT_EQ("foo", FromStringLike(std::string("foo")));
1158 #if GTEST_INTERNAL_HAS_STRING_VIEW
1159 EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
1160 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1161
1162 // Non deducible types.
1163 EXPECT_EQ("", FromStringLike({}));
1164 EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
1165 const char buf[] = "foo";
1166 EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
1167 }
1168
1169 TEST(StrEqTest, MatchesEqualString) {
1170 Matcher<const char*> m = StrEq(std::string("Hello"));
1171 EXPECT_TRUE(m.Matches("Hello"));
1172 EXPECT_FALSE(m.Matches("hello"));
1173 EXPECT_FALSE(m.Matches(nullptr));
1174
1175 Matcher<const std::string&> m2 = StrEq("Hello");
1176 EXPECT_TRUE(m2.Matches("Hello"));
1177 EXPECT_FALSE(m2.Matches("Hi"));
1178
1179 #if GTEST_INTERNAL_HAS_STRING_VIEW
1180 Matcher<const internal::StringView&> m3 =
1181 StrEq(internal::StringView("Hello"));
1182 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1183 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1184 EXPECT_FALSE(m3.Matches(internal::StringView()));
1185
1186 Matcher<const internal::StringView&> m_empty = StrEq("");
1187 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1188 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1189 EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
1190 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1191 }
1192
1193 TEST(StrEqTest, CanDescribeSelf) {
1194 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1195 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1196 Describe(m));
1197
1198 std::string str("01204500800");
1199 str[3] = '\0';
1200 Matcher<std::string> m2 = StrEq(str);
1201 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1202 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1203 Matcher<std::string> m3 = StrEq(str);
1204 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1205 }
1206
1207 TEST(StrNeTest, MatchesUnequalString) {
1208 Matcher<const char*> m = StrNe("Hello");
1209 EXPECT_TRUE(m.Matches(""));
1210 EXPECT_TRUE(m.Matches(nullptr));
1211 EXPECT_FALSE(m.Matches("Hello"));
1212
1213 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1214 EXPECT_TRUE(m2.Matches("hello"));
1215 EXPECT_FALSE(m2.Matches("Hello"));
1216
1217 #if GTEST_INTERNAL_HAS_STRING_VIEW
1218 Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
1219 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1220 EXPECT_TRUE(m3.Matches(internal::StringView()));
1221 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1222 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1223 }
1224
1225 TEST(StrNeTest, CanDescribeSelf) {
1226 Matcher<const char*> m = StrNe("Hi");
1227 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1228 }
1229
1230 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1231 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1232 EXPECT_TRUE(m.Matches("Hello"));
1233 EXPECT_TRUE(m.Matches("hello"));
1234 EXPECT_FALSE(m.Matches("Hi"));
1235 EXPECT_FALSE(m.Matches(nullptr));
1236
1237 Matcher<const std::string&> m2 = StrCaseEq("Hello");
1238 EXPECT_TRUE(m2.Matches("hello"));
1239 EXPECT_FALSE(m2.Matches("Hi"));
1240
1241 #if GTEST_INTERNAL_HAS_STRING_VIEW
1242 Matcher<const internal::StringView&> m3 =
1243 StrCaseEq(internal::StringView("Hello"));
1244 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1245 EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
1246 EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
1247 EXPECT_FALSE(m3.Matches(internal::StringView()));
1248 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1249 }
1250
1251 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1252 std::string str1("oabocdooeoo");
1253 std::string str2("OABOCDOOEOO");
1254 Matcher<const std::string&> m0 = StrCaseEq(str1);
1255 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1256
1257 str1[3] = str2[3] = '\0';
1258 Matcher<const std::string&> m1 = StrCaseEq(str1);
1259 EXPECT_TRUE(m1.Matches(str2));
1260
1261 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1262 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1263 Matcher<const std::string&> m2 = StrCaseEq(str1);
1264 str1[9] = str2[9] = '\0';
1265 EXPECT_FALSE(m2.Matches(str2));
1266
1267 Matcher<const std::string&> m3 = StrCaseEq(str1);
1268 EXPECT_TRUE(m3.Matches(str2));
1269
1270 EXPECT_FALSE(m3.Matches(str2 + "x"));
1271 str2.append(1, '\0');
1272 EXPECT_FALSE(m3.Matches(str2));
1273 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1274 }
1275
1276 TEST(StrCaseEqTest, CanDescribeSelf) {
1277 Matcher<std::string> m = StrCaseEq("Hi");
1278 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1279 }
1280
1281 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1282 Matcher<const char*> m = StrCaseNe("Hello");
1283 EXPECT_TRUE(m.Matches("Hi"));
1284 EXPECT_TRUE(m.Matches(nullptr));
1285 EXPECT_FALSE(m.Matches("Hello"));
1286 EXPECT_FALSE(m.Matches("hello"));
1287
1288 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1289 EXPECT_TRUE(m2.Matches(""));
1290 EXPECT_FALSE(m2.Matches("Hello"));
1291
1292 #if GTEST_INTERNAL_HAS_STRING_VIEW
1293 Matcher<const internal::StringView> m3 =
1294 StrCaseNe(internal::StringView("Hello"));
1295 EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
1296 EXPECT_TRUE(m3.Matches(internal::StringView()));
1297 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1298 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1299 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1300 }
1301
1302 TEST(StrCaseNeTest, CanDescribeSelf) {
1303 Matcher<const char*> m = StrCaseNe("Hi");
1304 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1305 }
1306
1307 // Tests that HasSubstr() works for matching string-typed values.
1308 TEST(HasSubstrTest, WorksForStringClasses) {
1309 const Matcher<std::string> m1 = HasSubstr("foo");
1310 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1311 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1312
1313 const Matcher<const std::string&> m2 = HasSubstr("foo");
1314 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1315 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1316
1317 const Matcher<std::string> m_empty = HasSubstr("");
1318 EXPECT_TRUE(m_empty.Matches(std::string()));
1319 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1320 }
1321
1322 // Tests that HasSubstr() works for matching C-string-typed values.
1323 TEST(HasSubstrTest, WorksForCStrings) {
1324 const Matcher<char*> m1 = HasSubstr("foo");
1325 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1326 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1327 EXPECT_FALSE(m1.Matches(nullptr));
1328
1329 const Matcher<const char*> m2 = HasSubstr("foo");
1330 EXPECT_TRUE(m2.Matches("I love food."));
1331 EXPECT_FALSE(m2.Matches("tofo"));
1332 EXPECT_FALSE(m2.Matches(nullptr));
1333
1334 const Matcher<const char*> m_empty = HasSubstr("");
1335 EXPECT_TRUE(m_empty.Matches("not empty"));
1336 EXPECT_TRUE(m_empty.Matches(""));
1337 EXPECT_FALSE(m_empty.Matches(nullptr));
1338 }
1339
1340 #if GTEST_INTERNAL_HAS_STRING_VIEW
1341 // Tests that HasSubstr() works for matching StringView-typed values.
1342 TEST(HasSubstrTest, WorksForStringViewClasses) {
1343 const Matcher<internal::StringView> m1 =
1344 HasSubstr(internal::StringView("foo"));
1345 EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
1346 EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
1347 EXPECT_FALSE(m1.Matches(internal::StringView()));
1348
1349 const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
1350 EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
1351 EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
1352 EXPECT_FALSE(m2.Matches(internal::StringView()));
1353
1354 const Matcher<const internal::StringView&> m3 = HasSubstr("");
1355 EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
1356 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1357 EXPECT_TRUE(m3.Matches(internal::StringView()));
1358 }
1359 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1360
1361 // Tests that HasSubstr(s) describes itself properly.
1362 TEST(HasSubstrTest, CanDescribeSelf) {
1363 Matcher<std::string> m = HasSubstr("foo\n\"");
1364 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1365 }
1366
1367 INSTANTIATE_GTEST_MATCHER_TEST_P(KeyTest);
1368
1369 TEST(KeyTest, CanDescribeSelf) {
1370 Matcher<const pair<std::string, int>&> m = Key("foo");
1371 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1372 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1373 }
1374
1375 TEST_P(KeyTestP, ExplainsResult) {
1376 Matcher<pair<int, bool>> m = Key(GreaterThan(10));
1377 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1378 Explain(m, make_pair(5, true)));
1379 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1380 Explain(m, make_pair(15, true)));
1381 }
1382
1383 TEST(KeyTest, MatchesCorrectly) {
1384 pair<int, std::string> p(25, "foo");
1385 EXPECT_THAT(p, Key(25));
1386 EXPECT_THAT(p, Not(Key(42)));
1387 EXPECT_THAT(p, Key(Ge(20)));
1388 EXPECT_THAT(p, Not(Key(Lt(25))));
1389 }
1390
1391 TEST(KeyTest, WorksWithMoveOnly) {
1392 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1393 EXPECT_THAT(p, Key(Eq(nullptr)));
1394 }
1395
1396 INSTANTIATE_GTEST_MATCHER_TEST_P(PairTest);
1397
1398 template <size_t I>
1399 struct Tag {};
1400
1401 struct PairWithGet {
1402 int member_1;
1403 std::string member_2;
1404 using first_type = int;
1405 using second_type = std::string;
1406
1407 const int& GetImpl(Tag<0>) const { return member_1; }
1408 const std::string& GetImpl(Tag<1>) const { return member_2; }
1409 };
1410 template <size_t I>
1411 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1412 return value.GetImpl(Tag<I>());
1413 }
1414 TEST(PairTest, MatchesPairWithGetCorrectly) {
1415 PairWithGet p{25, "foo"};
1416 EXPECT_THAT(p, Key(25));
1417 EXPECT_THAT(p, Not(Key(42)));
1418 EXPECT_THAT(p, Key(Ge(20)));
1419 EXPECT_THAT(p, Not(Key(Lt(25))));
1420
1421 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1422 EXPECT_THAT(v, Contains(Key(29)));
1423 }
1424
1425 TEST(KeyTest, SafelyCastsInnerMatcher) {
1426 Matcher<int> is_positive = Gt(0);
1427 Matcher<int> is_negative = Lt(0);
1428 pair<char, bool> p('a', true);
1429 EXPECT_THAT(p, Key(is_positive));
1430 EXPECT_THAT(p, Not(Key(is_negative)));
1431 }
1432
1433 TEST(KeyTest, InsideContainsUsingMap) {
1434 map<int, char> container;
1435 container.insert(make_pair(1, 'a'));
1436 container.insert(make_pair(2, 'b'));
1437 container.insert(make_pair(4, 'c'));
1438 EXPECT_THAT(container, Contains(Key(1)));
1439 EXPECT_THAT(container, Not(Contains(Key(3))));
1440 }
1441
1442 TEST(KeyTest, InsideContainsUsingMultimap) {
1443 multimap<int, char> container;
1444 container.insert(make_pair(1, 'a'));
1445 container.insert(make_pair(2, 'b'));
1446 container.insert(make_pair(4, 'c'));
1447
1448 EXPECT_THAT(container, Not(Contains(Key(25))));
1449 container.insert(make_pair(25, 'd'));
1450 EXPECT_THAT(container, Contains(Key(25)));
1451 container.insert(make_pair(25, 'e'));
1452 EXPECT_THAT(container, Contains(Key(25)));
1453
1454 EXPECT_THAT(container, Contains(Key(1)));
1455 EXPECT_THAT(container, Not(Contains(Key(3))));
1456 }
1457
1458 TEST(PairTest, Typing) {
1459 // Test verifies the following type conversions can be compiled.
1460 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1461 Matcher<const pair<const char*, int>> m2 = Pair("foo", 42);
1462 Matcher<pair<const char*, int>> m3 = Pair("foo", 42);
1463
1464 Matcher<pair<int, const std::string>> m4 = Pair(25, "42");
1465 Matcher<pair<const std::string, int>> m5 = Pair("25", 42);
1466 }
1467
1468 TEST(PairTest, CanDescribeSelf) {
1469 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1470 EXPECT_EQ(
1471 "has a first field that is equal to \"foo\""
1472 ", and has a second field that is equal to 42",
1473 Describe(m1));
1474 EXPECT_EQ(
1475 "has a first field that isn't equal to \"foo\""
1476 ", or has a second field that isn't equal to 42",
1477 DescribeNegation(m1));
1478 // Double and triple negation (1 or 2 times not and description of negation).
1479 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1480 EXPECT_EQ(
1481 "has a first field that isn't equal to 13"
1482 ", and has a second field that is equal to 42",
1483 DescribeNegation(m2));
1484 }
1485
1486 TEST_P(PairTestP, CanExplainMatchResultTo) {
1487 // If neither field matches, Pair() should explain about the first
1488 // field.
1489 const Matcher<pair<int, int>> m = Pair(GreaterThan(0), GreaterThan(0));
1490 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1491 Explain(m, make_pair(-1, -2)));
1492
1493 // If the first field matches but the second doesn't, Pair() should
1494 // explain about the second field.
1495 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1496 Explain(m, make_pair(1, -2)));
1497
1498 // If the first field doesn't match but the second does, Pair()
1499 // should explain about the first field.
1500 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1501 Explain(m, make_pair(-1, 2)));
1502
1503 // If both fields match, Pair() should explain about them both.
1504 EXPECT_EQ(
1505 "whose both fields match, where the first field is a value "
1506 "which is 1 more than 0, and the second field is a value "
1507 "which is 2 more than 0",
1508 Explain(m, make_pair(1, 2)));
1509
1510 // If only the first match has an explanation, only this explanation should
1511 // be printed.
1512 const Matcher<pair<int, int>> explain_first = Pair(GreaterThan(0), 0);
1513 EXPECT_EQ(
1514 "whose both fields match, where the first field is a value "
1515 "which is 1 more than 0",
1516 Explain(explain_first, make_pair(1, 0)));
1517
1518 // If only the second match has an explanation, only this explanation should
1519 // be printed.
1520 const Matcher<pair<int, int>> explain_second = Pair(0, GreaterThan(0));
1521 EXPECT_EQ(
1522 "whose both fields match, where the second field is a value "
1523 "which is 1 more than 0",
1524 Explain(explain_second, make_pair(0, 1)));
1525 }
1526
1527 TEST(PairTest, MatchesCorrectly) {
1528 pair<int, std::string> p(25, "foo");
1529
1530 // Both fields match.
1531 EXPECT_THAT(p, Pair(25, "foo"));
1532 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1533
1534 // 'first' doesn't match, but 'second' matches.
1535 EXPECT_THAT(p, Not(Pair(42, "foo")));
1536 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1537
1538 // 'first' matches, but 'second' doesn't match.
1539 EXPECT_THAT(p, Not(Pair(25, "bar")));
1540 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1541
1542 // Neither field matches.
1543 EXPECT_THAT(p, Not(Pair(13, "bar")));
1544 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1545 }
1546
1547 TEST(PairTest, WorksWithMoveOnly) {
1548 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1549 p.second = std::make_unique<int>(7);
1550 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1551 }
1552
1553 TEST(PairTest, SafelyCastsInnerMatchers) {
1554 Matcher<int> is_positive = Gt(0);
1555 Matcher<int> is_negative = Lt(0);
1556 pair<char, bool> p('a', true);
1557 EXPECT_THAT(p, Pair(is_positive, _));
1558 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1559 EXPECT_THAT(p, Pair(_, is_positive));
1560 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1561 }
1562
1563 TEST(PairTest, InsideContainsUsingMap) {
1564 map<int, char> container;
1565 container.insert(make_pair(1, 'a'));
1566 container.insert(make_pair(2, 'b'));
1567 container.insert(make_pair(4, 'c'));
1568 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1569 EXPECT_THAT(container, Contains(Pair(1, _)));
1570 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1571 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1572 }
1573
1574 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldsAreTest);
1575
1576 TEST(FieldsAreTest, MatchesCorrectly) {
1577 std::tuple<int, std::string, double> p(25, "foo", .5);
1578
1579 // All fields match.
1580 EXPECT_THAT(p, FieldsAre(25, "foo", .5));
1581 EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
1582
1583 // Some don't match.
1584 EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
1585 EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
1586 EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
1587 }
1588
1589 TEST(FieldsAreTest, CanDescribeSelf) {
1590 Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
1591 EXPECT_EQ(
1592 "has field #0 that is equal to \"foo\""
1593 ", and has field #1 that is equal to 42",
1594 Describe(m1));
1595 EXPECT_EQ(
1596 "has field #0 that isn't equal to \"foo\""
1597 ", or has field #1 that isn't equal to 42",
1598 DescribeNegation(m1));
1599 }
1600
1601 TEST_P(FieldsAreTestP, CanExplainMatchResultTo) {
1602 // The first one that fails is the one that gives the error.
1603 Matcher<std::tuple<int, int, int>> m =
1604 FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
1605
1606 EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
1607 Explain(m, std::make_tuple(-1, -2, -3)));
1608 EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
1609 Explain(m, std::make_tuple(1, -2, -3)));
1610 EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
1611 Explain(m, std::make_tuple(1, 2, -3)));
1612
1613 // If they all match, we get a long explanation of success.
1614 EXPECT_EQ(
1615 "whose all elements match, "
1616 "where field #0 is a value which is 1 more than 0"
1617 ", and field #1 is a value which is 2 more than 0"
1618 ", and field #2 is a value which is 3 more than 0",
1619 Explain(m, std::make_tuple(1, 2, 3)));
1620
1621 // Only print those that have an explanation.
1622 m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
1623 EXPECT_EQ(
1624 "whose all elements match, "
1625 "where field #0 is a value which is 1 more than 0"
1626 ", and field #2 is a value which is 3 more than 0",
1627 Explain(m, std::make_tuple(1, 0, 3)));
1628
1629 // If only one has an explanation, then print that one.
1630 m = FieldsAre(0, GreaterThan(0), 0);
1631 EXPECT_EQ(
1632 "whose all elements match, "
1633 "where field #1 is a value which is 1 more than 0",
1634 Explain(m, std::make_tuple(0, 1, 0)));
1635 }
1636
1637 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
1638 TEST(FieldsAreTest, StructuredBindings) {
1639 // testing::FieldsAre can also match aggregates and such with C++17 and up.
1640 struct MyType {
1641 int i;
1642 std::string str;
1643 };
1644 EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
1645
1646 // Test all the supported arities.
1647 struct MyVarType1 {
1648 int a;
1649 };
1650 EXPECT_THAT(MyVarType1{}, FieldsAre(0));
1651 struct MyVarType2 {
1652 int a, b;
1653 };
1654 EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
1655 struct MyVarType3 {
1656 int a, b, c;
1657 };
1658 EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
1659 struct MyVarType4 {
1660 int a, b, c, d;
1661 };
1662 EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
1663 struct MyVarType5 {
1664 int a, b, c, d, e;
1665 };
1666 EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
1667 struct MyVarType6 {
1668 int a, b, c, d, e, f;
1669 };
1670 EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
1671 struct MyVarType7 {
1672 int a, b, c, d, e, f, g;
1673 };
1674 EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
1675 struct MyVarType8 {
1676 int a, b, c, d, e, f, g, h;
1677 };
1678 EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
1679 struct MyVarType9 {
1680 int a, b, c, d, e, f, g, h, i;
1681 };
1682 EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
1683 struct MyVarType10 {
1684 int a, b, c, d, e, f, g, h, i, j;
1685 };
1686 EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1687 struct MyVarType11 {
1688 int a, b, c, d, e, f, g, h, i, j, k;
1689 };
1690 EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1691 struct MyVarType12 {
1692 int a, b, c, d, e, f, g, h, i, j, k, l;
1693 };
1694 EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1695 struct MyVarType13 {
1696 int a, b, c, d, e, f, g, h, i, j, k, l, m;
1697 };
1698 EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1699 struct MyVarType14 {
1700 int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
1701 };
1702 EXPECT_THAT(MyVarType14{},
1703 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1704 struct MyVarType15 {
1705 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
1706 };
1707 EXPECT_THAT(MyVarType15{},
1708 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1709 struct MyVarType16 {
1710 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
1711 };
1712 EXPECT_THAT(MyVarType16{},
1713 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1714 struct MyVarType17 {
1715 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q;
1716 };
1717 EXPECT_THAT(MyVarType17{},
1718 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1719 struct MyVarType18 {
1720 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r;
1721 };
1722 EXPECT_THAT(MyVarType18{},
1723 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1724 struct MyVarType19 {
1725 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s;
1726 };
1727 EXPECT_THAT(MyVarType19{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1728 0, 0, 0, 0, 0));
1729 }
1730 #endif
1731
1732 TEST(PairTest, UseGetInsteadOfMembers) {
1733 PairWithGet pair{7, "ABC"};
1734 EXPECT_THAT(pair, Pair(7, "ABC"));
1735 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1736 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1737
1738 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1739 EXPECT_THAT(v,
1740 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1741 }
1742
1743 // Tests StartsWith(s).
1744
1745 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1746 const Matcher<const char*> m1 = StartsWith(std::string(""));
1747 EXPECT_TRUE(m1.Matches("Hi"));
1748 EXPECT_TRUE(m1.Matches(""));
1749 EXPECT_FALSE(m1.Matches(nullptr));
1750
1751 const Matcher<const std::string&> m2 = StartsWith("Hi");
1752 EXPECT_TRUE(m2.Matches("Hi"));
1753 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1754 EXPECT_TRUE(m2.Matches("High"));
1755 EXPECT_FALSE(m2.Matches("H"));
1756 EXPECT_FALSE(m2.Matches(" Hi"));
1757
1758 #if GTEST_INTERNAL_HAS_STRING_VIEW
1759 const Matcher<internal::StringView> m_empty =
1760 StartsWith(internal::StringView(""));
1761 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1762 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1763 EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
1764 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1765 }
1766
1767 TEST(StartsWithTest, CanDescribeSelf) {
1768 Matcher<const std::string> m = StartsWith("Hi");
1769 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1770 }
1771
1772 // Tests EndsWith(s).
1773
1774 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1775 const Matcher<const char*> m1 = EndsWith("");
1776 EXPECT_TRUE(m1.Matches("Hi"));
1777 EXPECT_TRUE(m1.Matches(""));
1778 EXPECT_FALSE(m1.Matches(nullptr));
1779
1780 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1781 EXPECT_TRUE(m2.Matches("Hi"));
1782 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1783 EXPECT_TRUE(m2.Matches("Super Hi"));
1784 EXPECT_FALSE(m2.Matches("i"));
1785 EXPECT_FALSE(m2.Matches("Hi "));
1786
1787 #if GTEST_INTERNAL_HAS_STRING_VIEW
1788 const Matcher<const internal::StringView&> m4 =
1789 EndsWith(internal::StringView(""));
1790 EXPECT_TRUE(m4.Matches("Hi"));
1791 EXPECT_TRUE(m4.Matches(""));
1792 EXPECT_TRUE(m4.Matches(internal::StringView()));
1793 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1794 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1795 }
1796
1797 TEST(EndsWithTest, CanDescribeSelf) {
1798 Matcher<const std::string> m = EndsWith("Hi");
1799 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1800 }
1801
1802 // Tests WhenBase64Unescaped.
1803
1804 TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
1805 const Matcher<const char*> m1 = WhenBase64Unescaped(EndsWith("!"));
1806 EXPECT_FALSE(m1.Matches("invalid base64"));
1807 EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world
1808 EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world!
1809 EXPECT_TRUE(m1.Matches("+/-_IQ")); // \xfb\xff\xbf!
1810
1811 const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
1812 EXPECT_FALSE(m2.Matches("invalid base64"));
1813 EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world
1814 EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world!
1815 EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
1816
1817 #if GTEST_INTERNAL_HAS_STRING_VIEW
1818 const Matcher<const internal::StringView&> m3 =
1819 WhenBase64Unescaped(EndsWith("!"));
1820 EXPECT_FALSE(m3.Matches("invalid base64"));
1821 EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world
1822 EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world!
1823 EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
1824 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1825 }
1826
1827 TEST(WhenBase64UnescapedTest, CanDescribeSelf) {
1828 const Matcher<const char*> m = WhenBase64Unescaped(EndsWith("!"));
1829 EXPECT_EQ("matches after Base64Unescape ends with \"!\"", Describe(m));
1830 }
1831
1832 // Tests MatchesRegex().
1833
1834 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1835 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1836 EXPECT_TRUE(m1.Matches("az"));
1837 EXPECT_TRUE(m1.Matches("abcz"));
1838 EXPECT_FALSE(m1.Matches(nullptr));
1839
1840 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1841 EXPECT_TRUE(m2.Matches("azbz"));
1842 EXPECT_FALSE(m2.Matches("az1"));
1843 EXPECT_FALSE(m2.Matches("1az"));
1844
1845 #if GTEST_INTERNAL_HAS_STRING_VIEW
1846 const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
1847 EXPECT_TRUE(m3.Matches(internal::StringView("az")));
1848 EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
1849 EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
1850 EXPECT_FALSE(m3.Matches(internal::StringView()));
1851 const Matcher<const internal::StringView&> m4 =
1852 MatchesRegex(internal::StringView(""));
1853 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1854 EXPECT_TRUE(m4.Matches(internal::StringView()));
1855 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1856 }
1857
1858 TEST(MatchesRegexTest, CanDescribeSelf) {
1859 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1860 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1861
1862 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1863 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1864
1865 #if GTEST_INTERNAL_HAS_STRING_VIEW
1866 Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
1867 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1868 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1869 }
1870
1871 // Tests ContainsRegex().
1872
1873 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1874 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1875 EXPECT_TRUE(m1.Matches("az"));
1876 EXPECT_TRUE(m1.Matches("0abcz1"));
1877 EXPECT_FALSE(m1.Matches(nullptr));
1878
1879 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1880 EXPECT_TRUE(m2.Matches("azbz"));
1881 EXPECT_TRUE(m2.Matches("az1"));
1882 EXPECT_FALSE(m2.Matches("1a"));
1883
1884 #if GTEST_INTERNAL_HAS_STRING_VIEW
1885 const Matcher<const internal::StringView&> m3 = ContainsRegex(new RE("a.*z"));
1886 EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
1887 EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
1888 EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
1889 EXPECT_FALSE(m3.Matches(internal::StringView()));
1890 const Matcher<const internal::StringView&> m4 =
1891 ContainsRegex(internal::StringView(""));
1892 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1893 EXPECT_TRUE(m4.Matches(internal::StringView()));
1894 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1895 }
1896
1897 TEST(ContainsRegexTest, CanDescribeSelf) {
1898 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1899 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1900
1901 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1902 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1903
1904 #if GTEST_INTERNAL_HAS_STRING_VIEW
1905 Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
1906 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1907 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1908 }
1909
1910 // Tests for wide strings.
1911 #if GTEST_HAS_STD_WSTRING
1912 TEST(StdWideStrEqTest, MatchesEqual) {
1913 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1914 EXPECT_TRUE(m.Matches(L"Hello"));
1915 EXPECT_FALSE(m.Matches(L"hello"));
1916 EXPECT_FALSE(m.Matches(nullptr));
1917
1918 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1919 EXPECT_TRUE(m2.Matches(L"Hello"));
1920 EXPECT_FALSE(m2.Matches(L"Hi"));
1921
1922 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1923 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1924 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1925
1926 ::std::wstring str(L"01204500800");
1927 str[3] = L'\0';
1928 Matcher<const ::std::wstring&> m4 = StrEq(str);
1929 EXPECT_TRUE(m4.Matches(str));
1930 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1931 Matcher<const ::std::wstring&> m5 = StrEq(str);
1932 EXPECT_TRUE(m5.Matches(str));
1933 }
1934
1935 TEST(StdWideStrEqTest, CanDescribeSelf) {
1936 Matcher<::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1937 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1938 Describe(m));
1939
1940 Matcher<::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1941 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2));
1942
1943 ::std::wstring str(L"01204500800");
1944 str[3] = L'\0';
1945 Matcher<const ::std::wstring&> m4 = StrEq(str);
1946 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1947 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1948 Matcher<const ::std::wstring&> m5 = StrEq(str);
1949 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1950 }
1951
1952 TEST(StdWideStrNeTest, MatchesUnequalString) {
1953 Matcher<const wchar_t*> m = StrNe(L"Hello");
1954 EXPECT_TRUE(m.Matches(L""));
1955 EXPECT_TRUE(m.Matches(nullptr));
1956 EXPECT_FALSE(m.Matches(L"Hello"));
1957
1958 Matcher<::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1959 EXPECT_TRUE(m2.Matches(L"hello"));
1960 EXPECT_FALSE(m2.Matches(L"Hello"));
1961 }
1962
1963 TEST(StdWideStrNeTest, CanDescribeSelf) {
1964 Matcher<const wchar_t*> m = StrNe(L"Hi");
1965 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1966 }
1967
1968 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1969 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1970 EXPECT_TRUE(m.Matches(L"Hello"));
1971 EXPECT_TRUE(m.Matches(L"hello"));
1972 EXPECT_FALSE(m.Matches(L"Hi"));
1973 EXPECT_FALSE(m.Matches(nullptr));
1974
1975 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1976 EXPECT_TRUE(m2.Matches(L"hello"));
1977 EXPECT_FALSE(m2.Matches(L"Hi"));
1978 }
1979
1980 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1981 ::std::wstring str1(L"oabocdooeoo");
1982 ::std::wstring str2(L"OABOCDOOEOO");
1983 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1984 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1985
1986 str1[3] = str2[3] = L'\0';
1987 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1988 EXPECT_TRUE(m1.Matches(str2));
1989
1990 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1991 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1992 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1993 str1[9] = str2[9] = L'\0';
1994 EXPECT_FALSE(m2.Matches(str2));
1995
1996 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1997 EXPECT_TRUE(m3.Matches(str2));
1998
1999 EXPECT_FALSE(m3.Matches(str2 + L"x"));
2000 str2.append(1, L'\0');
2001 EXPECT_FALSE(m3.Matches(str2));
2002 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
2003 }
2004
2005 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2006 Matcher<::std::wstring> m = StrCaseEq(L"Hi");
2007 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2008 }
2009
2010 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2011 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2012 EXPECT_TRUE(m.Matches(L"Hi"));
2013 EXPECT_TRUE(m.Matches(nullptr));
2014 EXPECT_FALSE(m.Matches(L"Hello"));
2015 EXPECT_FALSE(m.Matches(L"hello"));
2016
2017 Matcher<::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
2018 EXPECT_TRUE(m2.Matches(L""));
2019 EXPECT_FALSE(m2.Matches(L"Hello"));
2020 }
2021
2022 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2023 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2024 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2025 }
2026
2027 // Tests that HasSubstr() works for matching wstring-typed values.
2028 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2029 const Matcher<::std::wstring> m1 = HasSubstr(L"foo");
2030 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
2031 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
2032
2033 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
2034 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
2035 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
2036 }
2037
2038 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2039 TEST(StdWideHasSubstrTest, WorksForCStrings) {
2040 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2041 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2042 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
2043 EXPECT_FALSE(m1.Matches(nullptr));
2044
2045 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2046 EXPECT_TRUE(m2.Matches(L"I love food."));
2047 EXPECT_FALSE(m2.Matches(L"tofo"));
2048 EXPECT_FALSE(m2.Matches(nullptr));
2049 }
2050
2051 // Tests that HasSubstr(s) describes itself properly.
2052 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2053 Matcher<::std::wstring> m = HasSubstr(L"foo\n\"");
2054 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2055 }
2056
2057 // Tests StartsWith(s).
2058
2059 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2060 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
2061 EXPECT_TRUE(m1.Matches(L"Hi"));
2062 EXPECT_TRUE(m1.Matches(L""));
2063 EXPECT_FALSE(m1.Matches(nullptr));
2064
2065 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
2066 EXPECT_TRUE(m2.Matches(L"Hi"));
2067 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2068 EXPECT_TRUE(m2.Matches(L"High"));
2069 EXPECT_FALSE(m2.Matches(L"H"));
2070 EXPECT_FALSE(m2.Matches(L" Hi"));
2071 }
2072
2073 TEST(StdWideStartsWithTest, CanDescribeSelf) {
2074 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2075 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2076 }
2077
2078 // Tests EndsWith(s).
2079
2080 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2081 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2082 EXPECT_TRUE(m1.Matches(L"Hi"));
2083 EXPECT_TRUE(m1.Matches(L""));
2084 EXPECT_FALSE(m1.Matches(nullptr));
2085
2086 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2087 EXPECT_TRUE(m2.Matches(L"Hi"));
2088 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2089 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2090 EXPECT_FALSE(m2.Matches(L"i"));
2091 EXPECT_FALSE(m2.Matches(L"Hi "));
2092 }
2093
2094 TEST(StdWideEndsWithTest, CanDescribeSelf) {
2095 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2096 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2097 }
2098
2099 #endif // GTEST_HAS_STD_WSTRING
2100
2101 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2102 StringMatchResultListener listener1;
2103 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2104 EXPECT_EQ("% 2 == 0", listener1.str());
2105
2106 StringMatchResultListener listener2;
2107 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2108 EXPECT_EQ("", listener2.str());
2109 }
2110
2111 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2112 const Matcher<int> is_even = PolymorphicIsEven();
2113 StringMatchResultListener listener1;
2114 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2115 EXPECT_EQ("% 2 == 0", listener1.str());
2116
2117 const Matcher<const double&> is_zero = Eq(0);
2118 StringMatchResultListener listener2;
2119 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2120 EXPECT_EQ("", listener2.str());
2121 }
2122
2123 MATCHER(ConstructNoArg, "") { return true; }
2124 MATCHER_P(Construct1Arg, arg1, "") { return true; }
2125 MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
2126
2127 TEST(MatcherConstruct, ExplicitVsImplicit) {
2128 {
2129 // No arg constructor can be constructed with empty brace.
2130 ConstructNoArgMatcher m = {};
2131 (void)m;
2132 // And with no args
2133 ConstructNoArgMatcher m2;
2134 (void)m2;
2135 }
2136 {
2137 // The one arg constructor has an explicit constructor.
2138 // This is to prevent the implicit conversion.
2139 using M = Construct1ArgMatcherP<int>;
2140 EXPECT_TRUE((std::is_constructible<M, int>::value));
2141 EXPECT_FALSE((std::is_convertible<int, M>::value));
2142 }
2143 {
2144 // Multiple arg matchers can be constructed with an implicit construction.
2145 Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
2146 (void)m;
2147 }
2148 }
2149
2150 MATCHER_P(Really, inner_matcher, "") {
2151 return ExplainMatchResult(inner_matcher, arg, result_listener);
2152 }
2153
2154 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2155 EXPECT_THAT(0, Really(Eq(0)));
2156 }
2157
2158 TEST(DescribeMatcherTest, WorksWithValue) {
2159 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
2160 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
2161 }
2162
2163 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
2164 const Matcher<int> monomorphic = Le(0);
2165 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
2166 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
2167 }
2168
2169 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
2170 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
2171 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
2172 }
2173
2174 MATCHER_P(FieldIIs, inner_matcher, "") {
2175 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
2176 }
2177
2178 #if GTEST_HAS_RTTI
2179 TEST(WhenDynamicCastToTest, SameType) {
2180 Derived derived;
2181 derived.i = 4;
2182
2183 // Right type. A pointer is passed down.
2184 Base* as_base_ptr = &derived;
2185 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
2186 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
2187 EXPECT_THAT(as_base_ptr,
2188 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
2189 }
2190
2191 TEST(WhenDynamicCastToTest, WrongTypes) {
2192 Base base;
2193 Derived derived;
2194 OtherDerived other_derived;
2195
2196 // Wrong types. NULL is passed.
2197 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
2198 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
2199 Base* as_base_ptr = &derived;
2200 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
2201 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
2202 as_base_ptr = &other_derived;
2203 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
2204 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
2205 }
2206
2207 TEST(WhenDynamicCastToTest, AlreadyNull) {
2208 // Already NULL.
2209 Base* as_base_ptr = nullptr;
2210 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
2211 }
2212
2213 struct AmbiguousCastTypes {
2214 class VirtualDerived : public virtual Base {};
2215 class DerivedSub1 : public VirtualDerived {};
2216 class DerivedSub2 : public VirtualDerived {};
2217 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
2218 };
2219
2220 TEST(WhenDynamicCastToTest, AmbiguousCast) {
2221 AmbiguousCastTypes::DerivedSub1 sub1;
2222 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
2223
2224 // This testcase fails on FreeBSD. See this GitHub issue for more details:
2225 // https://github.com/google/googletest/issues/2172
2226 #ifdef __FreeBSD__
2227 EXPECT_NONFATAL_FAILURE({
2228 #endif
2229 // Multiply derived from Base. dynamic_cast<> returns NULL.
2230 Base* as_base_ptr =
2231 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
2232
2233 EXPECT_THAT(as_base_ptr,
2234 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
2235 as_base_ptr = &sub1;
2236 EXPECT_THAT(
2237 as_base_ptr,
2238 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
2239 #ifdef __FreeBSD__
2240 }, "");
2241 #endif
2242 }
2243
2244 TEST(WhenDynamicCastToTest, Describe) {
2245 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
2246 const std::string prefix =
2247 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
2248 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
2249 EXPECT_EQ(prefix + "does not point to a value that is anything",
2250 DescribeNegation(matcher));
2251 }
2252
2253 TEST(WhenDynamicCastToTest, Explain) {
2254 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
2255 Base* null = nullptr;
2256 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
2257 Derived derived;
2258 EXPECT_TRUE(matcher.Matches(&derived));
2259 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
2260
2261 // With references, the matcher itself can fail. Test for that one.
2262 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
2263 EXPECT_THAT(Explain(ref_matcher, derived),
2264 HasSubstr("which cannot be dynamic_cast"));
2265 }
2266
2267 TEST(WhenDynamicCastToTest, GoodReference) {
2268 Derived derived;
2269 derived.i = 4;
2270 Base& as_base_ref = derived;
2271 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
2272 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
2273 }
2274
2275 TEST(WhenDynamicCastToTest, BadReference) {
2276 Derived derived;
2277 Base& as_base_ref = derived;
2278 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
2279 }
2280 #endif // GTEST_HAS_RTTI
2281
2282 class DivisibleByImpl {
2283 public:
2284 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
2285
2286 // For testing using ExplainMatchResultTo() with polymorphic matchers.
2287 template <typename T>
2288 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
2289 *listener << "which is " << (n % divider_) << " modulo " << divider_;
2290 return (n % divider_) == 0;
2291 }
2292
2293 void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; }
2294
2295 void DescribeNegationTo(ostream* os) const {
2296 *os << "is not divisible by " << divider_;
2297 }
2298
2299 void set_divider(int a_divider) { divider_ = a_divider; }
2300 int divider() const { return divider_; }
2301
2302 private:
2303 int divider_;
2304 };
2305
2306 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
2307 return MakePolymorphicMatcher(DivisibleByImpl(n));
2308 }
2309
2310 // Tests that when AllOf() fails, only the first failing matcher is
2311 // asked to explain why.
2312 TEST(ExplainMatchResultTest, AllOf_False_False) {
2313 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
2314 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
2315 }
2316
2317 // Tests that when AllOf() fails, only the first failing matcher is
2318 // asked to explain why.
2319 TEST(ExplainMatchResultTest, AllOf_False_True) {
2320 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
2321 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
2322 }
2323
2324 // Tests that when AllOf() fails, only the first failing matcher is
2325 // asked to explain why.
2326 TEST(ExplainMatchResultTest, AllOf_True_False) {
2327 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
2328 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
2329 }
2330
2331 // Tests that when AllOf() succeeds, all matchers are asked to explain
2332 // why.
2333 TEST(ExplainMatchResultTest, AllOf_True_True) {
2334 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
2335 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
2336 }
2337
2338 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
2339 const Matcher<int> m = AllOf(Ge(2), Le(3));
2340 EXPECT_EQ("", Explain(m, 2));
2341 }
2342
2343 INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);
2344
2345 TEST_P(ExplainmatcherResultTestP, MonomorphicMatcher) {
2346 const Matcher<int> m = GreaterThan(5);
2347 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
2348 }
2349
2350 // Tests PolymorphicMatcher::mutable_impl().
2351 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
2352 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
2353 DivisibleByImpl& impl = m.mutable_impl();
2354 EXPECT_EQ(42, impl.divider());
2355
2356 impl.set_divider(0);
2357 EXPECT_EQ(0, m.mutable_impl().divider());
2358 }
2359
2360 // Tests PolymorphicMatcher::impl().
2361 TEST(PolymorphicMatcherTest, CanAccessImpl) {
2362 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
2363 const DivisibleByImpl& impl = m.impl();
2364 EXPECT_EQ(42, impl.divider());
2365 }
2366
2367 } // namespace
2368 } // namespace gmock_matchers_test
2369 } // namespace testing
2370
2371 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
2372