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 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file tests some commonly used argument matchers.
35
36 #include "gmock/gmock-matchers.h"
37
38 #include <string.h>
39 #include <functional>
40 #include <iostream>
41 #include <list>
42 #include <map>
43 #include <set>
44 #include <sstream>
45 #include <string>
46 #include <utility>
47 #include <vector>
48 #include "gmock/gmock.h"
49 #include "gtest/gtest.h"
50 #include "gtest/gtest-spi.h"
51
52 namespace testing {
53
54 namespace internal {
55 GTEST_API_ string JoinAsTuple(const Strings& fields);
56 } // namespace internal
57
58 namespace gmock_matchers_test {
59
60 using std::greater;
61 using std::less;
62 using std::list;
63 using std::make_pair;
64 using std::map;
65 using std::multimap;
66 using std::multiset;
67 using std::ostream;
68 using std::pair;
69 using std::set;
70 using std::stringstream;
71 using std::tr1::get;
72 using std::tr1::make_tuple;
73 using std::tr1::tuple;
74 using std::vector;
75 using testing::A;
76 using testing::AllArgs;
77 using testing::AllOf;
78 using testing::An;
79 using testing::AnyOf;
80 using testing::ByRef;
81 using testing::ContainsRegex;
82 using testing::DoubleEq;
83 using testing::EndsWith;
84 using testing::Eq;
85 using testing::ExplainMatchResult;
86 using testing::Field;
87 using testing::FloatEq;
88 using testing::Ge;
89 using testing::Gt;
90 using testing::HasSubstr;
91 using testing::IsNull;
92 using testing::Key;
93 using testing::Le;
94 using testing::Lt;
95 using testing::MakeMatcher;
96 using testing::MakePolymorphicMatcher;
97 using testing::MatchResultListener;
98 using testing::Matcher;
99 using testing::MatcherCast;
100 using testing::MatcherInterface;
101 using testing::Matches;
102 using testing::MatchesRegex;
103 using testing::NanSensitiveDoubleEq;
104 using testing::NanSensitiveFloatEq;
105 using testing::Ne;
106 using testing::Not;
107 using testing::NotNull;
108 using testing::Pair;
109 using testing::Pointee;
110 using testing::Pointwise;
111 using testing::PolymorphicMatcher;
112 using testing::Property;
113 using testing::Ref;
114 using testing::ResultOf;
115 using testing::StartsWith;
116 using testing::StrCaseEq;
117 using testing::StrCaseNe;
118 using testing::StrEq;
119 using testing::StrNe;
120 using testing::Truly;
121 using testing::TypedEq;
122 using testing::Value;
123 using testing::WhenSorted;
124 using testing::WhenSortedBy;
125 using testing::_;
126 using testing::internal::DummyMatchResultListener;
127 using testing::internal::ExplainMatchFailureTupleTo;
128 using testing::internal::FloatingEqMatcher;
129 using testing::internal::FormatMatcherDescription;
130 using testing::internal::IsReadableTypeName;
131 using testing::internal::JoinAsTuple;
132 using testing::internal::RE;
133 using testing::internal::StreamMatchResultListener;
134 using testing::internal::String;
135 using testing::internal::StringMatchResultListener;
136 using testing::internal::Strings;
137 using testing::internal::linked_ptr;
138 using testing::internal::scoped_ptr;
139 using testing::internal::string;
140
141 // For testing ExplainMatchResultTo().
142 class GreaterThanMatcher : public MatcherInterface<int> {
143 public:
GreaterThanMatcher(int rhs)144 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
145
DescribeTo(ostream * os) const146 virtual void DescribeTo(ostream* os) const {
147 *os << "is > " << rhs_;
148 }
149
MatchAndExplain(int lhs,MatchResultListener * listener) const150 virtual bool MatchAndExplain(int lhs,
151 MatchResultListener* listener) const {
152 const int diff = lhs - rhs_;
153 if (diff > 0) {
154 *listener << "which is " << diff << " more than " << rhs_;
155 } else if (diff == 0) {
156 *listener << "which is the same as " << rhs_;
157 } else {
158 *listener << "which is " << -diff << " less than " << rhs_;
159 }
160
161 return lhs > rhs_;
162 }
163
164 private:
165 int rhs_;
166 };
167
GreaterThan(int n)168 Matcher<int> GreaterThan(int n) {
169 return MakeMatcher(new GreaterThanMatcher(n));
170 }
171
OfType(const string & type_name)172 string OfType(const string& type_name) {
173 #if GTEST_HAS_RTTI
174 return " (of type " + type_name + ")";
175 #else
176 return "";
177 #endif
178 }
179
180 // Returns the description of the given matcher.
181 template <typename T>
Describe(const Matcher<T> & m)182 string Describe(const Matcher<T>& m) {
183 stringstream ss;
184 m.DescribeTo(&ss);
185 return ss.str();
186 }
187
188 // Returns the description of the negation of the given matcher.
189 template <typename T>
DescribeNegation(const Matcher<T> & m)190 string DescribeNegation(const Matcher<T>& m) {
191 stringstream ss;
192 m.DescribeNegationTo(&ss);
193 return ss.str();
194 }
195
196 // Returns the reason why x matches, or doesn't match, m.
197 template <typename MatcherType, typename Value>
Explain(const MatcherType & m,const Value & x)198 string Explain(const MatcherType& m, const Value& x) {
199 StringMatchResultListener listener;
200 ExplainMatchResult(m, x, &listener);
201 return listener.str();
202 }
203
TEST(MatchResultListenerTest,StreamingWorks)204 TEST(MatchResultListenerTest, StreamingWorks) {
205 StringMatchResultListener listener;
206 listener << "hi" << 5;
207 EXPECT_EQ("hi5", listener.str());
208
209 // Streaming shouldn't crash when the underlying ostream is NULL.
210 DummyMatchResultListener dummy;
211 dummy << "hi" << 5;
212 }
213
TEST(MatchResultListenerTest,CanAccessUnderlyingStream)214 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
215 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
216 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
217
218 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
219 }
220
TEST(MatchResultListenerTest,IsInterestedWorks)221 TEST(MatchResultListenerTest, IsInterestedWorks) {
222 EXPECT_TRUE(StringMatchResultListener().IsInterested());
223 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
224
225 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
226 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
227 }
228
229 // Makes sure that the MatcherInterface<T> interface doesn't
230 // change.
231 class EvenMatcherImpl : public MatcherInterface<int> {
232 public:
MatchAndExplain(int x,MatchResultListener *) const233 virtual bool MatchAndExplain(int x,
234 MatchResultListener* /* listener */) const {
235 return x % 2 == 0;
236 }
237
DescribeTo(ostream * os) const238 virtual void DescribeTo(ostream* os) const {
239 *os << "is an even number";
240 }
241
242 // We deliberately don't define DescribeNegationTo() and
243 // ExplainMatchResultTo() here, to make sure the definition of these
244 // two methods is optional.
245 };
246
247 // Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest,CanBeImplementedUsingPublishedAPI)248 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
249 EvenMatcherImpl m;
250 }
251
252 // Tests implementing a monomorphic matcher using MatchAndExplain().
253
254 class NewEvenMatcherImpl : public MatcherInterface<int> {
255 public:
MatchAndExplain(int x,MatchResultListener * listener) const256 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
257 const bool match = x % 2 == 0;
258 // Verifies that we can stream to a listener directly.
259 *listener << "value % " << 2;
260 if (listener->stream() != NULL) {
261 // Verifies that we can stream to a listener's underlying stream
262 // too.
263 *listener->stream() << " == " << (x % 2);
264 }
265 return match;
266 }
267
DescribeTo(ostream * os) const268 virtual void DescribeTo(ostream* os) const {
269 *os << "is an even number";
270 }
271 };
272
TEST(MatcherInterfaceTest,CanBeImplementedUsingNewAPI)273 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
274 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
275 EXPECT_TRUE(m.Matches(2));
276 EXPECT_FALSE(m.Matches(3));
277 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
278 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
279 }
280
281 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)282 TEST(MatcherTest, CanBeDefaultConstructed) {
283 Matcher<double> m;
284 }
285
286 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)287 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
288 const MatcherInterface<int>* impl = new EvenMatcherImpl;
289 Matcher<int> m(impl);
290 EXPECT_TRUE(m.Matches(4));
291 EXPECT_FALSE(m.Matches(5));
292 }
293
294 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)295 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
296 Matcher<int> m1 = 5;
297 EXPECT_TRUE(m1.Matches(5));
298 EXPECT_FALSE(m1.Matches(6));
299 }
300
301 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)302 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
303 Matcher<int*> m1 = NULL;
304 EXPECT_TRUE(m1.Matches(NULL));
305 int n = 0;
306 EXPECT_FALSE(m1.Matches(&n));
307 }
308
309 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)310 TEST(MatcherTest, IsCopyable) {
311 // Tests the copy constructor.
312 Matcher<bool> m1 = Eq(false);
313 EXPECT_TRUE(m1.Matches(false));
314 EXPECT_FALSE(m1.Matches(true));
315
316 // Tests the assignment operator.
317 m1 = Eq(true);
318 EXPECT_TRUE(m1.Matches(true));
319 EXPECT_FALSE(m1.Matches(false));
320 }
321
322 // Tests that Matcher<T>::DescribeTo() calls
323 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)324 TEST(MatcherTest, CanDescribeItself) {
325 EXPECT_EQ("is an even number",
326 Describe(Matcher<int>(new EvenMatcherImpl)));
327 }
328
329 // Tests Matcher<T>::MatchAndExplain().
TEST(MatcherTest,MatchAndExplain)330 TEST(MatcherTest, MatchAndExplain) {
331 Matcher<int> m = GreaterThan(0);
332 StringMatchResultListener listener1;
333 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
334 EXPECT_EQ("which is 42 more than 0", listener1.str());
335
336 StringMatchResultListener listener2;
337 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
338 EXPECT_EQ("which is 9 less than 0", listener2.str());
339 }
340
341 // Tests that a C-string literal can be implicitly converted to a
342 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)343 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
344 Matcher<string> m1 = "hi";
345 EXPECT_TRUE(m1.Matches("hi"));
346 EXPECT_FALSE(m1.Matches("hello"));
347
348 Matcher<const string&> m2 = "hi";
349 EXPECT_TRUE(m2.Matches("hi"));
350 EXPECT_FALSE(m2.Matches("hello"));
351 }
352
353 // Tests that a string object can be implicitly converted to a
354 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)355 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
356 Matcher<string> m1 = string("hi");
357 EXPECT_TRUE(m1.Matches("hi"));
358 EXPECT_FALSE(m1.Matches("hello"));
359
360 Matcher<const string&> m2 = string("hi");
361 EXPECT_TRUE(m2.Matches("hi"));
362 EXPECT_FALSE(m2.Matches("hello"));
363 }
364
365 // Tests that MakeMatcher() constructs a Matcher<T> from a
366 // MatcherInterface* without requiring the user to explicitly
367 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)368 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
369 const MatcherInterface<int>* dummy_impl = NULL;
370 Matcher<int> m = MakeMatcher(dummy_impl);
371 }
372
373 // Tests that MakePolymorphicMatcher() can construct a polymorphic
374 // matcher from its implementation using the old API.
375 const int g_bar = 1;
376 class ReferencesBarOrIsZeroImpl {
377 public:
378 template <typename T>
MatchAndExplain(const T & x,MatchResultListener *) const379 bool MatchAndExplain(const T& x,
380 MatchResultListener* /* listener */) const {
381 const void* p = &x;
382 return p == &g_bar || x == 0;
383 }
384
DescribeTo(ostream * os) const385 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
386
DescribeNegationTo(ostream * os) const387 void DescribeNegationTo(ostream* os) const {
388 *os << "doesn't reference g_bar and is not zero";
389 }
390 };
391
392 // This function verifies that MakePolymorphicMatcher() returns a
393 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()394 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
395 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
396 }
397
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingOldAPI)398 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
399 // Using a polymorphic matcher to match a reference type.
400 Matcher<const int&> m1 = ReferencesBarOrIsZero();
401 EXPECT_TRUE(m1.Matches(0));
402 // Verifies that the identity of a by-reference argument is preserved.
403 EXPECT_TRUE(m1.Matches(g_bar));
404 EXPECT_FALSE(m1.Matches(1));
405 EXPECT_EQ("g_bar or zero", Describe(m1));
406
407 // Using a polymorphic matcher to match a value type.
408 Matcher<double> m2 = ReferencesBarOrIsZero();
409 EXPECT_TRUE(m2.Matches(0.0));
410 EXPECT_FALSE(m2.Matches(0.1));
411 EXPECT_EQ("g_bar or zero", Describe(m2));
412 }
413
414 // Tests implementing a polymorphic matcher using MatchAndExplain().
415
416 class PolymorphicIsEvenImpl {
417 public:
DescribeTo(ostream * os) const418 void DescribeTo(ostream* os) const { *os << "is even"; }
419
DescribeNegationTo(ostream * os) const420 void DescribeNegationTo(ostream* os) const {
421 *os << "is odd";
422 }
423
424 template <typename T>
MatchAndExplain(const T & x,MatchResultListener * listener) const425 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
426 // Verifies that we can stream to the listener directly.
427 *listener << "% " << 2;
428 if (listener->stream() != NULL) {
429 // Verifies that we can stream to the listener's underlying stream
430 // too.
431 *listener->stream() << " == " << (x % 2);
432 }
433 return (x % 2) == 0;
434 }
435 };
436
PolymorphicIsEven()437 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
438 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
439 }
440
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingNewAPI)441 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
442 // Using PolymorphicIsEven() as a Matcher<int>.
443 const Matcher<int> m1 = PolymorphicIsEven();
444 EXPECT_TRUE(m1.Matches(42));
445 EXPECT_FALSE(m1.Matches(43));
446 EXPECT_EQ("is even", Describe(m1));
447
448 const Matcher<int> not_m1 = Not(m1);
449 EXPECT_EQ("is odd", Describe(not_m1));
450
451 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
452
453 // Using PolymorphicIsEven() as a Matcher<char>.
454 const Matcher<char> m2 = PolymorphicIsEven();
455 EXPECT_TRUE(m2.Matches('\x42'));
456 EXPECT_FALSE(m2.Matches('\x43'));
457 EXPECT_EQ("is even", Describe(m2));
458
459 const Matcher<char> not_m2 = Not(m2);
460 EXPECT_EQ("is odd", Describe(not_m2));
461
462 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
463 }
464
465 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest,FromPolymorphicMatcher)466 TEST(MatcherCastTest, FromPolymorphicMatcher) {
467 Matcher<int> m = MatcherCast<int>(Eq(5));
468 EXPECT_TRUE(m.Matches(5));
469 EXPECT_FALSE(m.Matches(6));
470 }
471
472 // For testing casting matchers between compatible types.
473 class IntValue {
474 public:
475 // An int can be statically (although not implicitly) cast to a
476 // IntValue.
IntValue(int a_value)477 explicit IntValue(int a_value) : value_(a_value) {}
478
value() const479 int value() const { return value_; }
480 private:
481 int value_;
482 };
483
484 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)485 bool IsPositiveIntValue(const IntValue& foo) {
486 return foo.value() > 0;
487 }
488
489 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
490 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)491 TEST(MatcherCastTest, FromCompatibleType) {
492 Matcher<double> m1 = Eq(2.0);
493 Matcher<int> m2 = MatcherCast<int>(m1);
494 EXPECT_TRUE(m2.Matches(2));
495 EXPECT_FALSE(m2.Matches(3));
496
497 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
498 Matcher<int> m4 = MatcherCast<int>(m3);
499 // In the following, the arguments 1 and 0 are statically converted
500 // to IntValue objects, and then tested by the IsPositiveIntValue()
501 // predicate.
502 EXPECT_TRUE(m4.Matches(1));
503 EXPECT_FALSE(m4.Matches(0));
504 }
505
506 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)507 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
508 Matcher<const int&> m1 = Eq(0);
509 Matcher<int> m2 = MatcherCast<int>(m1);
510 EXPECT_TRUE(m2.Matches(0));
511 EXPECT_FALSE(m2.Matches(1));
512 }
513
514 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)515 TEST(MatcherCastTest, FromReferenceToNonReference) {
516 Matcher<int&> m1 = Eq(0);
517 Matcher<int> m2 = MatcherCast<int>(m1);
518 EXPECT_TRUE(m2.Matches(0));
519 EXPECT_FALSE(m2.Matches(1));
520 }
521
522 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)523 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
524 Matcher<int> m1 = Eq(0);
525 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
526 EXPECT_TRUE(m2.Matches(0));
527 EXPECT_FALSE(m2.Matches(1));
528 }
529
530 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)531 TEST(MatcherCastTest, FromNonReferenceToReference) {
532 Matcher<int> m1 = Eq(0);
533 Matcher<int&> m2 = MatcherCast<int&>(m1);
534 int n = 0;
535 EXPECT_TRUE(m2.Matches(n));
536 n = 1;
537 EXPECT_FALSE(m2.Matches(n));
538 }
539
540 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)541 TEST(MatcherCastTest, FromSameType) {
542 Matcher<int> m1 = Eq(0);
543 Matcher<int> m2 = MatcherCast<int>(m1);
544 EXPECT_TRUE(m2.Matches(0));
545 EXPECT_FALSE(m2.Matches(1));
546 }
547
548 // Implicitly convertible form any type.
549 struct ConvertibleFromAny {
ConvertibleFromAnytesting::gmock_matchers_test::ConvertibleFromAny550 ConvertibleFromAny(int a_value) : value(a_value) {}
551 template <typename T>
ConvertibleFromAnytesting::gmock_matchers_test::ConvertibleFromAny552 ConvertibleFromAny(const T& a_value) : value(-1) {
553 ADD_FAILURE() << "Conversion constructor called";
554 }
555 int value;
556 };
557
operator ==(const ConvertibleFromAny & a,const ConvertibleFromAny & b)558 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
559 return a.value == b.value;
560 }
561
operator <<(ostream & os,const ConvertibleFromAny & a)562 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
563 return os << a.value;
564 }
565
TEST(MatcherCastTest,ConversionConstructorIsUsed)566 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
567 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
568 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
569 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
570 }
571
TEST(MatcherCastTest,FromConvertibleFromAny)572 TEST(MatcherCastTest, FromConvertibleFromAny) {
573 Matcher<ConvertibleFromAny> m =
574 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
575 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
576 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
577 }
578
579 class Base {};
580 class Derived : public Base {};
581
582 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest,FromPolymorphicMatcher)583 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
584 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
585 EXPECT_TRUE(m2.Matches(' '));
586 EXPECT_FALSE(m2.Matches('\n'));
587 }
588
589 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
590 // T and U are arithmetic types and T can be losslessly converted to
591 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)592 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
593 Matcher<double> m1 = DoubleEq(1.0);
594 Matcher<float> m2 = SafeMatcherCast<float>(m1);
595 EXPECT_TRUE(m2.Matches(1.0f));
596 EXPECT_FALSE(m2.Matches(2.0f));
597
598 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
599 EXPECT_TRUE(m3.Matches('a'));
600 EXPECT_FALSE(m3.Matches('b'));
601 }
602
603 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
604 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)605 TEST(SafeMatcherCastTest, FromBaseClass) {
606 Derived d, d2;
607 Matcher<Base*> m1 = Eq(&d);
608 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
609 EXPECT_TRUE(m2.Matches(&d));
610 EXPECT_FALSE(m2.Matches(&d2));
611
612 Matcher<Base&> m3 = Ref(d);
613 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
614 EXPECT_TRUE(m4.Matches(d));
615 EXPECT_FALSE(m4.Matches(d2));
616 }
617
618 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)619 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
620 int n = 0;
621 Matcher<const int&> m1 = Ref(n);
622 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
623 int n1 = 0;
624 EXPECT_TRUE(m2.Matches(n));
625 EXPECT_FALSE(m2.Matches(n1));
626 }
627
628 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)629 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
630 Matcher<int> m1 = Eq(0);
631 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
632 EXPECT_TRUE(m2.Matches(0));
633 EXPECT_FALSE(m2.Matches(1));
634 }
635
636 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)637 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
638 Matcher<int> m1 = Eq(0);
639 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
640 int n = 0;
641 EXPECT_TRUE(m2.Matches(n));
642 n = 1;
643 EXPECT_FALSE(m2.Matches(n));
644 }
645
646 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)647 TEST(SafeMatcherCastTest, FromSameType) {
648 Matcher<int> m1 = Eq(0);
649 Matcher<int> m2 = SafeMatcherCast<int>(m1);
650 EXPECT_TRUE(m2.Matches(0));
651 EXPECT_FALSE(m2.Matches(1));
652 }
653
TEST(SafeMatcherCastTest,ConversionConstructorIsUsed)654 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
655 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
656 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
657 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
658 }
659
TEST(SafeMatcherCastTest,FromConvertibleFromAny)660 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
661 Matcher<ConvertibleFromAny> m =
662 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
663 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
664 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
665 }
666
667 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)668 TEST(ATest, MatchesAnyValue) {
669 // Tests a matcher for a value type.
670 Matcher<double> m1 = A<double>();
671 EXPECT_TRUE(m1.Matches(91.43));
672 EXPECT_TRUE(m1.Matches(-15.32));
673
674 // Tests a matcher for a reference type.
675 int a = 2;
676 int b = -6;
677 Matcher<int&> m2 = A<int&>();
678 EXPECT_TRUE(m2.Matches(a));
679 EXPECT_TRUE(m2.Matches(b));
680 }
681
682 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)683 TEST(ATest, CanDescribeSelf) {
684 EXPECT_EQ("is anything", Describe(A<bool>()));
685 }
686
687 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)688 TEST(AnTest, MatchesAnyValue) {
689 // Tests a matcher for a value type.
690 Matcher<int> m1 = An<int>();
691 EXPECT_TRUE(m1.Matches(9143));
692 EXPECT_TRUE(m1.Matches(-1532));
693
694 // Tests a matcher for a reference type.
695 int a = 2;
696 int b = -6;
697 Matcher<int&> m2 = An<int&>();
698 EXPECT_TRUE(m2.Matches(a));
699 EXPECT_TRUE(m2.Matches(b));
700 }
701
702 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)703 TEST(AnTest, CanDescribeSelf) {
704 EXPECT_EQ("is anything", Describe(An<int>()));
705 }
706
707 // Tests that _ can be used as a matcher for any type and matches any
708 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)709 TEST(UnderscoreTest, MatchesAnyValue) {
710 // Uses _ as a matcher for a value type.
711 Matcher<int> m1 = _;
712 EXPECT_TRUE(m1.Matches(123));
713 EXPECT_TRUE(m1.Matches(-242));
714
715 // Uses _ as a matcher for a reference type.
716 bool a = false;
717 const bool b = true;
718 Matcher<const bool&> m2 = _;
719 EXPECT_TRUE(m2.Matches(a));
720 EXPECT_TRUE(m2.Matches(b));
721 }
722
723 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)724 TEST(UnderscoreTest, CanDescribeSelf) {
725 Matcher<int> m = _;
726 EXPECT_EQ("is anything", Describe(m));
727 }
728
729 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)730 TEST(EqTest, MatchesEqualValue) {
731 // 2 C-strings with same content but different addresses.
732 const char a1[] = "hi";
733 const char a2[] = "hi";
734
735 Matcher<const char*> m1 = Eq(a1);
736 EXPECT_TRUE(m1.Matches(a1));
737 EXPECT_FALSE(m1.Matches(a2));
738 }
739
740 // Tests that Eq(v) describes itself properly.
741
742 class Unprintable {
743 public:
Unprintable()744 Unprintable() : c_('a') {}
745
operator ==(const Unprintable &)746 bool operator==(const Unprintable& /* rhs */) { return true; }
747 private:
748 char c_;
749 };
750
TEST(EqTest,CanDescribeSelf)751 TEST(EqTest, CanDescribeSelf) {
752 Matcher<Unprintable> m = Eq(Unprintable());
753 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
754 }
755
756 // Tests that Eq(v) can be used to match any type that supports
757 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)758 TEST(EqTest, IsPolymorphic) {
759 Matcher<int> m1 = Eq(1);
760 EXPECT_TRUE(m1.Matches(1));
761 EXPECT_FALSE(m1.Matches(2));
762
763 Matcher<char> m2 = Eq(1);
764 EXPECT_TRUE(m2.Matches('\1'));
765 EXPECT_FALSE(m2.Matches('a'));
766 }
767
768 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)769 TEST(TypedEqTest, ChecksEqualityForGivenType) {
770 Matcher<char> m1 = TypedEq<char>('a');
771 EXPECT_TRUE(m1.Matches('a'));
772 EXPECT_FALSE(m1.Matches('b'));
773
774 Matcher<int> m2 = TypedEq<int>(6);
775 EXPECT_TRUE(m2.Matches(6));
776 EXPECT_FALSE(m2.Matches(7));
777 }
778
779 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)780 TEST(TypedEqTest, CanDescribeSelf) {
781 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
782 }
783
784 // Tests that TypedEq<T>(v) has type Matcher<T>.
785
786 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
787 // is a "bare" type (i.e. not in the form of const U or U&). If v's
788 // type is not T, the compiler will generate a message about
789 // "undefined referece".
790 template <typename T>
791 struct Type {
IsTypeOftesting::gmock_matchers_test::Type792 static bool IsTypeOf(const T& /* v */) { return true; }
793
794 template <typename T2>
795 static void IsTypeOf(T2 v);
796 };
797
TEST(TypedEqTest,HasSpecifiedType)798 TEST(TypedEqTest, HasSpecifiedType) {
799 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
800 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
801 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
802 }
803
804 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)805 TEST(GeTest, ImplementsGreaterThanOrEqual) {
806 Matcher<int> m1 = Ge(0);
807 EXPECT_TRUE(m1.Matches(1));
808 EXPECT_TRUE(m1.Matches(0));
809 EXPECT_FALSE(m1.Matches(-1));
810 }
811
812 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)813 TEST(GeTest, CanDescribeSelf) {
814 Matcher<int> m = Ge(5);
815 EXPECT_EQ("is >= 5", Describe(m));
816 }
817
818 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)819 TEST(GtTest, ImplementsGreaterThan) {
820 Matcher<double> m1 = Gt(0);
821 EXPECT_TRUE(m1.Matches(1.0));
822 EXPECT_FALSE(m1.Matches(0.0));
823 EXPECT_FALSE(m1.Matches(-1.0));
824 }
825
826 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)827 TEST(GtTest, CanDescribeSelf) {
828 Matcher<int> m = Gt(5);
829 EXPECT_EQ("is > 5", Describe(m));
830 }
831
832 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)833 TEST(LeTest, ImplementsLessThanOrEqual) {
834 Matcher<char> m1 = Le('b');
835 EXPECT_TRUE(m1.Matches('a'));
836 EXPECT_TRUE(m1.Matches('b'));
837 EXPECT_FALSE(m1.Matches('c'));
838 }
839
840 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)841 TEST(LeTest, CanDescribeSelf) {
842 Matcher<int> m = Le(5);
843 EXPECT_EQ("is <= 5", Describe(m));
844 }
845
846 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)847 TEST(LtTest, ImplementsLessThan) {
848 Matcher<const string&> m1 = Lt("Hello");
849 EXPECT_TRUE(m1.Matches("Abc"));
850 EXPECT_FALSE(m1.Matches("Hello"));
851 EXPECT_FALSE(m1.Matches("Hello, world!"));
852 }
853
854 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)855 TEST(LtTest, CanDescribeSelf) {
856 Matcher<int> m = Lt(5);
857 EXPECT_EQ("is < 5", Describe(m));
858 }
859
860 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)861 TEST(NeTest, ImplementsNotEqual) {
862 Matcher<int> m1 = Ne(0);
863 EXPECT_TRUE(m1.Matches(1));
864 EXPECT_TRUE(m1.Matches(-1));
865 EXPECT_FALSE(m1.Matches(0));
866 }
867
868 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)869 TEST(NeTest, CanDescribeSelf) {
870 Matcher<int> m = Ne(5);
871 EXPECT_EQ("isn't equal to 5", Describe(m));
872 }
873
874 // Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest,MatchesNullPointer)875 TEST(IsNullTest, MatchesNullPointer) {
876 Matcher<int*> m1 = IsNull();
877 int* p1 = NULL;
878 int n = 0;
879 EXPECT_TRUE(m1.Matches(p1));
880 EXPECT_FALSE(m1.Matches(&n));
881
882 Matcher<const char*> m2 = IsNull();
883 const char* p2 = NULL;
884 EXPECT_TRUE(m2.Matches(p2));
885 EXPECT_FALSE(m2.Matches("hi"));
886
887 #if !GTEST_OS_SYMBIAN
888 // Nokia's Symbian compiler generates:
889 // gmock-matchers.h: ambiguous access to overloaded function
890 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
891 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
892 // MatcherInterface<void *> *)'
893 // gmock-matchers.h: (point of instantiation: 'testing::
894 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
895 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
896 Matcher<void*> m3 = IsNull();
897 void* p3 = NULL;
898 EXPECT_TRUE(m3.Matches(p3));
899 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
900 #endif
901 }
902
TEST(IsNullTest,LinkedPtr)903 TEST(IsNullTest, LinkedPtr) {
904 const Matcher<linked_ptr<int> > m = IsNull();
905 const linked_ptr<int> null_p;
906 const linked_ptr<int> non_null_p(new int);
907
908 EXPECT_TRUE(m.Matches(null_p));
909 EXPECT_FALSE(m.Matches(non_null_p));
910 }
911
TEST(IsNullTest,ReferenceToConstLinkedPtr)912 TEST(IsNullTest, ReferenceToConstLinkedPtr) {
913 const Matcher<const linked_ptr<double>&> m = IsNull();
914 const linked_ptr<double> null_p;
915 const linked_ptr<double> non_null_p(new double);
916
917 EXPECT_TRUE(m.Matches(null_p));
918 EXPECT_FALSE(m.Matches(non_null_p));
919 }
920
TEST(IsNullTest,ReferenceToConstScopedPtr)921 TEST(IsNullTest, ReferenceToConstScopedPtr) {
922 const Matcher<const scoped_ptr<double>&> m = IsNull();
923 const scoped_ptr<double> null_p;
924 const scoped_ptr<double> non_null_p(new double);
925
926 EXPECT_TRUE(m.Matches(null_p));
927 EXPECT_FALSE(m.Matches(non_null_p));
928 }
929
930 // Tests that IsNull() describes itself properly.
TEST(IsNullTest,CanDescribeSelf)931 TEST(IsNullTest, CanDescribeSelf) {
932 Matcher<int*> m = IsNull();
933 EXPECT_EQ("is NULL", Describe(m));
934 EXPECT_EQ("isn't NULL", DescribeNegation(m));
935 }
936
937 // Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest,MatchesNonNullPointer)938 TEST(NotNullTest, MatchesNonNullPointer) {
939 Matcher<int*> m1 = NotNull();
940 int* p1 = NULL;
941 int n = 0;
942 EXPECT_FALSE(m1.Matches(p1));
943 EXPECT_TRUE(m1.Matches(&n));
944
945 Matcher<const char*> m2 = NotNull();
946 const char* p2 = NULL;
947 EXPECT_FALSE(m2.Matches(p2));
948 EXPECT_TRUE(m2.Matches("hi"));
949 }
950
TEST(NotNullTest,LinkedPtr)951 TEST(NotNullTest, LinkedPtr) {
952 const Matcher<linked_ptr<int> > m = NotNull();
953 const linked_ptr<int> null_p;
954 const linked_ptr<int> non_null_p(new int);
955
956 EXPECT_FALSE(m.Matches(null_p));
957 EXPECT_TRUE(m.Matches(non_null_p));
958 }
959
TEST(NotNullTest,ReferenceToConstLinkedPtr)960 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
961 const Matcher<const linked_ptr<double>&> m = NotNull();
962 const linked_ptr<double> null_p;
963 const linked_ptr<double> non_null_p(new double);
964
965 EXPECT_FALSE(m.Matches(null_p));
966 EXPECT_TRUE(m.Matches(non_null_p));
967 }
968
TEST(NotNullTest,ReferenceToConstScopedPtr)969 TEST(NotNullTest, ReferenceToConstScopedPtr) {
970 const Matcher<const scoped_ptr<double>&> m = NotNull();
971 const scoped_ptr<double> null_p;
972 const scoped_ptr<double> non_null_p(new double);
973
974 EXPECT_FALSE(m.Matches(null_p));
975 EXPECT_TRUE(m.Matches(non_null_p));
976 }
977
978 // Tests that NotNull() describes itself properly.
TEST(NotNullTest,CanDescribeSelf)979 TEST(NotNullTest, CanDescribeSelf) {
980 Matcher<int*> m = NotNull();
981 EXPECT_EQ("isn't NULL", Describe(m));
982 }
983
984 // Tests that Ref(variable) matches an argument that references
985 // 'variable'.
TEST(RefTest,MatchesSameVariable)986 TEST(RefTest, MatchesSameVariable) {
987 int a = 0;
988 int b = 0;
989 Matcher<int&> m = Ref(a);
990 EXPECT_TRUE(m.Matches(a));
991 EXPECT_FALSE(m.Matches(b));
992 }
993
994 // Tests that Ref(variable) describes itself properly.
TEST(RefTest,CanDescribeSelf)995 TEST(RefTest, CanDescribeSelf) {
996 int n = 5;
997 Matcher<int&> m = Ref(n);
998 stringstream ss;
999 ss << "references the variable @" << &n << " 5";
1000 EXPECT_EQ(string(ss.str()), Describe(m));
1001 }
1002
1003 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1004 // const reference.
TEST(RefTest,CanBeUsedAsMatcherForConstReference)1005 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1006 int a = 0;
1007 int b = 0;
1008 Matcher<const int&> m = Ref(a);
1009 EXPECT_TRUE(m.Matches(a));
1010 EXPECT_FALSE(m.Matches(b));
1011 }
1012
1013 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1014 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1015 // of Ref(base), but not vice versa.
1016
TEST(RefTest,IsCovariant)1017 TEST(RefTest, IsCovariant) {
1018 Base base, base2;
1019 Derived derived;
1020 Matcher<const Base&> m1 = Ref(base);
1021 EXPECT_TRUE(m1.Matches(base));
1022 EXPECT_FALSE(m1.Matches(base2));
1023 EXPECT_FALSE(m1.Matches(derived));
1024
1025 m1 = Ref(derived);
1026 EXPECT_TRUE(m1.Matches(derived));
1027 EXPECT_FALSE(m1.Matches(base));
1028 EXPECT_FALSE(m1.Matches(base2));
1029 }
1030
TEST(RefTest,ExplainsResult)1031 TEST(RefTest, ExplainsResult) {
1032 int n = 0;
1033 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1034 StartsWith("which is located @"));
1035
1036 int m = 0;
1037 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1038 StartsWith("which is located @"));
1039 }
1040
1041 // Tests string comparison matchers.
1042
TEST(StrEqTest,MatchesEqualString)1043 TEST(StrEqTest, MatchesEqualString) {
1044 Matcher<const char*> m = StrEq(string("Hello"));
1045 EXPECT_TRUE(m.Matches("Hello"));
1046 EXPECT_FALSE(m.Matches("hello"));
1047 EXPECT_FALSE(m.Matches(NULL));
1048
1049 Matcher<const string&> m2 = StrEq("Hello");
1050 EXPECT_TRUE(m2.Matches("Hello"));
1051 EXPECT_FALSE(m2.Matches("Hi"));
1052 }
1053
TEST(StrEqTest,CanDescribeSelf)1054 TEST(StrEqTest, CanDescribeSelf) {
1055 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1056 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1057 Describe(m));
1058
1059 string str("01204500800");
1060 str[3] = '\0';
1061 Matcher<string> m2 = StrEq(str);
1062 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1063 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1064 Matcher<string> m3 = StrEq(str);
1065 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1066 }
1067
TEST(StrNeTest,MatchesUnequalString)1068 TEST(StrNeTest, MatchesUnequalString) {
1069 Matcher<const char*> m = StrNe("Hello");
1070 EXPECT_TRUE(m.Matches(""));
1071 EXPECT_TRUE(m.Matches(NULL));
1072 EXPECT_FALSE(m.Matches("Hello"));
1073
1074 Matcher<string> m2 = StrNe(string("Hello"));
1075 EXPECT_TRUE(m2.Matches("hello"));
1076 EXPECT_FALSE(m2.Matches("Hello"));
1077 }
1078
TEST(StrNeTest,CanDescribeSelf)1079 TEST(StrNeTest, CanDescribeSelf) {
1080 Matcher<const char*> m = StrNe("Hi");
1081 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1082 }
1083
TEST(StrCaseEqTest,MatchesEqualStringIgnoringCase)1084 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1085 Matcher<const char*> m = StrCaseEq(string("Hello"));
1086 EXPECT_TRUE(m.Matches("Hello"));
1087 EXPECT_TRUE(m.Matches("hello"));
1088 EXPECT_FALSE(m.Matches("Hi"));
1089 EXPECT_FALSE(m.Matches(NULL));
1090
1091 Matcher<const string&> m2 = StrCaseEq("Hello");
1092 EXPECT_TRUE(m2.Matches("hello"));
1093 EXPECT_FALSE(m2.Matches("Hi"));
1094 }
1095
TEST(StrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1096 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1097 string str1("oabocdooeoo");
1098 string str2("OABOCDOOEOO");
1099 Matcher<const string&> m0 = StrCaseEq(str1);
1100 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1101
1102 str1[3] = str2[3] = '\0';
1103 Matcher<const string&> m1 = StrCaseEq(str1);
1104 EXPECT_TRUE(m1.Matches(str2));
1105
1106 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1107 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1108 Matcher<const string&> m2 = StrCaseEq(str1);
1109 str1[9] = str2[9] = '\0';
1110 EXPECT_FALSE(m2.Matches(str2));
1111
1112 Matcher<const string&> m3 = StrCaseEq(str1);
1113 EXPECT_TRUE(m3.Matches(str2));
1114
1115 EXPECT_FALSE(m3.Matches(str2 + "x"));
1116 str2.append(1, '\0');
1117 EXPECT_FALSE(m3.Matches(str2));
1118 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1119 }
1120
TEST(StrCaseEqTest,CanDescribeSelf)1121 TEST(StrCaseEqTest, CanDescribeSelf) {
1122 Matcher<string> m = StrCaseEq("Hi");
1123 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1124 }
1125
TEST(StrCaseNeTest,MatchesUnequalStringIgnoringCase)1126 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1127 Matcher<const char*> m = StrCaseNe("Hello");
1128 EXPECT_TRUE(m.Matches("Hi"));
1129 EXPECT_TRUE(m.Matches(NULL));
1130 EXPECT_FALSE(m.Matches("Hello"));
1131 EXPECT_FALSE(m.Matches("hello"));
1132
1133 Matcher<string> m2 = StrCaseNe(string("Hello"));
1134 EXPECT_TRUE(m2.Matches(""));
1135 EXPECT_FALSE(m2.Matches("Hello"));
1136 }
1137
TEST(StrCaseNeTest,CanDescribeSelf)1138 TEST(StrCaseNeTest, CanDescribeSelf) {
1139 Matcher<const char*> m = StrCaseNe("Hi");
1140 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1141 }
1142
1143 // Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest,WorksForStringClasses)1144 TEST(HasSubstrTest, WorksForStringClasses) {
1145 const Matcher<string> m1 = HasSubstr("foo");
1146 EXPECT_TRUE(m1.Matches(string("I love food.")));
1147 EXPECT_FALSE(m1.Matches(string("tofo")));
1148
1149 const Matcher<const std::string&> m2 = HasSubstr("foo");
1150 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1151 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1152 }
1153
1154 // Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest,WorksForCStrings)1155 TEST(HasSubstrTest, WorksForCStrings) {
1156 const Matcher<char*> m1 = HasSubstr("foo");
1157 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1158 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1159 EXPECT_FALSE(m1.Matches(NULL));
1160
1161 const Matcher<const char*> m2 = HasSubstr("foo");
1162 EXPECT_TRUE(m2.Matches("I love food."));
1163 EXPECT_FALSE(m2.Matches("tofo"));
1164 EXPECT_FALSE(m2.Matches(NULL));
1165 }
1166
1167 // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest,CanDescribeSelf)1168 TEST(HasSubstrTest, CanDescribeSelf) {
1169 Matcher<string> m = HasSubstr("foo\n\"");
1170 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1171 }
1172
TEST(KeyTest,CanDescribeSelf)1173 TEST(KeyTest, CanDescribeSelf) {
1174 Matcher<const pair<std::string, int>&> m = Key("foo");
1175 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1176 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1177 }
1178
TEST(KeyTest,ExplainsResult)1179 TEST(KeyTest, ExplainsResult) {
1180 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1181 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1182 Explain(m, make_pair(5, true)));
1183 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1184 Explain(m, make_pair(15, true)));
1185 }
1186
TEST(KeyTest,MatchesCorrectly)1187 TEST(KeyTest, MatchesCorrectly) {
1188 pair<int, std::string> p(25, "foo");
1189 EXPECT_THAT(p, Key(25));
1190 EXPECT_THAT(p, Not(Key(42)));
1191 EXPECT_THAT(p, Key(Ge(20)));
1192 EXPECT_THAT(p, Not(Key(Lt(25))));
1193 }
1194
TEST(KeyTest,SafelyCastsInnerMatcher)1195 TEST(KeyTest, SafelyCastsInnerMatcher) {
1196 Matcher<int> is_positive = Gt(0);
1197 Matcher<int> is_negative = Lt(0);
1198 pair<char, bool> p('a', true);
1199 EXPECT_THAT(p, Key(is_positive));
1200 EXPECT_THAT(p, Not(Key(is_negative)));
1201 }
1202
TEST(KeyTest,InsideContainsUsingMap)1203 TEST(KeyTest, InsideContainsUsingMap) {
1204 map<int, char> container;
1205 container.insert(make_pair(1, 'a'));
1206 container.insert(make_pair(2, 'b'));
1207 container.insert(make_pair(4, 'c'));
1208 EXPECT_THAT(container, Contains(Key(1)));
1209 EXPECT_THAT(container, Not(Contains(Key(3))));
1210 }
1211
TEST(KeyTest,InsideContainsUsingMultimap)1212 TEST(KeyTest, InsideContainsUsingMultimap) {
1213 multimap<int, char> container;
1214 container.insert(make_pair(1, 'a'));
1215 container.insert(make_pair(2, 'b'));
1216 container.insert(make_pair(4, 'c'));
1217
1218 EXPECT_THAT(container, Not(Contains(Key(25))));
1219 container.insert(make_pair(25, 'd'));
1220 EXPECT_THAT(container, Contains(Key(25)));
1221 container.insert(make_pair(25, 'e'));
1222 EXPECT_THAT(container, Contains(Key(25)));
1223
1224 EXPECT_THAT(container, Contains(Key(1)));
1225 EXPECT_THAT(container, Not(Contains(Key(3))));
1226 }
1227
TEST(PairTest,Typing)1228 TEST(PairTest, Typing) {
1229 // Test verifies the following type conversions can be compiled.
1230 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1231 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1232 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1233
1234 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1235 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1236 }
1237
TEST(PairTest,CanDescribeSelf)1238 TEST(PairTest, CanDescribeSelf) {
1239 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1240 EXPECT_EQ("has a first field that is equal to \"foo\""
1241 ", and has a second field that is equal to 42",
1242 Describe(m1));
1243 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1244 ", or has a second field that isn't equal to 42",
1245 DescribeNegation(m1));
1246 // Double and triple negation (1 or 2 times not and description of negation).
1247 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1248 EXPECT_EQ("has a first field that isn't equal to 13"
1249 ", and has a second field that is equal to 42",
1250 DescribeNegation(m2));
1251 }
1252
TEST(PairTest,CanExplainMatchResultTo)1253 TEST(PairTest, CanExplainMatchResultTo) {
1254 // If neither field matches, Pair() should explain about the first
1255 // field.
1256 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1257 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1258 Explain(m, make_pair(-1, -2)));
1259
1260 // If the first field matches but the second doesn't, Pair() should
1261 // explain about the second field.
1262 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1263 Explain(m, make_pair(1, -2)));
1264
1265 // If the first field doesn't match but the second does, Pair()
1266 // should explain about the first field.
1267 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1268 Explain(m, make_pair(-1, 2)));
1269
1270 // If both fields match, Pair() should explain about them both.
1271 EXPECT_EQ("whose both fields match, where the first field is a value "
1272 "which is 1 more than 0, and the second field is a value "
1273 "which is 2 more than 0",
1274 Explain(m, make_pair(1, 2)));
1275
1276 // If only the first match has an explanation, only this explanation should
1277 // be printed.
1278 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1279 EXPECT_EQ("whose both fields match, where the first field is a value "
1280 "which is 1 more than 0",
1281 Explain(explain_first, make_pair(1, 0)));
1282
1283 // If only the second match has an explanation, only this explanation should
1284 // be printed.
1285 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1286 EXPECT_EQ("whose both fields match, where the second field is a value "
1287 "which is 1 more than 0",
1288 Explain(explain_second, make_pair(0, 1)));
1289 }
1290
TEST(PairTest,MatchesCorrectly)1291 TEST(PairTest, MatchesCorrectly) {
1292 pair<int, std::string> p(25, "foo");
1293
1294 // Both fields match.
1295 EXPECT_THAT(p, Pair(25, "foo"));
1296 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1297
1298 // 'first' doesnt' match, but 'second' matches.
1299 EXPECT_THAT(p, Not(Pair(42, "foo")));
1300 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1301
1302 // 'first' matches, but 'second' doesn't match.
1303 EXPECT_THAT(p, Not(Pair(25, "bar")));
1304 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1305
1306 // Neither field matches.
1307 EXPECT_THAT(p, Not(Pair(13, "bar")));
1308 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1309 }
1310
TEST(PairTest,SafelyCastsInnerMatchers)1311 TEST(PairTest, SafelyCastsInnerMatchers) {
1312 Matcher<int> is_positive = Gt(0);
1313 Matcher<int> is_negative = Lt(0);
1314 pair<char, bool> p('a', true);
1315 EXPECT_THAT(p, Pair(is_positive, _));
1316 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1317 EXPECT_THAT(p, Pair(_, is_positive));
1318 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1319 }
1320
TEST(PairTest,InsideContainsUsingMap)1321 TEST(PairTest, InsideContainsUsingMap) {
1322 map<int, char> container;
1323 container.insert(make_pair(1, 'a'));
1324 container.insert(make_pair(2, 'b'));
1325 container.insert(make_pair(4, 'c'));
1326 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1327 EXPECT_THAT(container, Contains(Pair(1, _)));
1328 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1329 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1330 }
1331
1332 // Tests StartsWith(s).
1333
TEST(StartsWithTest,MatchesStringWithGivenPrefix)1334 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1335 const Matcher<const char*> m1 = StartsWith(string(""));
1336 EXPECT_TRUE(m1.Matches("Hi"));
1337 EXPECT_TRUE(m1.Matches(""));
1338 EXPECT_FALSE(m1.Matches(NULL));
1339
1340 const Matcher<const string&> m2 = StartsWith("Hi");
1341 EXPECT_TRUE(m2.Matches("Hi"));
1342 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1343 EXPECT_TRUE(m2.Matches("High"));
1344 EXPECT_FALSE(m2.Matches("H"));
1345 EXPECT_FALSE(m2.Matches(" Hi"));
1346 }
1347
TEST(StartsWithTest,CanDescribeSelf)1348 TEST(StartsWithTest, CanDescribeSelf) {
1349 Matcher<const std::string> m = StartsWith("Hi");
1350 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1351 }
1352
1353 // Tests EndsWith(s).
1354
TEST(EndsWithTest,MatchesStringWithGivenSuffix)1355 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1356 const Matcher<const char*> m1 = EndsWith("");
1357 EXPECT_TRUE(m1.Matches("Hi"));
1358 EXPECT_TRUE(m1.Matches(""));
1359 EXPECT_FALSE(m1.Matches(NULL));
1360
1361 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1362 EXPECT_TRUE(m2.Matches("Hi"));
1363 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1364 EXPECT_TRUE(m2.Matches("Super Hi"));
1365 EXPECT_FALSE(m2.Matches("i"));
1366 EXPECT_FALSE(m2.Matches("Hi "));
1367 }
1368
TEST(EndsWithTest,CanDescribeSelf)1369 TEST(EndsWithTest, CanDescribeSelf) {
1370 Matcher<const std::string> m = EndsWith("Hi");
1371 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1372 }
1373
1374 // Tests MatchesRegex().
1375
TEST(MatchesRegexTest,MatchesStringMatchingGivenRegex)1376 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1377 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1378 EXPECT_TRUE(m1.Matches("az"));
1379 EXPECT_TRUE(m1.Matches("abcz"));
1380 EXPECT_FALSE(m1.Matches(NULL));
1381
1382 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1383 EXPECT_TRUE(m2.Matches("azbz"));
1384 EXPECT_FALSE(m2.Matches("az1"));
1385 EXPECT_FALSE(m2.Matches("1az"));
1386 }
1387
TEST(MatchesRegexTest,CanDescribeSelf)1388 TEST(MatchesRegexTest, CanDescribeSelf) {
1389 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1390 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1391
1392 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1393 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1394 }
1395
1396 // Tests ContainsRegex().
1397
TEST(ContainsRegexTest,MatchesStringContainingGivenRegex)1398 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1399 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1400 EXPECT_TRUE(m1.Matches("az"));
1401 EXPECT_TRUE(m1.Matches("0abcz1"));
1402 EXPECT_FALSE(m1.Matches(NULL));
1403
1404 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1405 EXPECT_TRUE(m2.Matches("azbz"));
1406 EXPECT_TRUE(m2.Matches("az1"));
1407 EXPECT_FALSE(m2.Matches("1a"));
1408 }
1409
TEST(ContainsRegexTest,CanDescribeSelf)1410 TEST(ContainsRegexTest, CanDescribeSelf) {
1411 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1412 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1413
1414 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1415 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1416 }
1417
1418 // Tests for wide strings.
1419 #if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest,MatchesEqual)1420 TEST(StdWideStrEqTest, MatchesEqual) {
1421 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1422 EXPECT_TRUE(m.Matches(L"Hello"));
1423 EXPECT_FALSE(m.Matches(L"hello"));
1424 EXPECT_FALSE(m.Matches(NULL));
1425
1426 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1427 EXPECT_TRUE(m2.Matches(L"Hello"));
1428 EXPECT_FALSE(m2.Matches(L"Hi"));
1429
1430 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1431 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1432 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1433
1434 ::std::wstring str(L"01204500800");
1435 str[3] = L'\0';
1436 Matcher<const ::std::wstring&> m4 = StrEq(str);
1437 EXPECT_TRUE(m4.Matches(str));
1438 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1439 Matcher<const ::std::wstring&> m5 = StrEq(str);
1440 EXPECT_TRUE(m5.Matches(str));
1441 }
1442
TEST(StdWideStrEqTest,CanDescribeSelf)1443 TEST(StdWideStrEqTest, CanDescribeSelf) {
1444 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1445 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1446 Describe(m));
1447
1448 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1449 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1450 Describe(m2));
1451
1452 ::std::wstring str(L"01204500800");
1453 str[3] = L'\0';
1454 Matcher<const ::std::wstring&> m4 = StrEq(str);
1455 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1456 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1457 Matcher<const ::std::wstring&> m5 = StrEq(str);
1458 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1459 }
1460
TEST(StdWideStrNeTest,MatchesUnequalString)1461 TEST(StdWideStrNeTest, MatchesUnequalString) {
1462 Matcher<const wchar_t*> m = StrNe(L"Hello");
1463 EXPECT_TRUE(m.Matches(L""));
1464 EXPECT_TRUE(m.Matches(NULL));
1465 EXPECT_FALSE(m.Matches(L"Hello"));
1466
1467 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1468 EXPECT_TRUE(m2.Matches(L"hello"));
1469 EXPECT_FALSE(m2.Matches(L"Hello"));
1470 }
1471
TEST(StdWideStrNeTest,CanDescribeSelf)1472 TEST(StdWideStrNeTest, CanDescribeSelf) {
1473 Matcher<const wchar_t*> m = StrNe(L"Hi");
1474 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1475 }
1476
TEST(StdWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1477 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1478 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1479 EXPECT_TRUE(m.Matches(L"Hello"));
1480 EXPECT_TRUE(m.Matches(L"hello"));
1481 EXPECT_FALSE(m.Matches(L"Hi"));
1482 EXPECT_FALSE(m.Matches(NULL));
1483
1484 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1485 EXPECT_TRUE(m2.Matches(L"hello"));
1486 EXPECT_FALSE(m2.Matches(L"Hi"));
1487 }
1488
TEST(StdWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1489 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1490 ::std::wstring str1(L"oabocdooeoo");
1491 ::std::wstring str2(L"OABOCDOOEOO");
1492 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1493 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1494
1495 str1[3] = str2[3] = L'\0';
1496 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1497 EXPECT_TRUE(m1.Matches(str2));
1498
1499 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1500 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1501 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1502 str1[9] = str2[9] = L'\0';
1503 EXPECT_FALSE(m2.Matches(str2));
1504
1505 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1506 EXPECT_TRUE(m3.Matches(str2));
1507
1508 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1509 str2.append(1, L'\0');
1510 EXPECT_FALSE(m3.Matches(str2));
1511 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1512 }
1513
TEST(StdWideStrCaseEqTest,CanDescribeSelf)1514 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1515 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1516 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1517 }
1518
TEST(StdWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1519 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1520 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1521 EXPECT_TRUE(m.Matches(L"Hi"));
1522 EXPECT_TRUE(m.Matches(NULL));
1523 EXPECT_FALSE(m.Matches(L"Hello"));
1524 EXPECT_FALSE(m.Matches(L"hello"));
1525
1526 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1527 EXPECT_TRUE(m2.Matches(L""));
1528 EXPECT_FALSE(m2.Matches(L"Hello"));
1529 }
1530
TEST(StdWideStrCaseNeTest,CanDescribeSelf)1531 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1532 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1533 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1534 }
1535
1536 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest,WorksForStringClasses)1537 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1538 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1539 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1540 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1541
1542 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1543 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1544 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1545 }
1546
1547 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest,WorksForCStrings)1548 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1549 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1550 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1551 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1552 EXPECT_FALSE(m1.Matches(NULL));
1553
1554 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1555 EXPECT_TRUE(m2.Matches(L"I love food."));
1556 EXPECT_FALSE(m2.Matches(L"tofo"));
1557 EXPECT_FALSE(m2.Matches(NULL));
1558 }
1559
1560 // Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest,CanDescribeSelf)1561 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1562 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1563 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1564 }
1565
1566 // Tests StartsWith(s).
1567
TEST(StdWideStartsWithTest,MatchesStringWithGivenPrefix)1568 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1569 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1570 EXPECT_TRUE(m1.Matches(L"Hi"));
1571 EXPECT_TRUE(m1.Matches(L""));
1572 EXPECT_FALSE(m1.Matches(NULL));
1573
1574 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1575 EXPECT_TRUE(m2.Matches(L"Hi"));
1576 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1577 EXPECT_TRUE(m2.Matches(L"High"));
1578 EXPECT_FALSE(m2.Matches(L"H"));
1579 EXPECT_FALSE(m2.Matches(L" Hi"));
1580 }
1581
TEST(StdWideStartsWithTest,CanDescribeSelf)1582 TEST(StdWideStartsWithTest, CanDescribeSelf) {
1583 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1584 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1585 }
1586
1587 // Tests EndsWith(s).
1588
TEST(StdWideEndsWithTest,MatchesStringWithGivenSuffix)1589 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1590 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1591 EXPECT_TRUE(m1.Matches(L"Hi"));
1592 EXPECT_TRUE(m1.Matches(L""));
1593 EXPECT_FALSE(m1.Matches(NULL));
1594
1595 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1596 EXPECT_TRUE(m2.Matches(L"Hi"));
1597 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1598 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1599 EXPECT_FALSE(m2.Matches(L"i"));
1600 EXPECT_FALSE(m2.Matches(L"Hi "));
1601 }
1602
TEST(StdWideEndsWithTest,CanDescribeSelf)1603 TEST(StdWideEndsWithTest, CanDescribeSelf) {
1604 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1605 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1606 }
1607
1608 #endif // GTEST_HAS_STD_WSTRING
1609
1610 #if GTEST_HAS_GLOBAL_WSTRING
TEST(GlobalWideStrEqTest,MatchesEqual)1611 TEST(GlobalWideStrEqTest, MatchesEqual) {
1612 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1613 EXPECT_TRUE(m.Matches(L"Hello"));
1614 EXPECT_FALSE(m.Matches(L"hello"));
1615 EXPECT_FALSE(m.Matches(NULL));
1616
1617 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1618 EXPECT_TRUE(m2.Matches(L"Hello"));
1619 EXPECT_FALSE(m2.Matches(L"Hi"));
1620
1621 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1622 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1623 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1624
1625 ::wstring str(L"01204500800");
1626 str[3] = L'\0';
1627 Matcher<const ::wstring&> m4 = StrEq(str);
1628 EXPECT_TRUE(m4.Matches(str));
1629 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1630 Matcher<const ::wstring&> m5 = StrEq(str);
1631 EXPECT_TRUE(m5.Matches(str));
1632 }
1633
TEST(GlobalWideStrEqTest,CanDescribeSelf)1634 TEST(GlobalWideStrEqTest, CanDescribeSelf) {
1635 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1636 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1637 Describe(m));
1638
1639 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1640 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1641 Describe(m2));
1642
1643 ::wstring str(L"01204500800");
1644 str[3] = L'\0';
1645 Matcher<const ::wstring&> m4 = StrEq(str);
1646 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1647 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1648 Matcher<const ::wstring&> m5 = StrEq(str);
1649 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1650 }
1651
TEST(GlobalWideStrNeTest,MatchesUnequalString)1652 TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1653 Matcher<const wchar_t*> m = StrNe(L"Hello");
1654 EXPECT_TRUE(m.Matches(L""));
1655 EXPECT_TRUE(m.Matches(NULL));
1656 EXPECT_FALSE(m.Matches(L"Hello"));
1657
1658 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1659 EXPECT_TRUE(m2.Matches(L"hello"));
1660 EXPECT_FALSE(m2.Matches(L"Hello"));
1661 }
1662
TEST(GlobalWideStrNeTest,CanDescribeSelf)1663 TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1664 Matcher<const wchar_t*> m = StrNe(L"Hi");
1665 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1666 }
1667
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1668 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1669 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1670 EXPECT_TRUE(m.Matches(L"Hello"));
1671 EXPECT_TRUE(m.Matches(L"hello"));
1672 EXPECT_FALSE(m.Matches(L"Hi"));
1673 EXPECT_FALSE(m.Matches(NULL));
1674
1675 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1676 EXPECT_TRUE(m2.Matches(L"hello"));
1677 EXPECT_FALSE(m2.Matches(L"Hi"));
1678 }
1679
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1680 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1681 ::wstring str1(L"oabocdooeoo");
1682 ::wstring str2(L"OABOCDOOEOO");
1683 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1684 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1685
1686 str1[3] = str2[3] = L'\0';
1687 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1688 EXPECT_TRUE(m1.Matches(str2));
1689
1690 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1691 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1692 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1693 str1[9] = str2[9] = L'\0';
1694 EXPECT_FALSE(m2.Matches(str2));
1695
1696 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1697 EXPECT_TRUE(m3.Matches(str2));
1698
1699 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1700 str2.append(1, L'\0');
1701 EXPECT_FALSE(m3.Matches(str2));
1702 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1703 }
1704
TEST(GlobalWideStrCaseEqTest,CanDescribeSelf)1705 TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1706 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1707 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1708 }
1709
TEST(GlobalWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1710 TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1711 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1712 EXPECT_TRUE(m.Matches(L"Hi"));
1713 EXPECT_TRUE(m.Matches(NULL));
1714 EXPECT_FALSE(m.Matches(L"Hello"));
1715 EXPECT_FALSE(m.Matches(L"hello"));
1716
1717 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1718 EXPECT_TRUE(m2.Matches(L""));
1719 EXPECT_FALSE(m2.Matches(L"Hello"));
1720 }
1721
TEST(GlobalWideStrCaseNeTest,CanDescribeSelf)1722 TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1723 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1724 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1725 }
1726
1727 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(GlobalWideHasSubstrTest,WorksForStringClasses)1728 TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1729 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1730 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1731 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1732
1733 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1734 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1735 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1736 }
1737
1738 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(GlobalWideHasSubstrTest,WorksForCStrings)1739 TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1740 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1741 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1742 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1743 EXPECT_FALSE(m1.Matches(NULL));
1744
1745 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1746 EXPECT_TRUE(m2.Matches(L"I love food."));
1747 EXPECT_FALSE(m2.Matches(L"tofo"));
1748 EXPECT_FALSE(m2.Matches(NULL));
1749 }
1750
1751 // Tests that HasSubstr(s) describes itself properly.
TEST(GlobalWideHasSubstrTest,CanDescribeSelf)1752 TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1753 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1754 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1755 }
1756
1757 // Tests StartsWith(s).
1758
TEST(GlobalWideStartsWithTest,MatchesStringWithGivenPrefix)1759 TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1760 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1761 EXPECT_TRUE(m1.Matches(L"Hi"));
1762 EXPECT_TRUE(m1.Matches(L""));
1763 EXPECT_FALSE(m1.Matches(NULL));
1764
1765 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1766 EXPECT_TRUE(m2.Matches(L"Hi"));
1767 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1768 EXPECT_TRUE(m2.Matches(L"High"));
1769 EXPECT_FALSE(m2.Matches(L"H"));
1770 EXPECT_FALSE(m2.Matches(L" Hi"));
1771 }
1772
TEST(GlobalWideStartsWithTest,CanDescribeSelf)1773 TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1774 Matcher<const ::wstring> m = StartsWith(L"Hi");
1775 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1776 }
1777
1778 // Tests EndsWith(s).
1779
TEST(GlobalWideEndsWithTest,MatchesStringWithGivenSuffix)1780 TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1781 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1782 EXPECT_TRUE(m1.Matches(L"Hi"));
1783 EXPECT_TRUE(m1.Matches(L""));
1784 EXPECT_FALSE(m1.Matches(NULL));
1785
1786 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1787 EXPECT_TRUE(m2.Matches(L"Hi"));
1788 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1789 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1790 EXPECT_FALSE(m2.Matches(L"i"));
1791 EXPECT_FALSE(m2.Matches(L"Hi "));
1792 }
1793
TEST(GlobalWideEndsWithTest,CanDescribeSelf)1794 TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1795 Matcher<const ::wstring> m = EndsWith(L"Hi");
1796 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1797 }
1798
1799 #endif // GTEST_HAS_GLOBAL_WSTRING
1800
1801
1802 typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1803
1804 // Tests that Eq() matches a 2-tuple where the first field == the
1805 // second field.
TEST(Eq2Test,MatchesEqualArguments)1806 TEST(Eq2Test, MatchesEqualArguments) {
1807 Matcher<const Tuple2&> m = Eq();
1808 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1809 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1810 }
1811
1812 // Tests that Eq() describes itself properly.
TEST(Eq2Test,CanDescribeSelf)1813 TEST(Eq2Test, CanDescribeSelf) {
1814 Matcher<const Tuple2&> m = Eq();
1815 EXPECT_EQ("are an equal pair", Describe(m));
1816 }
1817
1818 // Tests that Ge() matches a 2-tuple where the first field >= the
1819 // second field.
TEST(Ge2Test,MatchesGreaterThanOrEqualArguments)1820 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1821 Matcher<const Tuple2&> m = Ge();
1822 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1823 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1824 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1825 }
1826
1827 // Tests that Ge() describes itself properly.
TEST(Ge2Test,CanDescribeSelf)1828 TEST(Ge2Test, CanDescribeSelf) {
1829 Matcher<const Tuple2&> m = Ge();
1830 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1831 }
1832
1833 // Tests that Gt() matches a 2-tuple where the first field > the
1834 // second field.
TEST(Gt2Test,MatchesGreaterThanArguments)1835 TEST(Gt2Test, MatchesGreaterThanArguments) {
1836 Matcher<const Tuple2&> m = Gt();
1837 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1838 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1839 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1840 }
1841
1842 // Tests that Gt() describes itself properly.
TEST(Gt2Test,CanDescribeSelf)1843 TEST(Gt2Test, CanDescribeSelf) {
1844 Matcher<const Tuple2&> m = Gt();
1845 EXPECT_EQ("are a pair where the first > the second", Describe(m));
1846 }
1847
1848 // Tests that Le() matches a 2-tuple where the first field <= the
1849 // second field.
TEST(Le2Test,MatchesLessThanOrEqualArguments)1850 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1851 Matcher<const Tuple2&> m = Le();
1852 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1853 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1854 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1855 }
1856
1857 // Tests that Le() describes itself properly.
TEST(Le2Test,CanDescribeSelf)1858 TEST(Le2Test, CanDescribeSelf) {
1859 Matcher<const Tuple2&> m = Le();
1860 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
1861 }
1862
1863 // Tests that Lt() matches a 2-tuple where the first field < the
1864 // second field.
TEST(Lt2Test,MatchesLessThanArguments)1865 TEST(Lt2Test, MatchesLessThanArguments) {
1866 Matcher<const Tuple2&> m = Lt();
1867 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1868 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1869 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1870 }
1871
1872 // Tests that Lt() describes itself properly.
TEST(Lt2Test,CanDescribeSelf)1873 TEST(Lt2Test, CanDescribeSelf) {
1874 Matcher<const Tuple2&> m = Lt();
1875 EXPECT_EQ("are a pair where the first < the second", Describe(m));
1876 }
1877
1878 // Tests that Ne() matches a 2-tuple where the first field != the
1879 // second field.
TEST(Ne2Test,MatchesUnequalArguments)1880 TEST(Ne2Test, MatchesUnequalArguments) {
1881 Matcher<const Tuple2&> m = Ne();
1882 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1883 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1884 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1885 }
1886
1887 // Tests that Ne() describes itself properly.
TEST(Ne2Test,CanDescribeSelf)1888 TEST(Ne2Test, CanDescribeSelf) {
1889 Matcher<const Tuple2&> m = Ne();
1890 EXPECT_EQ("are an unequal pair", Describe(m));
1891 }
1892
1893 // Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest,NegatesMatcher)1894 TEST(NotTest, NegatesMatcher) {
1895 Matcher<int> m;
1896 m = Not(Eq(2));
1897 EXPECT_TRUE(m.Matches(3));
1898 EXPECT_FALSE(m.Matches(2));
1899 }
1900
1901 // Tests that Not(m) describes itself properly.
TEST(NotTest,CanDescribeSelf)1902 TEST(NotTest, CanDescribeSelf) {
1903 Matcher<int> m = Not(Eq(5));
1904 EXPECT_EQ("isn't equal to 5", Describe(m));
1905 }
1906
1907 // Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest,NotMatcherSafelyCastsMonomorphicMatchers)1908 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
1909 // greater_than_5 is a monomorphic matcher.
1910 Matcher<int> greater_than_5 = Gt(5);
1911
1912 Matcher<const int&> m = Not(greater_than_5);
1913 Matcher<int&> m2 = Not(greater_than_5);
1914 Matcher<int&> m3 = Not(m);
1915 }
1916
1917 // Helper to allow easy testing of AllOf matchers with num parameters.
AllOfMatches(int num,const Matcher<int> & m)1918 void AllOfMatches(int num, const Matcher<int>& m) {
1919 SCOPED_TRACE(Describe(m));
1920 EXPECT_TRUE(m.Matches(0));
1921 for (int i = 1; i <= num; ++i) {
1922 EXPECT_FALSE(m.Matches(i));
1923 }
1924 EXPECT_TRUE(m.Matches(num + 1));
1925 }
1926
1927 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
1928 // the given matchers.
TEST(AllOfTest,MatchesWhenAllMatch)1929 TEST(AllOfTest, MatchesWhenAllMatch) {
1930 Matcher<int> m;
1931 m = AllOf(Le(2), Ge(1));
1932 EXPECT_TRUE(m.Matches(1));
1933 EXPECT_TRUE(m.Matches(2));
1934 EXPECT_FALSE(m.Matches(0));
1935 EXPECT_FALSE(m.Matches(3));
1936
1937 m = AllOf(Gt(0), Ne(1), Ne(2));
1938 EXPECT_TRUE(m.Matches(3));
1939 EXPECT_FALSE(m.Matches(2));
1940 EXPECT_FALSE(m.Matches(1));
1941 EXPECT_FALSE(m.Matches(0));
1942
1943 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1944 EXPECT_TRUE(m.Matches(4));
1945 EXPECT_FALSE(m.Matches(3));
1946 EXPECT_FALSE(m.Matches(2));
1947 EXPECT_FALSE(m.Matches(1));
1948 EXPECT_FALSE(m.Matches(0));
1949
1950 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1951 EXPECT_TRUE(m.Matches(0));
1952 EXPECT_TRUE(m.Matches(1));
1953 EXPECT_FALSE(m.Matches(3));
1954
1955 // The following tests for varying number of sub-matchers. Due to the way
1956 // the sub-matchers are handled it is enough to test every sub-matcher once
1957 // with sub-matchers using the same matcher type. Varying matcher types are
1958 // checked for above.
1959 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
1960 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
1961 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
1962 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
1963 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
1964 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
1965 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
1966 Ne(8)));
1967 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
1968 Ne(8), Ne(9)));
1969 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
1970 Ne(9), Ne(10)));
1971 }
1972
1973 // Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest,CanDescribeSelf)1974 TEST(AllOfTest, CanDescribeSelf) {
1975 Matcher<int> m;
1976 m = AllOf(Le(2), Ge(1));
1977 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
1978
1979 m = AllOf(Gt(0), Ne(1), Ne(2));
1980 EXPECT_EQ("(is > 0) and "
1981 "((isn't equal to 1) and "
1982 "(isn't equal to 2))",
1983 Describe(m));
1984
1985
1986 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1987 EXPECT_EQ("((is > 0) and "
1988 "(isn't equal to 1)) and "
1989 "((isn't equal to 2) and "
1990 "(isn't equal to 3))",
1991 Describe(m));
1992
1993
1994 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1995 EXPECT_EQ("((is >= 0) and "
1996 "(is < 10)) and "
1997 "((isn't equal to 3) and "
1998 "((isn't equal to 5) and "
1999 "(isn't equal to 7)))",
2000 Describe(m));
2001 }
2002
2003 // Tests that AllOf(m1, ..., mn) describes its negation properly.
TEST(AllOfTest,CanDescribeNegation)2004 TEST(AllOfTest, CanDescribeNegation) {
2005 Matcher<int> m;
2006 m = AllOf(Le(2), Ge(1));
2007 EXPECT_EQ("(isn't <= 2) or "
2008 "(isn't >= 1)",
2009 DescribeNegation(m));
2010
2011 m = AllOf(Gt(0), Ne(1), Ne(2));
2012 EXPECT_EQ("(isn't > 0) or "
2013 "((is equal to 1) or "
2014 "(is equal to 2))",
2015 DescribeNegation(m));
2016
2017
2018 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2019 EXPECT_EQ("((isn't > 0) or "
2020 "(is equal to 1)) or "
2021 "((is equal to 2) or "
2022 "(is equal to 3))",
2023 DescribeNegation(m));
2024
2025
2026 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2027 EXPECT_EQ("((isn't >= 0) or "
2028 "(isn't < 10)) or "
2029 "((is equal to 3) or "
2030 "((is equal to 5) or "
2031 "(is equal to 7)))",
2032 DescribeNegation(m));
2033 }
2034
2035 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest,AllOfMatcherSafelyCastsMonomorphicMatchers)2036 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2037 // greater_than_5 and less_than_10 are monomorphic matchers.
2038 Matcher<int> greater_than_5 = Gt(5);
2039 Matcher<int> less_than_10 = Lt(10);
2040
2041 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2042 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2043 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2044
2045 // Tests that BothOf works when composing itself.
2046 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2047 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2048 }
2049
TEST(AllOfTest,ExplainsResult)2050 TEST(AllOfTest, ExplainsResult) {
2051 Matcher<int> m;
2052
2053 // Successful match. Both matchers need to explain. The second
2054 // matcher doesn't give an explanation, so only the first matcher's
2055 // explanation is printed.
2056 m = AllOf(GreaterThan(10), Lt(30));
2057 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2058
2059 // Successful match. Both matchers need to explain.
2060 m = AllOf(GreaterThan(10), GreaterThan(20));
2061 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2062 Explain(m, 30));
2063
2064 // Successful match. All matchers need to explain. The second
2065 // matcher doesn't given an explanation.
2066 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2067 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2068 Explain(m, 25));
2069
2070 // Successful match. All matchers need to explain.
2071 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2072 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2073 "and which is 10 more than 30",
2074 Explain(m, 40));
2075
2076 // Failed match. The first matcher, which failed, needs to
2077 // explain.
2078 m = AllOf(GreaterThan(10), GreaterThan(20));
2079 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2080
2081 // Failed match. The second matcher, which failed, needs to
2082 // explain. Since it doesn't given an explanation, nothing is
2083 // printed.
2084 m = AllOf(GreaterThan(10), Lt(30));
2085 EXPECT_EQ("", Explain(m, 40));
2086
2087 // Failed match. The second matcher, which failed, needs to
2088 // explain.
2089 m = AllOf(GreaterThan(10), GreaterThan(20));
2090 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2091 }
2092
2093 // Helper to allow easy testing of AnyOf matchers with num parameters.
AnyOfMatches(int num,const Matcher<int> & m)2094 void AnyOfMatches(int num, const Matcher<int>& m) {
2095 SCOPED_TRACE(Describe(m));
2096 EXPECT_FALSE(m.Matches(0));
2097 for (int i = 1; i <= num; ++i) {
2098 EXPECT_TRUE(m.Matches(i));
2099 }
2100 EXPECT_FALSE(m.Matches(num + 1));
2101 }
2102
2103 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2104 // least one of the given matchers.
TEST(AnyOfTest,MatchesWhenAnyMatches)2105 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2106 Matcher<int> m;
2107 m = AnyOf(Le(1), Ge(3));
2108 EXPECT_TRUE(m.Matches(1));
2109 EXPECT_TRUE(m.Matches(4));
2110 EXPECT_FALSE(m.Matches(2));
2111
2112 m = AnyOf(Lt(0), Eq(1), Eq(2));
2113 EXPECT_TRUE(m.Matches(-1));
2114 EXPECT_TRUE(m.Matches(1));
2115 EXPECT_TRUE(m.Matches(2));
2116 EXPECT_FALSE(m.Matches(0));
2117
2118 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2119 EXPECT_TRUE(m.Matches(-1));
2120 EXPECT_TRUE(m.Matches(1));
2121 EXPECT_TRUE(m.Matches(2));
2122 EXPECT_TRUE(m.Matches(3));
2123 EXPECT_FALSE(m.Matches(0));
2124
2125 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2126 EXPECT_TRUE(m.Matches(0));
2127 EXPECT_TRUE(m.Matches(11));
2128 EXPECT_TRUE(m.Matches(3));
2129 EXPECT_FALSE(m.Matches(2));
2130
2131 // The following tests for varying number of sub-matchers. Due to the way
2132 // the sub-matchers are handled it is enough to test every sub-matcher once
2133 // with sub-matchers using the same matcher type. Varying matcher types are
2134 // checked for above.
2135 AnyOfMatches(2, AnyOf(1, 2));
2136 AnyOfMatches(3, AnyOf(1, 2, 3));
2137 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2138 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2139 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2140 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2141 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2142 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2143 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2144 }
2145
2146 // Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest,CanDescribeSelf)2147 TEST(AnyOfTest, CanDescribeSelf) {
2148 Matcher<int> m;
2149 m = AnyOf(Le(1), Ge(3));
2150 EXPECT_EQ("(is <= 1) or (is >= 3)",
2151 Describe(m));
2152
2153 m = AnyOf(Lt(0), Eq(1), Eq(2));
2154 EXPECT_EQ("(is < 0) or "
2155 "((is equal to 1) or (is equal to 2))",
2156 Describe(m));
2157
2158 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2159 EXPECT_EQ("((is < 0) or "
2160 "(is equal to 1)) or "
2161 "((is equal to 2) or "
2162 "(is equal to 3))",
2163 Describe(m));
2164
2165 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2166 EXPECT_EQ("((is <= 0) or "
2167 "(is > 10)) or "
2168 "((is equal to 3) or "
2169 "((is equal to 5) or "
2170 "(is equal to 7)))",
2171 Describe(m));
2172 }
2173
2174 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
TEST(AnyOfTest,CanDescribeNegation)2175 TEST(AnyOfTest, CanDescribeNegation) {
2176 Matcher<int> m;
2177 m = AnyOf(Le(1), Ge(3));
2178 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2179 DescribeNegation(m));
2180
2181 m = AnyOf(Lt(0), Eq(1), Eq(2));
2182 EXPECT_EQ("(isn't < 0) and "
2183 "((isn't equal to 1) and (isn't equal to 2))",
2184 DescribeNegation(m));
2185
2186 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2187 EXPECT_EQ("((isn't < 0) and "
2188 "(isn't equal to 1)) and "
2189 "((isn't equal to 2) and "
2190 "(isn't equal to 3))",
2191 DescribeNegation(m));
2192
2193 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2194 EXPECT_EQ("((isn't <= 0) and "
2195 "(isn't > 10)) and "
2196 "((isn't equal to 3) and "
2197 "((isn't equal to 5) and "
2198 "(isn't equal to 7)))",
2199 DescribeNegation(m));
2200 }
2201
2202 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest,AnyOfMatcherSafelyCastsMonomorphicMatchers)2203 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2204 // greater_than_5 and less_than_10 are monomorphic matchers.
2205 Matcher<int> greater_than_5 = Gt(5);
2206 Matcher<int> less_than_10 = Lt(10);
2207
2208 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2209 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2210 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2211
2212 // Tests that EitherOf works when composing itself.
2213 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2214 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2215 }
2216
TEST(AnyOfTest,ExplainsResult)2217 TEST(AnyOfTest, ExplainsResult) {
2218 Matcher<int> m;
2219
2220 // Failed match. Both matchers need to explain. The second
2221 // matcher doesn't give an explanation, so only the first matcher's
2222 // explanation is printed.
2223 m = AnyOf(GreaterThan(10), Lt(0));
2224 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2225
2226 // Failed match. Both matchers need to explain.
2227 m = AnyOf(GreaterThan(10), GreaterThan(20));
2228 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2229 Explain(m, 5));
2230
2231 // Failed match. All matchers need to explain. The second
2232 // matcher doesn't given an explanation.
2233 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2234 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2235 Explain(m, 5));
2236
2237 // Failed match. All matchers need to explain.
2238 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2239 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2240 "and which is 25 less than 30",
2241 Explain(m, 5));
2242
2243 // Successful match. The first matcher, which succeeded, needs to
2244 // explain.
2245 m = AnyOf(GreaterThan(10), GreaterThan(20));
2246 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2247
2248 // Successful match. The second matcher, which succeeded, needs to
2249 // explain. Since it doesn't given an explanation, nothing is
2250 // printed.
2251 m = AnyOf(GreaterThan(10), Lt(30));
2252 EXPECT_EQ("", Explain(m, 0));
2253
2254 // Successful match. The second matcher, which succeeded, needs to
2255 // explain.
2256 m = AnyOf(GreaterThan(30), GreaterThan(20));
2257 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2258 }
2259
2260 // The following predicate function and predicate functor are for
2261 // testing the Truly(predicate) matcher.
2262
2263 // Returns non-zero if the input is positive. Note that the return
2264 // type of this function is not bool. It's OK as Truly() accepts any
2265 // unary function or functor whose return type can be implicitly
2266 // converted to bool.
IsPositive(double x)2267 int IsPositive(double x) {
2268 return x > 0 ? 1 : 0;
2269 }
2270
2271 // This functor returns true if the input is greater than the given
2272 // number.
2273 class IsGreaterThan {
2274 public:
IsGreaterThan(int threshold)2275 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2276
operator ()(int n) const2277 bool operator()(int n) const { return n > threshold_; }
2278
2279 private:
2280 int threshold_;
2281 };
2282
2283 // For testing Truly().
2284 const int foo = 0;
2285
2286 // This predicate returns true iff the argument references foo and has
2287 // a zero value.
ReferencesFooAndIsZero(const int & n)2288 bool ReferencesFooAndIsZero(const int& n) {
2289 return (&n == &foo) && (n == 0);
2290 }
2291
2292 // Tests that Truly(predicate) matches what satisfies the given
2293 // predicate.
TEST(TrulyTest,MatchesWhatSatisfiesThePredicate)2294 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2295 Matcher<double> m = Truly(IsPositive);
2296 EXPECT_TRUE(m.Matches(2.0));
2297 EXPECT_FALSE(m.Matches(-1.5));
2298 }
2299
2300 // Tests that Truly(predicate_functor) works too.
TEST(TrulyTest,CanBeUsedWithFunctor)2301 TEST(TrulyTest, CanBeUsedWithFunctor) {
2302 Matcher<int> m = Truly(IsGreaterThan(5));
2303 EXPECT_TRUE(m.Matches(6));
2304 EXPECT_FALSE(m.Matches(4));
2305 }
2306
2307 // A class that can be implicitly converted to bool.
2308 class ConvertibleToBool {
2309 public:
ConvertibleToBool(int number)2310 explicit ConvertibleToBool(int number) : number_(number) {}
operator bool() const2311 operator bool() const { return number_ != 0; }
2312
2313 private:
2314 int number_;
2315 };
2316
IsNotZero(int number)2317 ConvertibleToBool IsNotZero(int number) {
2318 return ConvertibleToBool(number);
2319 }
2320
2321 // Tests that the predicate used in Truly() may return a class that's
2322 // implicitly convertible to bool, even when the class has no
2323 // operator!().
TEST(TrulyTest,PredicateCanReturnAClassConvertibleToBool)2324 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2325 Matcher<int> m = Truly(IsNotZero);
2326 EXPECT_TRUE(m.Matches(1));
2327 EXPECT_FALSE(m.Matches(0));
2328 }
2329
2330 // Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest,CanDescribeSelf)2331 TEST(TrulyTest, CanDescribeSelf) {
2332 Matcher<double> m = Truly(IsPositive);
2333 EXPECT_EQ("satisfies the given predicate",
2334 Describe(m));
2335 }
2336
2337 // Tests that Truly(predicate) works when the matcher takes its
2338 // argument by reference.
TEST(TrulyTest,WorksForByRefArguments)2339 TEST(TrulyTest, WorksForByRefArguments) {
2340 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2341 EXPECT_TRUE(m.Matches(foo));
2342 int n = 0;
2343 EXPECT_FALSE(m.Matches(n));
2344 }
2345
2346 // Tests that Matches(m) is a predicate satisfied by whatever that
2347 // matches matcher m.
TEST(MatchesTest,IsSatisfiedByWhatMatchesTheMatcher)2348 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2349 EXPECT_TRUE(Matches(Ge(0))(1));
2350 EXPECT_FALSE(Matches(Eq('a'))('b'));
2351 }
2352
2353 // Tests that Matches(m) works when the matcher takes its argument by
2354 // reference.
TEST(MatchesTest,WorksOnByRefArguments)2355 TEST(MatchesTest, WorksOnByRefArguments) {
2356 int m = 0, n = 0;
2357 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2358 EXPECT_FALSE(Matches(Ref(m))(n));
2359 }
2360
2361 // Tests that a Matcher on non-reference type can be used in
2362 // Matches().
TEST(MatchesTest,WorksWithMatcherOnNonRefType)2363 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2364 Matcher<int> eq5 = Eq(5);
2365 EXPECT_TRUE(Matches(eq5)(5));
2366 EXPECT_FALSE(Matches(eq5)(2));
2367 }
2368
2369 // Tests Value(value, matcher). Since Value() is a simple wrapper for
2370 // Matches(), which has been tested already, we don't spend a lot of
2371 // effort on testing Value().
TEST(ValueTest,WorksWithPolymorphicMatcher)2372 TEST(ValueTest, WorksWithPolymorphicMatcher) {
2373 EXPECT_TRUE(Value("hi", StartsWith("h")));
2374 EXPECT_FALSE(Value(5, Gt(10)));
2375 }
2376
TEST(ValueTest,WorksWithMonomorphicMatcher)2377 TEST(ValueTest, WorksWithMonomorphicMatcher) {
2378 const Matcher<int> is_zero = Eq(0);
2379 EXPECT_TRUE(Value(0, is_zero));
2380 EXPECT_FALSE(Value('a', is_zero));
2381
2382 int n = 0;
2383 const Matcher<const int&> ref_n = Ref(n);
2384 EXPECT_TRUE(Value(n, ref_n));
2385 EXPECT_FALSE(Value(1, ref_n));
2386 }
2387
TEST(ExplainMatchResultTest,WorksWithPolymorphicMatcher)2388 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2389 StringMatchResultListener listener1;
2390 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2391 EXPECT_EQ("% 2 == 0", listener1.str());
2392
2393 StringMatchResultListener listener2;
2394 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2395 EXPECT_EQ("", listener2.str());
2396 }
2397
TEST(ExplainMatchResultTest,WorksWithMonomorphicMatcher)2398 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2399 const Matcher<int> is_even = PolymorphicIsEven();
2400 StringMatchResultListener listener1;
2401 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2402 EXPECT_EQ("% 2 == 0", listener1.str());
2403
2404 const Matcher<const double&> is_zero = Eq(0);
2405 StringMatchResultListener listener2;
2406 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2407 EXPECT_EQ("", listener2.str());
2408 }
2409
2410 MATCHER_P(Really, inner_matcher, "") {
2411 return ExplainMatchResult(inner_matcher, arg, result_listener);
2412 }
2413
TEST(ExplainMatchResultTest,WorksInsideMATCHER)2414 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2415 EXPECT_THAT(0, Really(Eq(0)));
2416 }
2417
TEST(AllArgsTest,WorksForTuple)2418 TEST(AllArgsTest, WorksForTuple) {
2419 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2420 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2421 }
2422
TEST(AllArgsTest,WorksForNonTuple)2423 TEST(AllArgsTest, WorksForNonTuple) {
2424 EXPECT_THAT(42, AllArgs(Gt(0)));
2425 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2426 }
2427
2428 class AllArgsHelper {
2429 public:
AllArgsHelper()2430 AllArgsHelper() {}
2431
2432 MOCK_METHOD2(Helper, int(char x, int y));
2433
2434 private:
2435 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2436 };
2437
TEST(AllArgsTest,WorksInWithClause)2438 TEST(AllArgsTest, WorksInWithClause) {
2439 AllArgsHelper helper;
2440 ON_CALL(helper, Helper(_, _))
2441 .With(AllArgs(Lt()))
2442 .WillByDefault(Return(1));
2443 EXPECT_CALL(helper, Helper(_, _));
2444 EXPECT_CALL(helper, Helper(_, _))
2445 .With(AllArgs(Gt()))
2446 .WillOnce(Return(2));
2447
2448 EXPECT_EQ(1, helper.Helper('\1', 2));
2449 EXPECT_EQ(2, helper.Helper('a', 1));
2450 }
2451
2452 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2453 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)2454 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2455 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2456 ASSERT_THAT("Foo", EndsWith("oo"));
2457 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2458 EXPECT_THAT("Hello", StartsWith("Hell"));
2459 }
2460
2461 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2462 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)2463 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2464 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2465 // which cannot reference auto variables.
2466 static unsigned short n; // NOLINT
2467 n = 5;
2468
2469 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2470 // functions declared in the namespace scope from within nested classes.
2471 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2472 // namespace-level functions invoked inside them need to be explicitly
2473 // resolved.
2474 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
2475 "Value of: n\n"
2476 "Expected: is > 10\n"
2477 " Actual: 5" + OfType("unsigned short"));
2478 n = 0;
2479 EXPECT_NONFATAL_FAILURE(
2480 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2481 "Value of: n\n"
2482 "Expected: (is <= 7) and (is >= 5)\n"
2483 " Actual: 0" + OfType("unsigned short"));
2484 }
2485
2486 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2487 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)2488 TEST(MatcherAssertionTest, WorksForByRefArguments) {
2489 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2490 // reference auto variables.
2491 static int n;
2492 n = 0;
2493 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
2494 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2495 "Value of: n\n"
2496 "Expected: does not reference the variable @");
2497 // Tests the "Actual" part.
2498 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2499 "Actual: 0" + OfType("int") + ", which is located @");
2500 }
2501
2502 #if !GTEST_OS_SYMBIAN
2503 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2504 // monomorphic.
2505
2506 // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2507 // Symbian compiler: it tries to compile
2508 // template<T, U> class MatcherCastImpl { ...
2509 // virtual bool MatchAndExplain(T x, ...) const {
2510 // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
2511 // with U == string and T == const char*
2512 // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2513 // the compiler silently crashes with no output.
2514 // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2515 // the code compiles but the converted string is bogus.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)2516 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2517 Matcher<const char*> starts_with_he = StartsWith("he");
2518 ASSERT_THAT("hello", starts_with_he);
2519
2520 Matcher<const string&> ends_with_ok = EndsWith("ok");
2521 ASSERT_THAT("book", ends_with_ok);
2522 const string bad = "bad";
2523 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2524 "Value of: bad\n"
2525 "Expected: ends with \"ok\"\n"
2526 " Actual: \"bad\"");
2527 Matcher<int> is_greater_than_5 = Gt(5);
2528 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2529 "Value of: 5\n"
2530 "Expected: is > 5\n"
2531 " Actual: 5" + OfType("int"));
2532 }
2533 #endif // !GTEST_OS_SYMBIAN
2534
2535 // Tests floating-point matchers.
2536 template <typename RawType>
2537 class FloatingPointTest : public testing::Test {
2538 protected:
2539 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2540 typedef typename Floating::Bits Bits;
2541
SetUp()2542 virtual void SetUp() {
2543 const size_t max_ulps = Floating::kMaxUlps;
2544
2545 // The bits that represent 0.0.
2546 const Bits zero_bits = Floating(0).bits();
2547
2548 // Makes some numbers close to 0.0.
2549 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
2550 close_to_negative_zero_ = -Floating::ReinterpretBits(
2551 zero_bits + max_ulps - max_ulps/2);
2552 further_from_negative_zero_ = -Floating::ReinterpretBits(
2553 zero_bits + max_ulps + 1 - max_ulps/2);
2554
2555 // The bits that represent 1.0.
2556 const Bits one_bits = Floating(1).bits();
2557
2558 // Makes some numbers close to 1.0.
2559 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
2560 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
2561
2562 // +infinity.
2563 infinity_ = Floating::Infinity();
2564
2565 // The bits that represent +infinity.
2566 const Bits infinity_bits = Floating(infinity_).bits();
2567
2568 // Makes some numbers close to infinity.
2569 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
2570 further_from_infinity_ = Floating::ReinterpretBits(
2571 infinity_bits - max_ulps - 1);
2572
2573 // Makes some NAN's.
2574 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
2575 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
2576 }
2577
TestSize()2578 void TestSize() {
2579 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2580 }
2581
2582 // A battery of tests for FloatingEqMatcher::Matches.
2583 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType))2584 void TestMatches(
2585 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2586 Matcher<RawType> m1 = matcher_maker(0.0);
2587 EXPECT_TRUE(m1.Matches(-0.0));
2588 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2589 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2590 EXPECT_FALSE(m1.Matches(1.0));
2591
2592 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2593 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2594
2595 Matcher<RawType> m3 = matcher_maker(1.0);
2596 EXPECT_TRUE(m3.Matches(close_to_one_));
2597 EXPECT_FALSE(m3.Matches(further_from_one_));
2598
2599 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2600 EXPECT_FALSE(m3.Matches(0.0));
2601
2602 Matcher<RawType> m4 = matcher_maker(-infinity_);
2603 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2604
2605 Matcher<RawType> m5 = matcher_maker(infinity_);
2606 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2607
2608 // This is interesting as the representations of infinity_ and nan1_
2609 // are only 1 DLP apart.
2610 EXPECT_FALSE(m5.Matches(nan1_));
2611
2612 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2613 // some cases.
2614 Matcher<const RawType&> m6 = matcher_maker(0.0);
2615 EXPECT_TRUE(m6.Matches(-0.0));
2616 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2617 EXPECT_FALSE(m6.Matches(1.0));
2618
2619 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2620 // cases.
2621 Matcher<RawType&> m7 = matcher_maker(0.0);
2622 RawType x = 0.0;
2623 EXPECT_TRUE(m7.Matches(x));
2624 x = 0.01f;
2625 EXPECT_FALSE(m7.Matches(x));
2626 }
2627
2628 // Pre-calculated numbers to be used by the tests.
2629
2630 static RawType close_to_positive_zero_;
2631 static RawType close_to_negative_zero_;
2632 static RawType further_from_negative_zero_;
2633
2634 static RawType close_to_one_;
2635 static RawType further_from_one_;
2636
2637 static RawType infinity_;
2638 static RawType close_to_infinity_;
2639 static RawType further_from_infinity_;
2640
2641 static RawType nan1_;
2642 static RawType nan2_;
2643 };
2644
2645 template <typename RawType>
2646 RawType FloatingPointTest<RawType>::close_to_positive_zero_;
2647
2648 template <typename RawType>
2649 RawType FloatingPointTest<RawType>::close_to_negative_zero_;
2650
2651 template <typename RawType>
2652 RawType FloatingPointTest<RawType>::further_from_negative_zero_;
2653
2654 template <typename RawType>
2655 RawType FloatingPointTest<RawType>::close_to_one_;
2656
2657 template <typename RawType>
2658 RawType FloatingPointTest<RawType>::further_from_one_;
2659
2660 template <typename RawType>
2661 RawType FloatingPointTest<RawType>::infinity_;
2662
2663 template <typename RawType>
2664 RawType FloatingPointTest<RawType>::close_to_infinity_;
2665
2666 template <typename RawType>
2667 RawType FloatingPointTest<RawType>::further_from_infinity_;
2668
2669 template <typename RawType>
2670 RawType FloatingPointTest<RawType>::nan1_;
2671
2672 template <typename RawType>
2673 RawType FloatingPointTest<RawType>::nan2_;
2674
2675 // Instantiate FloatingPointTest for testing floats.
2676 typedef FloatingPointTest<float> FloatTest;
2677
TEST_F(FloatTest,FloatEqApproximatelyMatchesFloats)2678 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2679 TestMatches(&FloatEq);
2680 }
2681
TEST_F(FloatTest,NanSensitiveFloatEqApproximatelyMatchesFloats)2682 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2683 TestMatches(&NanSensitiveFloatEq);
2684 }
2685
TEST_F(FloatTest,FloatEqCannotMatchNaN)2686 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2687 // FloatEq never matches NaN.
2688 Matcher<float> m = FloatEq(nan1_);
2689 EXPECT_FALSE(m.Matches(nan1_));
2690 EXPECT_FALSE(m.Matches(nan2_));
2691 EXPECT_FALSE(m.Matches(1.0));
2692 }
2693
TEST_F(FloatTest,NanSensitiveFloatEqCanMatchNaN)2694 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2695 // NanSensitiveFloatEq will match NaN.
2696 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2697 EXPECT_TRUE(m.Matches(nan1_));
2698 EXPECT_TRUE(m.Matches(nan2_));
2699 EXPECT_FALSE(m.Matches(1.0));
2700 }
2701
TEST_F(FloatTest,FloatEqCanDescribeSelf)2702 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2703 Matcher<float> m1 = FloatEq(2.0f);
2704 EXPECT_EQ("is approximately 2", Describe(m1));
2705 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2706
2707 Matcher<float> m2 = FloatEq(0.5f);
2708 EXPECT_EQ("is approximately 0.5", Describe(m2));
2709 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2710
2711 Matcher<float> m3 = FloatEq(nan1_);
2712 EXPECT_EQ("never matches", Describe(m3));
2713 EXPECT_EQ("is anything", DescribeNegation(m3));
2714 }
2715
TEST_F(FloatTest,NanSensitiveFloatEqCanDescribeSelf)2716 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2717 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2718 EXPECT_EQ("is approximately 2", Describe(m1));
2719 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2720
2721 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2722 EXPECT_EQ("is approximately 0.5", Describe(m2));
2723 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2724
2725 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2726 EXPECT_EQ("is NaN", Describe(m3));
2727 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2728 }
2729
2730 // Instantiate FloatingPointTest for testing doubles.
2731 typedef FloatingPointTest<double> DoubleTest;
2732
TEST_F(DoubleTest,DoubleEqApproximatelyMatchesDoubles)2733 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2734 TestMatches(&DoubleEq);
2735 }
2736
TEST_F(DoubleTest,NanSensitiveDoubleEqApproximatelyMatchesDoubles)2737 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2738 TestMatches(&NanSensitiveDoubleEq);
2739 }
2740
TEST_F(DoubleTest,DoubleEqCannotMatchNaN)2741 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2742 // DoubleEq never matches NaN.
2743 Matcher<double> m = DoubleEq(nan1_);
2744 EXPECT_FALSE(m.Matches(nan1_));
2745 EXPECT_FALSE(m.Matches(nan2_));
2746 EXPECT_FALSE(m.Matches(1.0));
2747 }
2748
TEST_F(DoubleTest,NanSensitiveDoubleEqCanMatchNaN)2749 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
2750 // NanSensitiveDoubleEq will match NaN.
2751 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2752 EXPECT_TRUE(m.Matches(nan1_));
2753 EXPECT_TRUE(m.Matches(nan2_));
2754 EXPECT_FALSE(m.Matches(1.0));
2755 }
2756
TEST_F(DoubleTest,DoubleEqCanDescribeSelf)2757 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
2758 Matcher<double> m1 = DoubleEq(2.0);
2759 EXPECT_EQ("is approximately 2", Describe(m1));
2760 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2761
2762 Matcher<double> m2 = DoubleEq(0.5);
2763 EXPECT_EQ("is approximately 0.5", Describe(m2));
2764 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2765
2766 Matcher<double> m3 = DoubleEq(nan1_);
2767 EXPECT_EQ("never matches", Describe(m3));
2768 EXPECT_EQ("is anything", DescribeNegation(m3));
2769 }
2770
TEST_F(DoubleTest,NanSensitiveDoubleEqCanDescribeSelf)2771 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
2772 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
2773 EXPECT_EQ("is approximately 2", Describe(m1));
2774 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2775
2776 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
2777 EXPECT_EQ("is approximately 0.5", Describe(m2));
2778 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2779
2780 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
2781 EXPECT_EQ("is NaN", Describe(m3));
2782 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2783 }
2784
TEST(PointeeTest,RawPointer)2785 TEST(PointeeTest, RawPointer) {
2786 const Matcher<int*> m = Pointee(Ge(0));
2787
2788 int n = 1;
2789 EXPECT_TRUE(m.Matches(&n));
2790 n = -1;
2791 EXPECT_FALSE(m.Matches(&n));
2792 EXPECT_FALSE(m.Matches(NULL));
2793 }
2794
TEST(PointeeTest,RawPointerToConst)2795 TEST(PointeeTest, RawPointerToConst) {
2796 const Matcher<const double*> m = Pointee(Ge(0));
2797
2798 double x = 1;
2799 EXPECT_TRUE(m.Matches(&x));
2800 x = -1;
2801 EXPECT_FALSE(m.Matches(&x));
2802 EXPECT_FALSE(m.Matches(NULL));
2803 }
2804
TEST(PointeeTest,ReferenceToConstRawPointer)2805 TEST(PointeeTest, ReferenceToConstRawPointer) {
2806 const Matcher<int* const &> m = Pointee(Ge(0));
2807
2808 int n = 1;
2809 EXPECT_TRUE(m.Matches(&n));
2810 n = -1;
2811 EXPECT_FALSE(m.Matches(&n));
2812 EXPECT_FALSE(m.Matches(NULL));
2813 }
2814
TEST(PointeeTest,ReferenceToNonConstRawPointer)2815 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
2816 const Matcher<double* &> m = Pointee(Ge(0));
2817
2818 double x = 1.0;
2819 double* p = &x;
2820 EXPECT_TRUE(m.Matches(p));
2821 x = -1;
2822 EXPECT_FALSE(m.Matches(p));
2823 p = NULL;
2824 EXPECT_FALSE(m.Matches(p));
2825 }
2826
2827 // Minimal const-propagating pointer.
2828 template <typename T>
2829 class ConstPropagatingPtr {
2830 public:
2831 typedef T element_type;
2832
ConstPropagatingPtr()2833 ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)2834 explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)2835 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
2836
get()2837 T* get() { return val_; }
operator *()2838 T& operator*() { return *val_; }
2839 // Most smart pointers return non-const T* and T& from the next methods.
get() const2840 const T* get() const { return val_; }
operator *() const2841 const T& operator*() const { return *val_; }
2842
2843 private:
2844 T* val_;
2845 };
2846
TEST(PointeeTest,WorksWithConstPropagatingPointers)2847 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
2848 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
2849 int three = 3;
2850 const ConstPropagatingPtr<int> co(&three);
2851 ConstPropagatingPtr<int> o(&three);
2852 EXPECT_TRUE(m.Matches(o));
2853 EXPECT_TRUE(m.Matches(co));
2854 *o = 6;
2855 EXPECT_FALSE(m.Matches(o));
2856 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
2857 }
2858
TEST(PointeeTest,NeverMatchesNull)2859 TEST(PointeeTest, NeverMatchesNull) {
2860 const Matcher<const char*> m = Pointee(_);
2861 EXPECT_FALSE(m.Matches(NULL));
2862 }
2863
2864 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)2865 TEST(PointeeTest, MatchesAgainstAValue) {
2866 const Matcher<int*> m = Pointee(5);
2867
2868 int n = 5;
2869 EXPECT_TRUE(m.Matches(&n));
2870 n = -1;
2871 EXPECT_FALSE(m.Matches(&n));
2872 EXPECT_FALSE(m.Matches(NULL));
2873 }
2874
TEST(PointeeTest,CanDescribeSelf)2875 TEST(PointeeTest, CanDescribeSelf) {
2876 const Matcher<int*> m = Pointee(Gt(3));
2877 EXPECT_EQ("points to a value that is > 3", Describe(m));
2878 EXPECT_EQ("does not point to a value that is > 3",
2879 DescribeNegation(m));
2880 }
2881
TEST(PointeeTest,CanExplainMatchResult)2882 TEST(PointeeTest, CanExplainMatchResult) {
2883 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
2884
2885 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
2886
2887 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
2888 long n = 3; // NOLINT
2889 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
2890 Explain(m2, &n));
2891 }
2892
TEST(PointeeTest,AlwaysExplainsPointee)2893 TEST(PointeeTest, AlwaysExplainsPointee) {
2894 const Matcher<int*> m = Pointee(0);
2895 int n = 42;
2896 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
2897 }
2898
2899 // An uncopyable class.
2900 class Uncopyable {
2901 public:
Uncopyable(int a_value)2902 explicit Uncopyable(int a_value) : value_(a_value) {}
2903
value() const2904 int value() const { return value_; }
2905 private:
2906 const int value_;
2907 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
2908 };
2909
2910 // Returns true iff x.value() is positive.
ValueIsPositive(const Uncopyable & x)2911 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
2912
2913 // A user-defined struct for testing Field().
2914 struct AStruct {
AStructtesting::gmock_matchers_test::AStruct2915 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
AStructtesting::gmock_matchers_test::AStruct2916 AStruct(const AStruct& rhs)
2917 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
2918
2919 int x; // A non-const field.
2920 const double y; // A const field.
2921 Uncopyable z; // An uncopyable field.
2922 const char* p; // A pointer field.
2923
2924 private:
2925 GTEST_DISALLOW_ASSIGN_(AStruct);
2926 };
2927
2928 // A derived struct for testing Field().
2929 struct DerivedStruct : public AStruct {
2930 char ch;
2931
2932 private:
2933 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
2934 };
2935
2936 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)2937 TEST(FieldTest, WorksForNonConstField) {
2938 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
2939
2940 AStruct a;
2941 EXPECT_TRUE(m.Matches(a));
2942 a.x = -1;
2943 EXPECT_FALSE(m.Matches(a));
2944 }
2945
2946 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)2947 TEST(FieldTest, WorksForConstField) {
2948 AStruct a;
2949
2950 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
2951 EXPECT_TRUE(m.Matches(a));
2952 m = Field(&AStruct::y, Le(0.0));
2953 EXPECT_FALSE(m.Matches(a));
2954 }
2955
2956 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)2957 TEST(FieldTest, WorksForUncopyableField) {
2958 AStruct a;
2959
2960 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
2961 EXPECT_TRUE(m.Matches(a));
2962 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
2963 EXPECT_FALSE(m.Matches(a));
2964 }
2965
2966 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)2967 TEST(FieldTest, WorksForPointerField) {
2968 // Matching against NULL.
2969 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
2970 AStruct a;
2971 EXPECT_TRUE(m.Matches(a));
2972 a.p = "hi";
2973 EXPECT_FALSE(m.Matches(a));
2974
2975 // Matching a pointer that is not NULL.
2976 m = Field(&AStruct::p, StartsWith("hi"));
2977 a.p = "hill";
2978 EXPECT_TRUE(m.Matches(a));
2979 a.p = "hole";
2980 EXPECT_FALSE(m.Matches(a));
2981 }
2982
2983 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)2984 TEST(FieldTest, WorksForByRefArgument) {
2985 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
2986
2987 AStruct a;
2988 EXPECT_TRUE(m.Matches(a));
2989 a.x = -1;
2990 EXPECT_FALSE(m.Matches(a));
2991 }
2992
2993 // Tests that Field(&Foo::field, ...) works when the argument's type
2994 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)2995 TEST(FieldTest, WorksForArgumentOfSubType) {
2996 // Note that the matcher expects DerivedStruct but we say AStruct
2997 // inside Field().
2998 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
2999
3000 DerivedStruct d;
3001 EXPECT_TRUE(m.Matches(d));
3002 d.x = -1;
3003 EXPECT_FALSE(m.Matches(d));
3004 }
3005
3006 // Tests that Field(&Foo::field, m) works when field's type and m's
3007 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)3008 TEST(FieldTest, WorksForCompatibleMatcherType) {
3009 // The field is an int, but the inner matcher expects a signed char.
3010 Matcher<const AStruct&> m = Field(&AStruct::x,
3011 Matcher<signed char>(Ge(0)));
3012
3013 AStruct a;
3014 EXPECT_TRUE(m.Matches(a));
3015 a.x = -1;
3016 EXPECT_FALSE(m.Matches(a));
3017 }
3018
3019 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)3020 TEST(FieldTest, CanDescribeSelf) {
3021 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3022
3023 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3024 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3025 }
3026
3027 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)3028 TEST(FieldTest, CanExplainMatchResult) {
3029 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3030
3031 AStruct a;
3032 a.x = 1;
3033 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3034
3035 m = Field(&AStruct::x, GreaterThan(0));
3036 EXPECT_EQ(
3037 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3038 Explain(m, a));
3039 }
3040
3041 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)3042 TEST(FieldForPointerTest, WorksForPointerToConst) {
3043 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3044
3045 AStruct a;
3046 EXPECT_TRUE(m.Matches(&a));
3047 a.x = -1;
3048 EXPECT_FALSE(m.Matches(&a));
3049 }
3050
3051 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)3052 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3053 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3054
3055 AStruct a;
3056 EXPECT_TRUE(m.Matches(&a));
3057 a.x = -1;
3058 EXPECT_FALSE(m.Matches(&a));
3059 }
3060
3061 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)3062 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3063 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3064
3065 AStruct a;
3066 EXPECT_TRUE(m.Matches(&a));
3067 a.x = -1;
3068 EXPECT_FALSE(m.Matches(&a));
3069 }
3070
3071 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)3072 TEST(FieldForPointerTest, DoesNotMatchNull) {
3073 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3074 EXPECT_FALSE(m.Matches(NULL));
3075 }
3076
3077 // Tests that Field(&Foo::field, ...) works when the argument's type
3078 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)3079 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3080 // Note that the matcher expects DerivedStruct but we say AStruct
3081 // inside Field().
3082 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3083
3084 DerivedStruct d;
3085 EXPECT_TRUE(m.Matches(&d));
3086 d.x = -1;
3087 EXPECT_FALSE(m.Matches(&d));
3088 }
3089
3090 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)3091 TEST(FieldForPointerTest, CanDescribeSelf) {
3092 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3093
3094 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3095 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3096 }
3097
3098 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)3099 TEST(FieldForPointerTest, CanExplainMatchResult) {
3100 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3101
3102 AStruct a;
3103 a.x = 1;
3104 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
3105 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3106 Explain(m, &a));
3107
3108 m = Field(&AStruct::x, GreaterThan(0));
3109 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3110 ", which is 1 more than 0", Explain(m, &a));
3111 }
3112
3113 // A user-defined class for testing Property().
3114 class AClass {
3115 public:
AClass()3116 AClass() : n_(0) {}
3117
3118 // A getter that returns a non-reference.
n() const3119 int n() const { return n_; }
3120
set_n(int new_n)3121 void set_n(int new_n) { n_ = new_n; }
3122
3123 // A getter that returns a reference to const.
s() const3124 const string& s() const { return s_; }
3125
set_s(const string & new_s)3126 void set_s(const string& new_s) { s_ = new_s; }
3127
3128 // A getter that returns a reference to non-const.
x() const3129 double& x() const { return x_; }
3130 private:
3131 int n_;
3132 string s_;
3133
3134 static double x_;
3135 };
3136
3137 double AClass::x_ = 0.0;
3138
3139 // A derived class for testing Property().
3140 class DerivedClass : public AClass {
3141 private:
3142 int k_;
3143 };
3144
3145 // Tests that Property(&Foo::property, ...) works when property()
3146 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)3147 TEST(PropertyTest, WorksForNonReferenceProperty) {
3148 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3149
3150 AClass a;
3151 a.set_n(1);
3152 EXPECT_TRUE(m.Matches(a));
3153
3154 a.set_n(-1);
3155 EXPECT_FALSE(m.Matches(a));
3156 }
3157
3158 // Tests that Property(&Foo::property, ...) works when property()
3159 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)3160 TEST(PropertyTest, WorksForReferenceToConstProperty) {
3161 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3162
3163 AClass a;
3164 a.set_s("hill");
3165 EXPECT_TRUE(m.Matches(a));
3166
3167 a.set_s("hole");
3168 EXPECT_FALSE(m.Matches(a));
3169 }
3170
3171 // Tests that Property(&Foo::property, ...) works when property()
3172 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)3173 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3174 double x = 0.0;
3175 AClass a;
3176
3177 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3178 EXPECT_FALSE(m.Matches(a));
3179
3180 m = Property(&AClass::x, Not(Ref(x)));
3181 EXPECT_TRUE(m.Matches(a));
3182 }
3183
3184 // Tests that Property(&Foo::property, ...) works when the argument is
3185 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)3186 TEST(PropertyTest, WorksForByValueArgument) {
3187 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3188
3189 AClass a;
3190 a.set_s("hill");
3191 EXPECT_TRUE(m.Matches(a));
3192
3193 a.set_s("hole");
3194 EXPECT_FALSE(m.Matches(a));
3195 }
3196
3197 // Tests that Property(&Foo::property, ...) works when the argument's
3198 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)3199 TEST(PropertyTest, WorksForArgumentOfSubType) {
3200 // The matcher expects a DerivedClass, but inside the Property() we
3201 // say AClass.
3202 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3203
3204 DerivedClass d;
3205 d.set_n(1);
3206 EXPECT_TRUE(m.Matches(d));
3207
3208 d.set_n(-1);
3209 EXPECT_FALSE(m.Matches(d));
3210 }
3211
3212 // Tests that Property(&Foo::property, m) works when property()'s type
3213 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)3214 TEST(PropertyTest, WorksForCompatibleMatcherType) {
3215 // n() returns an int but the inner matcher expects a signed char.
3216 Matcher<const AClass&> m = Property(&AClass::n,
3217 Matcher<signed char>(Ge(0)));
3218
3219 AClass a;
3220 EXPECT_TRUE(m.Matches(a));
3221 a.set_n(-1);
3222 EXPECT_FALSE(m.Matches(a));
3223 }
3224
3225 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)3226 TEST(PropertyTest, CanDescribeSelf) {
3227 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3228
3229 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3230 EXPECT_EQ("is an object whose given property isn't >= 0",
3231 DescribeNegation(m));
3232 }
3233
3234 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)3235 TEST(PropertyTest, CanExplainMatchResult) {
3236 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3237
3238 AClass a;
3239 a.set_n(1);
3240 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
3241
3242 m = Property(&AClass::n, GreaterThan(0));
3243 EXPECT_EQ(
3244 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3245 Explain(m, a));
3246 }
3247
3248 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)3249 TEST(PropertyForPointerTest, WorksForPointerToConst) {
3250 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3251
3252 AClass a;
3253 a.set_n(1);
3254 EXPECT_TRUE(m.Matches(&a));
3255
3256 a.set_n(-1);
3257 EXPECT_FALSE(m.Matches(&a));
3258 }
3259
3260 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)3261 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3262 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3263
3264 AClass a;
3265 a.set_s("hill");
3266 EXPECT_TRUE(m.Matches(&a));
3267
3268 a.set_s("hole");
3269 EXPECT_FALSE(m.Matches(&a));
3270 }
3271
3272 // Tests that Property() works when the argument is a reference to a
3273 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)3274 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3275 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3276
3277 AClass a;
3278 a.set_s("hill");
3279 EXPECT_TRUE(m.Matches(&a));
3280
3281 a.set_s("hole");
3282 EXPECT_FALSE(m.Matches(&a));
3283 }
3284
3285 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)3286 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3287 Matcher<const AClass*> m = Property(&AClass::x, _);
3288 EXPECT_FALSE(m.Matches(NULL));
3289 }
3290
3291 // Tests that Property(&Foo::property, ...) works when the argument's
3292 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)3293 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3294 // The matcher expects a DerivedClass, but inside the Property() we
3295 // say AClass.
3296 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3297
3298 DerivedClass d;
3299 d.set_n(1);
3300 EXPECT_TRUE(m.Matches(&d));
3301
3302 d.set_n(-1);
3303 EXPECT_FALSE(m.Matches(&d));
3304 }
3305
3306 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)3307 TEST(PropertyForPointerTest, CanDescribeSelf) {
3308 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3309
3310 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3311 EXPECT_EQ("is an object whose given property isn't >= 0",
3312 DescribeNegation(m));
3313 }
3314
3315 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)3316 TEST(PropertyForPointerTest, CanExplainMatchResult) {
3317 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3318
3319 AClass a;
3320 a.set_n(1);
3321 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
3322 EXPECT_EQ(
3323 "which points to an object whose given property is 1" + OfType("int"),
3324 Explain(m, &a));
3325
3326 m = Property(&AClass::n, GreaterThan(0));
3327 EXPECT_EQ("which points to an object whose given property is 1" +
3328 OfType("int") + ", which is 1 more than 0",
3329 Explain(m, &a));
3330 }
3331
3332 // Tests ResultOf.
3333
3334 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3335 // function pointer.
IntToStringFunction(int input)3336 string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3337
TEST(ResultOfTest,WorksForFunctionPointers)3338 TEST(ResultOfTest, WorksForFunctionPointers) {
3339 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3340
3341 EXPECT_TRUE(matcher.Matches(1));
3342 EXPECT_FALSE(matcher.Matches(2));
3343 }
3344
3345 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)3346 TEST(ResultOfTest, CanDescribeItself) {
3347 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3348
3349 EXPECT_EQ("is mapped by the given callable to a value that "
3350 "is equal to \"foo\"", Describe(matcher));
3351 EXPECT_EQ("is mapped by the given callable to a value that "
3352 "isn't equal to \"foo\"", DescribeNegation(matcher));
3353 }
3354
3355 // Tests that ResultOf() can explain the match result.
IntFunction(int input)3356 int IntFunction(int input) { return input == 42 ? 80 : 90; }
3357
TEST(ResultOfTest,CanExplainMatchResult)3358 TEST(ResultOfTest, CanExplainMatchResult) {
3359 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
3360 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
3361 Explain(matcher, 36));
3362
3363 matcher = ResultOf(&IntFunction, GreaterThan(85));
3364 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3365 ", which is 5 more than 85", Explain(matcher, 36));
3366 }
3367
3368 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3369 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)3370 TEST(ResultOfTest, WorksForNonReferenceResults) {
3371 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3372
3373 EXPECT_TRUE(matcher.Matches(42));
3374 EXPECT_FALSE(matcher.Matches(36));
3375 }
3376
3377 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3378 // returns a reference to non-const.
DoubleFunction(double & input)3379 double& DoubleFunction(double& input) { return input; } // NOLINT
3380
RefUncopyableFunction(Uncopyable & obj)3381 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
3382 return obj;
3383 }
3384
TEST(ResultOfTest,WorksForReferenceToNonConstResults)3385 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3386 double x = 3.14;
3387 double x2 = x;
3388 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3389
3390 EXPECT_TRUE(matcher.Matches(x));
3391 EXPECT_FALSE(matcher.Matches(x2));
3392
3393 // Test that ResultOf works with uncopyable objects
3394 Uncopyable obj(0);
3395 Uncopyable obj2(0);
3396 Matcher<Uncopyable&> matcher2 =
3397 ResultOf(&RefUncopyableFunction, Ref(obj));
3398
3399 EXPECT_TRUE(matcher2.Matches(obj));
3400 EXPECT_FALSE(matcher2.Matches(obj2));
3401 }
3402
3403 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3404 // returns a reference to const.
StringFunction(const string & input)3405 const string& StringFunction(const string& input) { return input; }
3406
TEST(ResultOfTest,WorksForReferenceToConstResults)3407 TEST(ResultOfTest, WorksForReferenceToConstResults) {
3408 string s = "foo";
3409 string s2 = s;
3410 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3411
3412 EXPECT_TRUE(matcher.Matches(s));
3413 EXPECT_FALSE(matcher.Matches(s2));
3414 }
3415
3416 // Tests that ResultOf(f, m) works when f(x) and m's
3417 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)3418 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3419 // IntFunction() returns int but the inner matcher expects a signed char.
3420 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3421
3422 EXPECT_TRUE(matcher.Matches(36));
3423 EXPECT_FALSE(matcher.Matches(42));
3424 }
3425
3426 // Tests that the program aborts when ResultOf is passed
3427 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)3428 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
3429 EXPECT_DEATH_IF_SUPPORTED(
3430 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
3431 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3432 }
3433
3434 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3435 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)3436 TEST(ResultOfTest, WorksForFunctionReferences) {
3437 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3438 EXPECT_TRUE(matcher.Matches(1));
3439 EXPECT_FALSE(matcher.Matches(2));
3440 }
3441
3442 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3443 // function object.
3444 struct Functor : public ::std::unary_function<int, string> {
operator ()testing::gmock_matchers_test::Functor3445 result_type operator()(argument_type input) const {
3446 return IntToStringFunction(input);
3447 }
3448 };
3449
TEST(ResultOfTest,WorksForFunctors)3450 TEST(ResultOfTest, WorksForFunctors) {
3451 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3452
3453 EXPECT_TRUE(matcher.Matches(1));
3454 EXPECT_FALSE(matcher.Matches(2));
3455 }
3456
3457 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3458 // functor with more then one operator() defined. ResultOf() must work
3459 // for each defined operator().
3460 struct PolymorphicFunctor {
3461 typedef int result_type;
operator ()testing::gmock_matchers_test::PolymorphicFunctor3462 int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::PolymorphicFunctor3463 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3464 };
3465
TEST(ResultOfTest,WorksForPolymorphicFunctors)3466 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3467 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3468
3469 EXPECT_TRUE(matcher_int.Matches(10));
3470 EXPECT_FALSE(matcher_int.Matches(2));
3471
3472 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3473
3474 EXPECT_TRUE(matcher_string.Matches("long string"));
3475 EXPECT_FALSE(matcher_string.Matches("shrt"));
3476 }
3477
ReferencingFunction(const int & n)3478 const int* ReferencingFunction(const int& n) { return &n; }
3479
3480 struct ReferencingFunctor {
3481 typedef const int* result_type;
operator ()testing::gmock_matchers_test::ReferencingFunctor3482 result_type operator()(const int& n) { return &n; }
3483 };
3484
TEST(ResultOfTest,WorksForReferencingCallables)3485 TEST(ResultOfTest, WorksForReferencingCallables) {
3486 const int n = 1;
3487 const int n2 = 1;
3488 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3489 EXPECT_TRUE(matcher2.Matches(n));
3490 EXPECT_FALSE(matcher2.Matches(n2));
3491
3492 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3493 EXPECT_TRUE(matcher3.Matches(n));
3494 EXPECT_FALSE(matcher3.Matches(n2));
3495 }
3496
3497 class DivisibleByImpl {
3498 public:
DivisibleByImpl(int a_divider)3499 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
3500
3501 // For testing using ExplainMatchResultTo() with polymorphic matchers.
3502 template <typename T>
MatchAndExplain(const T & n,MatchResultListener * listener) const3503 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
3504 *listener << "which is " << (n % divider_) << " modulo "
3505 << divider_;
3506 return (n % divider_) == 0;
3507 }
3508
DescribeTo(ostream * os) const3509 void DescribeTo(ostream* os) const {
3510 *os << "is divisible by " << divider_;
3511 }
3512
DescribeNegationTo(ostream * os) const3513 void DescribeNegationTo(ostream* os) const {
3514 *os << "is not divisible by " << divider_;
3515 }
3516
set_divider(int a_divider)3517 void set_divider(int a_divider) { divider_ = a_divider; }
divider() const3518 int divider() const { return divider_; }
3519
3520 private:
3521 int divider_;
3522 };
3523
DivisibleBy(int n)3524 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3525 return MakePolymorphicMatcher(DivisibleByImpl(n));
3526 }
3527
3528 // Tests that when AllOf() fails, only the first failing matcher is
3529 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_False)3530 TEST(ExplainMatchResultTest, AllOf_False_False) {
3531 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
3532 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
3533 }
3534
3535 // Tests that when AllOf() fails, only the first failing matcher is
3536 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_True)3537 TEST(ExplainMatchResultTest, AllOf_False_True) {
3538 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
3539 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
3540 }
3541
3542 // Tests that when AllOf() fails, only the first failing matcher is
3543 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_True_False)3544 TEST(ExplainMatchResultTest, AllOf_True_False) {
3545 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
3546 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
3547 }
3548
3549 // Tests that when AllOf() succeeds, all matchers are asked to explain
3550 // why.
TEST(ExplainMatchResultTest,AllOf_True_True)3551 TEST(ExplainMatchResultTest, AllOf_True_True) {
3552 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
3553 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
3554 }
3555
TEST(ExplainMatchResultTest,AllOf_True_True_2)3556 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3557 const Matcher<int> m = AllOf(Ge(2), Le(3));
3558 EXPECT_EQ("", Explain(m, 2));
3559 }
3560
TEST(ExplainmatcherResultTest,MonomorphicMatcher)3561 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3562 const Matcher<int> m = GreaterThan(5);
3563 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
3564 }
3565
3566 // The following two tests verify that values without a public copy
3567 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3568 // with the help of ByRef().
3569
3570 class NotCopyable {
3571 public:
NotCopyable(int a_value)3572 explicit NotCopyable(int a_value) : value_(a_value) {}
3573
value() const3574 int value() const { return value_; }
3575
operator ==(const NotCopyable & rhs) const3576 bool operator==(const NotCopyable& rhs) const {
3577 return value() == rhs.value();
3578 }
3579
operator >=(const NotCopyable & rhs) const3580 bool operator>=(const NotCopyable& rhs) const {
3581 return value() >= rhs.value();
3582 }
3583 private:
3584 int value_;
3585
3586 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3587 };
3588
TEST(ByRefTest,AllowsNotCopyableConstValueInMatchers)3589 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3590 const NotCopyable const_value1(1);
3591 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3592
3593 const NotCopyable n1(1), n2(2);
3594 EXPECT_TRUE(m.Matches(n1));
3595 EXPECT_FALSE(m.Matches(n2));
3596 }
3597
TEST(ByRefTest,AllowsNotCopyableValueInMatchers)3598 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3599 NotCopyable value2(2);
3600 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3601
3602 NotCopyable n1(1), n2(2);
3603 EXPECT_FALSE(m.Matches(n1));
3604 EXPECT_TRUE(m.Matches(n2));
3605 }
3606
3607 #if GTEST_HAS_TYPED_TEST
3608 // Tests ContainerEq with different container types, and
3609 // different element types.
3610
3611 template <typename T>
3612 class ContainerEqTest : public testing::Test {};
3613
3614 typedef testing::Types<
3615 set<int>,
3616 vector<size_t>,
3617 multiset<size_t>,
3618 list<int> >
3619 ContainerEqTestTypes;
3620
3621 TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
3622
3623 // Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest,EqualsSelf)3624 TYPED_TEST(ContainerEqTest, EqualsSelf) {
3625 static const int vals[] = {1, 1, 2, 3, 5, 8};
3626 TypeParam my_set(vals, vals + 6);
3627 const Matcher<TypeParam> m = ContainerEq(my_set);
3628 EXPECT_TRUE(m.Matches(my_set));
3629 EXPECT_EQ("", Explain(m, my_set));
3630 }
3631
3632 // Tests that missing values are reported.
TYPED_TEST(ContainerEqTest,ValueMissing)3633 TYPED_TEST(ContainerEqTest, ValueMissing) {
3634 static const int vals[] = {1, 1, 2, 3, 5, 8};
3635 static const int test_vals[] = {2, 1, 8, 5};
3636 TypeParam my_set(vals, vals + 6);
3637 TypeParam test_set(test_vals, test_vals + 4);
3638 const Matcher<TypeParam> m = ContainerEq(my_set);
3639 EXPECT_FALSE(m.Matches(test_set));
3640 EXPECT_EQ("which doesn't have these expected elements: 3",
3641 Explain(m, test_set));
3642 }
3643
3644 // Tests that added values are reported.
TYPED_TEST(ContainerEqTest,ValueAdded)3645 TYPED_TEST(ContainerEqTest, ValueAdded) {
3646 static const int vals[] = {1, 1, 2, 3, 5, 8};
3647 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
3648 TypeParam my_set(vals, vals + 6);
3649 TypeParam test_set(test_vals, test_vals + 6);
3650 const Matcher<const TypeParam&> m = ContainerEq(my_set);
3651 EXPECT_FALSE(m.Matches(test_set));
3652 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
3653 }
3654
3655 // Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest,ValueAddedAndRemoved)3656 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
3657 static const int vals[] = {1, 1, 2, 3, 5, 8};
3658 static const int test_vals[] = {1, 2, 3, 8, 46};
3659 TypeParam my_set(vals, vals + 6);
3660 TypeParam test_set(test_vals, test_vals + 5);
3661 const Matcher<TypeParam> m = ContainerEq(my_set);
3662 EXPECT_FALSE(m.Matches(test_set));
3663 EXPECT_EQ("which has these unexpected elements: 46,\n"
3664 "and doesn't have these expected elements: 5",
3665 Explain(m, test_set));
3666 }
3667
3668 // Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest,DuplicateDifference)3669 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
3670 static const int vals[] = {1, 1, 2, 3, 5, 8};
3671 static const int test_vals[] = {1, 2, 3, 5, 8};
3672 TypeParam my_set(vals, vals + 6);
3673 TypeParam test_set(test_vals, test_vals + 5);
3674 const Matcher<const TypeParam&> m = ContainerEq(my_set);
3675 // Depending on the container, match may be true or false
3676 // But in any case there should be no explanation.
3677 EXPECT_EQ("", Explain(m, test_set));
3678 }
3679 #endif // GTEST_HAS_TYPED_TEST
3680
3681 // Tests that mutliple missing values are reported.
3682 // Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest,MultipleValuesMissing)3683 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
3684 static const int vals[] = {1, 1, 2, 3, 5, 8};
3685 static const int test_vals[] = {2, 1, 5};
3686 vector<int> my_set(vals, vals + 6);
3687 vector<int> test_set(test_vals, test_vals + 3);
3688 const Matcher<vector<int> > m = ContainerEq(my_set);
3689 EXPECT_FALSE(m.Matches(test_set));
3690 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
3691 Explain(m, test_set));
3692 }
3693
3694 // Tests that added values are reported.
3695 // Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest,MultipleValuesAdded)3696 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
3697 static const int vals[] = {1, 1, 2, 3, 5, 8};
3698 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
3699 list<size_t> my_set(vals, vals + 6);
3700 list<size_t> test_set(test_vals, test_vals + 7);
3701 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
3702 EXPECT_FALSE(m.Matches(test_set));
3703 EXPECT_EQ("which has these unexpected elements: 92, 46",
3704 Explain(m, test_set));
3705 }
3706
3707 // Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest,MultipleValuesAddedAndRemoved)3708 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
3709 static const int vals[] = {1, 1, 2, 3, 5, 8};
3710 static const int test_vals[] = {1, 2, 3, 92, 46};
3711 list<size_t> my_set(vals, vals + 6);
3712 list<size_t> test_set(test_vals, test_vals + 5);
3713 const Matcher<const list<size_t> > m = ContainerEq(my_set);
3714 EXPECT_FALSE(m.Matches(test_set));
3715 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
3716 "and doesn't have these expected elements: 5, 8",
3717 Explain(m, test_set));
3718 }
3719
3720 // Tests to see that duplicate elements are detected,
3721 // but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest,MultiSetOfIntDuplicateDifference)3722 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
3723 static const int vals[] = {1, 1, 2, 3, 5, 8};
3724 static const int test_vals[] = {1, 2, 3, 5, 8};
3725 vector<int> my_set(vals, vals + 6);
3726 vector<int> test_set(test_vals, test_vals + 5);
3727 const Matcher<vector<int> > m = ContainerEq(my_set);
3728 EXPECT_TRUE(m.Matches(my_set));
3729 EXPECT_FALSE(m.Matches(test_set));
3730 // There is nothing to report when both sets contain all the same values.
3731 EXPECT_EQ("", Explain(m, test_set));
3732 }
3733
3734 // Tests that ContainerEq works for non-trivial associative containers,
3735 // like maps.
TEST(ContainerEqExtraTest,WorksForMaps)3736 TEST(ContainerEqExtraTest, WorksForMaps) {
3737 map<int, std::string> my_map;
3738 my_map[0] = "a";
3739 my_map[1] = "b";
3740
3741 map<int, std::string> test_map;
3742 test_map[0] = "aa";
3743 test_map[1] = "b";
3744
3745 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
3746 EXPECT_TRUE(m.Matches(my_map));
3747 EXPECT_FALSE(m.Matches(test_map));
3748
3749 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
3750 "and doesn't have these expected elements: (0, \"a\")",
3751 Explain(m, test_map));
3752 }
3753
TEST(ContainerEqExtraTest,WorksForNativeArray)3754 TEST(ContainerEqExtraTest, WorksForNativeArray) {
3755 int a1[] = { 1, 2, 3 };
3756 int a2[] = { 1, 2, 3 };
3757 int b[] = { 1, 2, 4 };
3758
3759 EXPECT_THAT(a1, ContainerEq(a2));
3760 EXPECT_THAT(a1, Not(ContainerEq(b)));
3761 }
3762
TEST(ContainerEqExtraTest,WorksForTwoDimensionalNativeArray)3763 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
3764 const char a1[][3] = { "hi", "lo" };
3765 const char a2[][3] = { "hi", "lo" };
3766 const char b[][3] = { "lo", "hi" };
3767
3768 // Tests using ContainerEq() in the first dimension.
3769 EXPECT_THAT(a1, ContainerEq(a2));
3770 EXPECT_THAT(a1, Not(ContainerEq(b)));
3771
3772 // Tests using ContainerEq() in the second dimension.
3773 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
3774 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
3775 }
3776
TEST(ContainerEqExtraTest,WorksForNativeArrayAsTuple)3777 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
3778 const int a1[] = { 1, 2, 3 };
3779 const int a2[] = { 1, 2, 3 };
3780 const int b[] = { 1, 2, 3, 4 };
3781
3782 const int* const p1 = a1;
3783 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
3784 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
3785
3786 const int c[] = { 1, 3, 2 };
3787 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
3788 }
3789
TEST(ContainerEqExtraTest,CopiesNativeArrayParameter)3790 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
3791 std::string a1[][3] = {
3792 { "hi", "hello", "ciao" },
3793 { "bye", "see you", "ciao" }
3794 };
3795
3796 std::string a2[][3] = {
3797 { "hi", "hello", "ciao" },
3798 { "bye", "see you", "ciao" }
3799 };
3800
3801 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
3802 EXPECT_THAT(a1, m);
3803
3804 a2[0][0] = "ha";
3805 EXPECT_THAT(a1, m);
3806 }
3807
TEST(WhenSortedByTest,WorksForEmptyContainer)3808 TEST(WhenSortedByTest, WorksForEmptyContainer) {
3809 const vector<int> numbers;
3810 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
3811 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
3812 }
3813
TEST(WhenSortedByTest,WorksForNonEmptyContainer)3814 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
3815 vector<unsigned> numbers;
3816 numbers.push_back(3);
3817 numbers.push_back(1);
3818 numbers.push_back(2);
3819 numbers.push_back(2);
3820 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
3821 ElementsAre(3, 2, 2, 1)));
3822 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
3823 ElementsAre(1, 2, 2, 3))));
3824 }
3825
TEST(WhenSortedByTest,WorksForNonVectorContainer)3826 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
3827 list<string> words;
3828 words.push_back("say");
3829 words.push_back("hello");
3830 words.push_back("world");
3831 EXPECT_THAT(words, WhenSortedBy(less<string>(),
3832 ElementsAre("hello", "say", "world")));
3833 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
3834 ElementsAre("say", "hello", "world"))));
3835 }
3836
TEST(WhenSortedByTest,WorksForNativeArray)3837 TEST(WhenSortedByTest, WorksForNativeArray) {
3838 const int numbers[] = { 1, 3, 2, 4 };
3839 const int sorted_numbers[] = { 1, 2, 3, 4 };
3840 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
3841 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
3842 ElementsAreArray(sorted_numbers)));
3843 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
3844 }
3845
TEST(WhenSortedByTest,CanDescribeSelf)3846 TEST(WhenSortedByTest, CanDescribeSelf) {
3847 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
3848 EXPECT_EQ("(when sorted) has 2 elements where\n"
3849 "element #0 is equal to 1,\n"
3850 "element #1 is equal to 2",
3851 Describe(m));
3852 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
3853 "element #0 isn't equal to 1, or\n"
3854 "element #1 isn't equal to 2",
3855 DescribeNegation(m));
3856 }
3857
TEST(WhenSortedByTest,ExplainsMatchResult)3858 TEST(WhenSortedByTest, ExplainsMatchResult) {
3859 const int a[] = { 2, 1 };
3860 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
3861 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
3862 EXPECT_EQ("which is { 1, 2 } when sorted",
3863 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
3864 }
3865
3866 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
3867 // need to test it as exhaustively as we test the latter.
3868
TEST(WhenSortedTest,WorksForEmptyContainer)3869 TEST(WhenSortedTest, WorksForEmptyContainer) {
3870 const vector<int> numbers;
3871 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
3872 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
3873 }
3874
TEST(WhenSortedTest,WorksForNonEmptyContainer)3875 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
3876 list<string> words;
3877 words.push_back("3");
3878 words.push_back("1");
3879 words.push_back("2");
3880 words.push_back("2");
3881 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
3882 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
3883 }
3884
3885 // Tests IsReadableTypeName().
3886
TEST(IsReadableTypeNameTest,ReturnsTrueForShortNames)3887 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
3888 EXPECT_TRUE(IsReadableTypeName("int"));
3889 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
3890 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
3891 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
3892 }
3893
TEST(IsReadableTypeNameTest,ReturnsTrueForLongNonTemplateNonFunctionNames)3894 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
3895 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
3896 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
3897 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
3898 }
3899
TEST(IsReadableTypeNameTest,ReturnsFalseForLongTemplateNames)3900 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
3901 EXPECT_FALSE(
3902 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
3903 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
3904 }
3905
TEST(IsReadableTypeNameTest,ReturnsFalseForLongFunctionTypeNames)3906 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
3907 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
3908 }
3909
3910 // Tests JoinAsTuple().
3911
TEST(JoinAsTupleTest,JoinsEmptyTuple)3912 TEST(JoinAsTupleTest, JoinsEmptyTuple) {
3913 EXPECT_EQ("", JoinAsTuple(Strings()));
3914 }
3915
TEST(JoinAsTupleTest,JoinsOneTuple)3916 TEST(JoinAsTupleTest, JoinsOneTuple) {
3917 const char* fields[] = { "1" };
3918 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
3919 }
3920
TEST(JoinAsTupleTest,JoinsTwoTuple)3921 TEST(JoinAsTupleTest, JoinsTwoTuple) {
3922 const char* fields[] = { "1", "a" };
3923 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
3924 }
3925
TEST(JoinAsTupleTest,JoinsTenTuple)3926 TEST(JoinAsTupleTest, JoinsTenTuple) {
3927 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
3928 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
3929 JoinAsTuple(Strings(fields, fields + 10)));
3930 }
3931
3932 // Tests FormatMatcherDescription().
3933
TEST(FormatMatcherDescriptionTest,WorksForEmptyDescription)3934 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
3935 EXPECT_EQ("is even",
3936 FormatMatcherDescription(false, "IsEven", Strings()));
3937 EXPECT_EQ("not (is even)",
3938 FormatMatcherDescription(true, "IsEven", Strings()));
3939
3940 const char* params[] = { "5" };
3941 EXPECT_EQ("equals 5",
3942 FormatMatcherDescription(false, "Equals",
3943 Strings(params, params + 1)));
3944
3945 const char* params2[] = { "5", "8" };
3946 EXPECT_EQ("is in range (5, 8)",
3947 FormatMatcherDescription(false, "IsInRange",
3948 Strings(params2, params2 + 2)));
3949 }
3950
3951 // Tests PolymorphicMatcher::mutable_impl().
TEST(PolymorphicMatcherTest,CanAccessMutableImpl)3952 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
3953 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
3954 DivisibleByImpl& impl = m.mutable_impl();
3955 EXPECT_EQ(42, impl.divider());
3956
3957 impl.set_divider(0);
3958 EXPECT_EQ(0, m.mutable_impl().divider());
3959 }
3960
3961 // Tests PolymorphicMatcher::impl().
TEST(PolymorphicMatcherTest,CanAccessImpl)3962 TEST(PolymorphicMatcherTest, CanAccessImpl) {
3963 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
3964 const DivisibleByImpl& impl = m.impl();
3965 EXPECT_EQ(42, impl.divider());
3966 }
3967
TEST(MatcherTupleTest,ExplainsMatchFailure)3968 TEST(MatcherTupleTest, ExplainsMatchFailure) {
3969 stringstream ss1;
3970 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
3971 make_tuple('a', 10), &ss1);
3972 EXPECT_EQ("", ss1.str()); // Successful match.
3973
3974 stringstream ss2;
3975 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
3976 make_tuple(2, 'b'), &ss2);
3977 EXPECT_EQ(" Expected arg #0: is > 5\n"
3978 " Actual: 2, which is 3 less than 5\n"
3979 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
3980 " Actual: 'b' (98, 0x62)\n",
3981 ss2.str()); // Failed match where both arguments need explanation.
3982
3983 stringstream ss3;
3984 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
3985 make_tuple(2, 'a'), &ss3);
3986 EXPECT_EQ(" Expected arg #0: is > 5\n"
3987 " Actual: 2, which is 3 less than 5\n",
3988 ss3.str()); // Failed match where only one argument needs
3989 // explanation.
3990 }
3991
3992 // Tests Each().
3993
TEST(EachTest,ExplainsMatchResultCorrectly)3994 TEST(EachTest, ExplainsMatchResultCorrectly) {
3995 set<int> a; // empty
3996
3997 Matcher<set<int> > m = Each(2);
3998 EXPECT_EQ("", Explain(m, a));
3999
4000 Matcher<const int(&)[1]> n = Each(1); // NOLINT
4001
4002 const int b[1] = { 1 };
4003 EXPECT_EQ("", Explain(n, b));
4004
4005 n = Each(3);
4006 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
4007
4008 a.insert(1);
4009 a.insert(2);
4010 a.insert(3);
4011 m = Each(GreaterThan(0));
4012 EXPECT_EQ("", Explain(m, a));
4013
4014 m = Each(GreaterThan(10));
4015 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
4016 Explain(m, a));
4017 }
4018
TEST(EachTest,DescribesItselfCorrectly)4019 TEST(EachTest, DescribesItselfCorrectly) {
4020 Matcher<vector<int> > m = Each(1);
4021 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
4022
4023 Matcher<vector<int> > m2 = Not(m);
4024 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
4025 }
4026
TEST(EachTest,MatchesVectorWhenAllElementsMatch)4027 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
4028 vector<int> some_vector;
4029 EXPECT_THAT(some_vector, Each(1));
4030 some_vector.push_back(3);
4031 EXPECT_THAT(some_vector, Not(Each(1)));
4032 EXPECT_THAT(some_vector, Each(3));
4033 some_vector.push_back(1);
4034 some_vector.push_back(2);
4035 EXPECT_THAT(some_vector, Not(Each(3)));
4036 EXPECT_THAT(some_vector, Each(Lt(3.5)));
4037
4038 vector<string> another_vector;
4039 another_vector.push_back("fee");
4040 EXPECT_THAT(another_vector, Each(string("fee")));
4041 another_vector.push_back("fie");
4042 another_vector.push_back("foe");
4043 another_vector.push_back("fum");
4044 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
4045 }
4046
TEST(EachTest,MatchesMapWhenAllElementsMatch)4047 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
4048 map<const char*, int> my_map;
4049 const char* bar = "a string";
4050 my_map[bar] = 2;
4051 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
4052
4053 map<string, int> another_map;
4054 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
4055 another_map["fee"] = 1;
4056 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
4057 another_map["fie"] = 2;
4058 another_map["foe"] = 3;
4059 another_map["fum"] = 4;
4060 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
4061 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
4062 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
4063 }
4064
TEST(EachTest,AcceptsMatcher)4065 TEST(EachTest, AcceptsMatcher) {
4066 const int a[] = { 1, 2, 3 };
4067 EXPECT_THAT(a, Each(Gt(0)));
4068 EXPECT_THAT(a, Not(Each(Gt(1))));
4069 }
4070
TEST(EachTest,WorksForNativeArrayAsTuple)4071 TEST(EachTest, WorksForNativeArrayAsTuple) {
4072 const int a[] = { 1, 2 };
4073 const int* const pointer = a;
4074 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
4075 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
4076 }
4077
4078 // For testing Pointwise().
4079 class IsHalfOfMatcher {
4080 public:
4081 template <typename T1, typename T2>
MatchAndExplain(const tuple<T1,T2> & a_pair,MatchResultListener * listener) const4082 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
4083 MatchResultListener* listener) const {
4084 if (get<0>(a_pair) == get<1>(a_pair)/2) {
4085 *listener << "where the second is " << get<1>(a_pair);
4086 return true;
4087 } else {
4088 *listener << "where the second/2 is " << get<1>(a_pair)/2;
4089 return false;
4090 }
4091 }
4092
DescribeTo(ostream * os) const4093 void DescribeTo(ostream* os) const {
4094 *os << "are a pair where the first is half of the second";
4095 }
4096
DescribeNegationTo(ostream * os) const4097 void DescribeNegationTo(ostream* os) const {
4098 *os << "are a pair where the first isn't half of the second";
4099 }
4100 };
4101
IsHalfOf()4102 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
4103 return MakePolymorphicMatcher(IsHalfOfMatcher());
4104 }
4105
TEST(PointwiseTest,DescribesSelf)4106 TEST(PointwiseTest, DescribesSelf) {
4107 vector<int> rhs;
4108 rhs.push_back(1);
4109 rhs.push_back(2);
4110 rhs.push_back(3);
4111 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
4112 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
4113 "in { 1, 2, 3 } are a pair where the first is half of the second",
4114 Describe(m));
4115 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
4116 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
4117 "where the first isn't half of the second",
4118 DescribeNegation(m));
4119 }
4120
TEST(PointwiseTest,MakesCopyOfRhs)4121 TEST(PointwiseTest, MakesCopyOfRhs) {
4122 list<signed char> rhs;
4123 rhs.push_back(2);
4124 rhs.push_back(4);
4125
4126 int lhs[] = { 1, 2 };
4127 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
4128 EXPECT_THAT(lhs, m);
4129
4130 // Changing rhs now shouldn't affect m, which made a copy of rhs.
4131 rhs.push_back(6);
4132 EXPECT_THAT(lhs, m);
4133 }
4134
TEST(PointwiseTest,WorksForLhsNativeArray)4135 TEST(PointwiseTest, WorksForLhsNativeArray) {
4136 const int lhs[] = { 1, 2, 3 };
4137 vector<int> rhs;
4138 rhs.push_back(2);
4139 rhs.push_back(4);
4140 rhs.push_back(6);
4141 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
4142 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
4143 }
4144
TEST(PointwiseTest,WorksForRhsNativeArray)4145 TEST(PointwiseTest, WorksForRhsNativeArray) {
4146 const int rhs[] = { 1, 2, 3 };
4147 vector<int> lhs;
4148 lhs.push_back(2);
4149 lhs.push_back(4);
4150 lhs.push_back(6);
4151 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
4152 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
4153 }
4154
TEST(PointwiseTest,RejectsWrongSize)4155 TEST(PointwiseTest, RejectsWrongSize) {
4156 const double lhs[2] = { 1, 2 };
4157 const int rhs[1] = { 0 };
4158 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
4159 EXPECT_EQ("which contains 2 values",
4160 Explain(Pointwise(Gt(), rhs), lhs));
4161
4162 const int rhs2[3] = { 0, 1, 2 };
4163 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
4164 }
4165
TEST(PointwiseTest,RejectsWrongContent)4166 TEST(PointwiseTest, RejectsWrongContent) {
4167 const double lhs[3] = { 1, 2, 3 };
4168 const int rhs[3] = { 2, 6, 4 };
4169 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
4170 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
4171 "where the second/2 is 3",
4172 Explain(Pointwise(IsHalfOf(), rhs), lhs));
4173 }
4174
TEST(PointwiseTest,AcceptsCorrectContent)4175 TEST(PointwiseTest, AcceptsCorrectContent) {
4176 const double lhs[3] = { 1, 2, 3 };
4177 const int rhs[3] = { 2, 4, 6 };
4178 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
4179 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
4180 }
4181
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)4182 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
4183 const double lhs[3] = { 1, 2, 3 };
4184 const int rhs[3] = { 2, 4, 6 };
4185 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
4186 EXPECT_THAT(lhs, Pointwise(m1, rhs));
4187 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
4188
4189 // This type works as a tuple<const double&, const int&> can be
4190 // implicitly cast to tuple<double, int>.
4191 const Matcher<tuple<double, int> > m2 = IsHalfOf();
4192 EXPECT_THAT(lhs, Pointwise(m2, rhs));
4193 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
4194 }
4195
4196 } // namespace gmock_matchers_test
4197 } // namespace testing
4198