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 <list>
41 #include <map>
42 #include <set>
43 #include <sstream>
44 #include <string>
45 #include <vector>
46 #include <gmock/gmock.h>
47 #include <gtest/gtest.h>
48 #include <gtest/gtest-spi.h>
49 
50 namespace testing {
51 
52 namespace internal {
53 string FormatMatcherDescriptionSyntaxError(const char* description,
54                                            const char* error_pos);
55 int GetParamIndex(const char* param_names[], const string& param_name);
56 string JoinAsTuple(const Strings& fields);
57 bool SkipPrefix(const char* prefix, const char** pstr);
58 }  // namespace internal
59 
60 namespace gmock_matchers_test {
61 
62 using std::stringstream;
63 using std::tr1::make_tuple;
64 using testing::A;
65 using testing::AllArgs;
66 using testing::AllOf;
67 using testing::An;
68 using testing::AnyOf;
69 using testing::ByRef;
70 using testing::DoubleEq;
71 using testing::EndsWith;
72 using testing::Eq;
73 using testing::Field;
74 using testing::FloatEq;
75 using testing::Ge;
76 using testing::Gt;
77 using testing::HasSubstr;
78 using testing::Le;
79 using testing::Lt;
80 using testing::MakeMatcher;
81 using testing::MakePolymorphicMatcher;
82 using testing::Matcher;
83 using testing::MatcherCast;
84 using testing::MatcherInterface;
85 using testing::Matches;
86 using testing::NanSensitiveDoubleEq;
87 using testing::NanSensitiveFloatEq;
88 using testing::Ne;
89 using testing::Not;
90 using testing::NotNull;
91 using testing::Pointee;
92 using testing::PolymorphicMatcher;
93 using testing::Property;
94 using testing::Ref;
95 using testing::ResultOf;
96 using testing::StartsWith;
97 using testing::StrCaseEq;
98 using testing::StrCaseNe;
99 using testing::StrEq;
100 using testing::StrNe;
101 using testing::Truly;
102 using testing::TypedEq;
103 using testing::Value;
104 using testing::_;
105 using testing::internal::FloatingEqMatcher;
106 using testing::internal::FormatMatcherDescriptionSyntaxError;
107 using testing::internal::GetParamIndex;
108 using testing::internal::Interpolation;
109 using testing::internal::Interpolations;
110 using testing::internal::JoinAsTuple;
111 using testing::internal::SkipPrefix;
112 using testing::internal::String;
113 using testing::internal::Strings;
114 using testing::internal::ValidateMatcherDescription;
115 using testing::internal::kInvalidInterpolation;
116 using testing::internal::kPercentInterpolation;
117 using testing::internal::kTupleInterpolation;
118 using testing::internal::string;
119 
120 #ifdef GMOCK_HAS_REGEX
121 using testing::ContainsRegex;
122 using testing::MatchesRegex;
123 using testing::internal::RE;
124 #endif  // GMOCK_HAS_REGEX
125 
126 // Returns the description of the given matcher.
127 template <typename T>
Describe(const Matcher<T> & m)128 string Describe(const Matcher<T>& m) {
129   stringstream ss;
130   m.DescribeTo(&ss);
131   return ss.str();
132 }
133 
134 // Returns the description of the negation of the given matcher.
135 template <typename T>
DescribeNegation(const Matcher<T> & m)136 string DescribeNegation(const Matcher<T>& m) {
137   stringstream ss;
138   m.DescribeNegationTo(&ss);
139   return ss.str();
140 }
141 
142 // Returns the reason why x matches, or doesn't match, m.
143 template <typename MatcherType, typename Value>
Explain(const MatcherType & m,const Value & x)144 string Explain(const MatcherType& m, const Value& x) {
145   stringstream ss;
146   m.ExplainMatchResultTo(x, &ss);
147   return ss.str();
148 }
149 
150 // Makes sure that the MatcherInterface<T> interface doesn't
151 // change.
152 class EvenMatcherImpl : public MatcherInterface<int> {
153  public:
Matches(int x) const154   virtual bool Matches(int x) const { return x % 2 == 0; }
155 
DescribeTo(::std::ostream * os) const156   virtual void DescribeTo(::std::ostream* os) const {
157     *os << "is an even number";
158   }
159 
160   // We deliberately don't define DescribeNegationTo() and
161   // ExplainMatchResultTo() here, to make sure the definition of these
162   // two methods is optional.
163 };
164 
TEST(MatcherInterfaceTest,CanBeImplemented)165 TEST(MatcherInterfaceTest, CanBeImplemented) {
166   EvenMatcherImpl m;
167 }
168 
169 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)170 TEST(MatcherTest, CanBeDefaultConstructed) {
171   Matcher<double> m;
172 }
173 
174 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)175 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
176   const MatcherInterface<int>* impl = new EvenMatcherImpl;
177   Matcher<int> m(impl);
178   EXPECT_TRUE(m.Matches(4));
179   EXPECT_FALSE(m.Matches(5));
180 }
181 
182 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)183 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
184   Matcher<int> m1 = 5;
185   EXPECT_TRUE(m1.Matches(5));
186   EXPECT_FALSE(m1.Matches(6));
187 }
188 
189 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)190 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
191   Matcher<int*> m1 = NULL;
192   EXPECT_TRUE(m1.Matches(NULL));
193   int n = 0;
194   EXPECT_FALSE(m1.Matches(&n));
195 }
196 
197 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)198 TEST(MatcherTest, IsCopyable) {
199   // Tests the copy constructor.
200   Matcher<bool> m1 = Eq(false);
201   EXPECT_TRUE(m1.Matches(false));
202   EXPECT_FALSE(m1.Matches(true));
203 
204   // Tests the assignment operator.
205   m1 = Eq(true);
206   EXPECT_TRUE(m1.Matches(true));
207   EXPECT_FALSE(m1.Matches(false));
208 }
209 
210 // Tests that Matcher<T>::DescribeTo() calls
211 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)212 TEST(MatcherTest, CanDescribeItself) {
213   EXPECT_EQ("is an even number",
214             Describe(Matcher<int>(new EvenMatcherImpl)));
215 }
216 
217 // Tests that a C-string literal can be implicitly converted to a
218 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)219 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
220   Matcher<string> m1 = "hi";
221   EXPECT_TRUE(m1.Matches("hi"));
222   EXPECT_FALSE(m1.Matches("hello"));
223 
224   Matcher<const string&> m2 = "hi";
225   EXPECT_TRUE(m2.Matches("hi"));
226   EXPECT_FALSE(m2.Matches("hello"));
227 }
228 
229 // Tests that a string object can be implicitly converted to a
230 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)231 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
232   Matcher<string> m1 = string("hi");
233   EXPECT_TRUE(m1.Matches("hi"));
234   EXPECT_FALSE(m1.Matches("hello"));
235 
236   Matcher<const string&> m2 = string("hi");
237   EXPECT_TRUE(m2.Matches("hi"));
238   EXPECT_FALSE(m2.Matches("hello"));
239 }
240 
241 // Tests that MakeMatcher() constructs a Matcher<T> from a
242 // MatcherInterface* without requiring the user to explicitly
243 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)244 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
245   const MatcherInterface<int>* dummy_impl = NULL;
246   Matcher<int> m = MakeMatcher(dummy_impl);
247 }
248 
249 // Tests that MakePolymorphicMatcher() constructs a polymorphic
250 // matcher from its implementation.
251 const int bar = 1;
252 class ReferencesBarOrIsZeroImpl {
253  public:
254   template <typename T>
Matches(const T & x) const255   bool Matches(const T& x) const {
256     const void* p = &x;
257     return p == &bar || x == 0;
258   }
259 
DescribeTo(::std::ostream * os) const260   void DescribeTo(::std::ostream* os) const { *os << "bar or zero"; }
261 
DescribeNegationTo(::std::ostream * os) const262   void DescribeNegationTo(::std::ostream* os) const {
263     *os << "doesn't reference bar and is not zero";
264   }
265 };
266 
267 // This function verifies that MakePolymorphicMatcher() returns a
268 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()269 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
270   return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
271 }
272 
TEST(MakePolymorphicMatcherTest,ConstructsMatcherFromImpl)273 TEST(MakePolymorphicMatcherTest, ConstructsMatcherFromImpl) {
274   // Using a polymorphic matcher to match a reference type.
275   Matcher<const int&> m1 = ReferencesBarOrIsZero();
276   EXPECT_TRUE(m1.Matches(0));
277   // Verifies that the identity of a by-reference argument is preserved.
278   EXPECT_TRUE(m1.Matches(bar));
279   EXPECT_FALSE(m1.Matches(1));
280   EXPECT_EQ("bar or zero", Describe(m1));
281 
282   // Using a polymorphic matcher to match a value type.
283   Matcher<double> m2 = ReferencesBarOrIsZero();
284   EXPECT_TRUE(m2.Matches(0.0));
285   EXPECT_FALSE(m2.Matches(0.1));
286   EXPECT_EQ("bar or zero", Describe(m2));
287 }
288 
289 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest,FromPolymorphicMatcher)290 TEST(MatcherCastTest, FromPolymorphicMatcher) {
291   Matcher<int> m = MatcherCast<int>(Eq(5));
292   EXPECT_TRUE(m.Matches(5));
293   EXPECT_FALSE(m.Matches(6));
294 }
295 
296 // For testing casting matchers between compatible types.
297 class IntValue {
298  public:
299   // An int can be statically (although not implicitly) cast to a
300   // IntValue.
IntValue(int value)301   explicit IntValue(int value) : value_(value) {}
302 
value() const303   int value() const { return value_; }
304  private:
305   int value_;
306 };
307 
308 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)309 bool IsPositiveIntValue(const IntValue& foo) {
310   return foo.value() > 0;
311 }
312 
313 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
314 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)315 TEST(MatcherCastTest, FromCompatibleType) {
316   Matcher<double> m1 = Eq(2.0);
317   Matcher<int> m2 = MatcherCast<int>(m1);
318   EXPECT_TRUE(m2.Matches(2));
319   EXPECT_FALSE(m2.Matches(3));
320 
321   Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
322   Matcher<int> m4 = MatcherCast<int>(m3);
323   // In the following, the arguments 1 and 0 are statically converted
324   // to IntValue objects, and then tested by the IsPositiveIntValue()
325   // predicate.
326   EXPECT_TRUE(m4.Matches(1));
327   EXPECT_FALSE(m4.Matches(0));
328 }
329 
330 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)331 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
332   Matcher<const int&> m1 = Eq(0);
333   Matcher<int> m2 = MatcherCast<int>(m1);
334   EXPECT_TRUE(m2.Matches(0));
335   EXPECT_FALSE(m2.Matches(1));
336 }
337 
338 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)339 TEST(MatcherCastTest, FromReferenceToNonReference) {
340   Matcher<int&> m1 = Eq(0);
341   Matcher<int> m2 = MatcherCast<int>(m1);
342   EXPECT_TRUE(m2.Matches(0));
343   EXPECT_FALSE(m2.Matches(1));
344 }
345 
346 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)347 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
348   Matcher<int> m1 = Eq(0);
349   Matcher<const int&> m2 = MatcherCast<const int&>(m1);
350   EXPECT_TRUE(m2.Matches(0));
351   EXPECT_FALSE(m2.Matches(1));
352 }
353 
354 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)355 TEST(MatcherCastTest, FromNonReferenceToReference) {
356   Matcher<int> m1 = Eq(0);
357   Matcher<int&> m2 = MatcherCast<int&>(m1);
358   int n = 0;
359   EXPECT_TRUE(m2.Matches(n));
360   n = 1;
361   EXPECT_FALSE(m2.Matches(n));
362 }
363 
364 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)365 TEST(MatcherCastTest, FromSameType) {
366   Matcher<int> m1 = Eq(0);
367   Matcher<int> m2 = MatcherCast<int>(m1);
368   EXPECT_TRUE(m2.Matches(0));
369   EXPECT_FALSE(m2.Matches(1));
370 }
371 
372 class Base {};
373 class Derived : public Base {};
374 
375 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest,FromPolymorphicMatcher)376 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
377   Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
378   EXPECT_TRUE(m2.Matches(' '));
379   EXPECT_FALSE(m2.Matches('\n'));
380 }
381 
382 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
383 // T and U are arithmetic types and T can be losslessly converted to
384 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)385 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
386   Matcher<double> m1 = DoubleEq(1.0);
387   Matcher<float> m2 = SafeMatcherCast<float>(m1);
388   EXPECT_TRUE(m2.Matches(1.0f));
389   EXPECT_FALSE(m2.Matches(2.0f));
390 
391   Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
392   EXPECT_TRUE(m3.Matches('a'));
393   EXPECT_FALSE(m3.Matches('b'));
394 }
395 
396 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
397 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)398 TEST(SafeMatcherCastTest, FromBaseClass) {
399   Derived d, d2;
400   Matcher<Base*> m1 = Eq(&d);
401   Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
402   EXPECT_TRUE(m2.Matches(&d));
403   EXPECT_FALSE(m2.Matches(&d2));
404 
405   Matcher<Base&> m3 = Ref(d);
406   Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
407   EXPECT_TRUE(m4.Matches(d));
408   EXPECT_FALSE(m4.Matches(d2));
409 }
410 
411 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)412 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
413   int n = 0;
414   Matcher<const int&> m1 = Ref(n);
415   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
416   int n1 = 0;
417   EXPECT_TRUE(m2.Matches(n));
418   EXPECT_FALSE(m2.Matches(n1));
419 }
420 
421 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)422 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
423   Matcher<int> m1 = Eq(0);
424   Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
425   EXPECT_TRUE(m2.Matches(0));
426   EXPECT_FALSE(m2.Matches(1));
427 }
428 
429 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)430 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
431   Matcher<int> m1 = Eq(0);
432   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
433   int n = 0;
434   EXPECT_TRUE(m2.Matches(n));
435   n = 1;
436   EXPECT_FALSE(m2.Matches(n));
437 }
438 
439 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)440 TEST(SafeMatcherCastTest, FromSameType) {
441   Matcher<int> m1 = Eq(0);
442   Matcher<int> m2 = SafeMatcherCast<int>(m1);
443   EXPECT_TRUE(m2.Matches(0));
444   EXPECT_FALSE(m2.Matches(1));
445 }
446 
447 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)448 TEST(ATest, MatchesAnyValue) {
449   // Tests a matcher for a value type.
450   Matcher<double> m1 = A<double>();
451   EXPECT_TRUE(m1.Matches(91.43));
452   EXPECT_TRUE(m1.Matches(-15.32));
453 
454   // Tests a matcher for a reference type.
455   int a = 2;
456   int b = -6;
457   Matcher<int&> m2 = A<int&>();
458   EXPECT_TRUE(m2.Matches(a));
459   EXPECT_TRUE(m2.Matches(b));
460 }
461 
462 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)463 TEST(ATest, CanDescribeSelf) {
464   EXPECT_EQ("is anything", Describe(A<bool>()));
465 }
466 
467 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)468 TEST(AnTest, MatchesAnyValue) {
469   // Tests a matcher for a value type.
470   Matcher<int> m1 = An<int>();
471   EXPECT_TRUE(m1.Matches(9143));
472   EXPECT_TRUE(m1.Matches(-1532));
473 
474   // Tests a matcher for a reference type.
475   int a = 2;
476   int b = -6;
477   Matcher<int&> m2 = An<int&>();
478   EXPECT_TRUE(m2.Matches(a));
479   EXPECT_TRUE(m2.Matches(b));
480 }
481 
482 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)483 TEST(AnTest, CanDescribeSelf) {
484   EXPECT_EQ("is anything", Describe(An<int>()));
485 }
486 
487 // Tests that _ can be used as a matcher for any type and matches any
488 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)489 TEST(UnderscoreTest, MatchesAnyValue) {
490   // Uses _ as a matcher for a value type.
491   Matcher<int> m1 = _;
492   EXPECT_TRUE(m1.Matches(123));
493   EXPECT_TRUE(m1.Matches(-242));
494 
495   // Uses _ as a matcher for a reference type.
496   bool a = false;
497   const bool b = true;
498   Matcher<const bool&> m2 = _;
499   EXPECT_TRUE(m2.Matches(a));
500   EXPECT_TRUE(m2.Matches(b));
501 }
502 
503 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)504 TEST(UnderscoreTest, CanDescribeSelf) {
505   Matcher<int> m = _;
506   EXPECT_EQ("is anything", Describe(m));
507 }
508 
509 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)510 TEST(EqTest, MatchesEqualValue) {
511   // 2 C-strings with same content but different addresses.
512   const char a1[] = "hi";
513   const char a2[] = "hi";
514 
515   Matcher<const char*> m1 = Eq(a1);
516   EXPECT_TRUE(m1.Matches(a1));
517   EXPECT_FALSE(m1.Matches(a2));
518 }
519 
520 // Tests that Eq(v) describes itself properly.
521 
522 class Unprintable {
523  public:
Unprintable()524   Unprintable() : c_('a') {}
525 
operator ==(const Unprintable & rhs)526   bool operator==(const Unprintable& rhs) { return true; }
527  private:
528   char c_;
529 };
530 
TEST(EqTest,CanDescribeSelf)531 TEST(EqTest, CanDescribeSelf) {
532   Matcher<Unprintable> m = Eq(Unprintable());
533   EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
534 }
535 
536 // Tests that Eq(v) can be used to match any type that supports
537 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)538 TEST(EqTest, IsPolymorphic) {
539   Matcher<int> m1 = Eq(1);
540   EXPECT_TRUE(m1.Matches(1));
541   EXPECT_FALSE(m1.Matches(2));
542 
543   Matcher<char> m2 = Eq(1);
544   EXPECT_TRUE(m2.Matches('\1'));
545   EXPECT_FALSE(m2.Matches('a'));
546 }
547 
548 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)549 TEST(TypedEqTest, ChecksEqualityForGivenType) {
550   Matcher<char> m1 = TypedEq<char>('a');
551   EXPECT_TRUE(m1.Matches('a'));
552   EXPECT_FALSE(m1.Matches('b'));
553 
554   Matcher<int> m2 = TypedEq<int>(6);
555   EXPECT_TRUE(m2.Matches(6));
556   EXPECT_FALSE(m2.Matches(7));
557 }
558 
559 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)560 TEST(TypedEqTest, CanDescribeSelf) {
561   EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
562 }
563 
564 // Tests that TypedEq<T>(v) has type Matcher<T>.
565 
566 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
567 // is a "bare" type (i.e. not in the form of const U or U&).  If v's
568 // type is not T, the compiler will generate a message about
569 // "undefined referece".
570 template <typename T>
571 struct Type {
IsTypeOftesting::gmock_matchers_test::Type572   static bool IsTypeOf(const T& v) { return true; }
573 
574   template <typename T2>
575   static void IsTypeOf(T2 v);
576 };
577 
TEST(TypedEqTest,HasSpecifiedType)578 TEST(TypedEqTest, HasSpecifiedType) {
579   // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
580   Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
581   Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
582 }
583 
584 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)585 TEST(GeTest, ImplementsGreaterThanOrEqual) {
586   Matcher<int> m1 = Ge(0);
587   EXPECT_TRUE(m1.Matches(1));
588   EXPECT_TRUE(m1.Matches(0));
589   EXPECT_FALSE(m1.Matches(-1));
590 }
591 
592 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)593 TEST(GeTest, CanDescribeSelf) {
594   Matcher<int> m = Ge(5);
595   EXPECT_EQ("is greater than or equal to 5", Describe(m));
596 }
597 
598 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)599 TEST(GtTest, ImplementsGreaterThan) {
600   Matcher<double> m1 = Gt(0);
601   EXPECT_TRUE(m1.Matches(1.0));
602   EXPECT_FALSE(m1.Matches(0.0));
603   EXPECT_FALSE(m1.Matches(-1.0));
604 }
605 
606 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)607 TEST(GtTest, CanDescribeSelf) {
608   Matcher<int> m = Gt(5);
609   EXPECT_EQ("is greater than 5", Describe(m));
610 }
611 
612 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)613 TEST(LeTest, ImplementsLessThanOrEqual) {
614   Matcher<char> m1 = Le('b');
615   EXPECT_TRUE(m1.Matches('a'));
616   EXPECT_TRUE(m1.Matches('b'));
617   EXPECT_FALSE(m1.Matches('c'));
618 }
619 
620 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)621 TEST(LeTest, CanDescribeSelf) {
622   Matcher<int> m = Le(5);
623   EXPECT_EQ("is less than or equal to 5", Describe(m));
624 }
625 
626 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)627 TEST(LtTest, ImplementsLessThan) {
628   Matcher<const string&> m1 = Lt("Hello");
629   EXPECT_TRUE(m1.Matches("Abc"));
630   EXPECT_FALSE(m1.Matches("Hello"));
631   EXPECT_FALSE(m1.Matches("Hello, world!"));
632 }
633 
634 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)635 TEST(LtTest, CanDescribeSelf) {
636   Matcher<int> m = Lt(5);
637   EXPECT_EQ("is less than 5", Describe(m));
638 }
639 
640 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)641 TEST(NeTest, ImplementsNotEqual) {
642   Matcher<int> m1 = Ne(0);
643   EXPECT_TRUE(m1.Matches(1));
644   EXPECT_TRUE(m1.Matches(-1));
645   EXPECT_FALSE(m1.Matches(0));
646 }
647 
648 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)649 TEST(NeTest, CanDescribeSelf) {
650   Matcher<int> m = Ne(5);
651   EXPECT_EQ("is not equal to 5", Describe(m));
652 }
653 
654 // Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest,MatchesNonNullPointer)655 TEST(NotNullTest, MatchesNonNullPointer) {
656   Matcher<int*> m1 = NotNull();
657   int* p1 = NULL;
658   int n = 0;
659   EXPECT_FALSE(m1.Matches(p1));
660   EXPECT_TRUE(m1.Matches(&n));
661 
662   Matcher<const char*> m2 = NotNull();
663   const char* p2 = NULL;
664   EXPECT_FALSE(m2.Matches(p2));
665   EXPECT_TRUE(m2.Matches("hi"));
666 }
667 
668 // Tests that NotNull() describes itself properly.
TEST(NotNullTest,CanDescribeSelf)669 TEST(NotNullTest, CanDescribeSelf) {
670   Matcher<int*> m = NotNull();
671   EXPECT_EQ("is not NULL", Describe(m));
672 }
673 
674 // Tests that Ref(variable) matches an argument that references
675 // 'variable'.
TEST(RefTest,MatchesSameVariable)676 TEST(RefTest, MatchesSameVariable) {
677   int a = 0;
678   int b = 0;
679   Matcher<int&> m = Ref(a);
680   EXPECT_TRUE(m.Matches(a));
681   EXPECT_FALSE(m.Matches(b));
682 }
683 
684 // Tests that Ref(variable) describes itself properly.
TEST(RefTest,CanDescribeSelf)685 TEST(RefTest, CanDescribeSelf) {
686   int n = 5;
687   Matcher<int&> m = Ref(n);
688   stringstream ss;
689   ss << "references the variable @" << &n << " 5";
690   EXPECT_EQ(string(ss.str()), Describe(m));
691 }
692 
693 // Test that Ref(non_const_varialbe) can be used as a matcher for a
694 // const reference.
TEST(RefTest,CanBeUsedAsMatcherForConstReference)695 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
696   int a = 0;
697   int b = 0;
698   Matcher<const int&> m = Ref(a);
699   EXPECT_TRUE(m.Matches(a));
700   EXPECT_FALSE(m.Matches(b));
701 }
702 
703 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
704 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
705 // of Ref(base), but not vice versa.
706 
TEST(RefTest,IsCovariant)707 TEST(RefTest, IsCovariant) {
708   Base base, base2;
709   Derived derived;
710   Matcher<const Base&> m1 = Ref(base);
711   EXPECT_TRUE(m1.Matches(base));
712   EXPECT_FALSE(m1.Matches(base2));
713   EXPECT_FALSE(m1.Matches(derived));
714 
715   m1 = Ref(derived);
716   EXPECT_TRUE(m1.Matches(derived));
717   EXPECT_FALSE(m1.Matches(base));
718   EXPECT_FALSE(m1.Matches(base2));
719 }
720 
721 // Tests string comparison matchers.
722 
TEST(StrEqTest,MatchesEqualString)723 TEST(StrEqTest, MatchesEqualString) {
724   Matcher<const char*> m = StrEq(string("Hello"));
725   EXPECT_TRUE(m.Matches("Hello"));
726   EXPECT_FALSE(m.Matches("hello"));
727   EXPECT_FALSE(m.Matches(NULL));
728 
729   Matcher<const string&> m2 = StrEq("Hello");
730   EXPECT_TRUE(m2.Matches("Hello"));
731   EXPECT_FALSE(m2.Matches("Hi"));
732 }
733 
TEST(StrEqTest,CanDescribeSelf)734 TEST(StrEqTest, CanDescribeSelf) {
735   Matcher<string> m = StrEq("Hi-\'\"\?\\\a\b\f\n\r\t\v\xD3");
736   EXPECT_EQ("is equal to \"Hi-\'\\\"\\?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
737       Describe(m));
738 
739   string str("01204500800");
740   str[3] = '\0';
741   Matcher<string> m2 = StrEq(str);
742   EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
743   str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
744   Matcher<string> m3 = StrEq(str);
745   EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
746 }
747 
TEST(StrNeTest,MatchesUnequalString)748 TEST(StrNeTest, MatchesUnequalString) {
749   Matcher<const char*> m = StrNe("Hello");
750   EXPECT_TRUE(m.Matches(""));
751   EXPECT_TRUE(m.Matches(NULL));
752   EXPECT_FALSE(m.Matches("Hello"));
753 
754   Matcher<string> m2 = StrNe(string("Hello"));
755   EXPECT_TRUE(m2.Matches("hello"));
756   EXPECT_FALSE(m2.Matches("Hello"));
757 }
758 
TEST(StrNeTest,CanDescribeSelf)759 TEST(StrNeTest, CanDescribeSelf) {
760   Matcher<const char*> m = StrNe("Hi");
761   EXPECT_EQ("is not equal to \"Hi\"", Describe(m));
762 }
763 
TEST(StrCaseEqTest,MatchesEqualStringIgnoringCase)764 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
765   Matcher<const char*> m = StrCaseEq(string("Hello"));
766   EXPECT_TRUE(m.Matches("Hello"));
767   EXPECT_TRUE(m.Matches("hello"));
768   EXPECT_FALSE(m.Matches("Hi"));
769   EXPECT_FALSE(m.Matches(NULL));
770 
771   Matcher<const string&> m2 = StrCaseEq("Hello");
772   EXPECT_TRUE(m2.Matches("hello"));
773   EXPECT_FALSE(m2.Matches("Hi"));
774 }
775 
TEST(StrCaseEqTest,MatchesEqualStringWith0IgnoringCase)776 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
777   string str1("oabocdooeoo");
778   string str2("OABOCDOOEOO");
779   Matcher<const string&> m0 = StrCaseEq(str1);
780   EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
781 
782   str1[3] = str2[3] = '\0';
783   Matcher<const string&> m1 = StrCaseEq(str1);
784   EXPECT_TRUE(m1.Matches(str2));
785 
786   str1[0] = str1[6] = str1[7] = str1[10] = '\0';
787   str2[0] = str2[6] = str2[7] = str2[10] = '\0';
788   Matcher<const string&> m2 = StrCaseEq(str1);
789   str1[9] = str2[9] = '\0';
790   EXPECT_FALSE(m2.Matches(str2));
791 
792   Matcher<const string&> m3 = StrCaseEq(str1);
793   EXPECT_TRUE(m3.Matches(str2));
794 
795   EXPECT_FALSE(m3.Matches(str2 + "x"));
796   str2.append(1, '\0');
797   EXPECT_FALSE(m3.Matches(str2));
798   EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
799 }
800 
TEST(StrCaseEqTest,CanDescribeSelf)801 TEST(StrCaseEqTest, CanDescribeSelf) {
802   Matcher<string> m = StrCaseEq("Hi");
803   EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
804 }
805 
TEST(StrCaseNeTest,MatchesUnequalStringIgnoringCase)806 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
807   Matcher<const char*> m = StrCaseNe("Hello");
808   EXPECT_TRUE(m.Matches("Hi"));
809   EXPECT_TRUE(m.Matches(NULL));
810   EXPECT_FALSE(m.Matches("Hello"));
811   EXPECT_FALSE(m.Matches("hello"));
812 
813   Matcher<string> m2 = StrCaseNe(string("Hello"));
814   EXPECT_TRUE(m2.Matches(""));
815   EXPECT_FALSE(m2.Matches("Hello"));
816 }
817 
TEST(StrCaseNeTest,CanDescribeSelf)818 TEST(StrCaseNeTest, CanDescribeSelf) {
819   Matcher<const char*> m = StrCaseNe("Hi");
820   EXPECT_EQ("is not equal to (ignoring case) \"Hi\"", Describe(m));
821 }
822 
823 // Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest,WorksForStringClasses)824 TEST(HasSubstrTest, WorksForStringClasses) {
825   const Matcher<string> m1 = HasSubstr("foo");
826   EXPECT_TRUE(m1.Matches(string("I love food.")));
827   EXPECT_FALSE(m1.Matches(string("tofo")));
828 
829   const Matcher<const std::string&> m2 = HasSubstr("foo");
830   EXPECT_TRUE(m2.Matches(std::string("I love food.")));
831   EXPECT_FALSE(m2.Matches(std::string("tofo")));
832 }
833 
834 // Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest,WorksForCStrings)835 TEST(HasSubstrTest, WorksForCStrings) {
836   const Matcher<char*> m1 = HasSubstr("foo");
837   EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
838   EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
839   EXPECT_FALSE(m1.Matches(NULL));
840 
841   const Matcher<const char*> m2 = HasSubstr("foo");
842   EXPECT_TRUE(m2.Matches("I love food."));
843   EXPECT_FALSE(m2.Matches("tofo"));
844   EXPECT_FALSE(m2.Matches(NULL));
845 }
846 
847 // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest,CanDescribeSelf)848 TEST(HasSubstrTest, CanDescribeSelf) {
849   Matcher<string> m = HasSubstr("foo\n\"");
850   EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
851 }
852 
853 // Tests StartsWith(s).
854 
TEST(StartsWithTest,MatchesStringWithGivenPrefix)855 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
856   const Matcher<const char*> m1 = StartsWith(string(""));
857   EXPECT_TRUE(m1.Matches("Hi"));
858   EXPECT_TRUE(m1.Matches(""));
859   EXPECT_FALSE(m1.Matches(NULL));
860 
861   const Matcher<const string&> m2 = StartsWith("Hi");
862   EXPECT_TRUE(m2.Matches("Hi"));
863   EXPECT_TRUE(m2.Matches("Hi Hi!"));
864   EXPECT_TRUE(m2.Matches("High"));
865   EXPECT_FALSE(m2.Matches("H"));
866   EXPECT_FALSE(m2.Matches(" Hi"));
867 }
868 
TEST(StartsWithTest,CanDescribeSelf)869 TEST(StartsWithTest, CanDescribeSelf) {
870   Matcher<const std::string> m = StartsWith("Hi");
871   EXPECT_EQ("starts with \"Hi\"", Describe(m));
872 }
873 
874 // Tests EndsWith(s).
875 
TEST(EndsWithTest,MatchesStringWithGivenSuffix)876 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
877   const Matcher<const char*> m1 = EndsWith("");
878   EXPECT_TRUE(m1.Matches("Hi"));
879   EXPECT_TRUE(m1.Matches(""));
880   EXPECT_FALSE(m1.Matches(NULL));
881 
882   const Matcher<const string&> m2 = EndsWith(string("Hi"));
883   EXPECT_TRUE(m2.Matches("Hi"));
884   EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
885   EXPECT_TRUE(m2.Matches("Super Hi"));
886   EXPECT_FALSE(m2.Matches("i"));
887   EXPECT_FALSE(m2.Matches("Hi "));
888 }
889 
TEST(EndsWithTest,CanDescribeSelf)890 TEST(EndsWithTest, CanDescribeSelf) {
891   Matcher<const std::string> m = EndsWith("Hi");
892   EXPECT_EQ("ends with \"Hi\"", Describe(m));
893 }
894 
895 #ifdef GMOCK_HAS_REGEX
896 
897 // Tests MatchesRegex().
898 
TEST(MatchesRegexTest,MatchesStringMatchingGivenRegex)899 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
900   const Matcher<const char*> m1 = MatchesRegex("a.*z");
901   EXPECT_TRUE(m1.Matches("az"));
902   EXPECT_TRUE(m1.Matches("abcz"));
903   EXPECT_FALSE(m1.Matches(NULL));
904 
905   const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
906   EXPECT_TRUE(m2.Matches("azbz"));
907   EXPECT_FALSE(m2.Matches("az1"));
908   EXPECT_FALSE(m2.Matches("1az"));
909 }
910 
TEST(MatchesRegexTest,CanDescribeSelf)911 TEST(MatchesRegexTest, CanDescribeSelf) {
912   Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
913   EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
914 
915   Matcher<const char*> m2 = MatchesRegex(new RE("[a-z].*"));
916   EXPECT_EQ("matches regular expression \"[a-z].*\"", Describe(m2));
917 }
918 
919 // Tests ContainsRegex().
920 
TEST(ContainsRegexTest,MatchesStringContainingGivenRegex)921 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
922   const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
923   EXPECT_TRUE(m1.Matches("az"));
924   EXPECT_TRUE(m1.Matches("0abcz1"));
925   EXPECT_FALSE(m1.Matches(NULL));
926 
927   const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
928   EXPECT_TRUE(m2.Matches("azbz"));
929   EXPECT_TRUE(m2.Matches("az1"));
930   EXPECT_FALSE(m2.Matches("1a"));
931 }
932 
TEST(ContainsRegexTest,CanDescribeSelf)933 TEST(ContainsRegexTest, CanDescribeSelf) {
934   Matcher<const std::string> m1 = ContainsRegex("Hi.*");
935   EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
936 
937   Matcher<const char*> m2 = ContainsRegex(new RE("[a-z].*"));
938   EXPECT_EQ("contains regular expression \"[a-z].*\"", Describe(m2));
939 }
940 #endif  // GMOCK_HAS_REGEX
941 
942 // Tests for wide strings.
943 #if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest,MatchesEqual)944 TEST(StdWideStrEqTest, MatchesEqual) {
945   Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
946   EXPECT_TRUE(m.Matches(L"Hello"));
947   EXPECT_FALSE(m.Matches(L"hello"));
948   EXPECT_FALSE(m.Matches(NULL));
949 
950   Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
951   EXPECT_TRUE(m2.Matches(L"Hello"));
952   EXPECT_FALSE(m2.Matches(L"Hi"));
953 
954   Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
955   EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
956   EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
957 
958   ::std::wstring str(L"01204500800");
959   str[3] = L'\0';
960   Matcher<const ::std::wstring&> m4 = StrEq(str);
961   EXPECT_TRUE(m4.Matches(str));
962   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
963   Matcher<const ::std::wstring&> m5 = StrEq(str);
964   EXPECT_TRUE(m5.Matches(str));
965 }
966 
TEST(StdWideStrEqTest,CanDescribeSelf)967 TEST(StdWideStrEqTest, CanDescribeSelf) {
968   Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"\?\\\a\b\f\n\r\t\v");
969   EXPECT_EQ("is equal to L\"Hi-\'\\\"\\?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
970     Describe(m));
971 
972   Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
973   EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
974     Describe(m2));
975 
976   ::std::wstring str(L"01204500800");
977   str[3] = L'\0';
978   Matcher<const ::std::wstring&> m4 = StrEq(str);
979   EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
980   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
981   Matcher<const ::std::wstring&> m5 = StrEq(str);
982   EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
983 }
984 
TEST(StdWideStrNeTest,MatchesUnequalString)985 TEST(StdWideStrNeTest, MatchesUnequalString) {
986   Matcher<const wchar_t*> m = StrNe(L"Hello");
987   EXPECT_TRUE(m.Matches(L""));
988   EXPECT_TRUE(m.Matches(NULL));
989   EXPECT_FALSE(m.Matches(L"Hello"));
990 
991   Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
992   EXPECT_TRUE(m2.Matches(L"hello"));
993   EXPECT_FALSE(m2.Matches(L"Hello"));
994 }
995 
TEST(StdWideStrNeTest,CanDescribeSelf)996 TEST(StdWideStrNeTest, CanDescribeSelf) {
997   Matcher<const wchar_t*> m = StrNe(L"Hi");
998   EXPECT_EQ("is not equal to L\"Hi\"", Describe(m));
999 }
1000 
TEST(StdWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1001 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1002   Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1003   EXPECT_TRUE(m.Matches(L"Hello"));
1004   EXPECT_TRUE(m.Matches(L"hello"));
1005   EXPECT_FALSE(m.Matches(L"Hi"));
1006   EXPECT_FALSE(m.Matches(NULL));
1007 
1008   Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1009   EXPECT_TRUE(m2.Matches(L"hello"));
1010   EXPECT_FALSE(m2.Matches(L"Hi"));
1011 }
1012 
TEST(StdWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1013 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1014   ::std::wstring str1(L"oabocdooeoo");
1015   ::std::wstring str2(L"OABOCDOOEOO");
1016   Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1017   EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1018 
1019   str1[3] = str2[3] = L'\0';
1020   Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1021   EXPECT_TRUE(m1.Matches(str2));
1022 
1023   str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1024   str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1025   Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1026   str1[9] = str2[9] = L'\0';
1027   EXPECT_FALSE(m2.Matches(str2));
1028 
1029   Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1030   EXPECT_TRUE(m3.Matches(str2));
1031 
1032   EXPECT_FALSE(m3.Matches(str2 + L"x"));
1033   str2.append(1, L'\0');
1034   EXPECT_FALSE(m3.Matches(str2));
1035   EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1036 }
1037 
TEST(StdWideStrCaseEqTest,CanDescribeSelf)1038 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1039   Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1040   EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1041 }
1042 
TEST(StdWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1043 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1044   Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1045   EXPECT_TRUE(m.Matches(L"Hi"));
1046   EXPECT_TRUE(m.Matches(NULL));
1047   EXPECT_FALSE(m.Matches(L"Hello"));
1048   EXPECT_FALSE(m.Matches(L"hello"));
1049 
1050   Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1051   EXPECT_TRUE(m2.Matches(L""));
1052   EXPECT_FALSE(m2.Matches(L"Hello"));
1053 }
1054 
TEST(StdWideStrCaseNeTest,CanDescribeSelf)1055 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1056   Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1057   EXPECT_EQ("is not equal to (ignoring case) L\"Hi\"", Describe(m));
1058 }
1059 
1060 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest,WorksForStringClasses)1061 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1062   const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1063   EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1064   EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1065 
1066   const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1067   EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1068   EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1069 }
1070 
1071 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest,WorksForCStrings)1072 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1073   const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1074   EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1075   EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1076   EXPECT_FALSE(m1.Matches(NULL));
1077 
1078   const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1079   EXPECT_TRUE(m2.Matches(L"I love food."));
1080   EXPECT_FALSE(m2.Matches(L"tofo"));
1081   EXPECT_FALSE(m2.Matches(NULL));
1082 }
1083 
1084 // Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest,CanDescribeSelf)1085 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1086   Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1087   EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1088 }
1089 
1090 // Tests StartsWith(s).
1091 
TEST(StdWideStartsWithTest,MatchesStringWithGivenPrefix)1092 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1093   const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1094   EXPECT_TRUE(m1.Matches(L"Hi"));
1095   EXPECT_TRUE(m1.Matches(L""));
1096   EXPECT_FALSE(m1.Matches(NULL));
1097 
1098   const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1099   EXPECT_TRUE(m2.Matches(L"Hi"));
1100   EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1101   EXPECT_TRUE(m2.Matches(L"High"));
1102   EXPECT_FALSE(m2.Matches(L"H"));
1103   EXPECT_FALSE(m2.Matches(L" Hi"));
1104 }
1105 
TEST(StdWideStartsWithTest,CanDescribeSelf)1106 TEST(StdWideStartsWithTest, CanDescribeSelf) {
1107   Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1108   EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1109 }
1110 
1111 // Tests EndsWith(s).
1112 
TEST(StdWideEndsWithTest,MatchesStringWithGivenSuffix)1113 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1114   const Matcher<const wchar_t*> m1 = EndsWith(L"");
1115   EXPECT_TRUE(m1.Matches(L"Hi"));
1116   EXPECT_TRUE(m1.Matches(L""));
1117   EXPECT_FALSE(m1.Matches(NULL));
1118 
1119   const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1120   EXPECT_TRUE(m2.Matches(L"Hi"));
1121   EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1122   EXPECT_TRUE(m2.Matches(L"Super Hi"));
1123   EXPECT_FALSE(m2.Matches(L"i"));
1124   EXPECT_FALSE(m2.Matches(L"Hi "));
1125 }
1126 
TEST(StdWideEndsWithTest,CanDescribeSelf)1127 TEST(StdWideEndsWithTest, CanDescribeSelf) {
1128   Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1129   EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1130 }
1131 
1132 #endif  // GTEST_HAS_STD_WSTRING
1133 
1134 #if GTEST_HAS_GLOBAL_WSTRING
TEST(GlobalWideStrEqTest,MatchesEqual)1135 TEST(GlobalWideStrEqTest, MatchesEqual) {
1136   Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1137   EXPECT_TRUE(m.Matches(L"Hello"));
1138   EXPECT_FALSE(m.Matches(L"hello"));
1139   EXPECT_FALSE(m.Matches(NULL));
1140 
1141   Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1142   EXPECT_TRUE(m2.Matches(L"Hello"));
1143   EXPECT_FALSE(m2.Matches(L"Hi"));
1144 
1145   Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1146   EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1147   EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1148 
1149   ::wstring str(L"01204500800");
1150   str[3] = L'\0';
1151   Matcher<const ::wstring&> m4 = StrEq(str);
1152   EXPECT_TRUE(m4.Matches(str));
1153   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1154   Matcher<const ::wstring&> m5 = StrEq(str);
1155   EXPECT_TRUE(m5.Matches(str));
1156 }
1157 
TEST(GlobalWideStrEqTest,CanDescribeSelf)1158 TEST(GlobalWideStrEqTest, CanDescribeSelf) {
1159   Matcher< ::wstring> m = StrEq(L"Hi-\'\"\?\\\a\b\f\n\r\t\v");
1160   EXPECT_EQ("is equal to L\"Hi-\'\\\"\\?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1161     Describe(m));
1162 
1163   Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1164   EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1165     Describe(m2));
1166 
1167   ::wstring str(L"01204500800");
1168   str[3] = L'\0';
1169   Matcher<const ::wstring&> m4 = StrEq(str);
1170   EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1171   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1172   Matcher<const ::wstring&> m5 = StrEq(str);
1173   EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1174 }
1175 
TEST(GlobalWideStrNeTest,MatchesUnequalString)1176 TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1177   Matcher<const wchar_t*> m = StrNe(L"Hello");
1178   EXPECT_TRUE(m.Matches(L""));
1179   EXPECT_TRUE(m.Matches(NULL));
1180   EXPECT_FALSE(m.Matches(L"Hello"));
1181 
1182   Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1183   EXPECT_TRUE(m2.Matches(L"hello"));
1184   EXPECT_FALSE(m2.Matches(L"Hello"));
1185 }
1186 
TEST(GlobalWideStrNeTest,CanDescribeSelf)1187 TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1188   Matcher<const wchar_t*> m = StrNe(L"Hi");
1189   EXPECT_EQ("is not equal to L\"Hi\"", Describe(m));
1190 }
1191 
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1192 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1193   Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1194   EXPECT_TRUE(m.Matches(L"Hello"));
1195   EXPECT_TRUE(m.Matches(L"hello"));
1196   EXPECT_FALSE(m.Matches(L"Hi"));
1197   EXPECT_FALSE(m.Matches(NULL));
1198 
1199   Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1200   EXPECT_TRUE(m2.Matches(L"hello"));
1201   EXPECT_FALSE(m2.Matches(L"Hi"));
1202 }
1203 
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1204 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1205   ::wstring str1(L"oabocdooeoo");
1206   ::wstring str2(L"OABOCDOOEOO");
1207   Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1208   EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1209 
1210   str1[3] = str2[3] = L'\0';
1211   Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1212   EXPECT_TRUE(m1.Matches(str2));
1213 
1214   str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1215   str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1216   Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1217   str1[9] = str2[9] = L'\0';
1218   EXPECT_FALSE(m2.Matches(str2));
1219 
1220   Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1221   EXPECT_TRUE(m3.Matches(str2));
1222 
1223   EXPECT_FALSE(m3.Matches(str2 + L"x"));
1224   str2.append(1, L'\0');
1225   EXPECT_FALSE(m3.Matches(str2));
1226   EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1227 }
1228 
TEST(GlobalWideStrCaseEqTest,CanDescribeSelf)1229 TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1230   Matcher< ::wstring> m = StrCaseEq(L"Hi");
1231   EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1232 }
1233 
TEST(GlobalWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1234 TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1235   Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1236   EXPECT_TRUE(m.Matches(L"Hi"));
1237   EXPECT_TRUE(m.Matches(NULL));
1238   EXPECT_FALSE(m.Matches(L"Hello"));
1239   EXPECT_FALSE(m.Matches(L"hello"));
1240 
1241   Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1242   EXPECT_TRUE(m2.Matches(L""));
1243   EXPECT_FALSE(m2.Matches(L"Hello"));
1244 }
1245 
TEST(GlobalWideStrCaseNeTest,CanDescribeSelf)1246 TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1247   Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1248   EXPECT_EQ("is not equal to (ignoring case) L\"Hi\"", Describe(m));
1249 }
1250 
1251 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(GlobalWideHasSubstrTest,WorksForStringClasses)1252 TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1253   const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1254   EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1255   EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1256 
1257   const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1258   EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1259   EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1260 }
1261 
1262 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(GlobalWideHasSubstrTest,WorksForCStrings)1263 TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1264   const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1265   EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1266   EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1267   EXPECT_FALSE(m1.Matches(NULL));
1268 
1269   const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1270   EXPECT_TRUE(m2.Matches(L"I love food."));
1271   EXPECT_FALSE(m2.Matches(L"tofo"));
1272   EXPECT_FALSE(m2.Matches(NULL));
1273 }
1274 
1275 // Tests that HasSubstr(s) describes itself properly.
TEST(GlobalWideHasSubstrTest,CanDescribeSelf)1276 TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1277   Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1278   EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1279 }
1280 
1281 // Tests StartsWith(s).
1282 
TEST(GlobalWideStartsWithTest,MatchesStringWithGivenPrefix)1283 TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1284   const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1285   EXPECT_TRUE(m1.Matches(L"Hi"));
1286   EXPECT_TRUE(m1.Matches(L""));
1287   EXPECT_FALSE(m1.Matches(NULL));
1288 
1289   const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1290   EXPECT_TRUE(m2.Matches(L"Hi"));
1291   EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1292   EXPECT_TRUE(m2.Matches(L"High"));
1293   EXPECT_FALSE(m2.Matches(L"H"));
1294   EXPECT_FALSE(m2.Matches(L" Hi"));
1295 }
1296 
TEST(GlobalWideStartsWithTest,CanDescribeSelf)1297 TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1298   Matcher<const ::wstring> m = StartsWith(L"Hi");
1299   EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1300 }
1301 
1302 // Tests EndsWith(s).
1303 
TEST(GlobalWideEndsWithTest,MatchesStringWithGivenSuffix)1304 TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1305   const Matcher<const wchar_t*> m1 = EndsWith(L"");
1306   EXPECT_TRUE(m1.Matches(L"Hi"));
1307   EXPECT_TRUE(m1.Matches(L""));
1308   EXPECT_FALSE(m1.Matches(NULL));
1309 
1310   const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1311   EXPECT_TRUE(m2.Matches(L"Hi"));
1312   EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1313   EXPECT_TRUE(m2.Matches(L"Super Hi"));
1314   EXPECT_FALSE(m2.Matches(L"i"));
1315   EXPECT_FALSE(m2.Matches(L"Hi "));
1316 }
1317 
TEST(GlobalWideEndsWithTest,CanDescribeSelf)1318 TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1319   Matcher<const ::wstring> m = EndsWith(L"Hi");
1320   EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1321 }
1322 
1323 #endif  // GTEST_HAS_GLOBAL_WSTRING
1324 
1325 
1326 typedef ::std::tr1::tuple<long, int> Tuple2;  // NOLINT
1327 
1328 // Tests that Eq() matches a 2-tuple where the first field == the
1329 // second field.
TEST(Eq2Test,MatchesEqualArguments)1330 TEST(Eq2Test, MatchesEqualArguments) {
1331   Matcher<const Tuple2&> m = Eq();
1332   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1333   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1334 }
1335 
1336 // Tests that Eq() describes itself properly.
TEST(Eq2Test,CanDescribeSelf)1337 TEST(Eq2Test, CanDescribeSelf) {
1338   Matcher<const Tuple2&> m = Eq();
1339   EXPECT_EQ("are a pair (x, y) where x == y", Describe(m));
1340 }
1341 
1342 // Tests that Ge() matches a 2-tuple where the first field >= the
1343 // second field.
TEST(Ge2Test,MatchesGreaterThanOrEqualArguments)1344 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1345   Matcher<const Tuple2&> m = Ge();
1346   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1347   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1348   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1349 }
1350 
1351 // Tests that Ge() describes itself properly.
TEST(Ge2Test,CanDescribeSelf)1352 TEST(Ge2Test, CanDescribeSelf) {
1353   Matcher<const Tuple2&> m = Ge();
1354   EXPECT_EQ("are a pair (x, y) where x >= y", Describe(m));
1355 }
1356 
1357 // Tests that Gt() matches a 2-tuple where the first field > the
1358 // second field.
TEST(Gt2Test,MatchesGreaterThanArguments)1359 TEST(Gt2Test, MatchesGreaterThanArguments) {
1360   Matcher<const Tuple2&> m = Gt();
1361   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1362   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1363   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1364 }
1365 
1366 // Tests that Gt() describes itself properly.
TEST(Gt2Test,CanDescribeSelf)1367 TEST(Gt2Test, CanDescribeSelf) {
1368   Matcher<const Tuple2&> m = Gt();
1369   EXPECT_EQ("are a pair (x, y) where x > y", Describe(m));
1370 }
1371 
1372 // Tests that Le() matches a 2-tuple where the first field <= the
1373 // second field.
TEST(Le2Test,MatchesLessThanOrEqualArguments)1374 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1375   Matcher<const Tuple2&> m = Le();
1376   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1377   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1378   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1379 }
1380 
1381 // Tests that Le() describes itself properly.
TEST(Le2Test,CanDescribeSelf)1382 TEST(Le2Test, CanDescribeSelf) {
1383   Matcher<const Tuple2&> m = Le();
1384   EXPECT_EQ("are a pair (x, y) where x <= y", Describe(m));
1385 }
1386 
1387 // Tests that Lt() matches a 2-tuple where the first field < the
1388 // second field.
TEST(Lt2Test,MatchesLessThanArguments)1389 TEST(Lt2Test, MatchesLessThanArguments) {
1390   Matcher<const Tuple2&> m = Lt();
1391   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1392   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1393   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1394 }
1395 
1396 // Tests that Lt() describes itself properly.
TEST(Lt2Test,CanDescribeSelf)1397 TEST(Lt2Test, CanDescribeSelf) {
1398   Matcher<const Tuple2&> m = Lt();
1399   EXPECT_EQ("are a pair (x, y) where x < y", Describe(m));
1400 }
1401 
1402 // Tests that Ne() matches a 2-tuple where the first field != the
1403 // second field.
TEST(Ne2Test,MatchesUnequalArguments)1404 TEST(Ne2Test, MatchesUnequalArguments) {
1405   Matcher<const Tuple2&> m = Ne();
1406   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1407   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1408   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1409 }
1410 
1411 // Tests that Ne() describes itself properly.
TEST(Ne2Test,CanDescribeSelf)1412 TEST(Ne2Test, CanDescribeSelf) {
1413   Matcher<const Tuple2&> m = Ne();
1414   EXPECT_EQ("are a pair (x, y) where x != y", Describe(m));
1415 }
1416 
1417 // Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest,NegatesMatcher)1418 TEST(NotTest, NegatesMatcher) {
1419   Matcher<int> m;
1420   m = Not(Eq(2));
1421   EXPECT_TRUE(m.Matches(3));
1422   EXPECT_FALSE(m.Matches(2));
1423 }
1424 
1425 // Tests that Not(m) describes itself properly.
TEST(NotTest,CanDescribeSelf)1426 TEST(NotTest, CanDescribeSelf) {
1427   Matcher<int> m = Not(Eq(5));
1428   EXPECT_EQ("is not equal to 5", Describe(m));
1429 }
1430 
1431 // Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest,NotMatcherSafelyCastsMonomorphicMatchers)1432 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
1433   // greater_than_5 is a monomorphic matcher.
1434   Matcher<int> greater_than_5 = Gt(5);
1435 
1436   Matcher<const int&> m = Not(greater_than_5);
1437   Matcher<int&> m2 = Not(greater_than_5);
1438   Matcher<int&> m3 = Not(m);
1439 }
1440 
1441 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
1442 // the given matchers.
TEST(AllOfTest,MatchesWhenAllMatch)1443 TEST(AllOfTest, MatchesWhenAllMatch) {
1444   Matcher<int> m;
1445   m = AllOf(Le(2), Ge(1));
1446   EXPECT_TRUE(m.Matches(1));
1447   EXPECT_TRUE(m.Matches(2));
1448   EXPECT_FALSE(m.Matches(0));
1449   EXPECT_FALSE(m.Matches(3));
1450 
1451   m = AllOf(Gt(0), Ne(1), Ne(2));
1452   EXPECT_TRUE(m.Matches(3));
1453   EXPECT_FALSE(m.Matches(2));
1454   EXPECT_FALSE(m.Matches(1));
1455   EXPECT_FALSE(m.Matches(0));
1456 
1457   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1458   EXPECT_TRUE(m.Matches(4));
1459   EXPECT_FALSE(m.Matches(3));
1460   EXPECT_FALSE(m.Matches(2));
1461   EXPECT_FALSE(m.Matches(1));
1462   EXPECT_FALSE(m.Matches(0));
1463 
1464   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1465   EXPECT_TRUE(m.Matches(0));
1466   EXPECT_TRUE(m.Matches(1));
1467   EXPECT_FALSE(m.Matches(3));
1468 }
1469 
1470 // Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest,CanDescribeSelf)1471 TEST(AllOfTest, CanDescribeSelf) {
1472   Matcher<int> m;
1473   m = AllOf(Le(2), Ge(1));
1474   EXPECT_EQ("(is less than or equal to 2) and "
1475             "(is greater than or equal to 1)",
1476             Describe(m));
1477 
1478   m = AllOf(Gt(0), Ne(1), Ne(2));
1479   EXPECT_EQ("(is greater than 0) and "
1480             "((is not equal to 1) and "
1481             "(is not equal to 2))",
1482             Describe(m));
1483 
1484 
1485   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1486   EXPECT_EQ("(is greater than 0) and "
1487             "((is not equal to 1) and "
1488             "((is not equal to 2) and "
1489             "(is not equal to 3)))",
1490             Describe(m));
1491 
1492 
1493   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1494   EXPECT_EQ("(is greater than or equal to 0) and "
1495             "((is less than 10) and "
1496             "((is not equal to 3) and "
1497             "((is not equal to 5) and "
1498             "(is not equal to 7))))", Describe(m));
1499 }
1500 
1501 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest,AllOfMatcherSafelyCastsMonomorphicMatchers)1502 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
1503   // greater_than_5 and less_than_10 are monomorphic matchers.
1504   Matcher<int> greater_than_5 = Gt(5);
1505   Matcher<int> less_than_10 = Lt(10);
1506 
1507   Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
1508   Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
1509   Matcher<int&> m3 = AllOf(greater_than_5, m2);
1510 
1511   // Tests that BothOf works when composing itself.
1512   Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
1513   Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
1514 }
1515 
1516 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
1517 // least one of the given matchers.
TEST(AnyOfTest,MatchesWhenAnyMatches)1518 TEST(AnyOfTest, MatchesWhenAnyMatches) {
1519   Matcher<int> m;
1520   m = AnyOf(Le(1), Ge(3));
1521   EXPECT_TRUE(m.Matches(1));
1522   EXPECT_TRUE(m.Matches(4));
1523   EXPECT_FALSE(m.Matches(2));
1524 
1525   m = AnyOf(Lt(0), Eq(1), Eq(2));
1526   EXPECT_TRUE(m.Matches(-1));
1527   EXPECT_TRUE(m.Matches(1));
1528   EXPECT_TRUE(m.Matches(2));
1529   EXPECT_FALSE(m.Matches(0));
1530 
1531   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
1532   EXPECT_TRUE(m.Matches(-1));
1533   EXPECT_TRUE(m.Matches(1));
1534   EXPECT_TRUE(m.Matches(2));
1535   EXPECT_TRUE(m.Matches(3));
1536   EXPECT_FALSE(m.Matches(0));
1537 
1538   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
1539   EXPECT_TRUE(m.Matches(0));
1540   EXPECT_TRUE(m.Matches(11));
1541   EXPECT_TRUE(m.Matches(3));
1542   EXPECT_FALSE(m.Matches(2));
1543 }
1544 
1545 // Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest,CanDescribeSelf)1546 TEST(AnyOfTest, CanDescribeSelf) {
1547   Matcher<int> m;
1548   m = AnyOf(Le(1), Ge(3));
1549   EXPECT_EQ("(is less than or equal to 1) or "
1550             "(is greater than or equal to 3)",
1551             Describe(m));
1552 
1553   m = AnyOf(Lt(0), Eq(1), Eq(2));
1554   EXPECT_EQ("(is less than 0) or "
1555             "((is equal to 1) or (is equal to 2))",
1556             Describe(m));
1557 
1558   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
1559   EXPECT_EQ("(is less than 0) or "
1560             "((is equal to 1) or "
1561             "((is equal to 2) or "
1562             "(is equal to 3)))",
1563             Describe(m));
1564 
1565   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
1566   EXPECT_EQ("(is less than or equal to 0) or "
1567             "((is greater than 10) or "
1568             "((is equal to 3) or "
1569             "((is equal to 5) or "
1570             "(is equal to 7))))",
1571             Describe(m));
1572 }
1573 
1574 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest,AnyOfMatcherSafelyCastsMonomorphicMatchers)1575 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
1576   // greater_than_5 and less_than_10 are monomorphic matchers.
1577   Matcher<int> greater_than_5 = Gt(5);
1578   Matcher<int> less_than_10 = Lt(10);
1579 
1580   Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
1581   Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
1582   Matcher<int&> m3 = AnyOf(greater_than_5, m2);
1583 
1584   // Tests that EitherOf works when composing itself.
1585   Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
1586   Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
1587 }
1588 
1589 // The following predicate function and predicate functor are for
1590 // testing the Truly(predicate) matcher.
1591 
1592 // Returns non-zero if the input is positive.  Note that the return
1593 // type of this function is not bool.  It's OK as Truly() accepts any
1594 // unary function or functor whose return type can be implicitly
1595 // converted to bool.
IsPositive(double x)1596 int IsPositive(double x) {
1597   return x > 0 ? 1 : 0;
1598 }
1599 
1600 // This functor returns true if the input is greater than the given
1601 // number.
1602 class IsGreaterThan {
1603  public:
IsGreaterThan(int threshold)1604   explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
1605 
operator ()(int n) const1606   bool operator()(int n) const { return n > threshold_; }
1607  private:
1608   const int threshold_;
1609 };
1610 
1611 // For testing Truly().
1612 const int foo = 0;
1613 
1614 // This predicate returns true iff the argument references foo and has
1615 // a zero value.
ReferencesFooAndIsZero(const int & n)1616 bool ReferencesFooAndIsZero(const int& n) {
1617   return (&n == &foo) && (n == 0);
1618 }
1619 
1620 // Tests that Truly(predicate) matches what satisfies the given
1621 // predicate.
TEST(TrulyTest,MatchesWhatSatisfiesThePredicate)1622 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
1623   Matcher<double> m = Truly(IsPositive);
1624   EXPECT_TRUE(m.Matches(2.0));
1625   EXPECT_FALSE(m.Matches(-1.5));
1626 }
1627 
1628 // Tests that Truly(predicate_functor) works too.
TEST(TrulyTest,CanBeUsedWithFunctor)1629 TEST(TrulyTest, CanBeUsedWithFunctor) {
1630   Matcher<int> m = Truly(IsGreaterThan(5));
1631   EXPECT_TRUE(m.Matches(6));
1632   EXPECT_FALSE(m.Matches(4));
1633 }
1634 
1635 // Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest,CanDescribeSelf)1636 TEST(TrulyTest, CanDescribeSelf) {
1637   Matcher<double> m = Truly(IsPositive);
1638   EXPECT_EQ("satisfies the given predicate",
1639             Describe(m));
1640 }
1641 
1642 // Tests that Truly(predicate) works when the matcher takes its
1643 // argument by reference.
TEST(TrulyTest,WorksForByRefArguments)1644 TEST(TrulyTest, WorksForByRefArguments) {
1645   Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
1646   EXPECT_TRUE(m.Matches(foo));
1647   int n = 0;
1648   EXPECT_FALSE(m.Matches(n));
1649 }
1650 
1651 // Tests that Matches(m) is a predicate satisfied by whatever that
1652 // matches matcher m.
TEST(MatchesTest,IsSatisfiedByWhatMatchesTheMatcher)1653 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
1654   EXPECT_TRUE(Matches(Ge(0))(1));
1655   EXPECT_FALSE(Matches(Eq('a'))('b'));
1656 }
1657 
1658 // Tests that Matches(m) works when the matcher takes its argument by
1659 // reference.
TEST(MatchesTest,WorksOnByRefArguments)1660 TEST(MatchesTest, WorksOnByRefArguments) {
1661   int m = 0, n = 0;
1662   EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
1663   EXPECT_FALSE(Matches(Ref(m))(n));
1664 }
1665 
1666 // Tests that a Matcher on non-reference type can be used in
1667 // Matches().
TEST(MatchesTest,WorksWithMatcherOnNonRefType)1668 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
1669   Matcher<int> eq5 = Eq(5);
1670   EXPECT_TRUE(Matches(eq5)(5));
1671   EXPECT_FALSE(Matches(eq5)(2));
1672 }
1673 
1674 // Tests Value(value, matcher).  Since Value() is a simple wrapper for
1675 // Matches(), which has been tested already, we don't spend a lot of
1676 // effort on testing Value().
TEST(ValueTest,WorksWithPolymorphicMatcher)1677 TEST(ValueTest, WorksWithPolymorphicMatcher) {
1678   EXPECT_TRUE(Value("hi", StartsWith("h")));
1679   EXPECT_FALSE(Value(5, Gt(10)));
1680 }
1681 
TEST(ValueTest,WorksWithMonomorphicMatcher)1682 TEST(ValueTest, WorksWithMonomorphicMatcher) {
1683   const Matcher<int> is_zero = Eq(0);
1684   EXPECT_TRUE(Value(0, is_zero));
1685   EXPECT_FALSE(Value('a', is_zero));
1686 
1687   int n = 0;
1688   const Matcher<const int&> ref_n = Ref(n);
1689   EXPECT_TRUE(Value(n, ref_n));
1690   EXPECT_FALSE(Value(1, ref_n));
1691 }
1692 
TEST(AllArgsTest,WorksForTuple)1693 TEST(AllArgsTest, WorksForTuple) {
1694   EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
1695   EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
1696 }
1697 
TEST(AllArgsTest,WorksForNonTuple)1698 TEST(AllArgsTest, WorksForNonTuple) {
1699   EXPECT_THAT(42, AllArgs(Gt(0)));
1700   EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
1701 }
1702 
1703 class AllArgsHelper {
1704  public:
1705   MOCK_METHOD2(Helper, int(char x, int y));
1706 };
1707 
TEST(AllArgsTest,WorksInWithClause)1708 TEST(AllArgsTest, WorksInWithClause) {
1709   AllArgsHelper helper;
1710   ON_CALL(helper, Helper(_, _))
1711       .With(AllArgs(Lt()))
1712       .WillByDefault(Return(1));
1713   EXPECT_CALL(helper, Helper(_, _));
1714   EXPECT_CALL(helper, Helper(_, _))
1715       .With(AllArgs(Gt()))
1716       .WillOnce(Return(2));
1717 
1718   EXPECT_EQ(1, helper.Helper('\1', 2));
1719   EXPECT_EQ(2, helper.Helper('a', 1));
1720 }
1721 
1722 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
1723 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)1724 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
1725   ASSERT_THAT(5, Ge(2)) << "This should succeed.";
1726   ASSERT_THAT("Foo", EndsWith("oo"));
1727   EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
1728   EXPECT_THAT("Hello", StartsWith("Hell"));
1729 }
1730 
1731 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
1732 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)1733 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
1734   // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
1735   // which cannot reference auto variables.
1736   static int n;
1737   n = 5;
1738   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)) << "This should fail.",
1739                        "Value of: n\n"
1740                        "Expected: is greater than 10\n"
1741                        "  Actual: 5\n"
1742                        "This should fail.");
1743   n = 0;
1744   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
1745                           "Value of: n\n"
1746                           "Expected: (is less than or equal to 7) and "
1747                           "(is greater than or equal to 5)\n"
1748                           "  Actual: 0");
1749 }
1750 
1751 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
1752 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)1753 TEST(MatcherAssertionTest, WorksForByRefArguments) {
1754   // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
1755   // reference auto variables.
1756   static int n;
1757   n = 0;
1758   EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
1759   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
1760                        "Value of: n\n"
1761                        "Expected: does not reference the variable @");
1762   // Tests the "Actual" part.
1763   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
1764                        "Actual: 0 (is located @");
1765 }
1766 
1767 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
1768 // monomorphic.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)1769 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
1770   Matcher<const char*> starts_with_he = StartsWith("he");
1771   ASSERT_THAT("hello", starts_with_he);
1772 
1773   Matcher<const string&> ends_with_ok = EndsWith("ok");
1774   ASSERT_THAT("book", ends_with_ok);
1775 
1776   Matcher<int> is_greater_than_5 = Gt(5);
1777   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
1778                           "Value of: 5\n"
1779                           "Expected: is greater than 5\n"
1780                           "  Actual: 5");
1781 }
1782 
1783 // Tests floating-point matchers.
1784 template <typename RawType>
1785 class FloatingPointTest : public testing::Test {
1786  protected:
1787   typedef typename testing::internal::FloatingPoint<RawType> Floating;
1788   typedef typename Floating::Bits Bits;
1789 
SetUp()1790   virtual void SetUp() {
1791     const size_t max_ulps = Floating::kMaxUlps;
1792 
1793     // The bits that represent 0.0.
1794     const Bits zero_bits = Floating(0).bits();
1795 
1796     // Makes some numbers close to 0.0.
1797     close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
1798     close_to_negative_zero_ = -Floating::ReinterpretBits(
1799         zero_bits + max_ulps - max_ulps/2);
1800     further_from_negative_zero_ = -Floating::ReinterpretBits(
1801         zero_bits + max_ulps + 1 - max_ulps/2);
1802 
1803     // The bits that represent 1.0.
1804     const Bits one_bits = Floating(1).bits();
1805 
1806     // Makes some numbers close to 1.0.
1807     close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
1808     further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
1809 
1810     // +infinity.
1811     infinity_ = Floating::Infinity();
1812 
1813     // The bits that represent +infinity.
1814     const Bits infinity_bits = Floating(infinity_).bits();
1815 
1816     // Makes some numbers close to infinity.
1817     close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
1818     further_from_infinity_ = Floating::ReinterpretBits(
1819         infinity_bits - max_ulps - 1);
1820 
1821     // Makes some NAN's.
1822     nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
1823     nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
1824   }
1825 
TestSize()1826   void TestSize() {
1827     EXPECT_EQ(sizeof(RawType), sizeof(Bits));
1828   }
1829 
1830   // A battery of tests for FloatingEqMatcher::Matches.
1831   // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType))1832   void TestMatches(
1833       testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
1834     Matcher<RawType> m1 = matcher_maker(0.0);
1835     EXPECT_TRUE(m1.Matches(-0.0));
1836     EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
1837     EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
1838     EXPECT_FALSE(m1.Matches(1.0));
1839 
1840     Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
1841     EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
1842 
1843     Matcher<RawType> m3 = matcher_maker(1.0);
1844     EXPECT_TRUE(m3.Matches(close_to_one_));
1845     EXPECT_FALSE(m3.Matches(further_from_one_));
1846 
1847     // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
1848     EXPECT_FALSE(m3.Matches(0.0));
1849 
1850     Matcher<RawType> m4 = matcher_maker(-infinity_);
1851     EXPECT_TRUE(m4.Matches(-close_to_infinity_));
1852 
1853     Matcher<RawType> m5 = matcher_maker(infinity_);
1854     EXPECT_TRUE(m5.Matches(close_to_infinity_));
1855 
1856     // This is interesting as the representations of infinity_ and nan1_
1857     // are only 1 DLP apart.
1858     EXPECT_FALSE(m5.Matches(nan1_));
1859 
1860     // matcher_maker can produce a Matcher<const RawType&>, which is needed in
1861     // some cases.
1862     Matcher<const RawType&> m6 = matcher_maker(0.0);
1863     EXPECT_TRUE(m6.Matches(-0.0));
1864     EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
1865     EXPECT_FALSE(m6.Matches(1.0));
1866 
1867     // matcher_maker can produce a Matcher<RawType&>, which is needed in some
1868     // cases.
1869     Matcher<RawType&> m7 = matcher_maker(0.0);
1870     RawType x = 0.0;
1871     EXPECT_TRUE(m7.Matches(x));
1872     x = 0.01f;
1873     EXPECT_FALSE(m7.Matches(x));
1874   }
1875 
1876   // Pre-calculated numbers to be used by the tests.
1877 
1878   static RawType close_to_positive_zero_;
1879   static RawType close_to_negative_zero_;
1880   static RawType further_from_negative_zero_;
1881 
1882   static RawType close_to_one_;
1883   static RawType further_from_one_;
1884 
1885   static RawType infinity_;
1886   static RawType close_to_infinity_;
1887   static RawType further_from_infinity_;
1888 
1889   static RawType nan1_;
1890   static RawType nan2_;
1891 };
1892 
1893 template <typename RawType>
1894 RawType FloatingPointTest<RawType>::close_to_positive_zero_;
1895 
1896 template <typename RawType>
1897 RawType FloatingPointTest<RawType>::close_to_negative_zero_;
1898 
1899 template <typename RawType>
1900 RawType FloatingPointTest<RawType>::further_from_negative_zero_;
1901 
1902 template <typename RawType>
1903 RawType FloatingPointTest<RawType>::close_to_one_;
1904 
1905 template <typename RawType>
1906 RawType FloatingPointTest<RawType>::further_from_one_;
1907 
1908 template <typename RawType>
1909 RawType FloatingPointTest<RawType>::infinity_;
1910 
1911 template <typename RawType>
1912 RawType FloatingPointTest<RawType>::close_to_infinity_;
1913 
1914 template <typename RawType>
1915 RawType FloatingPointTest<RawType>::further_from_infinity_;
1916 
1917 template <typename RawType>
1918 RawType FloatingPointTest<RawType>::nan1_;
1919 
1920 template <typename RawType>
1921 RawType FloatingPointTest<RawType>::nan2_;
1922 
1923 // Instantiate FloatingPointTest for testing floats.
1924 typedef FloatingPointTest<float> FloatTest;
1925 
TEST_F(FloatTest,FloatEqApproximatelyMatchesFloats)1926 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
1927   TestMatches(&FloatEq);
1928 }
1929 
TEST_F(FloatTest,NanSensitiveFloatEqApproximatelyMatchesFloats)1930 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
1931   TestMatches(&NanSensitiveFloatEq);
1932 }
1933 
TEST_F(FloatTest,FloatEqCannotMatchNaN)1934 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
1935   // FloatEq never matches NaN.
1936   Matcher<float> m = FloatEq(nan1_);
1937   EXPECT_FALSE(m.Matches(nan1_));
1938   EXPECT_FALSE(m.Matches(nan2_));
1939   EXPECT_FALSE(m.Matches(1.0));
1940 }
1941 
TEST_F(FloatTest,NanSensitiveFloatEqCanMatchNaN)1942 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
1943   // NanSensitiveFloatEq will match NaN.
1944   Matcher<float> m = NanSensitiveFloatEq(nan1_);
1945   EXPECT_TRUE(m.Matches(nan1_));
1946   EXPECT_TRUE(m.Matches(nan2_));
1947   EXPECT_FALSE(m.Matches(1.0));
1948 }
1949 
TEST_F(FloatTest,FloatEqCanDescribeSelf)1950 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
1951   Matcher<float> m1 = FloatEq(2.0f);
1952   EXPECT_EQ("is approximately 2", Describe(m1));
1953   EXPECT_EQ("is not approximately 2", DescribeNegation(m1));
1954 
1955   Matcher<float> m2 = FloatEq(0.5f);
1956   EXPECT_EQ("is approximately 0.5", Describe(m2));
1957   EXPECT_EQ("is not approximately 0.5", DescribeNegation(m2));
1958 
1959   Matcher<float> m3 = FloatEq(nan1_);
1960   EXPECT_EQ("never matches", Describe(m3));
1961   EXPECT_EQ("is anything", DescribeNegation(m3));
1962 }
1963 
TEST_F(FloatTest,NanSensitiveFloatEqCanDescribeSelf)1964 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
1965   Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
1966   EXPECT_EQ("is approximately 2", Describe(m1));
1967   EXPECT_EQ("is not approximately 2", DescribeNegation(m1));
1968 
1969   Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
1970   EXPECT_EQ("is approximately 0.5", Describe(m2));
1971   EXPECT_EQ("is not approximately 0.5", DescribeNegation(m2));
1972 
1973   Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
1974   EXPECT_EQ("is NaN", Describe(m3));
1975   EXPECT_EQ("is not NaN", DescribeNegation(m3));
1976 }
1977 
1978 // Instantiate FloatingPointTest for testing doubles.
1979 typedef FloatingPointTest<double> DoubleTest;
1980 
TEST_F(DoubleTest,DoubleEqApproximatelyMatchesDoubles)1981 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
1982   TestMatches(&DoubleEq);
1983 }
1984 
TEST_F(DoubleTest,NanSensitiveDoubleEqApproximatelyMatchesDoubles)1985 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
1986   TestMatches(&NanSensitiveDoubleEq);
1987 }
1988 
TEST_F(DoubleTest,DoubleEqCannotMatchNaN)1989 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
1990   // DoubleEq never matches NaN.
1991   Matcher<double> m = DoubleEq(nan1_);
1992   EXPECT_FALSE(m.Matches(nan1_));
1993   EXPECT_FALSE(m.Matches(nan2_));
1994   EXPECT_FALSE(m.Matches(1.0));
1995 }
1996 
TEST_F(DoubleTest,NanSensitiveDoubleEqCanMatchNaN)1997 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
1998   // NanSensitiveDoubleEq will match NaN.
1999   Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2000   EXPECT_TRUE(m.Matches(nan1_));
2001   EXPECT_TRUE(m.Matches(nan2_));
2002   EXPECT_FALSE(m.Matches(1.0));
2003 }
2004 
TEST_F(DoubleTest,DoubleEqCanDescribeSelf)2005 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
2006   Matcher<double> m1 = DoubleEq(2.0);
2007   EXPECT_EQ("is approximately 2", Describe(m1));
2008   EXPECT_EQ("is not approximately 2", DescribeNegation(m1));
2009 
2010   Matcher<double> m2 = DoubleEq(0.5);
2011   EXPECT_EQ("is approximately 0.5", Describe(m2));
2012   EXPECT_EQ("is not approximately 0.5", DescribeNegation(m2));
2013 
2014   Matcher<double> m3 = DoubleEq(nan1_);
2015   EXPECT_EQ("never matches", Describe(m3));
2016   EXPECT_EQ("is anything", DescribeNegation(m3));
2017 }
2018 
TEST_F(DoubleTest,NanSensitiveDoubleEqCanDescribeSelf)2019 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
2020   Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
2021   EXPECT_EQ("is approximately 2", Describe(m1));
2022   EXPECT_EQ("is not approximately 2", DescribeNegation(m1));
2023 
2024   Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
2025   EXPECT_EQ("is approximately 0.5", Describe(m2));
2026   EXPECT_EQ("is not approximately 0.5", DescribeNegation(m2));
2027 
2028   Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
2029   EXPECT_EQ("is NaN", Describe(m3));
2030   EXPECT_EQ("is not NaN", DescribeNegation(m3));
2031 }
2032 
TEST(PointeeTest,RawPointer)2033 TEST(PointeeTest, RawPointer) {
2034   const Matcher<int*> m = Pointee(Ge(0));
2035 
2036   int n = 1;
2037   EXPECT_TRUE(m.Matches(&n));
2038   n = -1;
2039   EXPECT_FALSE(m.Matches(&n));
2040   EXPECT_FALSE(m.Matches(NULL));
2041 }
2042 
TEST(PointeeTest,RawPointerToConst)2043 TEST(PointeeTest, RawPointerToConst) {
2044   const Matcher<const double*> m = Pointee(Ge(0));
2045 
2046   double x = 1;
2047   EXPECT_TRUE(m.Matches(&x));
2048   x = -1;
2049   EXPECT_FALSE(m.Matches(&x));
2050   EXPECT_FALSE(m.Matches(NULL));
2051 }
2052 
TEST(PointeeTest,ReferenceToConstRawPointer)2053 TEST(PointeeTest, ReferenceToConstRawPointer) {
2054   const Matcher<int* const &> m = Pointee(Ge(0));
2055 
2056   int n = 1;
2057   EXPECT_TRUE(m.Matches(&n));
2058   n = -1;
2059   EXPECT_FALSE(m.Matches(&n));
2060   EXPECT_FALSE(m.Matches(NULL));
2061 }
2062 
TEST(PointeeTest,ReferenceToNonConstRawPointer)2063 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
2064   const Matcher<double* &> m = Pointee(Ge(0));
2065 
2066   double x = 1.0;
2067   double* p = &x;
2068   EXPECT_TRUE(m.Matches(p));
2069   x = -1;
2070   EXPECT_FALSE(m.Matches(p));
2071   p = NULL;
2072   EXPECT_FALSE(m.Matches(p));
2073 }
2074 
TEST(PointeeTest,NeverMatchesNull)2075 TEST(PointeeTest, NeverMatchesNull) {
2076   const Matcher<const char*> m = Pointee(_);
2077   EXPECT_FALSE(m.Matches(NULL));
2078 }
2079 
2080 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)2081 TEST(PointeeTest, MatchesAgainstAValue) {
2082   const Matcher<int*> m = Pointee(5);
2083 
2084   int n = 5;
2085   EXPECT_TRUE(m.Matches(&n));
2086   n = -1;
2087   EXPECT_FALSE(m.Matches(&n));
2088   EXPECT_FALSE(m.Matches(NULL));
2089 }
2090 
TEST(PointeeTest,CanDescribeSelf)2091 TEST(PointeeTest, CanDescribeSelf) {
2092   const Matcher<int*> m = Pointee(Gt(3));
2093   EXPECT_EQ("points to a value that is greater than 3", Describe(m));
2094   EXPECT_EQ("does not point to a value that is greater than 3",
2095             DescribeNegation(m));
2096 }
2097 
2098 // For testing ExplainMatchResultTo().
2099 class GreaterThanMatcher : public MatcherInterface<int> {
2100  public:
GreaterThanMatcher(int rhs)2101   explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
2102 
Matches(int lhs) const2103   virtual bool Matches(int lhs) const { return lhs > rhs_; }
2104 
DescribeTo(::std::ostream * os) const2105   virtual void DescribeTo(::std::ostream* os) const {
2106     *os << "is greater than " << rhs_;
2107   }
2108 
ExplainMatchResultTo(int lhs,::std::ostream * os) const2109   virtual void ExplainMatchResultTo(int lhs, ::std::ostream* os) const {
2110     const int diff = lhs - rhs_;
2111     if (diff > 0) {
2112       *os << "is " << diff << " more than " << rhs_;
2113     } else if (diff == 0) {
2114       *os << "is the same as " << rhs_;
2115     } else {
2116       *os << "is " << -diff << " less than " << rhs_;
2117     }
2118   }
2119  private:
2120   const int rhs_;
2121 };
2122 
GreaterThan(int n)2123 Matcher<int> GreaterThan(int n) {
2124   return MakeMatcher(new GreaterThanMatcher(n));
2125 }
2126 
TEST(PointeeTest,CanExplainMatchResult)2127 TEST(PointeeTest, CanExplainMatchResult) {
2128   const Matcher<const string*> m = Pointee(StartsWith("Hi"));
2129 
2130   EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
2131 
2132   const Matcher<int*> m2 = Pointee(GreaterThan(1));
2133   int n = 3;
2134   EXPECT_EQ("points to a value that is 2 more than 1", Explain(m2, &n));
2135 }
2136 
2137 // An uncopyable class.
2138 class Uncopyable {
2139  public:
Uncopyable(int value)2140   explicit Uncopyable(int value) : value_(value) {}
2141 
value() const2142   int value() const { return value_; }
2143  private:
2144   const int value_;
2145   GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
2146 };
2147 
2148 // Returns true iff x.value() is positive.
ValueIsPositive(const Uncopyable & x)2149 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
2150 
2151 // A user-defined struct for testing Field().
2152 struct AStruct {
AStructtesting::gmock_matchers_test::AStruct2153   AStruct() : x(0), y(1.0), z(5), p(NULL) {}
AStructtesting::gmock_matchers_test::AStruct2154   AStruct(const AStruct& rhs)
2155       : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
2156 
2157   int x;           // A non-const field.
2158   const double y;  // A const field.
2159   Uncopyable z;    // An uncopyable field.
2160   const char* p;   // A pointer field.
2161 };
2162 
2163 // A derived struct for testing Field().
2164 struct DerivedStruct : public AStruct {
2165   char ch;
2166 };
2167 
2168 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)2169 TEST(FieldTest, WorksForNonConstField) {
2170   Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
2171 
2172   AStruct a;
2173   EXPECT_TRUE(m.Matches(a));
2174   a.x = -1;
2175   EXPECT_FALSE(m.Matches(a));
2176 }
2177 
2178 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)2179 TEST(FieldTest, WorksForConstField) {
2180   AStruct a;
2181 
2182   Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
2183   EXPECT_TRUE(m.Matches(a));
2184   m = Field(&AStruct::y, Le(0.0));
2185   EXPECT_FALSE(m.Matches(a));
2186 }
2187 
2188 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)2189 TEST(FieldTest, WorksForUncopyableField) {
2190   AStruct a;
2191 
2192   Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
2193   EXPECT_TRUE(m.Matches(a));
2194   m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
2195   EXPECT_FALSE(m.Matches(a));
2196 }
2197 
2198 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)2199 TEST(FieldTest, WorksForPointerField) {
2200   // Matching against NULL.
2201   Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
2202   AStruct a;
2203   EXPECT_TRUE(m.Matches(a));
2204   a.p = "hi";
2205   EXPECT_FALSE(m.Matches(a));
2206 
2207   // Matching a pointer that is not NULL.
2208   m = Field(&AStruct::p, StartsWith("hi"));
2209   a.p = "hill";
2210   EXPECT_TRUE(m.Matches(a));
2211   a.p = "hole";
2212   EXPECT_FALSE(m.Matches(a));
2213 }
2214 
2215 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)2216 TEST(FieldTest, WorksForByRefArgument) {
2217   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
2218 
2219   AStruct a;
2220   EXPECT_TRUE(m.Matches(a));
2221   a.x = -1;
2222   EXPECT_FALSE(m.Matches(a));
2223 }
2224 
2225 // Tests that Field(&Foo::field, ...) works when the argument's type
2226 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)2227 TEST(FieldTest, WorksForArgumentOfSubType) {
2228   // Note that the matcher expects DerivedStruct but we say AStruct
2229   // inside Field().
2230   Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
2231 
2232   DerivedStruct d;
2233   EXPECT_TRUE(m.Matches(d));
2234   d.x = -1;
2235   EXPECT_FALSE(m.Matches(d));
2236 }
2237 
2238 // Tests that Field(&Foo::field, m) works when field's type and m's
2239 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)2240 TEST(FieldTest, WorksForCompatibleMatcherType) {
2241   // The field is an int, but the inner matcher expects a signed char.
2242   Matcher<const AStruct&> m = Field(&AStruct::x,
2243                                     Matcher<signed char>(Ge(0)));
2244 
2245   AStruct a;
2246   EXPECT_TRUE(m.Matches(a));
2247   a.x = -1;
2248   EXPECT_FALSE(m.Matches(a));
2249 }
2250 
2251 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)2252 TEST(FieldTest, CanDescribeSelf) {
2253   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
2254 
2255   EXPECT_EQ("the given field is greater than or equal to 0", Describe(m));
2256   EXPECT_EQ("the given field is not greater than or equal to 0",
2257             DescribeNegation(m));
2258 }
2259 
2260 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)2261 TEST(FieldTest, CanExplainMatchResult) {
2262   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
2263 
2264   AStruct a;
2265   a.x = 1;
2266   EXPECT_EQ("", Explain(m, a));
2267 
2268   m = Field(&AStruct::x, GreaterThan(0));
2269   EXPECT_EQ("the given field is 1 more than 0", Explain(m, a));
2270 }
2271 
2272 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)2273 TEST(FieldForPointerTest, WorksForPointerToConst) {
2274   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
2275 
2276   AStruct a;
2277   EXPECT_TRUE(m.Matches(&a));
2278   a.x = -1;
2279   EXPECT_FALSE(m.Matches(&a));
2280 }
2281 
2282 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)2283 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
2284   Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
2285 
2286   AStruct a;
2287   EXPECT_TRUE(m.Matches(&a));
2288   a.x = -1;
2289   EXPECT_FALSE(m.Matches(&a));
2290 }
2291 
2292 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)2293 TEST(FieldForPointerTest, DoesNotMatchNull) {
2294   Matcher<const AStruct*> m = Field(&AStruct::x, _);
2295   EXPECT_FALSE(m.Matches(NULL));
2296 }
2297 
2298 // Tests that Field(&Foo::field, ...) works when the argument's type
2299 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)2300 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
2301   // Note that the matcher expects DerivedStruct but we say AStruct
2302   // inside Field().
2303   Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
2304 
2305   DerivedStruct d;
2306   EXPECT_TRUE(m.Matches(&d));
2307   d.x = -1;
2308   EXPECT_FALSE(m.Matches(&d));
2309 }
2310 
2311 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)2312 TEST(FieldForPointerTest, CanDescribeSelf) {
2313   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
2314 
2315   EXPECT_EQ("the given field is greater than or equal to 0", Describe(m));
2316   EXPECT_EQ("the given field is not greater than or equal to 0",
2317             DescribeNegation(m));
2318 }
2319 
2320 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)2321 TEST(FieldForPointerTest, CanExplainMatchResult) {
2322   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
2323 
2324   AStruct a;
2325   a.x = 1;
2326   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
2327   EXPECT_EQ("", Explain(m, &a));
2328 
2329   m = Field(&AStruct::x, GreaterThan(0));
2330   EXPECT_EQ("the given field is 1 more than 0", Explain(m, &a));
2331 }
2332 
2333 // A user-defined class for testing Property().
2334 class AClass {
2335  public:
AClass()2336   AClass() : n_(0) {}
2337 
2338   // A getter that returns a non-reference.
n() const2339   int n() const { return n_; }
2340 
set_n(int new_n)2341   void set_n(int new_n) { n_ = new_n; }
2342 
2343   // A getter that returns a reference to const.
s() const2344   const string& s() const { return s_; }
2345 
set_s(const string & new_s)2346   void set_s(const string& new_s) { s_ = new_s; }
2347 
2348   // A getter that returns a reference to non-const.
x() const2349   double& x() const { return x_; }
2350  private:
2351   int n_;
2352   string s_;
2353 
2354   static double x_;
2355 };
2356 
2357 double AClass::x_ = 0.0;
2358 
2359 // A derived class for testing Property().
2360 class DerivedClass : public AClass {
2361  private:
2362   int k_;
2363 };
2364 
2365 // Tests that Property(&Foo::property, ...) works when property()
2366 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)2367 TEST(PropertyTest, WorksForNonReferenceProperty) {
2368   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
2369 
2370   AClass a;
2371   a.set_n(1);
2372   EXPECT_TRUE(m.Matches(a));
2373 
2374   a.set_n(-1);
2375   EXPECT_FALSE(m.Matches(a));
2376 }
2377 
2378 // Tests that Property(&Foo::property, ...) works when property()
2379 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)2380 TEST(PropertyTest, WorksForReferenceToConstProperty) {
2381   Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
2382 
2383   AClass a;
2384   a.set_s("hill");
2385   EXPECT_TRUE(m.Matches(a));
2386 
2387   a.set_s("hole");
2388   EXPECT_FALSE(m.Matches(a));
2389 }
2390 
2391 // Tests that Property(&Foo::property, ...) works when property()
2392 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)2393 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
2394   double x = 0.0;
2395   AClass a;
2396 
2397   Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
2398   EXPECT_FALSE(m.Matches(a));
2399 
2400   m = Property(&AClass::x, Not(Ref(x)));
2401   EXPECT_TRUE(m.Matches(a));
2402 }
2403 
2404 // Tests that Property(&Foo::property, ...) works when the argument is
2405 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)2406 TEST(PropertyTest, WorksForByValueArgument) {
2407   Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
2408 
2409   AClass a;
2410   a.set_s("hill");
2411   EXPECT_TRUE(m.Matches(a));
2412 
2413   a.set_s("hole");
2414   EXPECT_FALSE(m.Matches(a));
2415 }
2416 
2417 // Tests that Property(&Foo::property, ...) works when the argument's
2418 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)2419 TEST(PropertyTest, WorksForArgumentOfSubType) {
2420   // The matcher expects a DerivedClass, but inside the Property() we
2421   // say AClass.
2422   Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
2423 
2424   DerivedClass d;
2425   d.set_n(1);
2426   EXPECT_TRUE(m.Matches(d));
2427 
2428   d.set_n(-1);
2429   EXPECT_FALSE(m.Matches(d));
2430 }
2431 
2432 // Tests that Property(&Foo::property, m) works when property()'s type
2433 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)2434 TEST(PropertyTest, WorksForCompatibleMatcherType) {
2435   // n() returns an int but the inner matcher expects a signed char.
2436   Matcher<const AClass&> m = Property(&AClass::n,
2437                                       Matcher<signed char>(Ge(0)));
2438 
2439   AClass a;
2440   EXPECT_TRUE(m.Matches(a));
2441   a.set_n(-1);
2442   EXPECT_FALSE(m.Matches(a));
2443 }
2444 
2445 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)2446 TEST(PropertyTest, CanDescribeSelf) {
2447   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
2448 
2449   EXPECT_EQ("the given property is greater than or equal to 0", Describe(m));
2450   EXPECT_EQ("the given property is not greater than or equal to 0",
2451             DescribeNegation(m));
2452 }
2453 
2454 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)2455 TEST(PropertyTest, CanExplainMatchResult) {
2456   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
2457 
2458   AClass a;
2459   a.set_n(1);
2460   EXPECT_EQ("", Explain(m, a));
2461 
2462   m = Property(&AClass::n, GreaterThan(0));
2463   EXPECT_EQ("the given property is 1 more than 0", Explain(m, a));
2464 }
2465 
2466 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)2467 TEST(PropertyForPointerTest, WorksForPointerToConst) {
2468   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
2469 
2470   AClass a;
2471   a.set_n(1);
2472   EXPECT_TRUE(m.Matches(&a));
2473 
2474   a.set_n(-1);
2475   EXPECT_FALSE(m.Matches(&a));
2476 }
2477 
2478 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)2479 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
2480   Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
2481 
2482   AClass a;
2483   a.set_s("hill");
2484   EXPECT_TRUE(m.Matches(&a));
2485 
2486   a.set_s("hole");
2487   EXPECT_FALSE(m.Matches(&a));
2488 }
2489 
2490 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)2491 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
2492   Matcher<const AClass*> m = Property(&AClass::x, _);
2493   EXPECT_FALSE(m.Matches(NULL));
2494 }
2495 
2496 // Tests that Property(&Foo::property, ...) works when the argument's
2497 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)2498 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
2499   // The matcher expects a DerivedClass, but inside the Property() we
2500   // say AClass.
2501   Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
2502 
2503   DerivedClass d;
2504   d.set_n(1);
2505   EXPECT_TRUE(m.Matches(&d));
2506 
2507   d.set_n(-1);
2508   EXPECT_FALSE(m.Matches(&d));
2509 }
2510 
2511 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)2512 TEST(PropertyForPointerTest, CanDescribeSelf) {
2513   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
2514 
2515   EXPECT_EQ("the given property is greater than or equal to 0", Describe(m));
2516   EXPECT_EQ("the given property is not greater than or equal to 0",
2517             DescribeNegation(m));
2518 }
2519 
2520 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)2521 TEST(PropertyForPointerTest, CanExplainMatchResult) {
2522   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
2523 
2524   AClass a;
2525   a.set_n(1);
2526   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
2527   EXPECT_EQ("", Explain(m, &a));
2528 
2529   m = Property(&AClass::n, GreaterThan(0));
2530   EXPECT_EQ("the given property is 1 more than 0", Explain(m, &a));
2531 }
2532 
2533 // Tests ResultOf.
2534 
2535 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
2536 // function pointer.
IntToStringFunction(int input)2537 string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
2538 
TEST(ResultOfTest,WorksForFunctionPointers)2539 TEST(ResultOfTest, WorksForFunctionPointers) {
2540   Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
2541 
2542   EXPECT_TRUE(matcher.Matches(1));
2543   EXPECT_FALSE(matcher.Matches(2));
2544 }
2545 
2546 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)2547 TEST(ResultOfTest, CanDescribeItself) {
2548   Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
2549 
2550   EXPECT_EQ("result of the given callable is equal to \"foo\"",
2551             Describe(matcher));
2552   EXPECT_EQ("result of the given callable is not equal to \"foo\"",
2553             DescribeNegation(matcher));
2554 }
2555 
2556 // Tests that ResultOf() can explain the match result.
IntFunction(int input)2557 int IntFunction(int input) { return input == 42 ? 80 : 90; }
2558 
TEST(ResultOfTest,CanExplainMatchResult)2559 TEST(ResultOfTest, CanExplainMatchResult) {
2560   Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
2561   EXPECT_EQ("", Explain(matcher, 36));
2562 
2563   matcher = ResultOf(&IntFunction, GreaterThan(85));
2564   EXPECT_EQ("result of the given callable is 5 more than 85",
2565             Explain(matcher, 36));
2566 }
2567 
2568 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
2569 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)2570 TEST(ResultOfTest, WorksForNonReferenceResults) {
2571   Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
2572 
2573   EXPECT_TRUE(matcher.Matches(42));
2574   EXPECT_FALSE(matcher.Matches(36));
2575 }
2576 
2577 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
2578 // returns a reference to non-const.
DoubleFunction(double & input)2579 double& DoubleFunction(double& input) { return input; }
2580 
RefUncopyableFunction(Uncopyable & obj)2581 Uncopyable& RefUncopyableFunction(Uncopyable& obj) {
2582   return obj;
2583 }
2584 
TEST(ResultOfTest,WorksForReferenceToNonConstResults)2585 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
2586   double x = 3.14;
2587   double x2 = x;
2588   Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
2589 
2590   EXPECT_TRUE(matcher.Matches(x));
2591   EXPECT_FALSE(matcher.Matches(x2));
2592 
2593   // Test that ResultOf works with uncopyable objects
2594   Uncopyable obj(0);
2595   Uncopyable obj2(0);
2596   Matcher<Uncopyable&> matcher2 =
2597       ResultOf(&RefUncopyableFunction, Ref(obj));
2598 
2599   EXPECT_TRUE(matcher2.Matches(obj));
2600   EXPECT_FALSE(matcher2.Matches(obj2));
2601 }
2602 
2603 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
2604 // returns a reference to const.
StringFunction(const string & input)2605 const string& StringFunction(const string& input) { return input; }
2606 
TEST(ResultOfTest,WorksForReferenceToConstResults)2607 TEST(ResultOfTest, WorksForReferenceToConstResults) {
2608   string s = "foo";
2609   string s2 = s;
2610   Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
2611 
2612   EXPECT_TRUE(matcher.Matches(s));
2613   EXPECT_FALSE(matcher.Matches(s2));
2614 }
2615 
2616 // Tests that ResultOf(f, m) works when f(x) and m's
2617 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)2618 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
2619   // IntFunction() returns int but the inner matcher expects a signed char.
2620   Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
2621 
2622   EXPECT_TRUE(matcher.Matches(36));
2623   EXPECT_FALSE(matcher.Matches(42));
2624 }
2625 
2626 #if GTEST_HAS_DEATH_TEST
2627 // Tests that the program aborts when ResultOf is passed
2628 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)2629 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
2630   EXPECT_DEATH(
2631       ResultOf(static_cast<string(*)(int)>(NULL), Eq(string("foo"))),
2632                "NULL function pointer is passed into ResultOf\\(\\)\\.");
2633 }
2634 #endif  // GTEST_HAS_DEATH_TEST
2635 
2636 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
2637 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)2638 TEST(ResultOfTest, WorksForFunctionReferences) {
2639   Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
2640   EXPECT_TRUE(matcher.Matches(1));
2641   EXPECT_FALSE(matcher.Matches(2));
2642 }
2643 
2644 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
2645 // function object.
2646 struct Functor : public ::std::unary_function<int, string> {
operator ()testing::gmock_matchers_test::Functor2647   result_type operator()(argument_type input) const {
2648     return IntToStringFunction(input);
2649   }
2650 };
2651 
TEST(ResultOfTest,WorksForFunctors)2652 TEST(ResultOfTest, WorksForFunctors) {
2653   Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
2654 
2655   EXPECT_TRUE(matcher.Matches(1));
2656   EXPECT_FALSE(matcher.Matches(2));
2657 }
2658 
2659 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
2660 // functor with more then one operator() defined. ResultOf() must work
2661 // for each defined operator().
2662 struct PolymorphicFunctor {
2663   typedef int result_type;
operator ()testing::gmock_matchers_test::PolymorphicFunctor2664   int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::PolymorphicFunctor2665   int operator()(const char* s) { return static_cast<int>(strlen(s)); }
2666 };
2667 
TEST(ResultOfTest,WorksForPolymorphicFunctors)2668 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
2669   Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
2670 
2671   EXPECT_TRUE(matcher_int.Matches(10));
2672   EXPECT_FALSE(matcher_int.Matches(2));
2673 
2674   Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
2675 
2676   EXPECT_TRUE(matcher_string.Matches("long string"));
2677   EXPECT_FALSE(matcher_string.Matches("shrt"));
2678 }
2679 
ReferencingFunction(const int & n)2680 const int* ReferencingFunction(const int& n) { return &n; }
2681 
2682 struct ReferencingFunctor {
2683   typedef const int* result_type;
operator ()testing::gmock_matchers_test::ReferencingFunctor2684   result_type operator()(const int& n) { return &n; }
2685 };
2686 
TEST(ResultOfTest,WorksForReferencingCallables)2687 TEST(ResultOfTest, WorksForReferencingCallables) {
2688   const int n = 1;
2689   const int n2 = 1;
2690   Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
2691   EXPECT_TRUE(matcher2.Matches(n));
2692   EXPECT_FALSE(matcher2.Matches(n2));
2693 
2694   Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
2695   EXPECT_TRUE(matcher3.Matches(n));
2696   EXPECT_FALSE(matcher3.Matches(n2));
2697 }
2698 
2699 
2700 class DivisibleByImpl {
2701  public:
DivisibleByImpl(int divider)2702   explicit DivisibleByImpl(int divider) : divider_(divider) {}
2703 
2704   template <typename T>
Matches(const T & n) const2705   bool Matches(const T& n) const {
2706     return (n % divider_) == 0;
2707   }
2708 
DescribeTo(::std::ostream * os) const2709   void DescribeTo(::std::ostream* os) const {
2710     *os << "is divisible by " << divider_;
2711   }
2712 
DescribeNegationTo(::std::ostream * os) const2713   void DescribeNegationTo(::std::ostream* os) const {
2714     *os << "is not divisible by " << divider_;
2715   }
2716 
divider() const2717   int divider() const { return divider_; }
2718  private:
2719   const int divider_;
2720 };
2721 
2722 // For testing using ExplainMatchResultTo() with polymorphic matchers.
2723 template <typename T>
ExplainMatchResultTo(const DivisibleByImpl & impl,const T & n,::std::ostream * os)2724 void ExplainMatchResultTo(const DivisibleByImpl& impl, const T& n,
2725                           ::std::ostream* os) {
2726   *os << "is " << (n % impl.divider()) << " modulo "
2727       << impl.divider();
2728 }
2729 
DivisibleBy(int n)2730 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
2731   return MakePolymorphicMatcher(DivisibleByImpl(n));
2732 }
2733 
2734 // Tests that when AllOf() fails, only the first failing matcher is
2735 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_False)2736 TEST(ExplainMatchResultTest, AllOf_False_False) {
2737   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
2738   EXPECT_EQ("is 1 modulo 4", Explain(m, 5));
2739 }
2740 
2741 // Tests that when AllOf() fails, only the first failing matcher is
2742 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_True)2743 TEST(ExplainMatchResultTest, AllOf_False_True) {
2744   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
2745   EXPECT_EQ("is 2 modulo 4", Explain(m, 6));
2746 }
2747 
2748 // Tests that when AllOf() fails, only the first failing matcher is
2749 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_True_False)2750 TEST(ExplainMatchResultTest, AllOf_True_False) {
2751   const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
2752   EXPECT_EQ("is 2 modulo 3", Explain(m, 5));
2753 }
2754 
2755 // Tests that when AllOf() succeeds, all matchers are asked to explain
2756 // why.
TEST(ExplainMatchResultTest,AllOf_True_True)2757 TEST(ExplainMatchResultTest, AllOf_True_True) {
2758   const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
2759   EXPECT_EQ("is 0 modulo 2; is 0 modulo 3", Explain(m, 6));
2760 }
2761 
TEST(ExplainMatchResultTest,AllOf_True_True_2)2762 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
2763   const Matcher<int> m = AllOf(Ge(2), Le(3));
2764   EXPECT_EQ("", Explain(m, 2));
2765 }
2766 
TEST(ExplainmatcherResultTest,MonomorphicMatcher)2767 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
2768   const Matcher<int> m = GreaterThan(5);
2769   EXPECT_EQ("is 1 more than 5", Explain(m, 6));
2770 }
2771 
2772 // The following two tests verify that values without a public copy
2773 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
2774 // with the help of ByRef().
2775 
2776 class NotCopyable {
2777  public:
NotCopyable(int value)2778   explicit NotCopyable(int value) : value_(value) {}
2779 
value() const2780   int value() const { return value_; }
2781 
operator ==(const NotCopyable & rhs) const2782   bool operator==(const NotCopyable& rhs) const {
2783     return value() == rhs.value();
2784   }
2785 
operator >=(const NotCopyable & rhs) const2786   bool operator>=(const NotCopyable& rhs) const {
2787     return value() >= rhs.value();
2788   }
2789  private:
2790   int value_;
2791 
2792   GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
2793 };
2794 
TEST(ByRefTest,AllowsNotCopyableConstValueInMatchers)2795 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
2796   const NotCopyable const_value1(1);
2797   const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
2798 
2799   const NotCopyable n1(1), n2(2);
2800   EXPECT_TRUE(m.Matches(n1));
2801   EXPECT_FALSE(m.Matches(n2));
2802 }
2803 
TEST(ByRefTest,AllowsNotCopyableValueInMatchers)2804 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
2805   NotCopyable value2(2);
2806   const Matcher<NotCopyable&> m = Ge(ByRef(value2));
2807 
2808   NotCopyable n1(1), n2(2);
2809   EXPECT_FALSE(m.Matches(n1));
2810   EXPECT_TRUE(m.Matches(n2));
2811 }
2812 
2813 // Tests ContainerEq with different container types, and
2814 // different element types.
2815 
2816 template <typename T>
2817 class ContainerEqTest : public testing::Test {};
2818 
2819 typedef testing::Types<
2820     std::set<int>,
2821     std::vector<size_t>,
2822     std::multiset<size_t>,
2823     std::list<int> >
2824     ContainerEqTestTypes;
2825 
2826 TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
2827 
2828 // Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest,EqualsSelf)2829 TYPED_TEST(ContainerEqTest, EqualsSelf) {
2830   static const int vals[] = {1, 1, 2, 3, 5, 8};
2831   TypeParam my_set(vals, vals + 6);
2832   const Matcher<TypeParam> m = ContainerEq(my_set);
2833   EXPECT_TRUE(m.Matches(my_set));
2834   EXPECT_EQ("", Explain(m, my_set));
2835 }
2836 
2837 // Tests that missing values are reported.
TYPED_TEST(ContainerEqTest,ValueMissing)2838 TYPED_TEST(ContainerEqTest, ValueMissing) {
2839   static const int vals[] = {1, 1, 2, 3, 5, 8};
2840   static const int test_vals[] = {2, 1, 8, 5};
2841   TypeParam my_set(vals, vals + 6);
2842   TypeParam test_set(test_vals, test_vals + 4);
2843   const Matcher<TypeParam> m = ContainerEq(my_set);
2844   EXPECT_FALSE(m.Matches(test_set));
2845   EXPECT_EQ("Not in actual: 3", Explain(m, test_set));
2846 }
2847 
2848 // Tests that added values are reported.
TYPED_TEST(ContainerEqTest,ValueAdded)2849 TYPED_TEST(ContainerEqTest, ValueAdded) {
2850   static const int vals[] = {1, 1, 2, 3, 5, 8};
2851   static const int test_vals[] = {1, 2, 3, 5, 8, 46};
2852   TypeParam my_set(vals, vals + 6);
2853   TypeParam test_set(test_vals, test_vals + 6);
2854   const Matcher<const TypeParam&> m = ContainerEq(my_set);
2855   EXPECT_FALSE(m.Matches(test_set));
2856   EXPECT_EQ("Only in actual: 46", Explain(m, test_set));
2857 }
2858 
2859 // Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest,ValueAddedAndRemoved)2860 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
2861   static const int vals[] = {1, 1, 2, 3, 5, 8};
2862   static const int test_vals[] = {1, 2, 3, 8, 46};
2863   TypeParam my_set(vals, vals + 6);
2864   TypeParam test_set(test_vals, test_vals + 5);
2865   const Matcher<TypeParam> m = ContainerEq(my_set);
2866   EXPECT_FALSE(m.Matches(test_set));
2867   EXPECT_EQ("Only in actual: 46; not in actual: 5", Explain(m, test_set));
2868 }
2869 
2870 // Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest,DuplicateDifference)2871 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
2872   static const int vals[] = {1, 1, 2, 3, 5, 8};
2873   static const int test_vals[] = {1, 2, 3, 5, 8};
2874   TypeParam my_set(vals, vals + 6);
2875   TypeParam test_set(test_vals, test_vals + 5);
2876   const Matcher<const TypeParam&> m = ContainerEq(my_set);
2877   // Depending on the container, match may be true or false
2878   // But in any case there should be no explanation.
2879   EXPECT_EQ("", Explain(m, test_set));
2880 }
2881 
2882 // Tests that mutliple missing values are reported.
2883 // Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest,MultipleValuesMissing)2884 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
2885   static const int vals[] = {1, 1, 2, 3, 5, 8};
2886   static const int test_vals[] = {2, 1, 5};
2887   std::vector<int> my_set(vals, vals + 6);
2888   std::vector<int> test_set(test_vals, test_vals + 3);
2889   const Matcher<std::vector<int> > m = ContainerEq(my_set);
2890   EXPECT_FALSE(m.Matches(test_set));
2891   EXPECT_EQ("Not in actual: 3, 8", Explain(m, test_set));
2892 }
2893 
2894 // Tests that added values are reported.
2895 // Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest,MultipleValuesAdded)2896 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
2897   static const int vals[] = {1, 1, 2, 3, 5, 8};
2898   static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
2899   std::list<size_t> my_set(vals, vals + 6);
2900   std::list<size_t> test_set(test_vals, test_vals + 7);
2901   const Matcher<const std::list<size_t>&> m = ContainerEq(my_set);
2902   EXPECT_FALSE(m.Matches(test_set));
2903   EXPECT_EQ("Only in actual: 92, 46", Explain(m, test_set));
2904 }
2905 
2906 // Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest,MultipleValuesAddedAndRemoved)2907 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
2908   static const int vals[] = {1, 1, 2, 3, 5, 8};
2909   static const int test_vals[] = {1, 2, 3, 92, 46};
2910   std::list<size_t> my_set(vals, vals + 6);
2911   std::list<size_t> test_set(test_vals, test_vals + 5);
2912   const Matcher<const std::list<size_t> > m = ContainerEq(my_set);
2913   EXPECT_FALSE(m.Matches(test_set));
2914   EXPECT_EQ("Only in actual: 92, 46; not in actual: 5, 8",
2915             Explain(m, test_set));
2916 }
2917 
2918 // Tests to see that duplicate elements are detected,
2919 // but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest,MultiSetOfIntDuplicateDifference)2920 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
2921   static const int vals[] = {1, 1, 2, 3, 5, 8};
2922   static const int test_vals[] = {1, 2, 3, 5, 8};
2923   std::vector<int> my_set(vals, vals + 6);
2924   std::vector<int> test_set(test_vals, test_vals + 5);
2925   const Matcher<std::vector<int> > m = ContainerEq(my_set);
2926   EXPECT_TRUE(m.Matches(my_set));
2927   EXPECT_FALSE(m.Matches(test_set));
2928   // There is nothing to report when both sets contain all the same values.
2929   EXPECT_EQ("", Explain(m, test_set));
2930 }
2931 
2932 // Tests that ContainerEq works for non-trivial associative containers,
2933 // like maps.
TEST(ContainerEqExtraTest,WorksForMaps)2934 TEST(ContainerEqExtraTest, WorksForMaps) {
2935   std::map<int, std::string> my_map;
2936   my_map[0] = "a";
2937   my_map[1] = "b";
2938 
2939   std::map<int, std::string> test_map;
2940   test_map[0] = "aa";
2941   test_map[1] = "b";
2942 
2943   const Matcher<const std::map<int, std::string>&> m = ContainerEq(my_map);
2944   EXPECT_TRUE(m.Matches(my_map));
2945   EXPECT_FALSE(m.Matches(test_map));
2946 
2947   EXPECT_EQ("Only in actual: (0, \"aa\"); not in actual: (0, \"a\")",
2948             Explain(m, test_map));
2949 }
2950 
TEST(ContainerEqExtraTest,WorksForNativeArray)2951 TEST(ContainerEqExtraTest, WorksForNativeArray) {
2952   int a1[] = { 1, 2, 3 };
2953   int a2[] = { 1, 2, 3 };
2954   int b[] = { 1, 2, 4 };
2955 
2956   EXPECT_THAT(a1, ContainerEq(a2));
2957   EXPECT_THAT(a1, Not(ContainerEq(b)));
2958 }
2959 
TEST(ContainerEqExtraTest,WorksForTwoDimensionalNativeArray)2960 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
2961   const char a1[][3] = { "hi", "lo" };
2962   const char a2[][3] = { "hi", "lo" };
2963   const char b[][3] = { "lo", "hi" };
2964 
2965   // Tests using ContainerEq() in the first dimension.
2966   EXPECT_THAT(a1, ContainerEq(a2));
2967   EXPECT_THAT(a1, Not(ContainerEq(b)));
2968 
2969   // Tests using ContainerEq() in the second dimension.
2970   EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
2971   EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
2972 }
2973 
TEST(ContainerEqExtraTest,WorksForNativeArrayAsTuple)2974 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
2975   const int a1[] = { 1, 2, 3 };
2976   const int a2[] = { 1, 2, 3 };
2977   const int b[] = { 1, 2, 3, 4 };
2978 
2979   const int* const p1 = a1;
2980   EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
2981   EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
2982 
2983   const int c[] = { 1, 3, 2 };
2984   EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
2985 }
2986 
TEST(ContainerEqExtraTest,CopiesNativeArrayParameter)2987 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
2988   std::string a1[][3] = {
2989     { "hi", "hello", "ciao" },
2990     { "bye", "see you", "ciao" }
2991   };
2992 
2993   std::string a2[][3] = {
2994     { "hi", "hello", "ciao" },
2995     { "bye", "see you", "ciao" }
2996   };
2997 
2998   const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
2999   EXPECT_THAT(a1, m);
3000 
3001   a2[0][0] = "ha";
3002   EXPECT_THAT(a1, m);
3003 }
3004 
3005 // Tests GetParamIndex().
3006 
TEST(GetParamIndexTest,WorksForEmptyParamList)3007 TEST(GetParamIndexTest, WorksForEmptyParamList) {
3008   const char* params[] = { NULL };
3009   EXPECT_EQ(kTupleInterpolation, GetParamIndex(params, "*"));
3010   EXPECT_EQ(kInvalidInterpolation, GetParamIndex(params, "a"));
3011 }
3012 
TEST(GetParamIndexTest,RecognizesStar)3013 TEST(GetParamIndexTest, RecognizesStar) {
3014   const char* params[] = { "a", "b", NULL };
3015   EXPECT_EQ(kTupleInterpolation, GetParamIndex(params, "*"));
3016 }
3017 
TEST(GetParamIndexTest,RecognizesKnownParam)3018 TEST(GetParamIndexTest, RecognizesKnownParam) {
3019   const char* params[] = { "foo", "bar", NULL };
3020   EXPECT_EQ(0, GetParamIndex(params, "foo"));
3021   EXPECT_EQ(1, GetParamIndex(params, "bar"));
3022 }
3023 
TEST(GetParamIndexTest,RejectsUnknownParam)3024 TEST(GetParamIndexTest, RejectsUnknownParam) {
3025   const char* params[] = { "foo", "bar", NULL };
3026   EXPECT_EQ(kInvalidInterpolation, GetParamIndex(params, "foobar"));
3027 }
3028 
3029 // Tests SkipPrefix().
3030 
TEST(SkipPrefixTest,SkipsWhenPrefixMatches)3031 TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
3032   const char* const str = "hello";
3033 
3034   const char* p = str;
3035   EXPECT_TRUE(SkipPrefix("", &p));
3036   EXPECT_EQ(str, p);
3037 
3038   p = str;
3039   EXPECT_TRUE(SkipPrefix("hell", &p));
3040   EXPECT_EQ(str + 4, p);
3041 }
3042 
TEST(SkipPrefixTest,DoesNotSkipWhenPrefixDoesNotMatch)3043 TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
3044   const char* const str = "world";
3045 
3046   const char* p = str;
3047   EXPECT_FALSE(SkipPrefix("W", &p));
3048   EXPECT_EQ(str, p);
3049 
3050   p = str;
3051   EXPECT_FALSE(SkipPrefix("world!", &p));
3052   EXPECT_EQ(str, p);
3053 }
3054 
3055 // Tests FormatMatcherDescriptionSyntaxError().
TEST(FormatMatcherDescriptionSyntaxErrorTest,FormatsCorrectly)3056 TEST(FormatMatcherDescriptionSyntaxErrorTest, FormatsCorrectly) {
3057   const char* const description = "hello%world";
3058   EXPECT_EQ("Syntax error at index 5 in matcher description \"hello%world\": ",
3059             FormatMatcherDescriptionSyntaxError(description, description + 5));
3060 }
3061 
3062 // Tests ValidateMatcherDescription().
3063 
TEST(ValidateMatcherDescriptionTest,AcceptsEmptyDescription)3064 TEST(ValidateMatcherDescriptionTest, AcceptsEmptyDescription) {
3065   const char* params[] = { "foo", "bar", NULL };
3066   EXPECT_THAT(ValidateMatcherDescription(params, ""),
3067               ElementsAre());
3068 }
3069 
TEST(ValidateMatcherDescriptionTest,AcceptsNonEmptyDescriptionWithNoInterpolation)3070 TEST(ValidateMatcherDescriptionTest,
3071      AcceptsNonEmptyDescriptionWithNoInterpolation) {
3072   const char* params[] = { "foo", "bar", NULL };
3073   EXPECT_THAT(ValidateMatcherDescription(params, "a simple description"),
3074               ElementsAre());
3075 }
3076 
3077 // We use MATCHER_P3() to define a matcher for testing
3078 // ValidateMatcherDescription(); otherwise we'll end up with much
3079 // plumbing code.  This is not circular as
3080 // ValidateMatcherDescription() doesn't affect whether the matcher
3081 // matches a value or not.
3082 MATCHER_P3(EqInterpolation, start, end, index, "equals Interpolation%(*)s") {
3083   return arg.start_pos == start && arg.end_pos == end &&
3084       arg.param_index == index;
3085 }
3086 
TEST(ValidateMatcherDescriptionTest,AcceptsPercentInterpolation)3087 TEST(ValidateMatcherDescriptionTest, AcceptsPercentInterpolation) {
3088   const char* params[] = { "foo", NULL };
3089   const char* const desc = "one %%";
3090   EXPECT_THAT(ValidateMatcherDescription(params, desc),
3091               ElementsAre(EqInterpolation(desc + 4, desc + 6,
3092                                           kPercentInterpolation)));
3093 }
3094 
TEST(ValidateMatcherDescriptionTest,AcceptsTupleInterpolation)3095 TEST(ValidateMatcherDescriptionTest, AcceptsTupleInterpolation) {
3096   const char* params[] = { "foo", "bar", "baz", NULL };
3097   const char* const desc = "%(*)s after";
3098   EXPECT_THAT(ValidateMatcherDescription(params, desc),
3099               ElementsAre(EqInterpolation(desc, desc + 5,
3100                                           kTupleInterpolation)));
3101 }
3102 
TEST(ValidateMatcherDescriptionTest,AcceptsParamInterpolation)3103 TEST(ValidateMatcherDescriptionTest, AcceptsParamInterpolation) {
3104   const char* params[] = { "foo", "bar", "baz", NULL };
3105   const char* const desc = "a %(bar)s.";
3106   EXPECT_THAT(ValidateMatcherDescription(params, desc),
3107               ElementsAre(EqInterpolation(desc + 2, desc + 9, 1)));
3108 }
3109 
TEST(ValidateMatcherDescriptionTest,AcceptsMultiplenterpolations)3110 TEST(ValidateMatcherDescriptionTest, AcceptsMultiplenterpolations) {
3111   const char* params[] = { "foo", "bar", "baz", NULL };
3112   const char* const desc = "%(baz)s %(foo)s %(bar)s";
3113   EXPECT_THAT(ValidateMatcherDescription(params, desc),
3114               ElementsAre(EqInterpolation(desc, desc + 7, 2),
3115                           EqInterpolation(desc + 8, desc + 15, 0),
3116                           EqInterpolation(desc + 16, desc + 23, 1)));
3117 }
3118 
TEST(ValidateMatcherDescriptionTest,AcceptsRepeatedParams)3119 TEST(ValidateMatcherDescriptionTest, AcceptsRepeatedParams) {
3120   const char* params[] = { "foo", "bar", NULL };
3121   const char* const desc = "%(foo)s and %(foo)s";
3122   EXPECT_THAT(ValidateMatcherDescription(params, desc),
3123               ElementsAre(EqInterpolation(desc, desc + 7, 0),
3124                           EqInterpolation(desc + 12, desc + 19, 0)));
3125 }
3126 
TEST(ValidateMatcherDescriptionTest,RejectsUnknownParam)3127 TEST(ValidateMatcherDescriptionTest, RejectsUnknownParam) {
3128   const char* params[] = { "a", "bar", NULL };
3129   EXPECT_NONFATAL_FAILURE({
3130     EXPECT_THAT(ValidateMatcherDescription(params, "%(foo)s"),
3131                 ElementsAre());
3132   }, "Syntax error at index 2 in matcher description \"%(foo)s\": "
3133      "\"foo\" is an invalid parameter name.");
3134 }
3135 
TEST(ValidateMatcherDescriptionTest,RejectsUnfinishedParam)3136 TEST(ValidateMatcherDescriptionTest, RejectsUnfinishedParam) {
3137   const char* params[] = { "a", "bar", NULL };
3138   EXPECT_NONFATAL_FAILURE({
3139     EXPECT_THAT(ValidateMatcherDescription(params, "%(foo)"),
3140                 ElementsAre());
3141   }, "Syntax error at index 0 in matcher description \"%(foo)\": "
3142      "an interpolation must end with \")s\", but \"%(foo)\" does not.");
3143 
3144   EXPECT_NONFATAL_FAILURE({
3145     EXPECT_THAT(ValidateMatcherDescription(params, "x%(a"),
3146                 ElementsAre());
3147   }, "Syntax error at index 1 in matcher description \"x%(a\": "
3148      "an interpolation must end with \")s\", but \"%(a\" does not.");
3149 }
3150 
TEST(ValidateMatcherDescriptionTest,RejectsSinglePercent)3151 TEST(ValidateMatcherDescriptionTest, RejectsSinglePercent) {
3152   const char* params[] = { "a", NULL };
3153   EXPECT_NONFATAL_FAILURE({
3154     EXPECT_THAT(ValidateMatcherDescription(params, "a %."),
3155                 ElementsAre());
3156   }, "Syntax error at index 2 in matcher description \"a %.\": "
3157      "use \"%%\" instead of \"%\" to print \"%\".");
3158 
3159 }
3160 
3161 // Tests JoinAsTuple().
3162 
TEST(JoinAsTupleTest,JoinsEmptyTuple)3163 TEST(JoinAsTupleTest, JoinsEmptyTuple) {
3164   EXPECT_EQ("", JoinAsTuple(Strings()));
3165 }
3166 
TEST(JoinAsTupleTest,JoinsOneTuple)3167 TEST(JoinAsTupleTest, JoinsOneTuple) {
3168   const char* fields[] = { "1" };
3169   EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
3170 }
3171 
TEST(JoinAsTupleTest,JoinsTwoTuple)3172 TEST(JoinAsTupleTest, JoinsTwoTuple) {
3173   const char* fields[] = { "1", "a" };
3174   EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
3175 }
3176 
TEST(JoinAsTupleTest,JoinsTenTuple)3177 TEST(JoinAsTupleTest, JoinsTenTuple) {
3178   const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
3179   EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
3180             JoinAsTuple(Strings(fields, fields + 10)));
3181 }
3182 
3183 // Tests FormatMatcherDescription().
3184 
TEST(FormatMatcherDescriptionTest,WorksForEmptyDescription)3185 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
3186   EXPECT_EQ("is even",
3187             FormatMatcherDescription("IsEven", "", Interpolations(),
3188                                      Strings()));
3189 
3190   const char* params[] = { "5" };
3191   EXPECT_EQ("equals 5",
3192             FormatMatcherDescription("Equals", "", Interpolations(),
3193                                      Strings(params, params + 1)));
3194 
3195   const char* params2[] = { "5", "8" };
3196   EXPECT_EQ("is in range (5, 8)",
3197             FormatMatcherDescription("IsInRange", "", Interpolations(),
3198                                      Strings(params2, params2 + 2)));
3199 }
3200 
TEST(FormatMatcherDescriptionTest,WorksForDescriptionWithNoInterpolation)3201 TEST(FormatMatcherDescriptionTest, WorksForDescriptionWithNoInterpolation) {
3202   EXPECT_EQ("is positive",
3203             FormatMatcherDescription("Gt0", "is positive", Interpolations(),
3204                                      Strings()));
3205 
3206   const char* params[] = { "5", "6" };
3207   EXPECT_EQ("is negative",
3208             FormatMatcherDescription("Lt0", "is negative", Interpolations(),
3209                                      Strings(params, params + 2)));
3210 }
3211 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionStartsWithInterpolation)3212 TEST(FormatMatcherDescriptionTest,
3213      WorksWhenDescriptionStartsWithInterpolation) {
3214   const char* params[] = { "5" };
3215   const char* const desc = "%(num)s times bigger";
3216   const Interpolation interp[] = { Interpolation(desc, desc + 7, 0) };
3217   EXPECT_EQ("5 times bigger",
3218             FormatMatcherDescription("Foo", desc,
3219                                      Interpolations(interp, interp + 1),
3220                                      Strings(params, params + 1)));
3221 }
3222 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionEndsWithInterpolation)3223 TEST(FormatMatcherDescriptionTest,
3224      WorksWhenDescriptionEndsWithInterpolation) {
3225   const char* params[] = { "5", "6" };
3226   const char* const desc = "is bigger than %(y)s";
3227   const Interpolation interp[] = { Interpolation(desc + 15, desc + 20, 1) };
3228   EXPECT_EQ("is bigger than 6",
3229             FormatMatcherDescription("Foo", desc,
3230                                      Interpolations(interp, interp + 1),
3231                                      Strings(params, params + 2)));
3232 }
3233 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionStartsAndEndsWithInterpolation)3234 TEST(FormatMatcherDescriptionTest,
3235      WorksWhenDescriptionStartsAndEndsWithInterpolation) {
3236   const char* params[] = { "5", "6" };
3237   const char* const desc = "%(x)s <= arg <= %(y)s";
3238   const Interpolation interp[] = {
3239     Interpolation(desc, desc + 5, 0),
3240     Interpolation(desc + 16, desc + 21, 1)
3241   };
3242   EXPECT_EQ("5 <= arg <= 6",
3243             FormatMatcherDescription("Foo", desc,
3244                                      Interpolations(interp, interp + 2),
3245                                      Strings(params, params + 2)));
3246 }
3247 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionDoesNotStartOrEndWithInterpolation)3248 TEST(FormatMatcherDescriptionTest,
3249      WorksWhenDescriptionDoesNotStartOrEndWithInterpolation) {
3250   const char* params[] = { "5.2" };
3251   const char* const desc = "has %(x)s cents";
3252   const Interpolation interp[] = { Interpolation(desc + 4, desc + 9, 0) };
3253   EXPECT_EQ("has 5.2 cents",
3254             FormatMatcherDescription("Foo", desc,
3255                                      Interpolations(interp, interp + 1),
3256                                      Strings(params, params + 1)));
3257 }
3258 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionContainsMultipleInterpolations)3259 TEST(FormatMatcherDescriptionTest,
3260      WorksWhenDescriptionContainsMultipleInterpolations) {
3261   const char* params[] = { "5", "6" };
3262   const char* const desc = "in %(*)s or [%(x)s, %(y)s]";
3263   const Interpolation interp[] = {
3264     Interpolation(desc + 3, desc + 8, kTupleInterpolation),
3265     Interpolation(desc + 13, desc + 18, 0),
3266     Interpolation(desc + 20, desc + 25, 1)
3267   };
3268   EXPECT_EQ("in (5, 6) or [5, 6]",
3269             FormatMatcherDescription("Foo", desc,
3270                                      Interpolations(interp, interp + 3),
3271                                      Strings(params, params + 2)));
3272 }
3273 
TEST(FormatMatcherDescriptionTest,WorksWhenDescriptionContainsRepeatedParams)3274 TEST(FormatMatcherDescriptionTest,
3275      WorksWhenDescriptionContainsRepeatedParams) {
3276   const char* params[] = { "9" };
3277   const char* const desc = "in [-%(x)s, %(x)s]";
3278   const Interpolation interp[] = {
3279     Interpolation(desc + 5, desc + 10, 0),
3280     Interpolation(desc + 12, desc + 17, 0)
3281   };
3282   EXPECT_EQ("in [-9, 9]",
3283             FormatMatcherDescription("Foo", desc,
3284                                      Interpolations(interp, interp + 2),
3285                                      Strings(params, params + 1)));
3286 }
3287 
TEST(FormatMatcherDescriptionTest,WorksForDescriptionWithInvalidInterpolation)3288 TEST(FormatMatcherDescriptionTest,
3289      WorksForDescriptionWithInvalidInterpolation) {
3290   const char* params[] = { "9" };
3291   const char* const desc = "> %(x)s %(x)";
3292   const Interpolation interp[] = { Interpolation(desc + 2, desc + 7, 0)  };
3293   EXPECT_EQ("> 9 %(x)",
3294             FormatMatcherDescription("Foo", desc,
3295                                      Interpolations(interp, interp + 1),
3296                                      Strings(params, params + 1)));
3297 }
3298 
3299 }  // namespace gmock_matchers_test
3300 }  // namespace testing
3301