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