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