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