1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file tests some commonly used argument matchers.
35
36 #include "gmock/gmock-matchers.h"
37 #include "gmock/gmock-more-matchers.h"
38
39 #include <string.h>
40 #include <time.h>
41 #include <deque>
42 #include <functional>
43 #include <iostream>
44 #include <iterator>
45 #include <limits>
46 #include <list>
47 #include <map>
48 #include <set>
49 #include <sstream>
50 #include <string>
51 #include <utility>
52 #include <vector>
53 #include "gmock/gmock.h"
54 #include "gtest/gtest.h"
55 #include "gtest/gtest-spi.h"
56
57 #if GTEST_HAS_STD_FORWARD_LIST_
58 # include <forward_list> // NOLINT
59 #endif
60
61 // Disable MSVC2015 warning for std::pair: "decorated name length exceeded, name was truncated".
62 #if defined(_MSC_VER) && (_MSC_VER == 1900)
63 # pragma warning(disable:4503)
64 #endif
65
66 namespace testing {
67
68 namespace gmock_matchers_test {
69
70 using std::greater;
71 using std::less;
72 using std::list;
73 using std::make_pair;
74 using std::map;
75 using std::multimap;
76 using std::multiset;
77 using std::ostream;
78 using std::pair;
79 using std::set;
80 using std::stringstream;
81 using std::vector;
82 using testing::A;
83 using testing::AllArgs;
84 using testing::AllOf;
85 using testing::An;
86 using testing::AnyOf;
87 using testing::ByRef;
88 using testing::ContainsRegex;
89 using testing::DoubleEq;
90 using testing::DoubleNear;
91 using testing::EndsWith;
92 using testing::Eq;
93 using testing::ExplainMatchResult;
94 using testing::Field;
95 using testing::FloatEq;
96 using testing::FloatNear;
97 using testing::Ge;
98 using testing::Gt;
99 using testing::HasSubstr;
100 using testing::IsEmpty;
101 using testing::IsNull;
102 using testing::Key;
103 using testing::Le;
104 using testing::Lt;
105 using testing::MakeMatcher;
106 using testing::MakePolymorphicMatcher;
107 using testing::MatchResultListener;
108 using testing::Matcher;
109 using testing::MatcherCast;
110 using testing::MatcherInterface;
111 using testing::Matches;
112 using testing::MatchesRegex;
113 using testing::NanSensitiveDoubleEq;
114 using testing::NanSensitiveDoubleNear;
115 using testing::NanSensitiveFloatEq;
116 using testing::NanSensitiveFloatNear;
117 using testing::Ne;
118 using testing::Not;
119 using testing::NotNull;
120 using testing::Pair;
121 using testing::Pointee;
122 using testing::Pointwise;
123 using testing::PolymorphicMatcher;
124 using testing::Property;
125 using testing::Ref;
126 using testing::ResultOf;
127 using testing::SizeIs;
128 using testing::StartsWith;
129 using testing::StrCaseEq;
130 using testing::StrCaseNe;
131 using testing::StrEq;
132 using testing::StrNe;
133 using testing::StringMatchResultListener;
134 using testing::Truly;
135 using testing::TypedEq;
136 using testing::UnorderedPointwise;
137 using testing::Value;
138 using testing::WhenSorted;
139 using testing::WhenSortedBy;
140 using testing::_;
141 using testing::get;
142 using testing::internal::DummyMatchResultListener;
143 using testing::internal::ElementMatcherPair;
144 using testing::internal::ElementMatcherPairs;
145 using testing::internal::ExplainMatchFailureTupleTo;
146 using testing::internal::FloatingEqMatcher;
147 using testing::internal::FormatMatcherDescription;
148 using testing::internal::IsReadableTypeName;
149 using testing::internal::linked_ptr;
150 using testing::internal::MatchMatrix;
151 using testing::internal::RE;
152 using testing::internal::scoped_ptr;
153 using testing::internal::StreamMatchResultListener;
154 using testing::internal::Strings;
155 using testing::internal::linked_ptr;
156 using testing::internal::scoped_ptr;
157 using testing::internal::string;
158 using testing::make_tuple;
159 using testing::tuple;
160
161 // For testing ExplainMatchResultTo().
162 class GreaterThanMatcher : public MatcherInterface<int> {
163 public:
GreaterThanMatcher(int rhs)164 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
165
DescribeTo(ostream * os) const166 virtual void DescribeTo(ostream* os) const {
167 *os << "is > " << rhs_;
168 }
169
MatchAndExplain(int lhs,MatchResultListener * listener) const170 virtual bool MatchAndExplain(int lhs,
171 MatchResultListener* listener) const {
172 const int diff = lhs - rhs_;
173 if (diff > 0) {
174 *listener << "which is " << diff << " more than " << rhs_;
175 } else if (diff == 0) {
176 *listener << "which is the same as " << rhs_;
177 } else {
178 *listener << "which is " << -diff << " less than " << rhs_;
179 }
180
181 return lhs > rhs_;
182 }
183
184 private:
185 int rhs_;
186 };
187
GreaterThan(int n)188 Matcher<int> GreaterThan(int n) {
189 return MakeMatcher(new GreaterThanMatcher(n));
190 }
191
OfType(const std::string & type_name)192 std::string OfType(const std::string& type_name) {
193 #if GTEST_HAS_RTTI
194 return " (of type " + type_name + ")";
195 #else
196 return "";
197 #endif
198 }
199
200 // Returns the description of the given matcher.
201 template <typename T>
Describe(const Matcher<T> & m)202 std::string Describe(const Matcher<T>& m) {
203 stringstream ss;
204 m.DescribeTo(&ss);
205 return ss.str();
206 }
207
208 // Returns the description of the negation of the given matcher.
209 template <typename T>
DescribeNegation(const Matcher<T> & m)210 std::string DescribeNegation(const Matcher<T>& m) {
211 stringstream ss;
212 m.DescribeNegationTo(&ss);
213 return ss.str();
214 }
215
216 // Returns the reason why x matches, or doesn't match, m.
217 template <typename MatcherType, typename Value>
Explain(const MatcherType & m,const Value & x)218 std::string Explain(const MatcherType& m, const Value& x) {
219 StringMatchResultListener listener;
220 ExplainMatchResult(m, x, &listener);
221 return listener.str();
222 }
223
TEST(MatchResultListenerTest,StreamingWorks)224 TEST(MatchResultListenerTest, StreamingWorks) {
225 StringMatchResultListener listener;
226 listener << "hi" << 5;
227 EXPECT_EQ("hi5", listener.str());
228
229 listener.Clear();
230 EXPECT_EQ("", listener.str());
231
232 listener << 42;
233 EXPECT_EQ("42", listener.str());
234
235 // Streaming shouldn't crash when the underlying ostream is NULL.
236 DummyMatchResultListener dummy;
237 dummy << "hi" << 5;
238 }
239
TEST(MatchResultListenerTest,CanAccessUnderlyingStream)240 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
241 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
242 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
243
244 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
245 }
246
TEST(MatchResultListenerTest,IsInterestedWorks)247 TEST(MatchResultListenerTest, IsInterestedWorks) {
248 EXPECT_TRUE(StringMatchResultListener().IsInterested());
249 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
250
251 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
252 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
253 }
254
255 // Makes sure that the MatcherInterface<T> interface doesn't
256 // change.
257 class EvenMatcherImpl : public MatcherInterface<int> {
258 public:
MatchAndExplain(int x,MatchResultListener *) const259 virtual bool MatchAndExplain(int x,
260 MatchResultListener* /* listener */) const {
261 return x % 2 == 0;
262 }
263
DescribeTo(ostream * os) const264 virtual void DescribeTo(ostream* os) const {
265 *os << "is an even number";
266 }
267
268 // We deliberately don't define DescribeNegationTo() and
269 // ExplainMatchResultTo() here, to make sure the definition of these
270 // two methods is optional.
271 };
272
273 // Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest,CanBeImplementedUsingPublishedAPI)274 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
275 EvenMatcherImpl m;
276 }
277
278 // Tests implementing a monomorphic matcher using MatchAndExplain().
279
280 class NewEvenMatcherImpl : public MatcherInterface<int> {
281 public:
MatchAndExplain(int x,MatchResultListener * listener) const282 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
283 const bool match = x % 2 == 0;
284 // Verifies that we can stream to a listener directly.
285 *listener << "value % " << 2;
286 if (listener->stream() != NULL) {
287 // Verifies that we can stream to a listener's underlying stream
288 // too.
289 *listener->stream() << " == " << (x % 2);
290 }
291 return match;
292 }
293
DescribeTo(ostream * os) const294 virtual void DescribeTo(ostream* os) const {
295 *os << "is an even number";
296 }
297 };
298
TEST(MatcherInterfaceTest,CanBeImplementedUsingNewAPI)299 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
300 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
301 EXPECT_TRUE(m.Matches(2));
302 EXPECT_FALSE(m.Matches(3));
303 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
304 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
305 }
306
307 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)308 TEST(MatcherTest, CanBeDefaultConstructed) {
309 Matcher<double> m;
310 }
311
312 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)313 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
314 const MatcherInterface<int>* impl = new EvenMatcherImpl;
315 Matcher<int> m(impl);
316 EXPECT_TRUE(m.Matches(4));
317 EXPECT_FALSE(m.Matches(5));
318 }
319
320 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)321 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
322 Matcher<int> m1 = 5;
323 EXPECT_TRUE(m1.Matches(5));
324 EXPECT_FALSE(m1.Matches(6));
325 }
326
327 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)328 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
329 Matcher<int*> m1 = NULL;
330 EXPECT_TRUE(m1.Matches(NULL));
331 int n = 0;
332 EXPECT_FALSE(m1.Matches(&n));
333 }
334
335 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)336 TEST(MatcherTest, IsCopyable) {
337 // Tests the copy constructor.
338 Matcher<bool> m1 = Eq(false);
339 EXPECT_TRUE(m1.Matches(false));
340 EXPECT_FALSE(m1.Matches(true));
341
342 // Tests the assignment operator.
343 m1 = Eq(true);
344 EXPECT_TRUE(m1.Matches(true));
345 EXPECT_FALSE(m1.Matches(false));
346 }
347
348 // Tests that Matcher<T>::DescribeTo() calls
349 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)350 TEST(MatcherTest, CanDescribeItself) {
351 EXPECT_EQ("is an even number",
352 Describe(Matcher<int>(new EvenMatcherImpl)));
353 }
354
355 // Tests Matcher<T>::MatchAndExplain().
TEST(MatcherTest,MatchAndExplain)356 TEST(MatcherTest, MatchAndExplain) {
357 Matcher<int> m = GreaterThan(0);
358 StringMatchResultListener listener1;
359 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
360 EXPECT_EQ("which is 42 more than 0", listener1.str());
361
362 StringMatchResultListener listener2;
363 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
364 EXPECT_EQ("which is 9 less than 0", listener2.str());
365 }
366
367 // Tests that a C-string literal can be implicitly converted to a
368 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)369 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
370 Matcher<string> m1 = "hi";
371 EXPECT_TRUE(m1.Matches("hi"));
372 EXPECT_FALSE(m1.Matches("hello"));
373
374 Matcher<const string&> m2 = "hi";
375 EXPECT_TRUE(m2.Matches("hi"));
376 EXPECT_FALSE(m2.Matches("hello"));
377 }
378
379 // Tests that a string object can be implicitly converted to a
380 // Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)381 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
382 Matcher<string> m1 = string("hi");
383 EXPECT_TRUE(m1.Matches("hi"));
384 EXPECT_FALSE(m1.Matches("hello"));
385
386 Matcher<const string&> m2 = string("hi");
387 EXPECT_TRUE(m2.Matches("hi"));
388 EXPECT_FALSE(m2.Matches("hello"));
389 }
390
391 #if GTEST_HAS_STRING_PIECE_
392 // Tests that a C-string literal can be implicitly converted to a
393 // Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)394 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
395 Matcher<StringPiece> m1 = "cats";
396 EXPECT_TRUE(m1.Matches("cats"));
397 EXPECT_FALSE(m1.Matches("dogs"));
398
399 Matcher<const StringPiece&> m2 = "cats";
400 EXPECT_TRUE(m2.Matches("cats"));
401 EXPECT_FALSE(m2.Matches("dogs"));
402 }
403
404 // Tests that a string object can be implicitly converted to a
405 // Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest,CanBeImplicitlyConstructedFromString)406 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
407 Matcher<StringPiece> m1 = string("cats");
408 EXPECT_TRUE(m1.Matches("cats"));
409 EXPECT_FALSE(m1.Matches("dogs"));
410
411 Matcher<const StringPiece&> m2 = string("cats");
412 EXPECT_TRUE(m2.Matches("cats"));
413 EXPECT_FALSE(m2.Matches("dogs"));
414 }
415
416 // Tests that a StringPiece object can be implicitly converted to a
417 // Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest,CanBeImplicitlyConstructedFromStringPiece)418 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
419 Matcher<StringPiece> m1 = StringPiece("cats");
420 EXPECT_TRUE(m1.Matches("cats"));
421 EXPECT_FALSE(m1.Matches("dogs"));
422
423 Matcher<const StringPiece&> m2 = StringPiece("cats");
424 EXPECT_TRUE(m2.Matches("cats"));
425 EXPECT_FALSE(m2.Matches("dogs"));
426 }
427 #endif // GTEST_HAS_STRING_PIECE_
428
429 // Tests that MakeMatcher() constructs a Matcher<T> from a
430 // MatcherInterface* without requiring the user to explicitly
431 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)432 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
433 const MatcherInterface<int>* dummy_impl = NULL;
434 Matcher<int> m = MakeMatcher(dummy_impl);
435 }
436
437 // Tests that MakePolymorphicMatcher() can construct a polymorphic
438 // matcher from its implementation using the old API.
439 const int g_bar = 1;
440 class ReferencesBarOrIsZeroImpl {
441 public:
442 template <typename T>
MatchAndExplain(const T & x,MatchResultListener *) const443 bool MatchAndExplain(const T& x,
444 MatchResultListener* /* listener */) const {
445 const void* p = &x;
446 return p == &g_bar || x == 0;
447 }
448
DescribeTo(ostream * os) const449 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
450
DescribeNegationTo(ostream * os) const451 void DescribeNegationTo(ostream* os) const {
452 *os << "doesn't reference g_bar and is not zero";
453 }
454 };
455
456 // This function verifies that MakePolymorphicMatcher() returns a
457 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()458 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
459 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
460 }
461
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingOldAPI)462 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
463 // Using a polymorphic matcher to match a reference type.
464 Matcher<const int&> m1 = ReferencesBarOrIsZero();
465 EXPECT_TRUE(m1.Matches(0));
466 // Verifies that the identity of a by-reference argument is preserved.
467 EXPECT_TRUE(m1.Matches(g_bar));
468 EXPECT_FALSE(m1.Matches(1));
469 EXPECT_EQ("g_bar or zero", Describe(m1));
470
471 // Using a polymorphic matcher to match a value type.
472 Matcher<double> m2 = ReferencesBarOrIsZero();
473 EXPECT_TRUE(m2.Matches(0.0));
474 EXPECT_FALSE(m2.Matches(0.1));
475 EXPECT_EQ("g_bar or zero", Describe(m2));
476 }
477
478 // Tests implementing a polymorphic matcher using MatchAndExplain().
479
480 class PolymorphicIsEvenImpl {
481 public:
DescribeTo(ostream * os) const482 void DescribeTo(ostream* os) const { *os << "is even"; }
483
DescribeNegationTo(ostream * os) const484 void DescribeNegationTo(ostream* os) const {
485 *os << "is odd";
486 }
487
488 template <typename T>
MatchAndExplain(const T & x,MatchResultListener * listener) const489 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
490 // Verifies that we can stream to the listener directly.
491 *listener << "% " << 2;
492 if (listener->stream() != NULL) {
493 // Verifies that we can stream to the listener's underlying stream
494 // too.
495 *listener->stream() << " == " << (x % 2);
496 }
497 return (x % 2) == 0;
498 }
499 };
500
PolymorphicIsEven()501 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
502 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
503 }
504
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingNewAPI)505 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
506 // Using PolymorphicIsEven() as a Matcher<int>.
507 const Matcher<int> m1 = PolymorphicIsEven();
508 EXPECT_TRUE(m1.Matches(42));
509 EXPECT_FALSE(m1.Matches(43));
510 EXPECT_EQ("is even", Describe(m1));
511
512 const Matcher<int> not_m1 = Not(m1);
513 EXPECT_EQ("is odd", Describe(not_m1));
514
515 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
516
517 // Using PolymorphicIsEven() as a Matcher<char>.
518 const Matcher<char> m2 = PolymorphicIsEven();
519 EXPECT_TRUE(m2.Matches('\x42'));
520 EXPECT_FALSE(m2.Matches('\x43'));
521 EXPECT_EQ("is even", Describe(m2));
522
523 const Matcher<char> not_m2 = Not(m2);
524 EXPECT_EQ("is odd", Describe(not_m2));
525
526 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
527 }
528
529 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest,FromPolymorphicMatcher)530 TEST(MatcherCastTest, FromPolymorphicMatcher) {
531 Matcher<int> m = MatcherCast<int>(Eq(5));
532 EXPECT_TRUE(m.Matches(5));
533 EXPECT_FALSE(m.Matches(6));
534 }
535
536 // For testing casting matchers between compatible types.
537 class IntValue {
538 public:
539 // An int can be statically (although not implicitly) cast to a
540 // IntValue.
IntValue(int a_value)541 explicit IntValue(int a_value) : value_(a_value) {}
542
value() const543 int value() const { return value_; }
544 private:
545 int value_;
546 };
547
548 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)549 bool IsPositiveIntValue(const IntValue& foo) {
550 return foo.value() > 0;
551 }
552
553 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
554 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)555 TEST(MatcherCastTest, FromCompatibleType) {
556 Matcher<double> m1 = Eq(2.0);
557 Matcher<int> m2 = MatcherCast<int>(m1);
558 EXPECT_TRUE(m2.Matches(2));
559 EXPECT_FALSE(m2.Matches(3));
560
561 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
562 Matcher<int> m4 = MatcherCast<int>(m3);
563 // In the following, the arguments 1 and 0 are statically converted
564 // to IntValue objects, and then tested by the IsPositiveIntValue()
565 // predicate.
566 EXPECT_TRUE(m4.Matches(1));
567 EXPECT_FALSE(m4.Matches(0));
568 }
569
570 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)571 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
572 Matcher<const int&> m1 = Eq(0);
573 Matcher<int> m2 = MatcherCast<int>(m1);
574 EXPECT_TRUE(m2.Matches(0));
575 EXPECT_FALSE(m2.Matches(1));
576 }
577
578 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)579 TEST(MatcherCastTest, FromReferenceToNonReference) {
580 Matcher<int&> m1 = Eq(0);
581 Matcher<int> m2 = MatcherCast<int>(m1);
582 EXPECT_TRUE(m2.Matches(0));
583 EXPECT_FALSE(m2.Matches(1));
584 }
585
586 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)587 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
588 Matcher<int> m1 = Eq(0);
589 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
590 EXPECT_TRUE(m2.Matches(0));
591 EXPECT_FALSE(m2.Matches(1));
592 }
593
594 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)595 TEST(MatcherCastTest, FromNonReferenceToReference) {
596 Matcher<int> m1 = Eq(0);
597 Matcher<int&> m2 = MatcherCast<int&>(m1);
598 int n = 0;
599 EXPECT_TRUE(m2.Matches(n));
600 n = 1;
601 EXPECT_FALSE(m2.Matches(n));
602 }
603
604 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)605 TEST(MatcherCastTest, FromSameType) {
606 Matcher<int> m1 = Eq(0);
607 Matcher<int> m2 = MatcherCast<int>(m1);
608 EXPECT_TRUE(m2.Matches(0));
609 EXPECT_FALSE(m2.Matches(1));
610 }
611
612 // Implicitly convertible from any type.
613 struct ConvertibleFromAny {
ConvertibleFromAnytesting::gmock_matchers_test::ConvertibleFromAny614 ConvertibleFromAny(int a_value) : value(a_value) {}
615 template <typename T>
ConvertibleFromAnytesting::gmock_matchers_test::ConvertibleFromAny616 explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
617 ADD_FAILURE() << "Conversion constructor called";
618 }
619 int value;
620 };
621
operator ==(const ConvertibleFromAny & a,const ConvertibleFromAny & b)622 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
623 return a.value == b.value;
624 }
625
operator <<(ostream & os,const ConvertibleFromAny & a)626 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
627 return os << a.value;
628 }
629
TEST(MatcherCastTest,ConversionConstructorIsUsed)630 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
631 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
632 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
633 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
634 }
635
TEST(MatcherCastTest,FromConvertibleFromAny)636 TEST(MatcherCastTest, FromConvertibleFromAny) {
637 Matcher<ConvertibleFromAny> m =
638 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
639 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
640 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
641 }
642
643 struct IntReferenceWrapper {
IntReferenceWrappertesting::gmock_matchers_test::IntReferenceWrapper644 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
645 const int* value;
646 };
647
operator ==(const IntReferenceWrapper & a,const IntReferenceWrapper & b)648 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
649 return a.value == b.value;
650 }
651
TEST(MatcherCastTest,ValueIsNotCopied)652 TEST(MatcherCastTest, ValueIsNotCopied) {
653 int n = 42;
654 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
655 // Verify that the matcher holds a reference to n, not to its temporary copy.
656 EXPECT_TRUE(m.Matches(n));
657 }
658
659 class Base {
660 public:
~Base()661 virtual ~Base() {}
Base()662 Base() {}
663 private:
664 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
665 };
666
667 class Derived : public Base {
668 public:
Derived()669 Derived() : Base() {}
670 int i;
671 };
672
673 class OtherDerived : public Base {};
674
675 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest,FromPolymorphicMatcher)676 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
677 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
678 EXPECT_TRUE(m2.Matches(' '));
679 EXPECT_FALSE(m2.Matches('\n'));
680 }
681
682 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
683 // T and U are arithmetic types and T can be losslessly converted to
684 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)685 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
686 Matcher<double> m1 = DoubleEq(1.0);
687 Matcher<float> m2 = SafeMatcherCast<float>(m1);
688 EXPECT_TRUE(m2.Matches(1.0f));
689 EXPECT_FALSE(m2.Matches(2.0f));
690
691 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
692 EXPECT_TRUE(m3.Matches('a'));
693 EXPECT_FALSE(m3.Matches('b'));
694 }
695
696 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
697 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)698 TEST(SafeMatcherCastTest, FromBaseClass) {
699 Derived d, d2;
700 Matcher<Base*> m1 = Eq(&d);
701 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
702 EXPECT_TRUE(m2.Matches(&d));
703 EXPECT_FALSE(m2.Matches(&d2));
704
705 Matcher<Base&> m3 = Ref(d);
706 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
707 EXPECT_TRUE(m4.Matches(d));
708 EXPECT_FALSE(m4.Matches(d2));
709 }
710
711 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)712 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
713 int n = 0;
714 Matcher<const int&> m1 = Ref(n);
715 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
716 int n1 = 0;
717 EXPECT_TRUE(m2.Matches(n));
718 EXPECT_FALSE(m2.Matches(n1));
719 }
720
721 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)722 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
723 Matcher<int> m1 = Eq(0);
724 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
725 EXPECT_TRUE(m2.Matches(0));
726 EXPECT_FALSE(m2.Matches(1));
727 }
728
729 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)730 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
731 Matcher<int> m1 = Eq(0);
732 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
733 int n = 0;
734 EXPECT_TRUE(m2.Matches(n));
735 n = 1;
736 EXPECT_FALSE(m2.Matches(n));
737 }
738
739 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)740 TEST(SafeMatcherCastTest, FromSameType) {
741 Matcher<int> m1 = Eq(0);
742 Matcher<int> m2 = SafeMatcherCast<int>(m1);
743 EXPECT_TRUE(m2.Matches(0));
744 EXPECT_FALSE(m2.Matches(1));
745 }
746
TEST(SafeMatcherCastTest,ConversionConstructorIsUsed)747 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
748 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
749 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
750 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
751 }
752
TEST(SafeMatcherCastTest,FromConvertibleFromAny)753 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
754 Matcher<ConvertibleFromAny> m =
755 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
756 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
757 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
758 }
759
TEST(SafeMatcherCastTest,ValueIsNotCopied)760 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
761 int n = 42;
762 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
763 // Verify that the matcher holds a reference to n, not to its temporary copy.
764 EXPECT_TRUE(m.Matches(n));
765 }
766
TEST(ExpectThat,TakesLiterals)767 TEST(ExpectThat, TakesLiterals) {
768 EXPECT_THAT(1, 1);
769 EXPECT_THAT(1.0, 1.0);
770 EXPECT_THAT(string(), "");
771 }
772
TEST(ExpectThat,TakesFunctions)773 TEST(ExpectThat, TakesFunctions) {
774 struct Helper {
775 static void Func() {}
776 };
777 void (*func)() = Helper::Func;
778 EXPECT_THAT(func, Helper::Func);
779 EXPECT_THAT(func, &Helper::Func);
780 }
781
782 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)783 TEST(ATest, MatchesAnyValue) {
784 // Tests a matcher for a value type.
785 Matcher<double> m1 = A<double>();
786 EXPECT_TRUE(m1.Matches(91.43));
787 EXPECT_TRUE(m1.Matches(-15.32));
788
789 // Tests a matcher for a reference type.
790 int a = 2;
791 int b = -6;
792 Matcher<int&> m2 = A<int&>();
793 EXPECT_TRUE(m2.Matches(a));
794 EXPECT_TRUE(m2.Matches(b));
795 }
796
TEST(ATest,WorksForDerivedClass)797 TEST(ATest, WorksForDerivedClass) {
798 Base base;
799 Derived derived;
800 EXPECT_THAT(&base, A<Base*>());
801 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
802 EXPECT_THAT(&derived, A<Base*>());
803 EXPECT_THAT(&derived, A<Derived*>());
804 }
805
806 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)807 TEST(ATest, CanDescribeSelf) {
808 EXPECT_EQ("is anything", Describe(A<bool>()));
809 }
810
811 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)812 TEST(AnTest, MatchesAnyValue) {
813 // Tests a matcher for a value type.
814 Matcher<int> m1 = An<int>();
815 EXPECT_TRUE(m1.Matches(9143));
816 EXPECT_TRUE(m1.Matches(-1532));
817
818 // Tests a matcher for a reference type.
819 int a = 2;
820 int b = -6;
821 Matcher<int&> m2 = An<int&>();
822 EXPECT_TRUE(m2.Matches(a));
823 EXPECT_TRUE(m2.Matches(b));
824 }
825
826 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)827 TEST(AnTest, CanDescribeSelf) {
828 EXPECT_EQ("is anything", Describe(An<int>()));
829 }
830
831 // Tests that _ can be used as a matcher for any type and matches any
832 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)833 TEST(UnderscoreTest, MatchesAnyValue) {
834 // Uses _ as a matcher for a value type.
835 Matcher<int> m1 = _;
836 EXPECT_TRUE(m1.Matches(123));
837 EXPECT_TRUE(m1.Matches(-242));
838
839 // Uses _ as a matcher for a reference type.
840 bool a = false;
841 const bool b = true;
842 Matcher<const bool&> m2 = _;
843 EXPECT_TRUE(m2.Matches(a));
844 EXPECT_TRUE(m2.Matches(b));
845 }
846
847 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)848 TEST(UnderscoreTest, CanDescribeSelf) {
849 Matcher<int> m = _;
850 EXPECT_EQ("is anything", Describe(m));
851 }
852
853 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)854 TEST(EqTest, MatchesEqualValue) {
855 // 2 C-strings with same content but different addresses.
856 const char a1[] = "hi";
857 const char a2[] = "hi";
858
859 Matcher<const char*> m1 = Eq(a1);
860 EXPECT_TRUE(m1.Matches(a1));
861 EXPECT_FALSE(m1.Matches(a2));
862 }
863
864 // Tests that Eq(v) describes itself properly.
865
866 class Unprintable {
867 public:
Unprintable()868 Unprintable() : c_('a') {}
869
870 private:
871 char c_;
872 };
873
operator ==(const Unprintable &,const Unprintable &)874 inline bool operator==(const Unprintable& /* lhs */,
875 const Unprintable& /* rhs */) {
876 return true;
877 }
878
TEST(EqTest,CanDescribeSelf)879 TEST(EqTest, CanDescribeSelf) {
880 Matcher<Unprintable> m = Eq(Unprintable());
881 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
882 }
883
884 // Tests that Eq(v) can be used to match any type that supports
885 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)886 TEST(EqTest, IsPolymorphic) {
887 Matcher<int> m1 = Eq(1);
888 EXPECT_TRUE(m1.Matches(1));
889 EXPECT_FALSE(m1.Matches(2));
890
891 Matcher<char> m2 = Eq(1);
892 EXPECT_TRUE(m2.Matches('\1'));
893 EXPECT_FALSE(m2.Matches('a'));
894 }
895
896 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)897 TEST(TypedEqTest, ChecksEqualityForGivenType) {
898 Matcher<char> m1 = TypedEq<char>('a');
899 EXPECT_TRUE(m1.Matches('a'));
900 EXPECT_FALSE(m1.Matches('b'));
901
902 Matcher<int> m2 = TypedEq<int>(6);
903 EXPECT_TRUE(m2.Matches(6));
904 EXPECT_FALSE(m2.Matches(7));
905 }
906
907 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)908 TEST(TypedEqTest, CanDescribeSelf) {
909 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
910 }
911
912 // Tests that TypedEq<T>(v) has type Matcher<T>.
913
914 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
915 // is a "bare" type (i.e. not in the form of const U or U&). If v's
916 // type is not T, the compiler will generate a message about
917 // "undefined reference".
918 template <typename T>
919 struct Type {
IsTypeOftesting::gmock_matchers_test::Type920 static bool IsTypeOf(const T& /* v */) { return true; }
921
922 template <typename T2>
923 static void IsTypeOf(T2 v);
924 };
925
TEST(TypedEqTest,HasSpecifiedType)926 TEST(TypedEqTest, HasSpecifiedType) {
927 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
928 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
929 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
930 }
931
932 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)933 TEST(GeTest, ImplementsGreaterThanOrEqual) {
934 Matcher<int> m1 = Ge(0);
935 EXPECT_TRUE(m1.Matches(1));
936 EXPECT_TRUE(m1.Matches(0));
937 EXPECT_FALSE(m1.Matches(-1));
938 }
939
940 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)941 TEST(GeTest, CanDescribeSelf) {
942 Matcher<int> m = Ge(5);
943 EXPECT_EQ("is >= 5", Describe(m));
944 }
945
946 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)947 TEST(GtTest, ImplementsGreaterThan) {
948 Matcher<double> m1 = Gt(0);
949 EXPECT_TRUE(m1.Matches(1.0));
950 EXPECT_FALSE(m1.Matches(0.0));
951 EXPECT_FALSE(m1.Matches(-1.0));
952 }
953
954 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)955 TEST(GtTest, CanDescribeSelf) {
956 Matcher<int> m = Gt(5);
957 EXPECT_EQ("is > 5", Describe(m));
958 }
959
960 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)961 TEST(LeTest, ImplementsLessThanOrEqual) {
962 Matcher<char> m1 = Le('b');
963 EXPECT_TRUE(m1.Matches('a'));
964 EXPECT_TRUE(m1.Matches('b'));
965 EXPECT_FALSE(m1.Matches('c'));
966 }
967
968 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)969 TEST(LeTest, CanDescribeSelf) {
970 Matcher<int> m = Le(5);
971 EXPECT_EQ("is <= 5", Describe(m));
972 }
973
974 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)975 TEST(LtTest, ImplementsLessThan) {
976 Matcher<const std::string&> m1 = Lt("Hello");
977 EXPECT_TRUE(m1.Matches("Abc"));
978 EXPECT_FALSE(m1.Matches("Hello"));
979 EXPECT_FALSE(m1.Matches("Hello, world!"));
980 }
981
982 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)983 TEST(LtTest, CanDescribeSelf) {
984 Matcher<int> m = Lt(5);
985 EXPECT_EQ("is < 5", Describe(m));
986 }
987
988 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)989 TEST(NeTest, ImplementsNotEqual) {
990 Matcher<int> m1 = Ne(0);
991 EXPECT_TRUE(m1.Matches(1));
992 EXPECT_TRUE(m1.Matches(-1));
993 EXPECT_FALSE(m1.Matches(0));
994 }
995
996 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)997 TEST(NeTest, CanDescribeSelf) {
998 Matcher<int> m = Ne(5);
999 EXPECT_EQ("isn't equal to 5", Describe(m));
1000 }
1001
1002 // Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest,MatchesNullPointer)1003 TEST(IsNullTest, MatchesNullPointer) {
1004 Matcher<int*> m1 = IsNull();
1005 int* p1 = NULL;
1006 int n = 0;
1007 EXPECT_TRUE(m1.Matches(p1));
1008 EXPECT_FALSE(m1.Matches(&n));
1009
1010 Matcher<const char*> m2 = IsNull();
1011 const char* p2 = NULL;
1012 EXPECT_TRUE(m2.Matches(p2));
1013 EXPECT_FALSE(m2.Matches("hi"));
1014
1015 #if !GTEST_OS_SYMBIAN
1016 // Nokia's Symbian compiler generates:
1017 // gmock-matchers.h: ambiguous access to overloaded function
1018 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1019 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1020 // MatcherInterface<void *> *)'
1021 // gmock-matchers.h: (point of instantiation: 'testing::
1022 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1023 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
1024 Matcher<void*> m3 = IsNull();
1025 void* p3 = NULL;
1026 EXPECT_TRUE(m3.Matches(p3));
1027 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1028 #endif
1029 }
1030
TEST(IsNullTest,LinkedPtr)1031 TEST(IsNullTest, LinkedPtr) {
1032 const Matcher<linked_ptr<int> > m = IsNull();
1033 const linked_ptr<int> null_p;
1034 const linked_ptr<int> non_null_p(new int);
1035
1036 EXPECT_TRUE(m.Matches(null_p));
1037 EXPECT_FALSE(m.Matches(non_null_p));
1038 }
1039
TEST(IsNullTest,ReferenceToConstLinkedPtr)1040 TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1041 const Matcher<const linked_ptr<double>&> m = IsNull();
1042 const linked_ptr<double> null_p;
1043 const linked_ptr<double> non_null_p(new double);
1044
1045 EXPECT_TRUE(m.Matches(null_p));
1046 EXPECT_FALSE(m.Matches(non_null_p));
1047 }
1048
1049 #if GTEST_HAS_STD_FUNCTION_
TEST(IsNullTest,StdFunction)1050 TEST(IsNullTest, StdFunction) {
1051 const Matcher<std::function<void()>> m = IsNull();
1052
1053 EXPECT_TRUE(m.Matches(std::function<void()>()));
1054 EXPECT_FALSE(m.Matches([]{}));
1055 }
1056 #endif // GTEST_HAS_STD_FUNCTION_
1057
1058 // Tests that IsNull() describes itself properly.
TEST(IsNullTest,CanDescribeSelf)1059 TEST(IsNullTest, CanDescribeSelf) {
1060 Matcher<int*> m = IsNull();
1061 EXPECT_EQ("is NULL", Describe(m));
1062 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1063 }
1064
1065 // Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest,MatchesNonNullPointer)1066 TEST(NotNullTest, MatchesNonNullPointer) {
1067 Matcher<int*> m1 = NotNull();
1068 int* p1 = NULL;
1069 int n = 0;
1070 EXPECT_FALSE(m1.Matches(p1));
1071 EXPECT_TRUE(m1.Matches(&n));
1072
1073 Matcher<const char*> m2 = NotNull();
1074 const char* p2 = NULL;
1075 EXPECT_FALSE(m2.Matches(p2));
1076 EXPECT_TRUE(m2.Matches("hi"));
1077 }
1078
TEST(NotNullTest,LinkedPtr)1079 TEST(NotNullTest, LinkedPtr) {
1080 const Matcher<linked_ptr<int> > m = NotNull();
1081 const linked_ptr<int> null_p;
1082 const linked_ptr<int> non_null_p(new int);
1083
1084 EXPECT_FALSE(m.Matches(null_p));
1085 EXPECT_TRUE(m.Matches(non_null_p));
1086 }
1087
TEST(NotNullTest,ReferenceToConstLinkedPtr)1088 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1089 const Matcher<const linked_ptr<double>&> m = NotNull();
1090 const linked_ptr<double> null_p;
1091 const linked_ptr<double> non_null_p(new double);
1092
1093 EXPECT_FALSE(m.Matches(null_p));
1094 EXPECT_TRUE(m.Matches(non_null_p));
1095 }
1096
1097 #if GTEST_HAS_STD_FUNCTION_
TEST(NotNullTest,StdFunction)1098 TEST(NotNullTest, StdFunction) {
1099 const Matcher<std::function<void()>> m = NotNull();
1100
1101 EXPECT_TRUE(m.Matches([]{}));
1102 EXPECT_FALSE(m.Matches(std::function<void()>()));
1103 }
1104 #endif // GTEST_HAS_STD_FUNCTION_
1105
1106 // Tests that NotNull() describes itself properly.
TEST(NotNullTest,CanDescribeSelf)1107 TEST(NotNullTest, CanDescribeSelf) {
1108 Matcher<int*> m = NotNull();
1109 EXPECT_EQ("isn't NULL", Describe(m));
1110 }
1111
1112 // Tests that Ref(variable) matches an argument that references
1113 // 'variable'.
TEST(RefTest,MatchesSameVariable)1114 TEST(RefTest, MatchesSameVariable) {
1115 int a = 0;
1116 int b = 0;
1117 Matcher<int&> m = Ref(a);
1118 EXPECT_TRUE(m.Matches(a));
1119 EXPECT_FALSE(m.Matches(b));
1120 }
1121
1122 // Tests that Ref(variable) describes itself properly.
TEST(RefTest,CanDescribeSelf)1123 TEST(RefTest, CanDescribeSelf) {
1124 int n = 5;
1125 Matcher<int&> m = Ref(n);
1126 stringstream ss;
1127 ss << "references the variable @" << &n << " 5";
1128 EXPECT_EQ(ss.str(), Describe(m));
1129 }
1130
1131 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1132 // const reference.
TEST(RefTest,CanBeUsedAsMatcherForConstReference)1133 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1134 int a = 0;
1135 int b = 0;
1136 Matcher<const int&> m = Ref(a);
1137 EXPECT_TRUE(m.Matches(a));
1138 EXPECT_FALSE(m.Matches(b));
1139 }
1140
1141 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1142 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1143 // of Ref(base), but not vice versa.
1144
TEST(RefTest,IsCovariant)1145 TEST(RefTest, IsCovariant) {
1146 Base base, base2;
1147 Derived derived;
1148 Matcher<const Base&> m1 = Ref(base);
1149 EXPECT_TRUE(m1.Matches(base));
1150 EXPECT_FALSE(m1.Matches(base2));
1151 EXPECT_FALSE(m1.Matches(derived));
1152
1153 m1 = Ref(derived);
1154 EXPECT_TRUE(m1.Matches(derived));
1155 EXPECT_FALSE(m1.Matches(base));
1156 EXPECT_FALSE(m1.Matches(base2));
1157 }
1158
TEST(RefTest,ExplainsResult)1159 TEST(RefTest, ExplainsResult) {
1160 int n = 0;
1161 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1162 StartsWith("which is located @"));
1163
1164 int m = 0;
1165 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1166 StartsWith("which is located @"));
1167 }
1168
1169 // Tests string comparison matchers.
1170
TEST(StrEqTest,MatchesEqualString)1171 TEST(StrEqTest, MatchesEqualString) {
1172 Matcher<const char*> m = StrEq(std::string("Hello"));
1173 EXPECT_TRUE(m.Matches("Hello"));
1174 EXPECT_FALSE(m.Matches("hello"));
1175 EXPECT_FALSE(m.Matches(NULL));
1176
1177 Matcher<const std::string&> m2 = StrEq("Hello");
1178 EXPECT_TRUE(m2.Matches("Hello"));
1179 EXPECT_FALSE(m2.Matches("Hi"));
1180 }
1181
TEST(StrEqTest,CanDescribeSelf)1182 TEST(StrEqTest, CanDescribeSelf) {
1183 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1184 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1185 Describe(m));
1186
1187 std::string str("01204500800");
1188 str[3] = '\0';
1189 Matcher<std::string> m2 = StrEq(str);
1190 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1191 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1192 Matcher<std::string> m3 = StrEq(str);
1193 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1194 }
1195
TEST(StrNeTest,MatchesUnequalString)1196 TEST(StrNeTest, MatchesUnequalString) {
1197 Matcher<const char*> m = StrNe("Hello");
1198 EXPECT_TRUE(m.Matches(""));
1199 EXPECT_TRUE(m.Matches(NULL));
1200 EXPECT_FALSE(m.Matches("Hello"));
1201
1202 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1203 EXPECT_TRUE(m2.Matches("hello"));
1204 EXPECT_FALSE(m2.Matches("Hello"));
1205 }
1206
TEST(StrNeTest,CanDescribeSelf)1207 TEST(StrNeTest, CanDescribeSelf) {
1208 Matcher<const char*> m = StrNe("Hi");
1209 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1210 }
1211
TEST(StrCaseEqTest,MatchesEqualStringIgnoringCase)1212 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1213 Matcher<const char*> m = StrCaseEq(string("Hello"));
1214 EXPECT_TRUE(m.Matches("Hello"));
1215 EXPECT_TRUE(m.Matches("hello"));
1216 EXPECT_FALSE(m.Matches("Hi"));
1217 EXPECT_FALSE(m.Matches(NULL));
1218
1219 Matcher<const string&> m2 = StrCaseEq("Hello");
1220 EXPECT_TRUE(m2.Matches("hello"));
1221 EXPECT_FALSE(m2.Matches("Hi"));
1222 }
1223
TEST(StrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1224 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1225 std::string str1("oabocdooeoo");
1226 std::string str2("OABOCDOOEOO");
1227 Matcher<const std::string&> m0 = StrCaseEq(str1);
1228 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1229
1230 str1[3] = str2[3] = '\0';
1231 Matcher<const std::string&> m1 = StrCaseEq(str1);
1232 EXPECT_TRUE(m1.Matches(str2));
1233
1234 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1235 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1236 Matcher<const std::string&> m2 = StrCaseEq(str1);
1237 str1[9] = str2[9] = '\0';
1238 EXPECT_FALSE(m2.Matches(str2));
1239
1240 Matcher<const std::string&> m3 = StrCaseEq(str1);
1241 EXPECT_TRUE(m3.Matches(str2));
1242
1243 EXPECT_FALSE(m3.Matches(str2 + "x"));
1244 str2.append(1, '\0');
1245 EXPECT_FALSE(m3.Matches(str2));
1246 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1247 }
1248
TEST(StrCaseEqTest,CanDescribeSelf)1249 TEST(StrCaseEqTest, CanDescribeSelf) {
1250 Matcher<std::string> m = StrCaseEq("Hi");
1251 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1252 }
1253
TEST(StrCaseNeTest,MatchesUnequalStringIgnoringCase)1254 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1255 Matcher<const char*> m = StrCaseNe("Hello");
1256 EXPECT_TRUE(m.Matches("Hi"));
1257 EXPECT_TRUE(m.Matches(NULL));
1258 EXPECT_FALSE(m.Matches("Hello"));
1259 EXPECT_FALSE(m.Matches("hello"));
1260
1261 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1262 EXPECT_TRUE(m2.Matches(""));
1263 EXPECT_FALSE(m2.Matches("Hello"));
1264 }
1265
TEST(StrCaseNeTest,CanDescribeSelf)1266 TEST(StrCaseNeTest, CanDescribeSelf) {
1267 Matcher<const char*> m = StrCaseNe("Hi");
1268 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1269 }
1270
1271 // Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest,WorksForStringClasses)1272 TEST(HasSubstrTest, WorksForStringClasses) {
1273 const Matcher<std::string> m1 = HasSubstr("foo");
1274 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1275 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1276
1277 const Matcher<const std::string&> m2 = HasSubstr("foo");
1278 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1279 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1280 }
1281
1282 // Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest,WorksForCStrings)1283 TEST(HasSubstrTest, WorksForCStrings) {
1284 const Matcher<char*> m1 = HasSubstr("foo");
1285 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1286 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1287 EXPECT_FALSE(m1.Matches(NULL));
1288
1289 const Matcher<const char*> m2 = HasSubstr("foo");
1290 EXPECT_TRUE(m2.Matches("I love food."));
1291 EXPECT_FALSE(m2.Matches("tofo"));
1292 EXPECT_FALSE(m2.Matches(NULL));
1293 }
1294
1295 // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest,CanDescribeSelf)1296 TEST(HasSubstrTest, CanDescribeSelf) {
1297 Matcher<std::string> m = HasSubstr("foo\n\"");
1298 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1299 }
1300
TEST(KeyTest,CanDescribeSelf)1301 TEST(KeyTest, CanDescribeSelf) {
1302 Matcher<const pair<std::string, int>&> m = Key("foo");
1303 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1304 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1305 }
1306
TEST(KeyTest,ExplainsResult)1307 TEST(KeyTest, ExplainsResult) {
1308 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1309 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1310 Explain(m, make_pair(5, true)));
1311 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1312 Explain(m, make_pair(15, true)));
1313 }
1314
TEST(KeyTest,MatchesCorrectly)1315 TEST(KeyTest, MatchesCorrectly) {
1316 pair<int, std::string> p(25, "foo");
1317 EXPECT_THAT(p, Key(25));
1318 EXPECT_THAT(p, Not(Key(42)));
1319 EXPECT_THAT(p, Key(Ge(20)));
1320 EXPECT_THAT(p, Not(Key(Lt(25))));
1321 }
1322
TEST(KeyTest,SafelyCastsInnerMatcher)1323 TEST(KeyTest, SafelyCastsInnerMatcher) {
1324 Matcher<int> is_positive = Gt(0);
1325 Matcher<int> is_negative = Lt(0);
1326 pair<char, bool> p('a', true);
1327 EXPECT_THAT(p, Key(is_positive));
1328 EXPECT_THAT(p, Not(Key(is_negative)));
1329 }
1330
TEST(KeyTest,InsideContainsUsingMap)1331 TEST(KeyTest, InsideContainsUsingMap) {
1332 map<int, char> container;
1333 container.insert(make_pair(1, 'a'));
1334 container.insert(make_pair(2, 'b'));
1335 container.insert(make_pair(4, 'c'));
1336 EXPECT_THAT(container, Contains(Key(1)));
1337 EXPECT_THAT(container, Not(Contains(Key(3))));
1338 }
1339
TEST(KeyTest,InsideContainsUsingMultimap)1340 TEST(KeyTest, InsideContainsUsingMultimap) {
1341 multimap<int, char> container;
1342 container.insert(make_pair(1, 'a'));
1343 container.insert(make_pair(2, 'b'));
1344 container.insert(make_pair(4, 'c'));
1345
1346 EXPECT_THAT(container, Not(Contains(Key(25))));
1347 container.insert(make_pair(25, 'd'));
1348 EXPECT_THAT(container, Contains(Key(25)));
1349 container.insert(make_pair(25, 'e'));
1350 EXPECT_THAT(container, Contains(Key(25)));
1351
1352 EXPECT_THAT(container, Contains(Key(1)));
1353 EXPECT_THAT(container, Not(Contains(Key(3))));
1354 }
1355
TEST(PairTest,Typing)1356 TEST(PairTest, Typing) {
1357 // Test verifies the following type conversions can be compiled.
1358 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1359 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1360 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1361
1362 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1363 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1364 }
1365
TEST(PairTest,CanDescribeSelf)1366 TEST(PairTest, CanDescribeSelf) {
1367 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1368 EXPECT_EQ("has a first field that is equal to \"foo\""
1369 ", and has a second field that is equal to 42",
1370 Describe(m1));
1371 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1372 ", or has a second field that isn't equal to 42",
1373 DescribeNegation(m1));
1374 // Double and triple negation (1 or 2 times not and description of negation).
1375 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1376 EXPECT_EQ("has a first field that isn't equal to 13"
1377 ", and has a second field that is equal to 42",
1378 DescribeNegation(m2));
1379 }
1380
TEST(PairTest,CanExplainMatchResultTo)1381 TEST(PairTest, CanExplainMatchResultTo) {
1382 // If neither field matches, Pair() should explain about the first
1383 // field.
1384 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1385 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1386 Explain(m, make_pair(-1, -2)));
1387
1388 // If the first field matches but the second doesn't, Pair() should
1389 // explain about the second field.
1390 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1391 Explain(m, make_pair(1, -2)));
1392
1393 // If the first field doesn't match but the second does, Pair()
1394 // should explain about the first field.
1395 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1396 Explain(m, make_pair(-1, 2)));
1397
1398 // If both fields match, Pair() should explain about them both.
1399 EXPECT_EQ("whose both fields match, where the first field is a value "
1400 "which is 1 more than 0, and the second field is a value "
1401 "which is 2 more than 0",
1402 Explain(m, make_pair(1, 2)));
1403
1404 // If only the first match has an explanation, only this explanation should
1405 // be printed.
1406 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1407 EXPECT_EQ("whose both fields match, where the first field is a value "
1408 "which is 1 more than 0",
1409 Explain(explain_first, make_pair(1, 0)));
1410
1411 // If only the second match has an explanation, only this explanation should
1412 // be printed.
1413 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1414 EXPECT_EQ("whose both fields match, where the second field is a value "
1415 "which is 1 more than 0",
1416 Explain(explain_second, make_pair(0, 1)));
1417 }
1418
TEST(PairTest,MatchesCorrectly)1419 TEST(PairTest, MatchesCorrectly) {
1420 pair<int, std::string> p(25, "foo");
1421
1422 // Both fields match.
1423 EXPECT_THAT(p, Pair(25, "foo"));
1424 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1425
1426 // 'first' does not match, but 'second' matches.
1427 EXPECT_THAT(p, Not(Pair(42, "foo")));
1428 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1429
1430 // 'first' matches, but 'second' doesn't match.
1431 EXPECT_THAT(p, Not(Pair(25, "bar")));
1432 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1433
1434 // Neither field matches.
1435 EXPECT_THAT(p, Not(Pair(13, "bar")));
1436 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1437 }
1438
TEST(PairTest,SafelyCastsInnerMatchers)1439 TEST(PairTest, SafelyCastsInnerMatchers) {
1440 Matcher<int> is_positive = Gt(0);
1441 Matcher<int> is_negative = Lt(0);
1442 pair<char, bool> p('a', true);
1443 EXPECT_THAT(p, Pair(is_positive, _));
1444 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1445 EXPECT_THAT(p, Pair(_, is_positive));
1446 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1447 }
1448
TEST(PairTest,InsideContainsUsingMap)1449 TEST(PairTest, InsideContainsUsingMap) {
1450 map<int, char> container;
1451 container.insert(make_pair(1, 'a'));
1452 container.insert(make_pair(2, 'b'));
1453 container.insert(make_pair(4, 'c'));
1454 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1455 EXPECT_THAT(container, Contains(Pair(1, _)));
1456 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1457 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1458 }
1459
1460 // Tests StartsWith(s).
1461
TEST(StartsWithTest,MatchesStringWithGivenPrefix)1462 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1463 const Matcher<const char*> m1 = StartsWith(std::string(""));
1464 EXPECT_TRUE(m1.Matches("Hi"));
1465 EXPECT_TRUE(m1.Matches(""));
1466 EXPECT_FALSE(m1.Matches(NULL));
1467
1468 const Matcher<const std::string&> m2 = StartsWith("Hi");
1469 EXPECT_TRUE(m2.Matches("Hi"));
1470 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1471 EXPECT_TRUE(m2.Matches("High"));
1472 EXPECT_FALSE(m2.Matches("H"));
1473 EXPECT_FALSE(m2.Matches(" Hi"));
1474 }
1475
TEST(StartsWithTest,CanDescribeSelf)1476 TEST(StartsWithTest, CanDescribeSelf) {
1477 Matcher<const std::string> m = StartsWith("Hi");
1478 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1479 }
1480
1481 // Tests EndsWith(s).
1482
TEST(EndsWithTest,MatchesStringWithGivenSuffix)1483 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1484 const Matcher<const char*> m1 = EndsWith("");
1485 EXPECT_TRUE(m1.Matches("Hi"));
1486 EXPECT_TRUE(m1.Matches(""));
1487 EXPECT_FALSE(m1.Matches(NULL));
1488
1489 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1490 EXPECT_TRUE(m2.Matches("Hi"));
1491 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1492 EXPECT_TRUE(m2.Matches("Super Hi"));
1493 EXPECT_FALSE(m2.Matches("i"));
1494 EXPECT_FALSE(m2.Matches("Hi "));
1495 }
1496
TEST(EndsWithTest,CanDescribeSelf)1497 TEST(EndsWithTest, CanDescribeSelf) {
1498 Matcher<const std::string> m = EndsWith("Hi");
1499 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1500 }
1501
1502 // Tests MatchesRegex().
1503
TEST(MatchesRegexTest,MatchesStringMatchingGivenRegex)1504 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1505 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1506 EXPECT_TRUE(m1.Matches("az"));
1507 EXPECT_TRUE(m1.Matches("abcz"));
1508 EXPECT_FALSE(m1.Matches(NULL));
1509
1510 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1511 EXPECT_TRUE(m2.Matches("azbz"));
1512 EXPECT_FALSE(m2.Matches("az1"));
1513 EXPECT_FALSE(m2.Matches("1az"));
1514 }
1515
TEST(MatchesRegexTest,CanDescribeSelf)1516 TEST(MatchesRegexTest, CanDescribeSelf) {
1517 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1518 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1519
1520 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1521 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1522 }
1523
1524 // Tests ContainsRegex().
1525
TEST(ContainsRegexTest,MatchesStringContainingGivenRegex)1526 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1527 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1528 EXPECT_TRUE(m1.Matches("az"));
1529 EXPECT_TRUE(m1.Matches("0abcz1"));
1530 EXPECT_FALSE(m1.Matches(NULL));
1531
1532 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1533 EXPECT_TRUE(m2.Matches("azbz"));
1534 EXPECT_TRUE(m2.Matches("az1"));
1535 EXPECT_FALSE(m2.Matches("1a"));
1536 }
1537
TEST(ContainsRegexTest,CanDescribeSelf)1538 TEST(ContainsRegexTest, CanDescribeSelf) {
1539 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1540 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1541
1542 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1543 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1544 }
1545
1546 // Tests for wide strings.
1547 #if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest,MatchesEqual)1548 TEST(StdWideStrEqTest, MatchesEqual) {
1549 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1550 EXPECT_TRUE(m.Matches(L"Hello"));
1551 EXPECT_FALSE(m.Matches(L"hello"));
1552 EXPECT_FALSE(m.Matches(NULL));
1553
1554 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1555 EXPECT_TRUE(m2.Matches(L"Hello"));
1556 EXPECT_FALSE(m2.Matches(L"Hi"));
1557
1558 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1559 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1560 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1561
1562 ::std::wstring str(L"01204500800");
1563 str[3] = L'\0';
1564 Matcher<const ::std::wstring&> m4 = StrEq(str);
1565 EXPECT_TRUE(m4.Matches(str));
1566 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1567 Matcher<const ::std::wstring&> m5 = StrEq(str);
1568 EXPECT_TRUE(m5.Matches(str));
1569 }
1570
TEST(StdWideStrEqTest,CanDescribeSelf)1571 TEST(StdWideStrEqTest, CanDescribeSelf) {
1572 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1573 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1574 Describe(m));
1575
1576 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1577 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1578 Describe(m2));
1579
1580 ::std::wstring str(L"01204500800");
1581 str[3] = L'\0';
1582 Matcher<const ::std::wstring&> m4 = StrEq(str);
1583 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1584 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1585 Matcher<const ::std::wstring&> m5 = StrEq(str);
1586 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1587 }
1588
TEST(StdWideStrNeTest,MatchesUnequalString)1589 TEST(StdWideStrNeTest, MatchesUnequalString) {
1590 Matcher<const wchar_t*> m = StrNe(L"Hello");
1591 EXPECT_TRUE(m.Matches(L""));
1592 EXPECT_TRUE(m.Matches(NULL));
1593 EXPECT_FALSE(m.Matches(L"Hello"));
1594
1595 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1596 EXPECT_TRUE(m2.Matches(L"hello"));
1597 EXPECT_FALSE(m2.Matches(L"Hello"));
1598 }
1599
TEST(StdWideStrNeTest,CanDescribeSelf)1600 TEST(StdWideStrNeTest, CanDescribeSelf) {
1601 Matcher<const wchar_t*> m = StrNe(L"Hi");
1602 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1603 }
1604
TEST(StdWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1605 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1606 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1607 EXPECT_TRUE(m.Matches(L"Hello"));
1608 EXPECT_TRUE(m.Matches(L"hello"));
1609 EXPECT_FALSE(m.Matches(L"Hi"));
1610 EXPECT_FALSE(m.Matches(NULL));
1611
1612 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1613 EXPECT_TRUE(m2.Matches(L"hello"));
1614 EXPECT_FALSE(m2.Matches(L"Hi"));
1615 }
1616
TEST(StdWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1617 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1618 ::std::wstring str1(L"oabocdooeoo");
1619 ::std::wstring str2(L"OABOCDOOEOO");
1620 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1621 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1622
1623 str1[3] = str2[3] = L'\0';
1624 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1625 EXPECT_TRUE(m1.Matches(str2));
1626
1627 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1628 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1629 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1630 str1[9] = str2[9] = L'\0';
1631 EXPECT_FALSE(m2.Matches(str2));
1632
1633 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1634 EXPECT_TRUE(m3.Matches(str2));
1635
1636 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1637 str2.append(1, L'\0');
1638 EXPECT_FALSE(m3.Matches(str2));
1639 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1640 }
1641
TEST(StdWideStrCaseEqTest,CanDescribeSelf)1642 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1643 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1644 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1645 }
1646
TEST(StdWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1647 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1648 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1649 EXPECT_TRUE(m.Matches(L"Hi"));
1650 EXPECT_TRUE(m.Matches(NULL));
1651 EXPECT_FALSE(m.Matches(L"Hello"));
1652 EXPECT_FALSE(m.Matches(L"hello"));
1653
1654 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1655 EXPECT_TRUE(m2.Matches(L""));
1656 EXPECT_FALSE(m2.Matches(L"Hello"));
1657 }
1658
TEST(StdWideStrCaseNeTest,CanDescribeSelf)1659 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1660 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1661 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1662 }
1663
1664 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest,WorksForStringClasses)1665 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1666 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1667 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1668 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1669
1670 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1671 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1672 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1673 }
1674
1675 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest,WorksForCStrings)1676 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1677 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1678 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1679 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1680 EXPECT_FALSE(m1.Matches(NULL));
1681
1682 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1683 EXPECT_TRUE(m2.Matches(L"I love food."));
1684 EXPECT_FALSE(m2.Matches(L"tofo"));
1685 EXPECT_FALSE(m2.Matches(NULL));
1686 }
1687
1688 // Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest,CanDescribeSelf)1689 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1690 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1691 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1692 }
1693
1694 // Tests StartsWith(s).
1695
TEST(StdWideStartsWithTest,MatchesStringWithGivenPrefix)1696 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1697 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1698 EXPECT_TRUE(m1.Matches(L"Hi"));
1699 EXPECT_TRUE(m1.Matches(L""));
1700 EXPECT_FALSE(m1.Matches(NULL));
1701
1702 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1703 EXPECT_TRUE(m2.Matches(L"Hi"));
1704 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1705 EXPECT_TRUE(m2.Matches(L"High"));
1706 EXPECT_FALSE(m2.Matches(L"H"));
1707 EXPECT_FALSE(m2.Matches(L" Hi"));
1708 }
1709
TEST(StdWideStartsWithTest,CanDescribeSelf)1710 TEST(StdWideStartsWithTest, CanDescribeSelf) {
1711 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1712 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1713 }
1714
1715 // Tests EndsWith(s).
1716
TEST(StdWideEndsWithTest,MatchesStringWithGivenSuffix)1717 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1718 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1719 EXPECT_TRUE(m1.Matches(L"Hi"));
1720 EXPECT_TRUE(m1.Matches(L""));
1721 EXPECT_FALSE(m1.Matches(NULL));
1722
1723 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1724 EXPECT_TRUE(m2.Matches(L"Hi"));
1725 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1726 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1727 EXPECT_FALSE(m2.Matches(L"i"));
1728 EXPECT_FALSE(m2.Matches(L"Hi "));
1729 }
1730
TEST(StdWideEndsWithTest,CanDescribeSelf)1731 TEST(StdWideEndsWithTest, CanDescribeSelf) {
1732 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1733 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1734 }
1735
1736 #endif // GTEST_HAS_STD_WSTRING
1737
1738 #if GTEST_HAS_GLOBAL_WSTRING
TEST(GlobalWideStrEqTest,MatchesEqual)1739 TEST(GlobalWideStrEqTest, MatchesEqual) {
1740 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1741 EXPECT_TRUE(m.Matches(L"Hello"));
1742 EXPECT_FALSE(m.Matches(L"hello"));
1743 EXPECT_FALSE(m.Matches(NULL));
1744
1745 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1746 EXPECT_TRUE(m2.Matches(L"Hello"));
1747 EXPECT_FALSE(m2.Matches(L"Hi"));
1748
1749 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1750 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1751 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1752
1753 ::wstring str(L"01204500800");
1754 str[3] = L'\0';
1755 Matcher<const ::wstring&> m4 = StrEq(str);
1756 EXPECT_TRUE(m4.Matches(str));
1757 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1758 Matcher<const ::wstring&> m5 = StrEq(str);
1759 EXPECT_TRUE(m5.Matches(str));
1760 }
1761
TEST(GlobalWideStrEqTest,CanDescribeSelf)1762 TEST(GlobalWideStrEqTest, CanDescribeSelf) {
1763 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1764 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1765 Describe(m));
1766
1767 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1768 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1769 Describe(m2));
1770
1771 ::wstring str(L"01204500800");
1772 str[3] = L'\0';
1773 Matcher<const ::wstring&> m4 = StrEq(str);
1774 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1775 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1776 Matcher<const ::wstring&> m5 = StrEq(str);
1777 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1778 }
1779
TEST(GlobalWideStrNeTest,MatchesUnequalString)1780 TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1781 Matcher<const wchar_t*> m = StrNe(L"Hello");
1782 EXPECT_TRUE(m.Matches(L""));
1783 EXPECT_TRUE(m.Matches(NULL));
1784 EXPECT_FALSE(m.Matches(L"Hello"));
1785
1786 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1787 EXPECT_TRUE(m2.Matches(L"hello"));
1788 EXPECT_FALSE(m2.Matches(L"Hello"));
1789 }
1790
TEST(GlobalWideStrNeTest,CanDescribeSelf)1791 TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1792 Matcher<const wchar_t*> m = StrNe(L"Hi");
1793 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1794 }
1795
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1796 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1797 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1798 EXPECT_TRUE(m.Matches(L"Hello"));
1799 EXPECT_TRUE(m.Matches(L"hello"));
1800 EXPECT_FALSE(m.Matches(L"Hi"));
1801 EXPECT_FALSE(m.Matches(NULL));
1802
1803 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1804 EXPECT_TRUE(m2.Matches(L"hello"));
1805 EXPECT_FALSE(m2.Matches(L"Hi"));
1806 }
1807
TEST(GlobalWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1808 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1809 ::wstring str1(L"oabocdooeoo");
1810 ::wstring str2(L"OABOCDOOEOO");
1811 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1812 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1813
1814 str1[3] = str2[3] = L'\0';
1815 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1816 EXPECT_TRUE(m1.Matches(str2));
1817
1818 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1819 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1820 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1821 str1[9] = str2[9] = L'\0';
1822 EXPECT_FALSE(m2.Matches(str2));
1823
1824 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1825 EXPECT_TRUE(m3.Matches(str2));
1826
1827 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1828 str2.append(1, L'\0');
1829 EXPECT_FALSE(m3.Matches(str2));
1830 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1831 }
1832
TEST(GlobalWideStrCaseEqTest,CanDescribeSelf)1833 TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1834 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1835 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1836 }
1837
TEST(GlobalWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1838 TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1839 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1840 EXPECT_TRUE(m.Matches(L"Hi"));
1841 EXPECT_TRUE(m.Matches(NULL));
1842 EXPECT_FALSE(m.Matches(L"Hello"));
1843 EXPECT_FALSE(m.Matches(L"hello"));
1844
1845 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1846 EXPECT_TRUE(m2.Matches(L""));
1847 EXPECT_FALSE(m2.Matches(L"Hello"));
1848 }
1849
TEST(GlobalWideStrCaseNeTest,CanDescribeSelf)1850 TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1851 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1852 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1853 }
1854
1855 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(GlobalWideHasSubstrTest,WorksForStringClasses)1856 TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1857 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1858 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1859 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1860
1861 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1862 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1863 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1864 }
1865
1866 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(GlobalWideHasSubstrTest,WorksForCStrings)1867 TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1868 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1869 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1870 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1871 EXPECT_FALSE(m1.Matches(NULL));
1872
1873 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1874 EXPECT_TRUE(m2.Matches(L"I love food."));
1875 EXPECT_FALSE(m2.Matches(L"tofo"));
1876 EXPECT_FALSE(m2.Matches(NULL));
1877 }
1878
1879 // Tests that HasSubstr(s) describes itself properly.
TEST(GlobalWideHasSubstrTest,CanDescribeSelf)1880 TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1881 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1882 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1883 }
1884
1885 // Tests StartsWith(s).
1886
TEST(GlobalWideStartsWithTest,MatchesStringWithGivenPrefix)1887 TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1888 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1889 EXPECT_TRUE(m1.Matches(L"Hi"));
1890 EXPECT_TRUE(m1.Matches(L""));
1891 EXPECT_FALSE(m1.Matches(NULL));
1892
1893 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1894 EXPECT_TRUE(m2.Matches(L"Hi"));
1895 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1896 EXPECT_TRUE(m2.Matches(L"High"));
1897 EXPECT_FALSE(m2.Matches(L"H"));
1898 EXPECT_FALSE(m2.Matches(L" Hi"));
1899 }
1900
TEST(GlobalWideStartsWithTest,CanDescribeSelf)1901 TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1902 Matcher<const ::wstring> m = StartsWith(L"Hi");
1903 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1904 }
1905
1906 // Tests EndsWith(s).
1907
TEST(GlobalWideEndsWithTest,MatchesStringWithGivenSuffix)1908 TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1909 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1910 EXPECT_TRUE(m1.Matches(L"Hi"));
1911 EXPECT_TRUE(m1.Matches(L""));
1912 EXPECT_FALSE(m1.Matches(NULL));
1913
1914 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1915 EXPECT_TRUE(m2.Matches(L"Hi"));
1916 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1917 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1918 EXPECT_FALSE(m2.Matches(L"i"));
1919 EXPECT_FALSE(m2.Matches(L"Hi "));
1920 }
1921
TEST(GlobalWideEndsWithTest,CanDescribeSelf)1922 TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1923 Matcher<const ::wstring> m = EndsWith(L"Hi");
1924 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1925 }
1926
1927 #endif // GTEST_HAS_GLOBAL_WSTRING
1928
1929
1930 typedef ::testing::tuple<long, int> Tuple2; // NOLINT
1931
1932 // Tests that Eq() matches a 2-tuple where the first field == the
1933 // second field.
TEST(Eq2Test,MatchesEqualArguments)1934 TEST(Eq2Test, MatchesEqualArguments) {
1935 Matcher<const Tuple2&> m = Eq();
1936 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1937 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1938 }
1939
1940 // Tests that Eq() describes itself properly.
TEST(Eq2Test,CanDescribeSelf)1941 TEST(Eq2Test, CanDescribeSelf) {
1942 Matcher<const Tuple2&> m = Eq();
1943 EXPECT_EQ("are an equal pair", Describe(m));
1944 }
1945
1946 // Tests that Ge() matches a 2-tuple where the first field >= the
1947 // second field.
TEST(Ge2Test,MatchesGreaterThanOrEqualArguments)1948 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1949 Matcher<const Tuple2&> m = Ge();
1950 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1951 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1952 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1953 }
1954
1955 // Tests that Ge() describes itself properly.
TEST(Ge2Test,CanDescribeSelf)1956 TEST(Ge2Test, CanDescribeSelf) {
1957 Matcher<const Tuple2&> m = Ge();
1958 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1959 }
1960
1961 // Tests that Gt() matches a 2-tuple where the first field > the
1962 // second field.
TEST(Gt2Test,MatchesGreaterThanArguments)1963 TEST(Gt2Test, MatchesGreaterThanArguments) {
1964 Matcher<const Tuple2&> m = Gt();
1965 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1966 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1967 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1968 }
1969
1970 // Tests that Gt() describes itself properly.
TEST(Gt2Test,CanDescribeSelf)1971 TEST(Gt2Test, CanDescribeSelf) {
1972 Matcher<const Tuple2&> m = Gt();
1973 EXPECT_EQ("are a pair where the first > the second", Describe(m));
1974 }
1975
1976 // Tests that Le() matches a 2-tuple where the first field <= the
1977 // second field.
TEST(Le2Test,MatchesLessThanOrEqualArguments)1978 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1979 Matcher<const Tuple2&> m = Le();
1980 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1981 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1982 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1983 }
1984
1985 // Tests that Le() describes itself properly.
TEST(Le2Test,CanDescribeSelf)1986 TEST(Le2Test, CanDescribeSelf) {
1987 Matcher<const Tuple2&> m = Le();
1988 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
1989 }
1990
1991 // Tests that Lt() matches a 2-tuple where the first field < the
1992 // second field.
TEST(Lt2Test,MatchesLessThanArguments)1993 TEST(Lt2Test, MatchesLessThanArguments) {
1994 Matcher<const Tuple2&> m = Lt();
1995 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1996 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1997 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1998 }
1999
2000 // Tests that Lt() describes itself properly.
TEST(Lt2Test,CanDescribeSelf)2001 TEST(Lt2Test, CanDescribeSelf) {
2002 Matcher<const Tuple2&> m = Lt();
2003 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2004 }
2005
2006 // Tests that Ne() matches a 2-tuple where the first field != the
2007 // second field.
TEST(Ne2Test,MatchesUnequalArguments)2008 TEST(Ne2Test, MatchesUnequalArguments) {
2009 Matcher<const Tuple2&> m = Ne();
2010 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2011 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2012 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2013 }
2014
2015 // Tests that Ne() describes itself properly.
TEST(Ne2Test,CanDescribeSelf)2016 TEST(Ne2Test, CanDescribeSelf) {
2017 Matcher<const Tuple2&> m = Ne();
2018 EXPECT_EQ("are an unequal pair", Describe(m));
2019 }
2020
2021 // Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest,NegatesMatcher)2022 TEST(NotTest, NegatesMatcher) {
2023 Matcher<int> m;
2024 m = Not(Eq(2));
2025 EXPECT_TRUE(m.Matches(3));
2026 EXPECT_FALSE(m.Matches(2));
2027 }
2028
2029 // Tests that Not(m) describes itself properly.
TEST(NotTest,CanDescribeSelf)2030 TEST(NotTest, CanDescribeSelf) {
2031 Matcher<int> m = Not(Eq(5));
2032 EXPECT_EQ("isn't equal to 5", Describe(m));
2033 }
2034
2035 // Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest,NotMatcherSafelyCastsMonomorphicMatchers)2036 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2037 // greater_than_5 is a monomorphic matcher.
2038 Matcher<int> greater_than_5 = Gt(5);
2039
2040 Matcher<const int&> m = Not(greater_than_5);
2041 Matcher<int&> m2 = Not(greater_than_5);
2042 Matcher<int&> m3 = Not(m);
2043 }
2044
2045 // Helper to allow easy testing of AllOf matchers with num parameters.
AllOfMatches(int num,const Matcher<int> & m)2046 void AllOfMatches(int num, const Matcher<int>& m) {
2047 SCOPED_TRACE(Describe(m));
2048 EXPECT_TRUE(m.Matches(0));
2049 for (int i = 1; i <= num; ++i) {
2050 EXPECT_FALSE(m.Matches(i));
2051 }
2052 EXPECT_TRUE(m.Matches(num + 1));
2053 }
2054
2055 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2056 // the given matchers.
TEST(AllOfTest,MatchesWhenAllMatch)2057 TEST(AllOfTest, MatchesWhenAllMatch) {
2058 Matcher<int> m;
2059 m = AllOf(Le(2), Ge(1));
2060 EXPECT_TRUE(m.Matches(1));
2061 EXPECT_TRUE(m.Matches(2));
2062 EXPECT_FALSE(m.Matches(0));
2063 EXPECT_FALSE(m.Matches(3));
2064
2065 m = AllOf(Gt(0), Ne(1), Ne(2));
2066 EXPECT_TRUE(m.Matches(3));
2067 EXPECT_FALSE(m.Matches(2));
2068 EXPECT_FALSE(m.Matches(1));
2069 EXPECT_FALSE(m.Matches(0));
2070
2071 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2072 EXPECT_TRUE(m.Matches(4));
2073 EXPECT_FALSE(m.Matches(3));
2074 EXPECT_FALSE(m.Matches(2));
2075 EXPECT_FALSE(m.Matches(1));
2076 EXPECT_FALSE(m.Matches(0));
2077
2078 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2079 EXPECT_TRUE(m.Matches(0));
2080 EXPECT_TRUE(m.Matches(1));
2081 EXPECT_FALSE(m.Matches(3));
2082
2083 // The following tests for varying number of sub-matchers. Due to the way
2084 // the sub-matchers are handled it is enough to test every sub-matcher once
2085 // with sub-matchers using the same matcher type. Varying matcher types are
2086 // checked for above.
2087 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2088 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2089 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2090 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2091 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2092 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2093 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2094 Ne(8)));
2095 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2096 Ne(8), Ne(9)));
2097 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2098 Ne(9), Ne(10)));
2099 }
2100
2101 #if GTEST_LANG_CXX11
2102 // Tests the variadic version of the AllOfMatcher.
TEST(AllOfTest,VariadicMatchesWhenAllMatch)2103 TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2104 // Make sure AllOf is defined in the right namespace and does not depend on
2105 // ADL.
2106 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2107 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2108 Ne(9), Ne(10), Ne(11));
2109 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2110 AllOfMatches(11, m);
2111 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2112 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2113 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2114 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2115 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2116 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2117 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2118 Ne(50)));
2119 }
2120
2121 #endif // GTEST_LANG_CXX11
2122
2123 // Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest,CanDescribeSelf)2124 TEST(AllOfTest, CanDescribeSelf) {
2125 Matcher<int> m;
2126 m = AllOf(Le(2), Ge(1));
2127 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2128
2129 m = AllOf(Gt(0), Ne(1), Ne(2));
2130 EXPECT_EQ("(is > 0) and "
2131 "((isn't equal to 1) and "
2132 "(isn't equal to 2))",
2133 Describe(m));
2134
2135
2136 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2137 EXPECT_EQ("((is > 0) and "
2138 "(isn't equal to 1)) and "
2139 "((isn't equal to 2) and "
2140 "(isn't equal to 3))",
2141 Describe(m));
2142
2143
2144 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2145 EXPECT_EQ("((is >= 0) and "
2146 "(is < 10)) and "
2147 "((isn't equal to 3) and "
2148 "((isn't equal to 5) and "
2149 "(isn't equal to 7)))",
2150 Describe(m));
2151 }
2152
2153 // Tests that AllOf(m1, ..., mn) describes its negation properly.
TEST(AllOfTest,CanDescribeNegation)2154 TEST(AllOfTest, CanDescribeNegation) {
2155 Matcher<int> m;
2156 m = AllOf(Le(2), Ge(1));
2157 EXPECT_EQ("(isn't <= 2) or "
2158 "(isn't >= 1)",
2159 DescribeNegation(m));
2160
2161 m = AllOf(Gt(0), Ne(1), Ne(2));
2162 EXPECT_EQ("(isn't > 0) or "
2163 "((is equal to 1) or "
2164 "(is equal to 2))",
2165 DescribeNegation(m));
2166
2167
2168 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2169 EXPECT_EQ("((isn't > 0) or "
2170 "(is equal to 1)) or "
2171 "((is equal to 2) or "
2172 "(is equal to 3))",
2173 DescribeNegation(m));
2174
2175
2176 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2177 EXPECT_EQ("((isn't >= 0) or "
2178 "(isn't < 10)) or "
2179 "((is equal to 3) or "
2180 "((is equal to 5) or "
2181 "(is equal to 7)))",
2182 DescribeNegation(m));
2183 }
2184
2185 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest,AllOfMatcherSafelyCastsMonomorphicMatchers)2186 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2187 // greater_than_5 and less_than_10 are monomorphic matchers.
2188 Matcher<int> greater_than_5 = Gt(5);
2189 Matcher<int> less_than_10 = Lt(10);
2190
2191 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2192 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2193 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2194
2195 // Tests that BothOf works when composing itself.
2196 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2197 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2198 }
2199
TEST(AllOfTest,ExplainsResult)2200 TEST(AllOfTest, ExplainsResult) {
2201 Matcher<int> m;
2202
2203 // Successful match. Both matchers need to explain. The second
2204 // matcher doesn't give an explanation, so only the first matcher's
2205 // explanation is printed.
2206 m = AllOf(GreaterThan(10), Lt(30));
2207 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2208
2209 // Successful match. Both matchers need to explain.
2210 m = AllOf(GreaterThan(10), GreaterThan(20));
2211 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2212 Explain(m, 30));
2213
2214 // Successful match. All matchers need to explain. The second
2215 // matcher doesn't given an explanation.
2216 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2217 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2218 Explain(m, 25));
2219
2220 // Successful match. All matchers need to explain.
2221 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2222 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2223 "and which is 10 more than 30",
2224 Explain(m, 40));
2225
2226 // Failed match. The first matcher, which failed, needs to
2227 // explain.
2228 m = AllOf(GreaterThan(10), GreaterThan(20));
2229 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2230
2231 // Failed match. The second matcher, which failed, needs to
2232 // explain. Since it doesn't given an explanation, nothing is
2233 // printed.
2234 m = AllOf(GreaterThan(10), Lt(30));
2235 EXPECT_EQ("", Explain(m, 40));
2236
2237 // Failed match. The second matcher, which failed, needs to
2238 // explain.
2239 m = AllOf(GreaterThan(10), GreaterThan(20));
2240 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2241 }
2242
2243 // Helper to allow easy testing of AnyOf matchers with num parameters.
AnyOfMatches(int num,const Matcher<int> & m)2244 void AnyOfMatches(int num, const Matcher<int>& m) {
2245 SCOPED_TRACE(Describe(m));
2246 EXPECT_FALSE(m.Matches(0));
2247 for (int i = 1; i <= num; ++i) {
2248 EXPECT_TRUE(m.Matches(i));
2249 }
2250 EXPECT_FALSE(m.Matches(num + 1));
2251 }
2252
2253 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2254 // least one of the given matchers.
TEST(AnyOfTest,MatchesWhenAnyMatches)2255 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2256 Matcher<int> m;
2257 m = AnyOf(Le(1), Ge(3));
2258 EXPECT_TRUE(m.Matches(1));
2259 EXPECT_TRUE(m.Matches(4));
2260 EXPECT_FALSE(m.Matches(2));
2261
2262 m = AnyOf(Lt(0), Eq(1), Eq(2));
2263 EXPECT_TRUE(m.Matches(-1));
2264 EXPECT_TRUE(m.Matches(1));
2265 EXPECT_TRUE(m.Matches(2));
2266 EXPECT_FALSE(m.Matches(0));
2267
2268 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2269 EXPECT_TRUE(m.Matches(-1));
2270 EXPECT_TRUE(m.Matches(1));
2271 EXPECT_TRUE(m.Matches(2));
2272 EXPECT_TRUE(m.Matches(3));
2273 EXPECT_FALSE(m.Matches(0));
2274
2275 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2276 EXPECT_TRUE(m.Matches(0));
2277 EXPECT_TRUE(m.Matches(11));
2278 EXPECT_TRUE(m.Matches(3));
2279 EXPECT_FALSE(m.Matches(2));
2280
2281 // The following tests for varying number of sub-matchers. Due to the way
2282 // the sub-matchers are handled it is enough to test every sub-matcher once
2283 // with sub-matchers using the same matcher type. Varying matcher types are
2284 // checked for above.
2285 AnyOfMatches(2, AnyOf(1, 2));
2286 AnyOfMatches(3, AnyOf(1, 2, 3));
2287 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2288 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2289 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2290 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2291 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2292 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2293 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2294 }
2295
2296 #if GTEST_LANG_CXX11
2297 // Tests the variadic version of the AnyOfMatcher.
TEST(AnyOfTest,VariadicMatchesWhenAnyMatches)2298 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2299 // Also make sure AnyOf is defined in the right namespace and does not depend
2300 // on ADL.
2301 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2302
2303 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2304 AnyOfMatches(11, m);
2305 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2306 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2307 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2308 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2309 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2310 }
2311
2312 #endif // GTEST_LANG_CXX11
2313
2314 // Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest,CanDescribeSelf)2315 TEST(AnyOfTest, CanDescribeSelf) {
2316 Matcher<int> m;
2317 m = AnyOf(Le(1), Ge(3));
2318 EXPECT_EQ("(is <= 1) or (is >= 3)",
2319 Describe(m));
2320
2321 m = AnyOf(Lt(0), Eq(1), Eq(2));
2322 EXPECT_EQ("(is < 0) or "
2323 "((is equal to 1) or (is equal to 2))",
2324 Describe(m));
2325
2326 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2327 EXPECT_EQ("((is < 0) or "
2328 "(is equal to 1)) or "
2329 "((is equal to 2) or "
2330 "(is equal to 3))",
2331 Describe(m));
2332
2333 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2334 EXPECT_EQ("((is <= 0) or "
2335 "(is > 10)) or "
2336 "((is equal to 3) or "
2337 "((is equal to 5) or "
2338 "(is equal to 7)))",
2339 Describe(m));
2340 }
2341
2342 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
TEST(AnyOfTest,CanDescribeNegation)2343 TEST(AnyOfTest, CanDescribeNegation) {
2344 Matcher<int> m;
2345 m = AnyOf(Le(1), Ge(3));
2346 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2347 DescribeNegation(m));
2348
2349 m = AnyOf(Lt(0), Eq(1), Eq(2));
2350 EXPECT_EQ("(isn't < 0) and "
2351 "((isn't equal to 1) and (isn't equal to 2))",
2352 DescribeNegation(m));
2353
2354 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2355 EXPECT_EQ("((isn't < 0) and "
2356 "(isn't equal to 1)) and "
2357 "((isn't equal to 2) and "
2358 "(isn't equal to 3))",
2359 DescribeNegation(m));
2360
2361 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2362 EXPECT_EQ("((isn't <= 0) and "
2363 "(isn't > 10)) and "
2364 "((isn't equal to 3) and "
2365 "((isn't equal to 5) and "
2366 "(isn't equal to 7)))",
2367 DescribeNegation(m));
2368 }
2369
2370 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest,AnyOfMatcherSafelyCastsMonomorphicMatchers)2371 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2372 // greater_than_5 and less_than_10 are monomorphic matchers.
2373 Matcher<int> greater_than_5 = Gt(5);
2374 Matcher<int> less_than_10 = Lt(10);
2375
2376 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2377 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2378 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2379
2380 // Tests that EitherOf works when composing itself.
2381 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2382 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2383 }
2384
TEST(AnyOfTest,ExplainsResult)2385 TEST(AnyOfTest, ExplainsResult) {
2386 Matcher<int> m;
2387
2388 // Failed match. Both matchers need to explain. The second
2389 // matcher doesn't give an explanation, so only the first matcher's
2390 // explanation is printed.
2391 m = AnyOf(GreaterThan(10), Lt(0));
2392 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2393
2394 // Failed match. Both matchers need to explain.
2395 m = AnyOf(GreaterThan(10), GreaterThan(20));
2396 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2397 Explain(m, 5));
2398
2399 // Failed match. All matchers need to explain. The second
2400 // matcher doesn't given an explanation.
2401 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2402 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2403 Explain(m, 5));
2404
2405 // Failed match. All matchers need to explain.
2406 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2407 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2408 "and which is 25 less than 30",
2409 Explain(m, 5));
2410
2411 // Successful match. The first matcher, which succeeded, needs to
2412 // explain.
2413 m = AnyOf(GreaterThan(10), GreaterThan(20));
2414 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2415
2416 // Successful match. The second matcher, which succeeded, needs to
2417 // explain. Since it doesn't given an explanation, nothing is
2418 // printed.
2419 m = AnyOf(GreaterThan(10), Lt(30));
2420 EXPECT_EQ("", Explain(m, 0));
2421
2422 // Successful match. The second matcher, which succeeded, needs to
2423 // explain.
2424 m = AnyOf(GreaterThan(30), GreaterThan(20));
2425 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2426 }
2427
2428 // The following predicate function and predicate functor are for
2429 // testing the Truly(predicate) matcher.
2430
2431 // Returns non-zero if the input is positive. Note that the return
2432 // type of this function is not bool. It's OK as Truly() accepts any
2433 // unary function or functor whose return type can be implicitly
2434 // converted to bool.
IsPositive(double x)2435 int IsPositive(double x) {
2436 return x > 0 ? 1 : 0;
2437 }
2438
2439 // This functor returns true if the input is greater than the given
2440 // number.
2441 class IsGreaterThan {
2442 public:
IsGreaterThan(int threshold)2443 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2444
operator ()(int n) const2445 bool operator()(int n) const { return n > threshold_; }
2446
2447 private:
2448 int threshold_;
2449 };
2450
2451 // For testing Truly().
2452 const int foo = 0;
2453
2454 // This predicate returns true iff the argument references foo and has
2455 // a zero value.
ReferencesFooAndIsZero(const int & n)2456 bool ReferencesFooAndIsZero(const int& n) {
2457 return (&n == &foo) && (n == 0);
2458 }
2459
2460 // Tests that Truly(predicate) matches what satisfies the given
2461 // predicate.
TEST(TrulyTest,MatchesWhatSatisfiesThePredicate)2462 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2463 Matcher<double> m = Truly(IsPositive);
2464 EXPECT_TRUE(m.Matches(2.0));
2465 EXPECT_FALSE(m.Matches(-1.5));
2466 }
2467
2468 // Tests that Truly(predicate_functor) works too.
TEST(TrulyTest,CanBeUsedWithFunctor)2469 TEST(TrulyTest, CanBeUsedWithFunctor) {
2470 Matcher<int> m = Truly(IsGreaterThan(5));
2471 EXPECT_TRUE(m.Matches(6));
2472 EXPECT_FALSE(m.Matches(4));
2473 }
2474
2475 // A class that can be implicitly converted to bool.
2476 class ConvertibleToBool {
2477 public:
ConvertibleToBool(int number)2478 explicit ConvertibleToBool(int number) : number_(number) {}
operator bool() const2479 operator bool() const { return number_ != 0; }
2480
2481 private:
2482 int number_;
2483 };
2484
IsNotZero(int number)2485 ConvertibleToBool IsNotZero(int number) {
2486 return ConvertibleToBool(number);
2487 }
2488
2489 // Tests that the predicate used in Truly() may return a class that's
2490 // implicitly convertible to bool, even when the class has no
2491 // operator!().
TEST(TrulyTest,PredicateCanReturnAClassConvertibleToBool)2492 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2493 Matcher<int> m = Truly(IsNotZero);
2494 EXPECT_TRUE(m.Matches(1));
2495 EXPECT_FALSE(m.Matches(0));
2496 }
2497
2498 // Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest,CanDescribeSelf)2499 TEST(TrulyTest, CanDescribeSelf) {
2500 Matcher<double> m = Truly(IsPositive);
2501 EXPECT_EQ("satisfies the given predicate",
2502 Describe(m));
2503 }
2504
2505 // Tests that Truly(predicate) works when the matcher takes its
2506 // argument by reference.
TEST(TrulyTest,WorksForByRefArguments)2507 TEST(TrulyTest, WorksForByRefArguments) {
2508 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2509 EXPECT_TRUE(m.Matches(foo));
2510 int n = 0;
2511 EXPECT_FALSE(m.Matches(n));
2512 }
2513
2514 // Tests that Matches(m) is a predicate satisfied by whatever that
2515 // matches matcher m.
TEST(MatchesTest,IsSatisfiedByWhatMatchesTheMatcher)2516 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2517 EXPECT_TRUE(Matches(Ge(0))(1));
2518 EXPECT_FALSE(Matches(Eq('a'))('b'));
2519 }
2520
2521 // Tests that Matches(m) works when the matcher takes its argument by
2522 // reference.
TEST(MatchesTest,WorksOnByRefArguments)2523 TEST(MatchesTest, WorksOnByRefArguments) {
2524 int m = 0, n = 0;
2525 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2526 EXPECT_FALSE(Matches(Ref(m))(n));
2527 }
2528
2529 // Tests that a Matcher on non-reference type can be used in
2530 // Matches().
TEST(MatchesTest,WorksWithMatcherOnNonRefType)2531 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2532 Matcher<int> eq5 = Eq(5);
2533 EXPECT_TRUE(Matches(eq5)(5));
2534 EXPECT_FALSE(Matches(eq5)(2));
2535 }
2536
2537 // Tests Value(value, matcher). Since Value() is a simple wrapper for
2538 // Matches(), which has been tested already, we don't spend a lot of
2539 // effort on testing Value().
TEST(ValueTest,WorksWithPolymorphicMatcher)2540 TEST(ValueTest, WorksWithPolymorphicMatcher) {
2541 EXPECT_TRUE(Value("hi", StartsWith("h")));
2542 EXPECT_FALSE(Value(5, Gt(10)));
2543 }
2544
TEST(ValueTest,WorksWithMonomorphicMatcher)2545 TEST(ValueTest, WorksWithMonomorphicMatcher) {
2546 const Matcher<int> is_zero = Eq(0);
2547 EXPECT_TRUE(Value(0, is_zero));
2548 EXPECT_FALSE(Value('a', is_zero));
2549
2550 int n = 0;
2551 const Matcher<const int&> ref_n = Ref(n);
2552 EXPECT_TRUE(Value(n, ref_n));
2553 EXPECT_FALSE(Value(1, ref_n));
2554 }
2555
TEST(ExplainMatchResultTest,WorksWithPolymorphicMatcher)2556 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2557 StringMatchResultListener listener1;
2558 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2559 EXPECT_EQ("% 2 == 0", listener1.str());
2560
2561 StringMatchResultListener listener2;
2562 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2563 EXPECT_EQ("", listener2.str());
2564 }
2565
TEST(ExplainMatchResultTest,WorksWithMonomorphicMatcher)2566 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2567 const Matcher<int> is_even = PolymorphicIsEven();
2568 StringMatchResultListener listener1;
2569 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2570 EXPECT_EQ("% 2 == 0", listener1.str());
2571
2572 const Matcher<const double&> is_zero = Eq(0);
2573 StringMatchResultListener listener2;
2574 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2575 EXPECT_EQ("", listener2.str());
2576 }
2577
2578 MATCHER_P(Really, inner_matcher, "") {
2579 return ExplainMatchResult(inner_matcher, arg, result_listener);
2580 }
2581
TEST(ExplainMatchResultTest,WorksInsideMATCHER)2582 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2583 EXPECT_THAT(0, Really(Eq(0)));
2584 }
2585
TEST(AllArgsTest,WorksForTuple)2586 TEST(AllArgsTest, WorksForTuple) {
2587 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2588 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2589 }
2590
TEST(AllArgsTest,WorksForNonTuple)2591 TEST(AllArgsTest, WorksForNonTuple) {
2592 EXPECT_THAT(42, AllArgs(Gt(0)));
2593 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2594 }
2595
2596 class AllArgsHelper {
2597 public:
AllArgsHelper()2598 AllArgsHelper() {}
2599
2600 MOCK_METHOD2(Helper, int(char x, int y));
2601
2602 private:
2603 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2604 };
2605
TEST(AllArgsTest,WorksInWithClause)2606 TEST(AllArgsTest, WorksInWithClause) {
2607 AllArgsHelper helper;
2608 ON_CALL(helper, Helper(_, _))
2609 .With(AllArgs(Lt()))
2610 .WillByDefault(Return(1));
2611 EXPECT_CALL(helper, Helper(_, _));
2612 EXPECT_CALL(helper, Helper(_, _))
2613 .With(AllArgs(Gt()))
2614 .WillOnce(Return(2));
2615
2616 EXPECT_EQ(1, helper.Helper('\1', 2));
2617 EXPECT_EQ(2, helper.Helper('a', 1));
2618 }
2619
2620 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2621 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)2622 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2623 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2624 ASSERT_THAT("Foo", EndsWith("oo"));
2625 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2626 EXPECT_THAT("Hello", StartsWith("Hell"));
2627 }
2628
2629 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2630 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)2631 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2632 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2633 // which cannot reference auto variables.
2634 static unsigned short n; // NOLINT
2635 n = 5;
2636
2637 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2638 // functions declared in the namespace scope from within nested classes.
2639 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2640 // namespace-level functions invoked inside them need to be explicitly
2641 // resolved.
2642 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
2643 "Value of: n\n"
2644 "Expected: is > 10\n"
2645 " Actual: 5" + OfType("unsigned short"));
2646 n = 0;
2647 EXPECT_NONFATAL_FAILURE(
2648 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2649 "Value of: n\n"
2650 "Expected: (is <= 7) and (is >= 5)\n"
2651 " Actual: 0" + OfType("unsigned short"));
2652 }
2653
2654 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2655 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)2656 TEST(MatcherAssertionTest, WorksForByRefArguments) {
2657 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2658 // reference auto variables.
2659 static int n;
2660 n = 0;
2661 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
2662 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2663 "Value of: n\n"
2664 "Expected: does not reference the variable @");
2665 // Tests the "Actual" part.
2666 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2667 "Actual: 0" + OfType("int") + ", which is located @");
2668 }
2669
2670 #if !GTEST_OS_SYMBIAN
2671 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2672 // monomorphic.
2673
2674 // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2675 // Symbian compiler: it tries to compile
2676 // template<T, U> class MatcherCastImpl { ...
2677 // virtual bool MatchAndExplain(T x, ...) const {
2678 // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
2679 // with U == string and T == const char*
2680 // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2681 // the compiler silently crashes with no output.
2682 // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2683 // the code compiles but the converted string is bogus.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)2684 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2685 Matcher<const char*> starts_with_he = StartsWith("he");
2686 ASSERT_THAT("hello", starts_with_he);
2687
2688 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
2689 ASSERT_THAT("book", ends_with_ok);
2690 const std::string bad = "bad";
2691 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2692 "Value of: bad\n"
2693 "Expected: ends with \"ok\"\n"
2694 " Actual: \"bad\"");
2695 Matcher<int> is_greater_than_5 = Gt(5);
2696 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2697 "Value of: 5\n"
2698 "Expected: is > 5\n"
2699 " Actual: 5" + OfType("int"));
2700 }
2701 #endif // !GTEST_OS_SYMBIAN
2702
2703 // Tests floating-point matchers.
2704 template <typename RawType>
2705 class FloatingPointTest : public testing::Test {
2706 protected:
2707 typedef testing::internal::FloatingPoint<RawType> Floating;
2708 typedef typename Floating::Bits Bits;
2709
FloatingPointTest()2710 FloatingPointTest()
2711 : max_ulps_(Floating::kMaxUlps),
2712 zero_bits_(Floating(0).bits()),
2713 one_bits_(Floating(1).bits()),
2714 infinity_bits_(Floating(Floating::Infinity()).bits()),
2715 close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)),
2716 close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2717 further_from_negative_zero_(-AsBits(
2718 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2719 close_to_one_(AsBits(one_bits_ + max_ulps_)),
2720 further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)),
2721 infinity_(Floating::Infinity()),
2722 close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)),
2723 further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)),
2724 max_(Floating::Max()),
2725 nan1_(AsBits(Floating::kExponentBitMask | 1)),
2726 nan2_(AsBits(Floating::kExponentBitMask | 200)) {
2727 }
2728
TestSize()2729 void TestSize() {
2730 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2731 }
2732
2733 // A battery of tests for FloatingEqMatcher::Matches.
2734 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType))2735 void TestMatches(
2736 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2737 Matcher<RawType> m1 = matcher_maker(0.0);
2738 EXPECT_TRUE(m1.Matches(-0.0));
2739 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2740 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2741 EXPECT_FALSE(m1.Matches(1.0));
2742
2743 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2744 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2745
2746 Matcher<RawType> m3 = matcher_maker(1.0);
2747 EXPECT_TRUE(m3.Matches(close_to_one_));
2748 EXPECT_FALSE(m3.Matches(further_from_one_));
2749
2750 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2751 EXPECT_FALSE(m3.Matches(0.0));
2752
2753 Matcher<RawType> m4 = matcher_maker(-infinity_);
2754 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2755
2756 Matcher<RawType> m5 = matcher_maker(infinity_);
2757 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2758
2759 // This is interesting as the representations of infinity_ and nan1_
2760 // are only 1 DLP apart.
2761 EXPECT_FALSE(m5.Matches(nan1_));
2762
2763 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2764 // some cases.
2765 Matcher<const RawType&> m6 = matcher_maker(0.0);
2766 EXPECT_TRUE(m6.Matches(-0.0));
2767 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2768 EXPECT_FALSE(m6.Matches(1.0));
2769
2770 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2771 // cases.
2772 Matcher<RawType&> m7 = matcher_maker(0.0);
2773 RawType x = 0.0;
2774 EXPECT_TRUE(m7.Matches(x));
2775 x = 0.01f;
2776 EXPECT_FALSE(m7.Matches(x));
2777 }
2778
2779 // Pre-calculated numbers to be used by the tests.
2780
2781 const size_t max_ulps_;
2782
2783 const Bits zero_bits_; // The bits that represent 0.0.
2784 const Bits one_bits_; // The bits that represent 1.0.
2785 const Bits infinity_bits_; // The bits that represent +infinity.
2786
2787 // Some numbers close to 0.0.
2788 const RawType close_to_positive_zero_;
2789 const RawType close_to_negative_zero_;
2790 const RawType further_from_negative_zero_;
2791
2792 // Some numbers close to 1.0.
2793 const RawType close_to_one_;
2794 const RawType further_from_one_;
2795
2796 // Some numbers close to +infinity.
2797 const RawType infinity_;
2798 const RawType close_to_infinity_;
2799 const RawType further_from_infinity_;
2800
2801 // Maximum representable value that's not infinity.
2802 const RawType max_;
2803
2804 // Some NaNs.
2805 const RawType nan1_;
2806 const RawType nan2_;
2807
2808 private:
2809 template <typename T>
AsBits(T value)2810 static RawType AsBits(T value) {
2811 return Floating::ReinterpretBits(static_cast<Bits>(value));
2812 }
2813 };
2814
2815 // Tests floating-point matchers with fixed epsilons.
2816 template <typename RawType>
2817 class FloatingPointNearTest : public FloatingPointTest<RawType> {
2818 protected:
2819 typedef FloatingPointTest<RawType> ParentType;
2820
2821 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2822 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestNearMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType,RawType))2823 void TestNearMatches(
2824 testing::internal::FloatingEqMatcher<RawType>
2825 (*matcher_maker)(RawType, RawType)) {
2826 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2827 EXPECT_TRUE(m1.Matches(0.0));
2828 EXPECT_TRUE(m1.Matches(-0.0));
2829 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2830 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2831 EXPECT_FALSE(m1.Matches(1.0));
2832
2833 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2834 EXPECT_TRUE(m2.Matches(0.0));
2835 EXPECT_TRUE(m2.Matches(-0.0));
2836 EXPECT_TRUE(m2.Matches(1.0));
2837 EXPECT_TRUE(m2.Matches(-1.0));
2838 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2839 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2840
2841 // Check that inf matches inf, regardless of the of the specified max
2842 // absolute error.
2843 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2844 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2845 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2846 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2847
2848 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2849 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2850 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2851 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2852
2853 // Test various overflow scenarios.
2854 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2855 EXPECT_TRUE(m5.Matches(ParentType::max_));
2856 EXPECT_FALSE(m5.Matches(-ParentType::max_));
2857
2858 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2859 EXPECT_FALSE(m6.Matches(ParentType::max_));
2860 EXPECT_TRUE(m6.Matches(-ParentType::max_));
2861
2862 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2863 EXPECT_TRUE(m7.Matches(ParentType::max_));
2864 EXPECT_FALSE(m7.Matches(-ParentType::max_));
2865
2866 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2867 EXPECT_FALSE(m8.Matches(ParentType::max_));
2868 EXPECT_TRUE(m8.Matches(-ParentType::max_));
2869
2870 // The difference between max() and -max() normally overflows to infinity,
2871 // but it should still match if the max_abs_error is also infinity.
2872 Matcher<RawType> m9 = matcher_maker(
2873 ParentType::max_, ParentType::infinity_);
2874 EXPECT_TRUE(m8.Matches(-ParentType::max_));
2875
2876 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2877 // some cases.
2878 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2879 EXPECT_TRUE(m10.Matches(-0.0));
2880 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2881 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2882
2883 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2884 // cases.
2885 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2886 RawType x = 0.0;
2887 EXPECT_TRUE(m11.Matches(x));
2888 x = 1.0f;
2889 EXPECT_TRUE(m11.Matches(x));
2890 x = -1.0f;
2891 EXPECT_TRUE(m11.Matches(x));
2892 x = 1.1f;
2893 EXPECT_FALSE(m11.Matches(x));
2894 x = -1.1f;
2895 EXPECT_FALSE(m11.Matches(x));
2896 }
2897 };
2898
2899 // Instantiate FloatingPointTest for testing floats.
2900 typedef FloatingPointTest<float> FloatTest;
2901
TEST_F(FloatTest,FloatEqApproximatelyMatchesFloats)2902 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2903 TestMatches(&FloatEq);
2904 }
2905
TEST_F(FloatTest,NanSensitiveFloatEqApproximatelyMatchesFloats)2906 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2907 TestMatches(&NanSensitiveFloatEq);
2908 }
2909
TEST_F(FloatTest,FloatEqCannotMatchNaN)2910 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2911 // FloatEq never matches NaN.
2912 Matcher<float> m = FloatEq(nan1_);
2913 EXPECT_FALSE(m.Matches(nan1_));
2914 EXPECT_FALSE(m.Matches(nan2_));
2915 EXPECT_FALSE(m.Matches(1.0));
2916 }
2917
TEST_F(FloatTest,NanSensitiveFloatEqCanMatchNaN)2918 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2919 // NanSensitiveFloatEq will match NaN.
2920 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2921 EXPECT_TRUE(m.Matches(nan1_));
2922 EXPECT_TRUE(m.Matches(nan2_));
2923 EXPECT_FALSE(m.Matches(1.0));
2924 }
2925
TEST_F(FloatTest,FloatEqCanDescribeSelf)2926 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2927 Matcher<float> m1 = FloatEq(2.0f);
2928 EXPECT_EQ("is approximately 2", Describe(m1));
2929 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2930
2931 Matcher<float> m2 = FloatEq(0.5f);
2932 EXPECT_EQ("is approximately 0.5", Describe(m2));
2933 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2934
2935 Matcher<float> m3 = FloatEq(nan1_);
2936 EXPECT_EQ("never matches", Describe(m3));
2937 EXPECT_EQ("is anything", DescribeNegation(m3));
2938 }
2939
TEST_F(FloatTest,NanSensitiveFloatEqCanDescribeSelf)2940 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2941 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2942 EXPECT_EQ("is approximately 2", Describe(m1));
2943 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2944
2945 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2946 EXPECT_EQ("is approximately 0.5", Describe(m2));
2947 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2948
2949 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2950 EXPECT_EQ("is NaN", Describe(m3));
2951 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2952 }
2953
2954 // Instantiate FloatingPointTest for testing floats with a user-specified
2955 // max absolute error.
2956 typedef FloatingPointNearTest<float> FloatNearTest;
2957
TEST_F(FloatNearTest,FloatNearMatches)2958 TEST_F(FloatNearTest, FloatNearMatches) {
2959 TestNearMatches(&FloatNear);
2960 }
2961
TEST_F(FloatNearTest,NanSensitiveFloatNearApproximatelyMatchesFloats)2962 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2963 TestNearMatches(&NanSensitiveFloatNear);
2964 }
2965
TEST_F(FloatNearTest,FloatNearCanDescribeSelf)2966 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2967 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2968 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2969 EXPECT_EQ(
2970 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2971
2972 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2973 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2974 EXPECT_EQ(
2975 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2976
2977 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2978 EXPECT_EQ("never matches", Describe(m3));
2979 EXPECT_EQ("is anything", DescribeNegation(m3));
2980 }
2981
TEST_F(FloatNearTest,NanSensitiveFloatNearCanDescribeSelf)2982 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2983 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2984 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2985 EXPECT_EQ(
2986 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2987
2988 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2989 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2990 EXPECT_EQ(
2991 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2992
2993 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2994 EXPECT_EQ("is NaN", Describe(m3));
2995 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2996 }
2997
TEST_F(FloatNearTest,FloatNearCannotMatchNaN)2998 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2999 // FloatNear never matches NaN.
3000 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3001 EXPECT_FALSE(m.Matches(nan1_));
3002 EXPECT_FALSE(m.Matches(nan2_));
3003 EXPECT_FALSE(m.Matches(1.0));
3004 }
3005
TEST_F(FloatNearTest,NanSensitiveFloatNearCanMatchNaN)3006 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3007 // NanSensitiveFloatNear will match NaN.
3008 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3009 EXPECT_TRUE(m.Matches(nan1_));
3010 EXPECT_TRUE(m.Matches(nan2_));
3011 EXPECT_FALSE(m.Matches(1.0));
3012 }
3013
3014 // Instantiate FloatingPointTest for testing doubles.
3015 typedef FloatingPointTest<double> DoubleTest;
3016
TEST_F(DoubleTest,DoubleEqApproximatelyMatchesDoubles)3017 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3018 TestMatches(&DoubleEq);
3019 }
3020
TEST_F(DoubleTest,NanSensitiveDoubleEqApproximatelyMatchesDoubles)3021 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3022 TestMatches(&NanSensitiveDoubleEq);
3023 }
3024
TEST_F(DoubleTest,DoubleEqCannotMatchNaN)3025 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3026 // DoubleEq never matches NaN.
3027 Matcher<double> m = DoubleEq(nan1_);
3028 EXPECT_FALSE(m.Matches(nan1_));
3029 EXPECT_FALSE(m.Matches(nan2_));
3030 EXPECT_FALSE(m.Matches(1.0));
3031 }
3032
TEST_F(DoubleTest,NanSensitiveDoubleEqCanMatchNaN)3033 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3034 // NanSensitiveDoubleEq will match NaN.
3035 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3036 EXPECT_TRUE(m.Matches(nan1_));
3037 EXPECT_TRUE(m.Matches(nan2_));
3038 EXPECT_FALSE(m.Matches(1.0));
3039 }
3040
TEST_F(DoubleTest,DoubleEqCanDescribeSelf)3041 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3042 Matcher<double> m1 = DoubleEq(2.0);
3043 EXPECT_EQ("is approximately 2", Describe(m1));
3044 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3045
3046 Matcher<double> m2 = DoubleEq(0.5);
3047 EXPECT_EQ("is approximately 0.5", Describe(m2));
3048 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3049
3050 Matcher<double> m3 = DoubleEq(nan1_);
3051 EXPECT_EQ("never matches", Describe(m3));
3052 EXPECT_EQ("is anything", DescribeNegation(m3));
3053 }
3054
TEST_F(DoubleTest,NanSensitiveDoubleEqCanDescribeSelf)3055 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3056 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3057 EXPECT_EQ("is approximately 2", Describe(m1));
3058 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3059
3060 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3061 EXPECT_EQ("is approximately 0.5", Describe(m2));
3062 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3063
3064 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3065 EXPECT_EQ("is NaN", Describe(m3));
3066 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3067 }
3068
3069 // Instantiate FloatingPointTest for testing floats with a user-specified
3070 // max absolute error.
3071 typedef FloatingPointNearTest<double> DoubleNearTest;
3072
TEST_F(DoubleNearTest,DoubleNearMatches)3073 TEST_F(DoubleNearTest, DoubleNearMatches) {
3074 TestNearMatches(&DoubleNear);
3075 }
3076
TEST_F(DoubleNearTest,NanSensitiveDoubleNearApproximatelyMatchesDoubles)3077 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3078 TestNearMatches(&NanSensitiveDoubleNear);
3079 }
3080
TEST_F(DoubleNearTest,DoubleNearCanDescribeSelf)3081 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3082 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3083 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3084 EXPECT_EQ(
3085 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3086
3087 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3088 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3089 EXPECT_EQ(
3090 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3091
3092 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3093 EXPECT_EQ("never matches", Describe(m3));
3094 EXPECT_EQ("is anything", DescribeNegation(m3));
3095 }
3096
TEST_F(DoubleNearTest,ExplainsResultWhenMatchFails)3097 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3098 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3099 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3100 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3101
3102 const std::string explanation =
3103 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3104 // Different C++ implementations may print floating-point numbers
3105 // slightly differently.
3106 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3107 explanation == "which is 1.2e-010 from 2.1") // MSVC
3108 << " where explanation is \"" << explanation << "\".";
3109 }
3110
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanDescribeSelf)3111 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3112 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3113 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3114 EXPECT_EQ(
3115 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3116
3117 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3118 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3119 EXPECT_EQ(
3120 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3121
3122 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3123 EXPECT_EQ("is NaN", Describe(m3));
3124 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3125 }
3126
TEST_F(DoubleNearTest,DoubleNearCannotMatchNaN)3127 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3128 // DoubleNear never matches NaN.
3129 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3130 EXPECT_FALSE(m.Matches(nan1_));
3131 EXPECT_FALSE(m.Matches(nan2_));
3132 EXPECT_FALSE(m.Matches(1.0));
3133 }
3134
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanMatchNaN)3135 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3136 // NanSensitiveDoubleNear will match NaN.
3137 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3138 EXPECT_TRUE(m.Matches(nan1_));
3139 EXPECT_TRUE(m.Matches(nan2_));
3140 EXPECT_FALSE(m.Matches(1.0));
3141 }
3142
TEST(PointeeTest,RawPointer)3143 TEST(PointeeTest, RawPointer) {
3144 const Matcher<int*> m = Pointee(Ge(0));
3145
3146 int n = 1;
3147 EXPECT_TRUE(m.Matches(&n));
3148 n = -1;
3149 EXPECT_FALSE(m.Matches(&n));
3150 EXPECT_FALSE(m.Matches(NULL));
3151 }
3152
TEST(PointeeTest,RawPointerToConst)3153 TEST(PointeeTest, RawPointerToConst) {
3154 const Matcher<const double*> m = Pointee(Ge(0));
3155
3156 double x = 1;
3157 EXPECT_TRUE(m.Matches(&x));
3158 x = -1;
3159 EXPECT_FALSE(m.Matches(&x));
3160 EXPECT_FALSE(m.Matches(NULL));
3161 }
3162
TEST(PointeeTest,ReferenceToConstRawPointer)3163 TEST(PointeeTest, ReferenceToConstRawPointer) {
3164 const Matcher<int* const &> m = Pointee(Ge(0));
3165
3166 int n = 1;
3167 EXPECT_TRUE(m.Matches(&n));
3168 n = -1;
3169 EXPECT_FALSE(m.Matches(&n));
3170 EXPECT_FALSE(m.Matches(NULL));
3171 }
3172
TEST(PointeeTest,ReferenceToNonConstRawPointer)3173 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3174 const Matcher<double* &> m = Pointee(Ge(0));
3175
3176 double x = 1.0;
3177 double* p = &x;
3178 EXPECT_TRUE(m.Matches(p));
3179 x = -1;
3180 EXPECT_FALSE(m.Matches(p));
3181 p = NULL;
3182 EXPECT_FALSE(m.Matches(p));
3183 }
3184
3185 MATCHER_P(FieldIIs, inner_matcher, "") {
3186 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3187 }
3188
3189 #if GTEST_HAS_RTTI
3190
TEST(WhenDynamicCastToTest,SameType)3191 TEST(WhenDynamicCastToTest, SameType) {
3192 Derived derived;
3193 derived.i = 4;
3194
3195 // Right type. A pointer is passed down.
3196 Base* as_base_ptr = &derived;
3197 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3198 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3199 EXPECT_THAT(as_base_ptr,
3200 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3201 }
3202
TEST(WhenDynamicCastToTest,WrongTypes)3203 TEST(WhenDynamicCastToTest, WrongTypes) {
3204 Base base;
3205 Derived derived;
3206 OtherDerived other_derived;
3207
3208 // Wrong types. NULL is passed.
3209 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3210 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3211 Base* as_base_ptr = &derived;
3212 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3213 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3214 as_base_ptr = &other_derived;
3215 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3216 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3217 }
3218
TEST(WhenDynamicCastToTest,AlreadyNull)3219 TEST(WhenDynamicCastToTest, AlreadyNull) {
3220 // Already NULL.
3221 Base* as_base_ptr = NULL;
3222 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3223 }
3224
3225 struct AmbiguousCastTypes {
3226 class VirtualDerived : public virtual Base {};
3227 class DerivedSub1 : public VirtualDerived {};
3228 class DerivedSub2 : public VirtualDerived {};
3229 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3230 };
3231
TEST(WhenDynamicCastToTest,AmbiguousCast)3232 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3233 AmbiguousCastTypes::DerivedSub1 sub1;
3234 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3235 // Multiply derived from Base. dynamic_cast<> returns NULL.
3236 Base* as_base_ptr =
3237 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3238 EXPECT_THAT(as_base_ptr,
3239 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3240 as_base_ptr = &sub1;
3241 EXPECT_THAT(
3242 as_base_ptr,
3243 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3244 }
3245
TEST(WhenDynamicCastToTest,Describe)3246 TEST(WhenDynamicCastToTest, Describe) {
3247 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3248 const string prefix =
3249 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3250 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3251 EXPECT_EQ(prefix + "does not point to a value that is anything",
3252 DescribeNegation(matcher));
3253 }
3254
TEST(WhenDynamicCastToTest,Explain)3255 TEST(WhenDynamicCastToTest, Explain) {
3256 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3257 Base* null = NULL;
3258 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3259 Derived derived;
3260 EXPECT_TRUE(matcher.Matches(&derived));
3261 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3262
3263 // With references, the matcher itself can fail. Test for that one.
3264 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3265 EXPECT_THAT(Explain(ref_matcher, derived),
3266 HasSubstr("which cannot be dynamic_cast"));
3267 }
3268
TEST(WhenDynamicCastToTest,GoodReference)3269 TEST(WhenDynamicCastToTest, GoodReference) {
3270 Derived derived;
3271 derived.i = 4;
3272 Base& as_base_ref = derived;
3273 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3274 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3275 }
3276
TEST(WhenDynamicCastToTest,BadReference)3277 TEST(WhenDynamicCastToTest, BadReference) {
3278 Derived derived;
3279 Base& as_base_ref = derived;
3280 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3281 }
3282
3283 #endif // GTEST_HAS_RTTI
3284
3285 // Minimal const-propagating pointer.
3286 template <typename T>
3287 class ConstPropagatingPtr {
3288 public:
3289 typedef T element_type;
3290
ConstPropagatingPtr()3291 ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)3292 explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)3293 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3294
get()3295 T* get() { return val_; }
operator *()3296 T& operator*() { return *val_; }
3297 // Most smart pointers return non-const T* and T& from the next methods.
get() const3298 const T* get() const { return val_; }
operator *() const3299 const T& operator*() const { return *val_; }
3300
3301 private:
3302 T* val_;
3303 };
3304
TEST(PointeeTest,WorksWithConstPropagatingPointers)3305 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3306 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3307 int three = 3;
3308 const ConstPropagatingPtr<int> co(&three);
3309 ConstPropagatingPtr<int> o(&three);
3310 EXPECT_TRUE(m.Matches(o));
3311 EXPECT_TRUE(m.Matches(co));
3312 *o = 6;
3313 EXPECT_FALSE(m.Matches(o));
3314 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3315 }
3316
TEST(PointeeTest,NeverMatchesNull)3317 TEST(PointeeTest, NeverMatchesNull) {
3318 const Matcher<const char*> m = Pointee(_);
3319 EXPECT_FALSE(m.Matches(NULL));
3320 }
3321
3322 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)3323 TEST(PointeeTest, MatchesAgainstAValue) {
3324 const Matcher<int*> m = Pointee(5);
3325
3326 int n = 5;
3327 EXPECT_TRUE(m.Matches(&n));
3328 n = -1;
3329 EXPECT_FALSE(m.Matches(&n));
3330 EXPECT_FALSE(m.Matches(NULL));
3331 }
3332
TEST(PointeeTest,CanDescribeSelf)3333 TEST(PointeeTest, CanDescribeSelf) {
3334 const Matcher<int*> m = Pointee(Gt(3));
3335 EXPECT_EQ("points to a value that is > 3", Describe(m));
3336 EXPECT_EQ("does not point to a value that is > 3",
3337 DescribeNegation(m));
3338 }
3339
TEST(PointeeTest,CanExplainMatchResult)3340 TEST(PointeeTest, CanExplainMatchResult) {
3341 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3342
3343 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL)));
3344
3345 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3346 long n = 3; // NOLINT
3347 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3348 Explain(m2, &n));
3349 }
3350
TEST(PointeeTest,AlwaysExplainsPointee)3351 TEST(PointeeTest, AlwaysExplainsPointee) {
3352 const Matcher<int*> m = Pointee(0);
3353 int n = 42;
3354 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3355 }
3356
3357 // An uncopyable class.
3358 class Uncopyable {
3359 public:
Uncopyable()3360 Uncopyable() : value_(-1) {}
Uncopyable(int a_value)3361 explicit Uncopyable(int a_value) : value_(a_value) {}
3362
value() const3363 int value() const { return value_; }
set_value(int i)3364 void set_value(int i) { value_ = i; }
3365
3366 private:
3367 int value_;
3368 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3369 };
3370
3371 // Returns true iff x.value() is positive.
ValueIsPositive(const Uncopyable & x)3372 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3373
3374 MATCHER_P(UncopyableIs, inner_matcher, "") {
3375 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3376 }
3377
3378 // A user-defined struct for testing Field().
3379 struct AStruct {
AStructtesting::gmock_matchers_test::AStruct3380 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
AStructtesting::gmock_matchers_test::AStruct3381 AStruct(const AStruct& rhs)
3382 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3383
3384 int x; // A non-const field.
3385 const double y; // A const field.
3386 Uncopyable z; // An uncopyable field.
3387 const char* p; // A pointer field.
3388
3389 private:
3390 GTEST_DISALLOW_ASSIGN_(AStruct);
3391 };
3392
3393 // A derived struct for testing Field().
3394 struct DerivedStruct : public AStruct {
3395 char ch;
3396
3397 private:
3398 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3399 };
3400
3401 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)3402 TEST(FieldTest, WorksForNonConstField) {
3403 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3404
3405 AStruct a;
3406 EXPECT_TRUE(m.Matches(a));
3407 a.x = -1;
3408 EXPECT_FALSE(m.Matches(a));
3409 }
3410
3411 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)3412 TEST(FieldTest, WorksForConstField) {
3413 AStruct a;
3414
3415 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3416 EXPECT_TRUE(m.Matches(a));
3417 m = Field(&AStruct::y, Le(0.0));
3418 EXPECT_FALSE(m.Matches(a));
3419 }
3420
3421 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)3422 TEST(FieldTest, WorksForUncopyableField) {
3423 AStruct a;
3424
3425 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3426 EXPECT_TRUE(m.Matches(a));
3427 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3428 EXPECT_FALSE(m.Matches(a));
3429 }
3430
3431 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)3432 TEST(FieldTest, WorksForPointerField) {
3433 // Matching against NULL.
3434 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3435 AStruct a;
3436 EXPECT_TRUE(m.Matches(a));
3437 a.p = "hi";
3438 EXPECT_FALSE(m.Matches(a));
3439
3440 // Matching a pointer that is not NULL.
3441 m = Field(&AStruct::p, StartsWith("hi"));
3442 a.p = "hill";
3443 EXPECT_TRUE(m.Matches(a));
3444 a.p = "hole";
3445 EXPECT_FALSE(m.Matches(a));
3446 }
3447
3448 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)3449 TEST(FieldTest, WorksForByRefArgument) {
3450 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3451
3452 AStruct a;
3453 EXPECT_TRUE(m.Matches(a));
3454 a.x = -1;
3455 EXPECT_FALSE(m.Matches(a));
3456 }
3457
3458 // Tests that Field(&Foo::field, ...) works when the argument's type
3459 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)3460 TEST(FieldTest, WorksForArgumentOfSubType) {
3461 // Note that the matcher expects DerivedStruct but we say AStruct
3462 // inside Field().
3463 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3464
3465 DerivedStruct d;
3466 EXPECT_TRUE(m.Matches(d));
3467 d.x = -1;
3468 EXPECT_FALSE(m.Matches(d));
3469 }
3470
3471 // Tests that Field(&Foo::field, m) works when field's type and m's
3472 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)3473 TEST(FieldTest, WorksForCompatibleMatcherType) {
3474 // The field is an int, but the inner matcher expects a signed char.
3475 Matcher<const AStruct&> m = Field(&AStruct::x,
3476 Matcher<signed char>(Ge(0)));
3477
3478 AStruct a;
3479 EXPECT_TRUE(m.Matches(a));
3480 a.x = -1;
3481 EXPECT_FALSE(m.Matches(a));
3482 }
3483
3484 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)3485 TEST(FieldTest, CanDescribeSelf) {
3486 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3487
3488 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3489 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3490 }
3491
3492 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)3493 TEST(FieldTest, CanExplainMatchResult) {
3494 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3495
3496 AStruct a;
3497 a.x = 1;
3498 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3499
3500 m = Field(&AStruct::x, GreaterThan(0));
3501 EXPECT_EQ(
3502 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3503 Explain(m, a));
3504 }
3505
3506 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)3507 TEST(FieldForPointerTest, WorksForPointerToConst) {
3508 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3509
3510 AStruct a;
3511 EXPECT_TRUE(m.Matches(&a));
3512 a.x = -1;
3513 EXPECT_FALSE(m.Matches(&a));
3514 }
3515
3516 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)3517 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3518 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3519
3520 AStruct a;
3521 EXPECT_TRUE(m.Matches(&a));
3522 a.x = -1;
3523 EXPECT_FALSE(m.Matches(&a));
3524 }
3525
3526 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)3527 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3528 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3529
3530 AStruct a;
3531 EXPECT_TRUE(m.Matches(&a));
3532 a.x = -1;
3533 EXPECT_FALSE(m.Matches(&a));
3534 }
3535
3536 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)3537 TEST(FieldForPointerTest, DoesNotMatchNull) {
3538 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3539 EXPECT_FALSE(m.Matches(NULL));
3540 }
3541
3542 // Tests that Field(&Foo::field, ...) works when the argument's type
3543 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)3544 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3545 // Note that the matcher expects DerivedStruct but we say AStruct
3546 // inside Field().
3547 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3548
3549 DerivedStruct d;
3550 EXPECT_TRUE(m.Matches(&d));
3551 d.x = -1;
3552 EXPECT_FALSE(m.Matches(&d));
3553 }
3554
3555 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)3556 TEST(FieldForPointerTest, CanDescribeSelf) {
3557 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3558
3559 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3560 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3561 }
3562
3563 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)3564 TEST(FieldForPointerTest, CanExplainMatchResult) {
3565 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3566
3567 AStruct a;
3568 a.x = 1;
3569 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
3570 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3571 Explain(m, &a));
3572
3573 m = Field(&AStruct::x, GreaterThan(0));
3574 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3575 ", which is 1 more than 0", Explain(m, &a));
3576 }
3577
3578 // A user-defined class for testing Property().
3579 class AClass {
3580 public:
AClass()3581 AClass() : n_(0) {}
3582
3583 // A getter that returns a non-reference.
n() const3584 int n() const { return n_; }
3585
set_n(int new_n)3586 void set_n(int new_n) { n_ = new_n; }
3587
3588 // A getter that returns a reference to const.
s() const3589 const std::string& s() const { return s_; }
3590
3591 #if GTEST_LANG_CXX11
s_ref() const3592 const std::string& s_ref() const & { return s_; }
3593 #endif
3594
set_s(const std::string & new_s)3595 void set_s(const std::string& new_s) { s_ = new_s; }
3596
3597 // A getter that returns a reference to non-const.
x() const3598 double& x() const { return x_; }
3599
3600 private:
3601 int n_;
3602 std::string s_;
3603
3604 static double x_;
3605 };
3606
3607 double AClass::x_ = 0.0;
3608
3609 // A derived class for testing Property().
3610 class DerivedClass : public AClass {
3611 public:
k() const3612 int k() const { return k_; }
3613 private:
3614 int k_;
3615 };
3616
3617 // Tests that Property(&Foo::property, ...) works when property()
3618 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)3619 TEST(PropertyTest, WorksForNonReferenceProperty) {
3620 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3621
3622 AClass a;
3623 a.set_n(1);
3624 EXPECT_TRUE(m.Matches(a));
3625
3626 a.set_n(-1);
3627 EXPECT_FALSE(m.Matches(a));
3628 }
3629
3630 // Tests that Property(&Foo::property, ...) works when property()
3631 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)3632 TEST(PropertyTest, WorksForReferenceToConstProperty) {
3633 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3634
3635 AClass a;
3636 a.set_s("hill");
3637 EXPECT_TRUE(m.Matches(a));
3638
3639 a.set_s("hole");
3640 EXPECT_FALSE(m.Matches(a));
3641 }
3642
3643 #if GTEST_LANG_CXX11
3644 // Tests that Property(&Foo::property, ...) works when property() is
3645 // ref-qualified.
TEST(PropertyTest,WorksForRefQualifiedProperty)3646 TEST(PropertyTest, WorksForRefQualifiedProperty) {
3647 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
3648
3649 AClass a;
3650 a.set_s("hill");
3651 EXPECT_TRUE(m.Matches(a));
3652
3653 a.set_s("hole");
3654 EXPECT_FALSE(m.Matches(a));
3655 }
3656 #endif
3657
3658 // Tests that Property(&Foo::property, ...) works when property()
3659 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)3660 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3661 double x = 0.0;
3662 AClass a;
3663
3664 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3665 EXPECT_FALSE(m.Matches(a));
3666
3667 m = Property(&AClass::x, Not(Ref(x)));
3668 EXPECT_TRUE(m.Matches(a));
3669 }
3670
3671 // Tests that Property(&Foo::property, ...) works when the argument is
3672 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)3673 TEST(PropertyTest, WorksForByValueArgument) {
3674 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3675
3676 AClass a;
3677 a.set_s("hill");
3678 EXPECT_TRUE(m.Matches(a));
3679
3680 a.set_s("hole");
3681 EXPECT_FALSE(m.Matches(a));
3682 }
3683
3684 // Tests that Property(&Foo::property, ...) works when the argument's
3685 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)3686 TEST(PropertyTest, WorksForArgumentOfSubType) {
3687 // The matcher expects a DerivedClass, but inside the Property() we
3688 // say AClass.
3689 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3690
3691 DerivedClass d;
3692 d.set_n(1);
3693 EXPECT_TRUE(m.Matches(d));
3694
3695 d.set_n(-1);
3696 EXPECT_FALSE(m.Matches(d));
3697 }
3698
3699 // Tests that Property(&Foo::property, m) works when property()'s type
3700 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)3701 TEST(PropertyTest, WorksForCompatibleMatcherType) {
3702 // n() returns an int but the inner matcher expects a signed char.
3703 Matcher<const AClass&> m = Property(&AClass::n,
3704 Matcher<signed char>(Ge(0)));
3705
3706 AClass a;
3707 EXPECT_TRUE(m.Matches(a));
3708 a.set_n(-1);
3709 EXPECT_FALSE(m.Matches(a));
3710 }
3711
3712 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)3713 TEST(PropertyTest, CanDescribeSelf) {
3714 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3715
3716 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3717 EXPECT_EQ("is an object whose given property isn't >= 0",
3718 DescribeNegation(m));
3719 }
3720
3721 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)3722 TEST(PropertyTest, CanExplainMatchResult) {
3723 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3724
3725 AClass a;
3726 a.set_n(1);
3727 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
3728
3729 m = Property(&AClass::n, GreaterThan(0));
3730 EXPECT_EQ(
3731 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3732 Explain(m, a));
3733 }
3734
3735 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)3736 TEST(PropertyForPointerTest, WorksForPointerToConst) {
3737 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3738
3739 AClass a;
3740 a.set_n(1);
3741 EXPECT_TRUE(m.Matches(&a));
3742
3743 a.set_n(-1);
3744 EXPECT_FALSE(m.Matches(&a));
3745 }
3746
3747 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)3748 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3749 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3750
3751 AClass a;
3752 a.set_s("hill");
3753 EXPECT_TRUE(m.Matches(&a));
3754
3755 a.set_s("hole");
3756 EXPECT_FALSE(m.Matches(&a));
3757 }
3758
3759 // Tests that Property() works when the argument is a reference to a
3760 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)3761 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3762 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3763
3764 AClass a;
3765 a.set_s("hill");
3766 EXPECT_TRUE(m.Matches(&a));
3767
3768 a.set_s("hole");
3769 EXPECT_FALSE(m.Matches(&a));
3770 }
3771
3772 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)3773 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3774 Matcher<const AClass*> m = Property(&AClass::x, _);
3775 EXPECT_FALSE(m.Matches(NULL));
3776 }
3777
3778 // Tests that Property(&Foo::property, ...) works when the argument's
3779 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)3780 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3781 // The matcher expects a DerivedClass, but inside the Property() we
3782 // say AClass.
3783 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3784
3785 DerivedClass d;
3786 d.set_n(1);
3787 EXPECT_TRUE(m.Matches(&d));
3788
3789 d.set_n(-1);
3790 EXPECT_FALSE(m.Matches(&d));
3791 }
3792
3793 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)3794 TEST(PropertyForPointerTest, CanDescribeSelf) {
3795 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3796
3797 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3798 EXPECT_EQ("is an object whose given property isn't >= 0",
3799 DescribeNegation(m));
3800 }
3801
3802 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)3803 TEST(PropertyForPointerTest, CanExplainMatchResult) {
3804 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3805
3806 AClass a;
3807 a.set_n(1);
3808 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
3809 EXPECT_EQ(
3810 "which points to an object whose given property is 1" + OfType("int"),
3811 Explain(m, &a));
3812
3813 m = Property(&AClass::n, GreaterThan(0));
3814 EXPECT_EQ("which points to an object whose given property is 1" +
3815 OfType("int") + ", which is 1 more than 0",
3816 Explain(m, &a));
3817 }
3818
3819 // Tests ResultOf.
3820
3821 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3822 // function pointer.
IntToStringFunction(int input)3823 std::string IntToStringFunction(int input) {
3824 return input == 1 ? "foo" : "bar";
3825 }
3826
TEST(ResultOfTest,WorksForFunctionPointers)3827 TEST(ResultOfTest, WorksForFunctionPointers) {
3828 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
3829
3830 EXPECT_TRUE(matcher.Matches(1));
3831 EXPECT_FALSE(matcher.Matches(2));
3832 }
3833
3834 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)3835 TEST(ResultOfTest, CanDescribeItself) {
3836 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3837
3838 EXPECT_EQ("is mapped by the given callable to a value that "
3839 "is equal to \"foo\"", Describe(matcher));
3840 EXPECT_EQ("is mapped by the given callable to a value that "
3841 "isn't equal to \"foo\"", DescribeNegation(matcher));
3842 }
3843
3844 // Tests that ResultOf() can explain the match result.
IntFunction(int input)3845 int IntFunction(int input) { return input == 42 ? 80 : 90; }
3846
TEST(ResultOfTest,CanExplainMatchResult)3847 TEST(ResultOfTest, CanExplainMatchResult) {
3848 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
3849 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
3850 Explain(matcher, 36));
3851
3852 matcher = ResultOf(&IntFunction, GreaterThan(85));
3853 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3854 ", which is 5 more than 85", Explain(matcher, 36));
3855 }
3856
3857 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3858 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)3859 TEST(ResultOfTest, WorksForNonReferenceResults) {
3860 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3861
3862 EXPECT_TRUE(matcher.Matches(42));
3863 EXPECT_FALSE(matcher.Matches(36));
3864 }
3865
3866 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3867 // returns a reference to non-const.
DoubleFunction(double & input)3868 double& DoubleFunction(double& input) { return input; } // NOLINT
3869
RefUncopyableFunction(Uncopyable & obj)3870 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
3871 return obj;
3872 }
3873
TEST(ResultOfTest,WorksForReferenceToNonConstResults)3874 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3875 double x = 3.14;
3876 double x2 = x;
3877 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3878
3879 EXPECT_TRUE(matcher.Matches(x));
3880 EXPECT_FALSE(matcher.Matches(x2));
3881
3882 // Test that ResultOf works with uncopyable objects
3883 Uncopyable obj(0);
3884 Uncopyable obj2(0);
3885 Matcher<Uncopyable&> matcher2 =
3886 ResultOf(&RefUncopyableFunction, Ref(obj));
3887
3888 EXPECT_TRUE(matcher2.Matches(obj));
3889 EXPECT_FALSE(matcher2.Matches(obj2));
3890 }
3891
3892 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3893 // returns a reference to const.
StringFunction(const std::string & input)3894 const std::string& StringFunction(const std::string& input) { return input; }
3895
TEST(ResultOfTest,WorksForReferenceToConstResults)3896 TEST(ResultOfTest, WorksForReferenceToConstResults) {
3897 std::string s = "foo";
3898 std::string s2 = s;
3899 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
3900
3901 EXPECT_TRUE(matcher.Matches(s));
3902 EXPECT_FALSE(matcher.Matches(s2));
3903 }
3904
3905 // Tests that ResultOf(f, m) works when f(x) and m's
3906 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)3907 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3908 // IntFunction() returns int but the inner matcher expects a signed char.
3909 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3910
3911 EXPECT_TRUE(matcher.Matches(36));
3912 EXPECT_FALSE(matcher.Matches(42));
3913 }
3914
3915 // Tests that the program aborts when ResultOf is passed
3916 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)3917 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
3918 EXPECT_DEATH_IF_SUPPORTED(
3919 ResultOf(static_cast<std::string (*)(int dummy)>(NULL),
3920 Eq(std::string("foo"))),
3921 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3922 }
3923
3924 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3925 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)3926 TEST(ResultOfTest, WorksForFunctionReferences) {
3927 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3928 EXPECT_TRUE(matcher.Matches(1));
3929 EXPECT_FALSE(matcher.Matches(2));
3930 }
3931
3932 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3933 // function object.
3934 struct Functor {
3935 typedef std::string result_type;
3936 typedef int argument_type;
3937
operator ()testing::gmock_matchers_test::Functor3938 std::string operator()(int input) const {
3939 return IntToStringFunction(input);
3940 }
3941 };
3942
TEST(ResultOfTest,WorksForFunctors)3943 TEST(ResultOfTest, WorksForFunctors) {
3944 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
3945
3946 EXPECT_TRUE(matcher.Matches(1));
3947 EXPECT_FALSE(matcher.Matches(2));
3948 }
3949
3950 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
3951 // functor with more then one operator() defined. ResultOf() must work
3952 // for each defined operator().
3953 struct PolymorphicFunctor {
3954 typedef int result_type;
operator ()testing::gmock_matchers_test::PolymorphicFunctor3955 int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::PolymorphicFunctor3956 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3957 };
3958
TEST(ResultOfTest,WorksForPolymorphicFunctors)3959 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3960 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3961
3962 EXPECT_TRUE(matcher_int.Matches(10));
3963 EXPECT_FALSE(matcher_int.Matches(2));
3964
3965 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3966
3967 EXPECT_TRUE(matcher_string.Matches("long string"));
3968 EXPECT_FALSE(matcher_string.Matches("shrt"));
3969 }
3970
ReferencingFunction(const int & n)3971 const int* ReferencingFunction(const int& n) { return &n; }
3972
3973 struct ReferencingFunctor {
3974 typedef const int* result_type;
operator ()testing::gmock_matchers_test::ReferencingFunctor3975 result_type operator()(const int& n) { return &n; }
3976 };
3977
TEST(ResultOfTest,WorksForReferencingCallables)3978 TEST(ResultOfTest, WorksForReferencingCallables) {
3979 const int n = 1;
3980 const int n2 = 1;
3981 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3982 EXPECT_TRUE(matcher2.Matches(n));
3983 EXPECT_FALSE(matcher2.Matches(n2));
3984
3985 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3986 EXPECT_TRUE(matcher3.Matches(n));
3987 EXPECT_FALSE(matcher3.Matches(n2));
3988 }
3989
3990 class DivisibleByImpl {
3991 public:
DivisibleByImpl(int a_divider)3992 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
3993
3994 // For testing using ExplainMatchResultTo() with polymorphic matchers.
3995 template <typename T>
MatchAndExplain(const T & n,MatchResultListener * listener) const3996 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
3997 *listener << "which is " << (n % divider_) << " modulo "
3998 << divider_;
3999 return (n % divider_) == 0;
4000 }
4001
DescribeTo(ostream * os) const4002 void DescribeTo(ostream* os) const {
4003 *os << "is divisible by " << divider_;
4004 }
4005
DescribeNegationTo(ostream * os) const4006 void DescribeNegationTo(ostream* os) const {
4007 *os << "is not divisible by " << divider_;
4008 }
4009
set_divider(int a_divider)4010 void set_divider(int a_divider) { divider_ = a_divider; }
divider() const4011 int divider() const { return divider_; }
4012
4013 private:
4014 int divider_;
4015 };
4016
DivisibleBy(int n)4017 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4018 return MakePolymorphicMatcher(DivisibleByImpl(n));
4019 }
4020
4021 // Tests that when AllOf() fails, only the first failing matcher is
4022 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_False)4023 TEST(ExplainMatchResultTest, AllOf_False_False) {
4024 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4025 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4026 }
4027
4028 // Tests that when AllOf() fails, only the first failing matcher is
4029 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_True)4030 TEST(ExplainMatchResultTest, AllOf_False_True) {
4031 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4032 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4033 }
4034
4035 // Tests that when AllOf() fails, only the first failing matcher is
4036 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_True_False)4037 TEST(ExplainMatchResultTest, AllOf_True_False) {
4038 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4039 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4040 }
4041
4042 // Tests that when AllOf() succeeds, all matchers are asked to explain
4043 // why.
TEST(ExplainMatchResultTest,AllOf_True_True)4044 TEST(ExplainMatchResultTest, AllOf_True_True) {
4045 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4046 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4047 }
4048
TEST(ExplainMatchResultTest,AllOf_True_True_2)4049 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4050 const Matcher<int> m = AllOf(Ge(2), Le(3));
4051 EXPECT_EQ("", Explain(m, 2));
4052 }
4053
TEST(ExplainmatcherResultTest,MonomorphicMatcher)4054 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4055 const Matcher<int> m = GreaterThan(5);
4056 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4057 }
4058
4059 // The following two tests verify that values without a public copy
4060 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4061 // with the help of ByRef().
4062
4063 class NotCopyable {
4064 public:
NotCopyable(int a_value)4065 explicit NotCopyable(int a_value) : value_(a_value) {}
4066
value() const4067 int value() const { return value_; }
4068
operator ==(const NotCopyable & rhs) const4069 bool operator==(const NotCopyable& rhs) const {
4070 return value() == rhs.value();
4071 }
4072
operator >=(const NotCopyable & rhs) const4073 bool operator>=(const NotCopyable& rhs) const {
4074 return value() >= rhs.value();
4075 }
4076 private:
4077 int value_;
4078
4079 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4080 };
4081
TEST(ByRefTest,AllowsNotCopyableConstValueInMatchers)4082 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4083 const NotCopyable const_value1(1);
4084 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4085
4086 const NotCopyable n1(1), n2(2);
4087 EXPECT_TRUE(m.Matches(n1));
4088 EXPECT_FALSE(m.Matches(n2));
4089 }
4090
TEST(ByRefTest,AllowsNotCopyableValueInMatchers)4091 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4092 NotCopyable value2(2);
4093 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4094
4095 NotCopyable n1(1), n2(2);
4096 EXPECT_FALSE(m.Matches(n1));
4097 EXPECT_TRUE(m.Matches(n2));
4098 }
4099
TEST(IsEmptyTest,ImplementsIsEmpty)4100 TEST(IsEmptyTest, ImplementsIsEmpty) {
4101 vector<int> container;
4102 EXPECT_THAT(container, IsEmpty());
4103 container.push_back(0);
4104 EXPECT_THAT(container, Not(IsEmpty()));
4105 container.push_back(1);
4106 EXPECT_THAT(container, Not(IsEmpty()));
4107 }
4108
TEST(IsEmptyTest,WorksWithString)4109 TEST(IsEmptyTest, WorksWithString) {
4110 std::string text;
4111 EXPECT_THAT(text, IsEmpty());
4112 text = "foo";
4113 EXPECT_THAT(text, Not(IsEmpty()));
4114 text = std::string("\0", 1);
4115 EXPECT_THAT(text, Not(IsEmpty()));
4116 }
4117
TEST(IsEmptyTest,CanDescribeSelf)4118 TEST(IsEmptyTest, CanDescribeSelf) {
4119 Matcher<vector<int> > m = IsEmpty();
4120 EXPECT_EQ("is empty", Describe(m));
4121 EXPECT_EQ("isn't empty", DescribeNegation(m));
4122 }
4123
TEST(IsEmptyTest,ExplainsResult)4124 TEST(IsEmptyTest, ExplainsResult) {
4125 Matcher<vector<int> > m = IsEmpty();
4126 vector<int> container;
4127 EXPECT_EQ("", Explain(m, container));
4128 container.push_back(0);
4129 EXPECT_EQ("whose size is 1", Explain(m, container));
4130 }
4131
TEST(SizeIsTest,ImplementsSizeIs)4132 TEST(SizeIsTest, ImplementsSizeIs) {
4133 vector<int> container;
4134 EXPECT_THAT(container, SizeIs(0));
4135 EXPECT_THAT(container, Not(SizeIs(1)));
4136 container.push_back(0);
4137 EXPECT_THAT(container, Not(SizeIs(0)));
4138 EXPECT_THAT(container, SizeIs(1));
4139 container.push_back(0);
4140 EXPECT_THAT(container, Not(SizeIs(0)));
4141 EXPECT_THAT(container, SizeIs(2));
4142 }
4143
TEST(SizeIsTest,WorksWithMap)4144 TEST(SizeIsTest, WorksWithMap) {
4145 map<std::string, int> container;
4146 EXPECT_THAT(container, SizeIs(0));
4147 EXPECT_THAT(container, Not(SizeIs(1)));
4148 container.insert(make_pair("foo", 1));
4149 EXPECT_THAT(container, Not(SizeIs(0)));
4150 EXPECT_THAT(container, SizeIs(1));
4151 container.insert(make_pair("bar", 2));
4152 EXPECT_THAT(container, Not(SizeIs(0)));
4153 EXPECT_THAT(container, SizeIs(2));
4154 }
4155
TEST(SizeIsTest,WorksWithReferences)4156 TEST(SizeIsTest, WorksWithReferences) {
4157 vector<int> container;
4158 Matcher<const vector<int>&> m = SizeIs(1);
4159 EXPECT_THAT(container, Not(m));
4160 container.push_back(0);
4161 EXPECT_THAT(container, m);
4162 }
4163
TEST(SizeIsTest,CanDescribeSelf)4164 TEST(SizeIsTest, CanDescribeSelf) {
4165 Matcher<vector<int> > m = SizeIs(2);
4166 EXPECT_EQ("size is equal to 2", Describe(m));
4167 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4168 }
4169
TEST(SizeIsTest,ExplainsResult)4170 TEST(SizeIsTest, ExplainsResult) {
4171 Matcher<vector<int> > m1 = SizeIs(2);
4172 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4173 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4174 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4175 vector<int> container;
4176 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4177 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4178 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4179 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4180 Explain(m4, container));
4181 container.push_back(0);
4182 container.push_back(0);
4183 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4184 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4185 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4186 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4187 Explain(m4, container));
4188 }
4189
4190 #if GTEST_HAS_TYPED_TEST
4191 // Tests ContainerEq with different container types, and
4192 // different element types.
4193
4194 template <typename T>
4195 class ContainerEqTest : public testing::Test {};
4196
4197 typedef testing::Types<
4198 set<int>,
4199 vector<size_t>,
4200 multiset<size_t>,
4201 list<int> >
4202 ContainerEqTestTypes;
4203
4204 TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4205
4206 // Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest,EqualsSelf)4207 TYPED_TEST(ContainerEqTest, EqualsSelf) {
4208 static const int vals[] = {1, 1, 2, 3, 5, 8};
4209 TypeParam my_set(vals, vals + 6);
4210 const Matcher<TypeParam> m = ContainerEq(my_set);
4211 EXPECT_TRUE(m.Matches(my_set));
4212 EXPECT_EQ("", Explain(m, my_set));
4213 }
4214
4215 // Tests that missing values are reported.
TYPED_TEST(ContainerEqTest,ValueMissing)4216 TYPED_TEST(ContainerEqTest, ValueMissing) {
4217 static const int vals[] = {1, 1, 2, 3, 5, 8};
4218 static const int test_vals[] = {2, 1, 8, 5};
4219 TypeParam my_set(vals, vals + 6);
4220 TypeParam test_set(test_vals, test_vals + 4);
4221 const Matcher<TypeParam> m = ContainerEq(my_set);
4222 EXPECT_FALSE(m.Matches(test_set));
4223 EXPECT_EQ("which doesn't have these expected elements: 3",
4224 Explain(m, test_set));
4225 }
4226
4227 // Tests that added values are reported.
TYPED_TEST(ContainerEqTest,ValueAdded)4228 TYPED_TEST(ContainerEqTest, ValueAdded) {
4229 static const int vals[] = {1, 1, 2, 3, 5, 8};
4230 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4231 TypeParam my_set(vals, vals + 6);
4232 TypeParam test_set(test_vals, test_vals + 6);
4233 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4234 EXPECT_FALSE(m.Matches(test_set));
4235 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4236 }
4237
4238 // Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest,ValueAddedAndRemoved)4239 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4240 static const int vals[] = {1, 1, 2, 3, 5, 8};
4241 static const int test_vals[] = {1, 2, 3, 8, 46};
4242 TypeParam my_set(vals, vals + 6);
4243 TypeParam test_set(test_vals, test_vals + 5);
4244 const Matcher<TypeParam> m = ContainerEq(my_set);
4245 EXPECT_FALSE(m.Matches(test_set));
4246 EXPECT_EQ("which has these unexpected elements: 46,\n"
4247 "and doesn't have these expected elements: 5",
4248 Explain(m, test_set));
4249 }
4250
4251 // Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest,DuplicateDifference)4252 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4253 static const int vals[] = {1, 1, 2, 3, 5, 8};
4254 static const int test_vals[] = {1, 2, 3, 5, 8};
4255 TypeParam my_set(vals, vals + 6);
4256 TypeParam test_set(test_vals, test_vals + 5);
4257 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4258 // Depending on the container, match may be true or false
4259 // But in any case there should be no explanation.
4260 EXPECT_EQ("", Explain(m, test_set));
4261 }
4262 #endif // GTEST_HAS_TYPED_TEST
4263
4264 // Tests that mutliple missing values are reported.
4265 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesMissing)4266 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4267 static const int vals[] = {1, 1, 2, 3, 5, 8};
4268 static const int test_vals[] = {2, 1, 5};
4269 vector<int> my_set(vals, vals + 6);
4270 vector<int> test_set(test_vals, test_vals + 3);
4271 const Matcher<vector<int> > m = ContainerEq(my_set);
4272 EXPECT_FALSE(m.Matches(test_set));
4273 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4274 Explain(m, test_set));
4275 }
4276
4277 // Tests that added values are reported.
4278 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesAdded)4279 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4280 static const int vals[] = {1, 1, 2, 3, 5, 8};
4281 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4282 list<size_t> my_set(vals, vals + 6);
4283 list<size_t> test_set(test_vals, test_vals + 7);
4284 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4285 EXPECT_FALSE(m.Matches(test_set));
4286 EXPECT_EQ("which has these unexpected elements: 92, 46",
4287 Explain(m, test_set));
4288 }
4289
4290 // Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest,MultipleValuesAddedAndRemoved)4291 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4292 static const int vals[] = {1, 1, 2, 3, 5, 8};
4293 static const int test_vals[] = {1, 2, 3, 92, 46};
4294 list<size_t> my_set(vals, vals + 6);
4295 list<size_t> test_set(test_vals, test_vals + 5);
4296 const Matcher<const list<size_t> > m = ContainerEq(my_set);
4297 EXPECT_FALSE(m.Matches(test_set));
4298 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4299 "and doesn't have these expected elements: 5, 8",
4300 Explain(m, test_set));
4301 }
4302
4303 // Tests to see that duplicate elements are detected,
4304 // but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest,MultiSetOfIntDuplicateDifference)4305 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4306 static const int vals[] = {1, 1, 2, 3, 5, 8};
4307 static const int test_vals[] = {1, 2, 3, 5, 8};
4308 vector<int> my_set(vals, vals + 6);
4309 vector<int> test_set(test_vals, test_vals + 5);
4310 const Matcher<vector<int> > m = ContainerEq(my_set);
4311 EXPECT_TRUE(m.Matches(my_set));
4312 EXPECT_FALSE(m.Matches(test_set));
4313 // There is nothing to report when both sets contain all the same values.
4314 EXPECT_EQ("", Explain(m, test_set));
4315 }
4316
4317 // Tests that ContainerEq works for non-trivial associative containers,
4318 // like maps.
TEST(ContainerEqExtraTest,WorksForMaps)4319 TEST(ContainerEqExtraTest, WorksForMaps) {
4320 map<int, std::string> my_map;
4321 my_map[0] = "a";
4322 my_map[1] = "b";
4323
4324 map<int, std::string> test_map;
4325 test_map[0] = "aa";
4326 test_map[1] = "b";
4327
4328 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
4329 EXPECT_TRUE(m.Matches(my_map));
4330 EXPECT_FALSE(m.Matches(test_map));
4331
4332 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4333 "and doesn't have these expected elements: (0, \"a\")",
4334 Explain(m, test_map));
4335 }
4336
TEST(ContainerEqExtraTest,WorksForNativeArray)4337 TEST(ContainerEqExtraTest, WorksForNativeArray) {
4338 int a1[] = {1, 2, 3};
4339 int a2[] = {1, 2, 3};
4340 int b[] = {1, 2, 4};
4341
4342 EXPECT_THAT(a1, ContainerEq(a2));
4343 EXPECT_THAT(a1, Not(ContainerEq(b)));
4344 }
4345
TEST(ContainerEqExtraTest,WorksForTwoDimensionalNativeArray)4346 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4347 const char a1[][3] = {"hi", "lo"};
4348 const char a2[][3] = {"hi", "lo"};
4349 const char b[][3] = {"lo", "hi"};
4350
4351 // Tests using ContainerEq() in the first dimension.
4352 EXPECT_THAT(a1, ContainerEq(a2));
4353 EXPECT_THAT(a1, Not(ContainerEq(b)));
4354
4355 // Tests using ContainerEq() in the second dimension.
4356 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4357 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4358 }
4359
TEST(ContainerEqExtraTest,WorksForNativeArrayAsTuple)4360 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4361 const int a1[] = {1, 2, 3};
4362 const int a2[] = {1, 2, 3};
4363 const int b[] = {1, 2, 3, 4};
4364
4365 const int* const p1 = a1;
4366 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4367 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
4368
4369 const int c[] = {1, 3, 2};
4370 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
4371 }
4372
TEST(ContainerEqExtraTest,CopiesNativeArrayParameter)4373 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4374 std::string a1[][3] = {
4375 {"hi", "hello", "ciao"},
4376 {"bye", "see you", "ciao"}
4377 };
4378
4379 std::string a2[][3] = {
4380 {"hi", "hello", "ciao"},
4381 {"bye", "see you", "ciao"}
4382 };
4383
4384 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4385 EXPECT_THAT(a1, m);
4386
4387 a2[0][0] = "ha";
4388 EXPECT_THAT(a1, m);
4389 }
4390
TEST(WhenSortedByTest,WorksForEmptyContainer)4391 TEST(WhenSortedByTest, WorksForEmptyContainer) {
4392 const vector<int> numbers;
4393 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4394 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4395 }
4396
TEST(WhenSortedByTest,WorksForNonEmptyContainer)4397 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4398 vector<unsigned> numbers;
4399 numbers.push_back(3);
4400 numbers.push_back(1);
4401 numbers.push_back(2);
4402 numbers.push_back(2);
4403 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4404 ElementsAre(3, 2, 2, 1)));
4405 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4406 ElementsAre(1, 2, 2, 3))));
4407 }
4408
TEST(WhenSortedByTest,WorksForNonVectorContainer)4409 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4410 list<std::string> words;
4411 words.push_back("say");
4412 words.push_back("hello");
4413 words.push_back("world");
4414 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
4415 ElementsAre("hello", "say", "world")));
4416 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
4417 ElementsAre("say", "hello", "world"))));
4418 }
4419
TEST(WhenSortedByTest,WorksForNativeArray)4420 TEST(WhenSortedByTest, WorksForNativeArray) {
4421 const int numbers[] = {1, 3, 2, 4};
4422 const int sorted_numbers[] = {1, 2, 3, 4};
4423 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4424 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4425 ElementsAreArray(sorted_numbers)));
4426 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4427 }
4428
TEST(WhenSortedByTest,CanDescribeSelf)4429 TEST(WhenSortedByTest, CanDescribeSelf) {
4430 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4431 EXPECT_EQ("(when sorted) has 2 elements where\n"
4432 "element #0 is equal to 1,\n"
4433 "element #1 is equal to 2",
4434 Describe(m));
4435 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4436 "element #0 isn't equal to 1, or\n"
4437 "element #1 isn't equal to 2",
4438 DescribeNegation(m));
4439 }
4440
TEST(WhenSortedByTest,ExplainsMatchResult)4441 TEST(WhenSortedByTest, ExplainsMatchResult) {
4442 const int a[] = {2, 1};
4443 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4444 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4445 EXPECT_EQ("which is { 1, 2 } when sorted",
4446 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4447 }
4448
4449 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4450 // need to test it as exhaustively as we test the latter.
4451
TEST(WhenSortedTest,WorksForEmptyContainer)4452 TEST(WhenSortedTest, WorksForEmptyContainer) {
4453 const vector<int> numbers;
4454 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4455 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4456 }
4457
TEST(WhenSortedTest,WorksForNonEmptyContainer)4458 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4459 list<std::string> words;
4460 words.push_back("3");
4461 words.push_back("1");
4462 words.push_back("2");
4463 words.push_back("2");
4464 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4465 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4466 }
4467
TEST(WhenSortedTest,WorksForMapTypes)4468 TEST(WhenSortedTest, WorksForMapTypes) {
4469 map<std::string, int> word_counts;
4470 word_counts["and"] = 1;
4471 word_counts["the"] = 1;
4472 word_counts["buffalo"] = 2;
4473 EXPECT_THAT(word_counts,
4474 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
4475 Pair("the", 1))));
4476 EXPECT_THAT(word_counts,
4477 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
4478 Pair("buffalo", 2)))));
4479 }
4480
TEST(WhenSortedTest,WorksForMultiMapTypes)4481 TEST(WhenSortedTest, WorksForMultiMapTypes) {
4482 multimap<int, int> ifib;
4483 ifib.insert(make_pair(8, 6));
4484 ifib.insert(make_pair(2, 3));
4485 ifib.insert(make_pair(1, 1));
4486 ifib.insert(make_pair(3, 4));
4487 ifib.insert(make_pair(1, 2));
4488 ifib.insert(make_pair(5, 5));
4489 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4490 Pair(1, 2),
4491 Pair(2, 3),
4492 Pair(3, 4),
4493 Pair(5, 5),
4494 Pair(8, 6))));
4495 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4496 Pair(2, 3),
4497 Pair(1, 1),
4498 Pair(3, 4),
4499 Pair(1, 2),
4500 Pair(5, 5)))));
4501 }
4502
TEST(WhenSortedTest,WorksForPolymorphicMatcher)4503 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4504 std::deque<int> d;
4505 d.push_back(2);
4506 d.push_back(1);
4507 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4508 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4509 }
4510
TEST(WhenSortedTest,WorksForVectorConstRefMatcher)4511 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4512 std::deque<int> d;
4513 d.push_back(2);
4514 d.push_back(1);
4515 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4516 EXPECT_THAT(d, WhenSorted(vector_match));
4517 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4518 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4519 }
4520
4521 // Deliberately bare pseudo-container.
4522 // Offers only begin() and end() accessors, yielding InputIterator.
4523 template <typename T>
4524 class Streamlike {
4525 private:
4526 class ConstIter;
4527 public:
4528 typedef ConstIter const_iterator;
4529 typedef T value_type;
4530
4531 template <typename InIter>
Streamlike(InIter first,InIter last)4532 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4533
begin() const4534 const_iterator begin() const {
4535 return const_iterator(this, remainder_.begin());
4536 }
end() const4537 const_iterator end() const {
4538 return const_iterator(this, remainder_.end());
4539 }
4540
4541 private:
4542 class ConstIter : public std::iterator<std::input_iterator_tag,
4543 value_type,
4544 ptrdiff_t,
4545 const value_type*,
4546 const value_type&> {
4547 public:
ConstIter(const Streamlike * s,typename std::list<value_type>::iterator pos)4548 ConstIter(const Streamlike* s,
4549 typename std::list<value_type>::iterator pos)
4550 : s_(s), pos_(pos) {}
4551
operator *() const4552 const value_type& operator*() const { return *pos_; }
operator ->() const4553 const value_type* operator->() const { return &*pos_; }
operator ++()4554 ConstIter& operator++() {
4555 s_->remainder_.erase(pos_++);
4556 return *this;
4557 }
4558
4559 // *iter++ is required to work (see std::istreambuf_iterator).
4560 // (void)iter++ is also required to work.
4561 class PostIncrProxy {
4562 public:
PostIncrProxy(const value_type & value)4563 explicit PostIncrProxy(const value_type& value) : value_(value) {}
operator *() const4564 value_type operator*() const { return value_; }
4565 private:
4566 value_type value_;
4567 };
operator ++(int)4568 PostIncrProxy operator++(int) {
4569 PostIncrProxy proxy(**this);
4570 ++(*this);
4571 return proxy;
4572 }
4573
operator ==(const ConstIter & a,const ConstIter & b)4574 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4575 return a.s_ == b.s_ && a.pos_ == b.pos_;
4576 }
operator !=(const ConstIter & a,const ConstIter & b)4577 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4578 return !(a == b);
4579 }
4580
4581 private:
4582 const Streamlike* s_;
4583 typename std::list<value_type>::iterator pos_;
4584 };
4585
operator <<(std::ostream & os,const Streamlike & s)4586 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4587 os << "[";
4588 typedef typename std::list<value_type>::const_iterator Iter;
4589 const char* sep = "";
4590 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4591 os << sep << *it;
4592 sep = ",";
4593 }
4594 os << "]";
4595 return os;
4596 }
4597
4598 mutable std::list<value_type> remainder_; // modified by iteration
4599 };
4600
TEST(StreamlikeTest,Iteration)4601 TEST(StreamlikeTest, Iteration) {
4602 const int a[5] = {2, 1, 4, 5, 3};
4603 Streamlike<int> s(a, a + 5);
4604 Streamlike<int>::const_iterator it = s.begin();
4605 const int* ip = a;
4606 while (it != s.end()) {
4607 SCOPED_TRACE(ip - a);
4608 EXPECT_EQ(*ip++, *it++);
4609 }
4610 }
4611
4612 #if GTEST_HAS_STD_FORWARD_LIST_
TEST(BeginEndDistanceIsTest,WorksWithForwardList)4613 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4614 std::forward_list<int> container;
4615 EXPECT_THAT(container, BeginEndDistanceIs(0));
4616 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4617 container.push_front(0);
4618 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4619 EXPECT_THAT(container, BeginEndDistanceIs(1));
4620 container.push_front(0);
4621 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4622 EXPECT_THAT(container, BeginEndDistanceIs(2));
4623 }
4624 #endif // GTEST_HAS_STD_FORWARD_LIST_
4625
TEST(BeginEndDistanceIsTest,WorksWithNonStdList)4626 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4627 const int a[5] = {1, 2, 3, 4, 5};
4628 Streamlike<int> s(a, a + 5);
4629 EXPECT_THAT(s, BeginEndDistanceIs(5));
4630 }
4631
TEST(BeginEndDistanceIsTest,CanDescribeSelf)4632 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4633 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4634 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4635 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4636 DescribeNegation(m));
4637 }
4638
TEST(BeginEndDistanceIsTest,ExplainsResult)4639 TEST(BeginEndDistanceIsTest, ExplainsResult) {
4640 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4641 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4642 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4643 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4644 vector<int> container;
4645 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4646 Explain(m1, container));
4647 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4648 Explain(m2, container));
4649 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4650 Explain(m3, container));
4651 EXPECT_EQ(
4652 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4653 "less than 1",
4654 Explain(m4, container));
4655 container.push_back(0);
4656 container.push_back(0);
4657 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4658 Explain(m1, container));
4659 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4660 Explain(m2, container));
4661 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4662 Explain(m3, container));
4663 EXPECT_EQ(
4664 "whose distance between begin() and end() 2 matches, which is 1 more "
4665 "than 1",
4666 Explain(m4, container));
4667 }
4668
TEST(WhenSortedTest,WorksForStreamlike)4669 TEST(WhenSortedTest, WorksForStreamlike) {
4670 // Streamlike 'container' provides only minimal iterator support.
4671 // Its iterators are tagged with input_iterator_tag.
4672 const int a[5] = {2, 1, 4, 5, 3};
4673 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4674 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4675 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4676 }
4677
TEST(WhenSortedTest,WorksForVectorConstRefMatcherOnStreamlike)4678 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
4679 const int a[] = {2, 1, 4, 5, 3};
4680 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4681 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4682 EXPECT_THAT(s, WhenSorted(vector_match));
4683 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4684 }
4685
4686 // Tests using ElementsAre() and ElementsAreArray() with stream-like
4687 // "containers".
4688
TEST(ElemensAreStreamTest,WorksForStreamlike)4689 TEST(ElemensAreStreamTest, WorksForStreamlike) {
4690 const int a[5] = {1, 2, 3, 4, 5};
4691 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4692 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4693 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4694 }
4695
TEST(ElemensAreArrayStreamTest,WorksForStreamlike)4696 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4697 const int a[5] = {1, 2, 3, 4, 5};
4698 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4699
4700 vector<int> expected;
4701 expected.push_back(1);
4702 expected.push_back(2);
4703 expected.push_back(3);
4704 expected.push_back(4);
4705 expected.push_back(5);
4706 EXPECT_THAT(s, ElementsAreArray(expected));
4707
4708 expected[3] = 0;
4709 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4710 }
4711
TEST(ElementsAreTest,WorksWithUncopyable)4712 TEST(ElementsAreTest, WorksWithUncopyable) {
4713 Uncopyable objs[2];
4714 objs[0].set_value(-3);
4715 objs[1].set_value(1);
4716 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4717 }
4718
TEST(ElementsAreTest,TakesStlContainer)4719 TEST(ElementsAreTest, TakesStlContainer) {
4720 const int actual[] = {3, 1, 2};
4721
4722 ::std::list<int> expected;
4723 expected.push_back(3);
4724 expected.push_back(1);
4725 expected.push_back(2);
4726 EXPECT_THAT(actual, ElementsAreArray(expected));
4727
4728 expected.push_back(4);
4729 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4730 }
4731
4732 // Tests for UnorderedElementsAreArray()
4733
TEST(UnorderedElementsAreArrayTest,SucceedsWhenExpected)4734 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4735 const int a[] = {0, 1, 2, 3, 4};
4736 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4737 do {
4738 StringMatchResultListener listener;
4739 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4740 s, &listener)) << listener.str();
4741 } while (std::next_permutation(s.begin(), s.end()));
4742 }
4743
TEST(UnorderedElementsAreArrayTest,VectorBool)4744 TEST(UnorderedElementsAreArrayTest, VectorBool) {
4745 const bool a[] = {0, 1, 0, 1, 1};
4746 const bool b[] = {1, 0, 1, 1, 0};
4747 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4748 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
4749 StringMatchResultListener listener;
4750 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4751 actual, &listener)) << listener.str();
4752 }
4753
TEST(UnorderedElementsAreArrayTest,WorksForStreamlike)4754 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4755 // Streamlike 'container' provides only minimal iterator support.
4756 // Its iterators are tagged with input_iterator_tag, and it has no
4757 // size() or empty() methods.
4758 const int a[5] = {2, 1, 4, 5, 3};
4759 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4760
4761 ::std::vector<int> expected;
4762 expected.push_back(1);
4763 expected.push_back(2);
4764 expected.push_back(3);
4765 expected.push_back(4);
4766 expected.push_back(5);
4767 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4768
4769 expected.push_back(6);
4770 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4771 }
4772
TEST(UnorderedElementsAreArrayTest,TakesStlContainer)4773 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4774 const int actual[] = {3, 1, 2};
4775
4776 ::std::list<int> expected;
4777 expected.push_back(1);
4778 expected.push_back(2);
4779 expected.push_back(3);
4780 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4781
4782 expected.push_back(4);
4783 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4784 }
4785
4786 #if GTEST_HAS_STD_INITIALIZER_LIST_
4787
TEST(UnorderedElementsAreArrayTest,TakesInitializerList)4788 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4789 const int a[5] = {2, 1, 4, 5, 3};
4790 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4791 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
4792 }
4793
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfCStrings)4794 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4795 const std::string a[5] = {"a", "b", "c", "d", "e"};
4796 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4797 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
4798 }
4799
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)4800 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4801 const int a[5] = {2, 1, 4, 5, 3};
4802 EXPECT_THAT(a, UnorderedElementsAreArray(
4803 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
4804 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4805 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
4806 }
4807
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)4808 TEST(UnorderedElementsAreArrayTest,
4809 TakesInitializerListOfDifferentTypedMatchers) {
4810 const int a[5] = {2, 1, 4, 5, 3};
4811 // The compiler cannot infer the type of the initializer list if its
4812 // elements have different types. We must explicitly specify the
4813 // unified element type in this case.
4814 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4815 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
4816 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4817 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
4818 }
4819
4820 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4821
4822 class UnorderedElementsAreTest : public testing::Test {
4823 protected:
4824 typedef std::vector<int> IntVec;
4825 };
4826
TEST_F(UnorderedElementsAreTest,WorksWithUncopyable)4827 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4828 Uncopyable objs[2];
4829 objs[0].set_value(-3);
4830 objs[1].set_value(1);
4831 EXPECT_THAT(objs,
4832 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4833 }
4834
TEST_F(UnorderedElementsAreTest,SucceedsWhenExpected)4835 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4836 const int a[] = {1, 2, 3};
4837 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4838 do {
4839 StringMatchResultListener listener;
4840 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4841 s, &listener)) << listener.str();
4842 } while (std::next_permutation(s.begin(), s.end()));
4843 }
4844
TEST_F(UnorderedElementsAreTest,FailsWhenAnElementMatchesNoMatcher)4845 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4846 const int a[] = {1, 2, 3};
4847 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4848 std::vector<Matcher<int> > mv;
4849 mv.push_back(1);
4850 mv.push_back(2);
4851 mv.push_back(2);
4852 // The element with value '3' matches nothing: fail fast.
4853 StringMatchResultListener listener;
4854 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4855 s, &listener)) << listener.str();
4856 }
4857
TEST_F(UnorderedElementsAreTest,WorksForStreamlike)4858 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4859 // Streamlike 'container' provides only minimal iterator support.
4860 // Its iterators are tagged with input_iterator_tag, and it has no
4861 // size() or empty() methods.
4862 const int a[5] = {2, 1, 4, 5, 3};
4863 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4864
4865 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4866 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4867 }
4868
4869 // One naive implementation of the matcher runs in O(N!) time, which is too
4870 // slow for many real-world inputs. This test shows that our matcher can match
4871 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4872 // iterations and obviously effectively incomputable.
4873 // [ RUN ] UnorderedElementsAreTest.Performance
4874 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
TEST_F(UnorderedElementsAreTest,Performance)4875 TEST_F(UnorderedElementsAreTest, Performance) {
4876 std::vector<int> s;
4877 std::vector<Matcher<int> > mv;
4878 for (int i = 0; i < 100; ++i) {
4879 s.push_back(i);
4880 mv.push_back(_);
4881 }
4882 mv[50] = Eq(0);
4883 StringMatchResultListener listener;
4884 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4885 s, &listener)) << listener.str();
4886 }
4887
4888 // Another variant of 'Performance' with similar expectations.
4889 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4890 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
TEST_F(UnorderedElementsAreTest,PerformanceHalfStrict)4891 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4892 std::vector<int> s;
4893 std::vector<Matcher<int> > mv;
4894 for (int i = 0; i < 100; ++i) {
4895 s.push_back(i);
4896 if (i & 1) {
4897 mv.push_back(_);
4898 } else {
4899 mv.push_back(i);
4900 }
4901 }
4902 StringMatchResultListener listener;
4903 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4904 s, &listener)) << listener.str();
4905 }
4906
TEST_F(UnorderedElementsAreTest,FailMessageCountWrong)4907 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4908 std::vector<int> v;
4909 v.push_back(4);
4910 StringMatchResultListener listener;
4911 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4912 v, &listener)) << listener.str();
4913 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4914 }
4915
TEST_F(UnorderedElementsAreTest,FailMessageCountWrongZero)4916 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4917 std::vector<int> v;
4918 StringMatchResultListener listener;
4919 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4920 v, &listener)) << listener.str();
4921 EXPECT_THAT(listener.str(), Eq(""));
4922 }
4923
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatchers)4924 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4925 std::vector<int> v;
4926 v.push_back(1);
4927 v.push_back(1);
4928 StringMatchResultListener listener;
4929 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4930 v, &listener)) << listener.str();
4931 EXPECT_THAT(
4932 listener.str(),
4933 Eq("where the following matchers don't match any elements:\n"
4934 "matcher #1: is equal to 2"));
4935 }
4936
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedElements)4937 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4938 std::vector<int> v;
4939 v.push_back(1);
4940 v.push_back(2);
4941 StringMatchResultListener listener;
4942 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4943 v, &listener)) << listener.str();
4944 EXPECT_THAT(
4945 listener.str(),
4946 Eq("where the following elements don't match any matchers:\n"
4947 "element #1: 2"));
4948 }
4949
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatcherAndElement)4950 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4951 std::vector<int> v;
4952 v.push_back(2);
4953 v.push_back(3);
4954 StringMatchResultListener listener;
4955 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4956 v, &listener)) << listener.str();
4957 EXPECT_THAT(
4958 listener.str(),
4959 Eq("where"
4960 " the following matchers don't match any elements:\n"
4961 "matcher #0: is equal to 1\n"
4962 "and"
4963 " where"
4964 " the following elements don't match any matchers:\n"
4965 "element #1: 3"));
4966 }
4967
4968 // Test helper for formatting element, matcher index pairs in expectations.
EMString(int element,int matcher)4969 static std::string EMString(int element, int matcher) {
4970 stringstream ss;
4971 ss << "(element #" << element << ", matcher #" << matcher << ")";
4972 return ss.str();
4973 }
4974
TEST_F(UnorderedElementsAreTest,FailMessageImperfectMatchOnly)4975 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4976 // A situation where all elements and matchers have a match
4977 // associated with them, but the max matching is not perfect.
4978 std::vector<std::string> v;
4979 v.push_back("a");
4980 v.push_back("b");
4981 v.push_back("c");
4982 StringMatchResultListener listener;
4983 EXPECT_FALSE(ExplainMatchResult(
4984 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4985 << listener.str();
4986
4987 std::string prefix =
4988 "where no permutation of the elements can satisfy all matchers, "
4989 "and the closest match is 2 of 3 matchers with the "
4990 "pairings:\n";
4991
4992 // We have to be a bit loose here, because there are 4 valid max matches.
4993 EXPECT_THAT(
4994 listener.str(),
4995 AnyOf(prefix + "{\n " + EMString(0, 0) +
4996 ",\n " + EMString(1, 2) + "\n}",
4997 prefix + "{\n " + EMString(0, 1) +
4998 ",\n " + EMString(1, 2) + "\n}",
4999 prefix + "{\n " + EMString(0, 0) +
5000 ",\n " + EMString(2, 2) + "\n}",
5001 prefix + "{\n " + EMString(0, 1) +
5002 ",\n " + EMString(2, 2) + "\n}"));
5003 }
5004
TEST_F(UnorderedElementsAreTest,Describe)5005 TEST_F(UnorderedElementsAreTest, Describe) {
5006 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5007 Eq("is empty"));
5008 EXPECT_THAT(
5009 Describe<IntVec>(UnorderedElementsAre(345)),
5010 Eq("has 1 element and that element is equal to 345"));
5011 EXPECT_THAT(
5012 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5013 Eq("has 3 elements and there exists some permutation "
5014 "of elements such that:\n"
5015 " - element #0 is equal to 111, and\n"
5016 " - element #1 is equal to 222, and\n"
5017 " - element #2 is equal to 333"));
5018 }
5019
TEST_F(UnorderedElementsAreTest,DescribeNegation)5020 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5021 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5022 Eq("isn't empty"));
5023 EXPECT_THAT(
5024 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5025 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5026 EXPECT_THAT(
5027 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5028 Eq("doesn't have 3 elements, or there exists no permutation "
5029 "of elements such that:\n"
5030 " - element #0 is equal to 123, and\n"
5031 " - element #1 is equal to 234, and\n"
5032 " - element #2 is equal to 345"));
5033 }
5034
5035 namespace {
5036
5037 // Used as a check on the more complex max flow method used in the
5038 // real testing::internal::FindMaxBipartiteMatching. This method is
5039 // compatible but runs in worst-case factorial time, so we only
5040 // use it in testing for small problem sizes.
5041 template <typename Graph>
5042 class BacktrackingMaxBPMState {
5043 public:
5044 // Does not take ownership of 'g'.
BacktrackingMaxBPMState(const Graph * g)5045 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5046
Compute()5047 ElementMatcherPairs Compute() {
5048 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5049 return best_so_far_;
5050 }
5051 lhs_used_.assign(graph_->LhsSize(), kUnused);
5052 rhs_used_.assign(graph_->RhsSize(), kUnused);
5053 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5054 matches_.clear();
5055 RecurseInto(irhs);
5056 if (best_so_far_.size() == graph_->RhsSize())
5057 break;
5058 }
5059 return best_so_far_;
5060 }
5061
5062 private:
5063 static const size_t kUnused = static_cast<size_t>(-1);
5064
PushMatch(size_t lhs,size_t rhs)5065 void PushMatch(size_t lhs, size_t rhs) {
5066 matches_.push_back(ElementMatcherPair(lhs, rhs));
5067 lhs_used_[lhs] = rhs;
5068 rhs_used_[rhs] = lhs;
5069 if (matches_.size() > best_so_far_.size()) {
5070 best_so_far_ = matches_;
5071 }
5072 }
5073
PopMatch()5074 void PopMatch() {
5075 const ElementMatcherPair& back = matches_.back();
5076 lhs_used_[back.first] = kUnused;
5077 rhs_used_[back.second] = kUnused;
5078 matches_.pop_back();
5079 }
5080
RecurseInto(size_t irhs)5081 bool RecurseInto(size_t irhs) {
5082 if (rhs_used_[irhs] != kUnused) {
5083 return true;
5084 }
5085 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5086 if (lhs_used_[ilhs] != kUnused) {
5087 continue;
5088 }
5089 if (!graph_->HasEdge(ilhs, irhs)) {
5090 continue;
5091 }
5092 PushMatch(ilhs, irhs);
5093 if (best_so_far_.size() == graph_->RhsSize()) {
5094 return false;
5095 }
5096 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5097 if (!RecurseInto(mi)) return false;
5098 }
5099 PopMatch();
5100 }
5101 return true;
5102 }
5103
5104 const Graph* graph_; // not owned
5105 std::vector<size_t> lhs_used_;
5106 std::vector<size_t> rhs_used_;
5107 ElementMatcherPairs matches_;
5108 ElementMatcherPairs best_so_far_;
5109 };
5110
5111 template <typename Graph>
5112 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5113
5114 } // namespace
5115
5116 // Implement a simple backtracking algorithm to determine if it is possible
5117 // to find one element per matcher, without reusing elements.
5118 template <typename Graph>
5119 ElementMatcherPairs
FindBacktrackingMaxBPM(const Graph & g)5120 FindBacktrackingMaxBPM(const Graph& g) {
5121 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5122 }
5123
5124 class BacktrackingBPMTest : public ::testing::Test { };
5125
5126 // Tests the MaxBipartiteMatching algorithm with square matrices.
5127 // The single int param is the # of nodes on each of the left and right sides.
5128 class BipartiteTest : public ::testing::TestWithParam<int> { };
5129
5130 // Verify all match graphs up to some moderate number of edges.
TEST_P(BipartiteTest,Exhaustive)5131 TEST_P(BipartiteTest, Exhaustive) {
5132 int nodes = GetParam();
5133 MatchMatrix graph(nodes, nodes);
5134 do {
5135 ElementMatcherPairs matches =
5136 internal::FindMaxBipartiteMatching(graph);
5137 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5138 << "graph: " << graph.DebugString();
5139 // Check that all elements of matches are in the graph.
5140 // Check that elements of first and second are unique.
5141 std::vector<bool> seen_element(graph.LhsSize());
5142 std::vector<bool> seen_matcher(graph.RhsSize());
5143 SCOPED_TRACE(PrintToString(matches));
5144 for (size_t i = 0; i < matches.size(); ++i) {
5145 size_t ilhs = matches[i].first;
5146 size_t irhs = matches[i].second;
5147 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5148 EXPECT_FALSE(seen_element[ilhs]);
5149 EXPECT_FALSE(seen_matcher[irhs]);
5150 seen_element[ilhs] = true;
5151 seen_matcher[irhs] = true;
5152 }
5153 } while (graph.NextGraph());
5154 }
5155
5156 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5157 ::testing::Range(0, 5));
5158
5159 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
5160 class BipartiteNonSquareTest
5161 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5162 };
5163
TEST_F(BipartiteNonSquareTest,SimpleBacktracking)5164 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5165 // .......
5166 // 0:-----\ :
5167 // 1:---\ | :
5168 // 2:---\ | :
5169 // 3:-\ | | :
5170 // :.......:
5171 // 0 1 2
5172 MatchMatrix g(4, 3);
5173 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
5174 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
5175 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5176 }
5177 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5178 ElementsAre(Pair(3, 0),
5179 Pair(AnyOf(1, 2), 1),
5180 Pair(0, 2))) << g.DebugString();
5181 }
5182
5183 // Verify a few nonsquare matrices.
TEST_P(BipartiteNonSquareTest,Exhaustive)5184 TEST_P(BipartiteNonSquareTest, Exhaustive) {
5185 size_t nlhs = GetParam().first;
5186 size_t nrhs = GetParam().second;
5187 MatchMatrix graph(nlhs, nrhs);
5188 do {
5189 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5190 internal::FindMaxBipartiteMatching(graph).size())
5191 << "graph: " << graph.DebugString()
5192 << "\nbacktracking: "
5193 << PrintToString(FindBacktrackingMaxBPM(graph))
5194 << "\nmax flow: "
5195 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5196 } while (graph.NextGraph());
5197 }
5198
5199 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5200 testing::Values(
5201 std::make_pair(1, 2),
5202 std::make_pair(2, 1),
5203 std::make_pair(3, 2),
5204 std::make_pair(2, 3),
5205 std::make_pair(4, 1),
5206 std::make_pair(1, 4),
5207 std::make_pair(4, 3),
5208 std::make_pair(3, 4)));
5209
5210 class BipartiteRandomTest
5211 : public ::testing::TestWithParam<std::pair<int, int> > {
5212 };
5213
5214 // Verifies a large sample of larger graphs.
TEST_P(BipartiteRandomTest,LargerNets)5215 TEST_P(BipartiteRandomTest, LargerNets) {
5216 int nodes = GetParam().first;
5217 int iters = GetParam().second;
5218 MatchMatrix graph(nodes, nodes);
5219
5220 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5221 if (seed == 0) {
5222 seed = static_cast<testing::internal::Int32>(time(NULL));
5223 }
5224
5225 for (; iters > 0; --iters, ++seed) {
5226 srand(static_cast<int>(seed));
5227 graph.Randomize();
5228 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5229 internal::FindMaxBipartiteMatching(graph).size())
5230 << " graph: " << graph.DebugString()
5231 << "\nTo reproduce the failure, rerun the test with the flag"
5232 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5233 }
5234 }
5235
5236 // Test argument is a std::pair<int, int> representing (nodes, iters).
5237 INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5238 testing::Values(
5239 std::make_pair(5, 10000),
5240 std::make_pair(6, 5000),
5241 std::make_pair(7, 2000),
5242 std::make_pair(8, 500),
5243 std::make_pair(9, 100)));
5244
5245 // Tests IsReadableTypeName().
5246
TEST(IsReadableTypeNameTest,ReturnsTrueForShortNames)5247 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5248 EXPECT_TRUE(IsReadableTypeName("int"));
5249 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5250 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5251 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5252 }
5253
TEST(IsReadableTypeNameTest,ReturnsTrueForLongNonTemplateNonFunctionNames)5254 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5255 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5256 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5257 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5258 }
5259
TEST(IsReadableTypeNameTest,ReturnsFalseForLongTemplateNames)5260 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5261 EXPECT_FALSE(
5262 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5263 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5264 }
5265
TEST(IsReadableTypeNameTest,ReturnsFalseForLongFunctionTypeNames)5266 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5267 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5268 }
5269
5270 // Tests FormatMatcherDescription().
5271
TEST(FormatMatcherDescriptionTest,WorksForEmptyDescription)5272 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5273 EXPECT_EQ("is even",
5274 FormatMatcherDescription(false, "IsEven", Strings()));
5275 EXPECT_EQ("not (is even)",
5276 FormatMatcherDescription(true, "IsEven", Strings()));
5277
5278 const char* params[] = {"5"};
5279 EXPECT_EQ("equals 5",
5280 FormatMatcherDescription(false, "Equals",
5281 Strings(params, params + 1)));
5282
5283 const char* params2[] = {"5", "8"};
5284 EXPECT_EQ("is in range (5, 8)",
5285 FormatMatcherDescription(false, "IsInRange",
5286 Strings(params2, params2 + 2)));
5287 }
5288
5289 // Tests PolymorphicMatcher::mutable_impl().
TEST(PolymorphicMatcherTest,CanAccessMutableImpl)5290 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5291 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5292 DivisibleByImpl& impl = m.mutable_impl();
5293 EXPECT_EQ(42, impl.divider());
5294
5295 impl.set_divider(0);
5296 EXPECT_EQ(0, m.mutable_impl().divider());
5297 }
5298
5299 // Tests PolymorphicMatcher::impl().
TEST(PolymorphicMatcherTest,CanAccessImpl)5300 TEST(PolymorphicMatcherTest, CanAccessImpl) {
5301 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5302 const DivisibleByImpl& impl = m.impl();
5303 EXPECT_EQ(42, impl.divider());
5304 }
5305
TEST(MatcherTupleTest,ExplainsMatchFailure)5306 TEST(MatcherTupleTest, ExplainsMatchFailure) {
5307 stringstream ss1;
5308 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5309 make_tuple('a', 10), &ss1);
5310 EXPECT_EQ("", ss1.str()); // Successful match.
5311
5312 stringstream ss2;
5313 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5314 make_tuple(2, 'b'), &ss2);
5315 EXPECT_EQ(" Expected arg #0: is > 5\n"
5316 " Actual: 2, which is 3 less than 5\n"
5317 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5318 " Actual: 'b' (98, 0x62)\n",
5319 ss2.str()); // Failed match where both arguments need explanation.
5320
5321 stringstream ss3;
5322 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5323 make_tuple(2, 'a'), &ss3);
5324 EXPECT_EQ(" Expected arg #0: is > 5\n"
5325 " Actual: 2, which is 3 less than 5\n",
5326 ss3.str()); // Failed match where only one argument needs
5327 // explanation.
5328 }
5329
5330 // Tests Each().
5331
TEST(EachTest,ExplainsMatchResultCorrectly)5332 TEST(EachTest, ExplainsMatchResultCorrectly) {
5333 set<int> a; // empty
5334
5335 Matcher<set<int> > m = Each(2);
5336 EXPECT_EQ("", Explain(m, a));
5337
5338 Matcher<const int(&)[1]> n = Each(1); // NOLINT
5339
5340 const int b[1] = {1};
5341 EXPECT_EQ("", Explain(n, b));
5342
5343 n = Each(3);
5344 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5345
5346 a.insert(1);
5347 a.insert(2);
5348 a.insert(3);
5349 m = Each(GreaterThan(0));
5350 EXPECT_EQ("", Explain(m, a));
5351
5352 m = Each(GreaterThan(10));
5353 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5354 Explain(m, a));
5355 }
5356
TEST(EachTest,DescribesItselfCorrectly)5357 TEST(EachTest, DescribesItselfCorrectly) {
5358 Matcher<vector<int> > m = Each(1);
5359 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5360
5361 Matcher<vector<int> > m2 = Not(m);
5362 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5363 }
5364
TEST(EachTest,MatchesVectorWhenAllElementsMatch)5365 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5366 vector<int> some_vector;
5367 EXPECT_THAT(some_vector, Each(1));
5368 some_vector.push_back(3);
5369 EXPECT_THAT(some_vector, Not(Each(1)));
5370 EXPECT_THAT(some_vector, Each(3));
5371 some_vector.push_back(1);
5372 some_vector.push_back(2);
5373 EXPECT_THAT(some_vector, Not(Each(3)));
5374 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5375
5376 vector<std::string> another_vector;
5377 another_vector.push_back("fee");
5378 EXPECT_THAT(another_vector, Each(std::string("fee")));
5379 another_vector.push_back("fie");
5380 another_vector.push_back("foe");
5381 another_vector.push_back("fum");
5382 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
5383 }
5384
TEST(EachTest,MatchesMapWhenAllElementsMatch)5385 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5386 map<const char*, int> my_map;
5387 const char* bar = "a string";
5388 my_map[bar] = 2;
5389 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5390
5391 map<std::string, int> another_map;
5392 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
5393 another_map["fee"] = 1;
5394 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
5395 another_map["fie"] = 2;
5396 another_map["foe"] = 3;
5397 another_map["fum"] = 4;
5398 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
5399 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
5400 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5401 }
5402
TEST(EachTest,AcceptsMatcher)5403 TEST(EachTest, AcceptsMatcher) {
5404 const int a[] = {1, 2, 3};
5405 EXPECT_THAT(a, Each(Gt(0)));
5406 EXPECT_THAT(a, Not(Each(Gt(1))));
5407 }
5408
TEST(EachTest,WorksForNativeArrayAsTuple)5409 TEST(EachTest, WorksForNativeArrayAsTuple) {
5410 const int a[] = {1, 2};
5411 const int* const pointer = a;
5412 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5413 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5414 }
5415
5416 // For testing Pointwise().
5417 class IsHalfOfMatcher {
5418 public:
5419 template <typename T1, typename T2>
MatchAndExplain(const tuple<T1,T2> & a_pair,MatchResultListener * listener) const5420 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5421 MatchResultListener* listener) const {
5422 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5423 *listener << "where the second is " << get<1>(a_pair);
5424 return true;
5425 } else {
5426 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5427 return false;
5428 }
5429 }
5430
DescribeTo(ostream * os) const5431 void DescribeTo(ostream* os) const {
5432 *os << "are a pair where the first is half of the second";
5433 }
5434
DescribeNegationTo(ostream * os) const5435 void DescribeNegationTo(ostream* os) const {
5436 *os << "are a pair where the first isn't half of the second";
5437 }
5438 };
5439
IsHalfOf()5440 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5441 return MakePolymorphicMatcher(IsHalfOfMatcher());
5442 }
5443
TEST(PointwiseTest,DescribesSelf)5444 TEST(PointwiseTest, DescribesSelf) {
5445 vector<int> rhs;
5446 rhs.push_back(1);
5447 rhs.push_back(2);
5448 rhs.push_back(3);
5449 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5450 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5451 "in { 1, 2, 3 } are a pair where the first is half of the second",
5452 Describe(m));
5453 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5454 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5455 "where the first isn't half of the second",
5456 DescribeNegation(m));
5457 }
5458
TEST(PointwiseTest,MakesCopyOfRhs)5459 TEST(PointwiseTest, MakesCopyOfRhs) {
5460 list<signed char> rhs;
5461 rhs.push_back(2);
5462 rhs.push_back(4);
5463
5464 int lhs[] = {1, 2};
5465 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5466 EXPECT_THAT(lhs, m);
5467
5468 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5469 rhs.push_back(6);
5470 EXPECT_THAT(lhs, m);
5471 }
5472
TEST(PointwiseTest,WorksForLhsNativeArray)5473 TEST(PointwiseTest, WorksForLhsNativeArray) {
5474 const int lhs[] = {1, 2, 3};
5475 vector<int> rhs;
5476 rhs.push_back(2);
5477 rhs.push_back(4);
5478 rhs.push_back(6);
5479 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5480 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5481 }
5482
TEST(PointwiseTest,WorksForRhsNativeArray)5483 TEST(PointwiseTest, WorksForRhsNativeArray) {
5484 const int rhs[] = {1, 2, 3};
5485 vector<int> lhs;
5486 lhs.push_back(2);
5487 lhs.push_back(4);
5488 lhs.push_back(6);
5489 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5490 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5491 }
5492
5493 #if GTEST_HAS_STD_INITIALIZER_LIST_
5494
TEST(PointwiseTest,WorksForRhsInitializerList)5495 TEST(PointwiseTest, WorksForRhsInitializerList) {
5496 const vector<int> lhs{2, 4, 6};
5497 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5498 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5499 }
5500
5501 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
5502
TEST(PointwiseTest,RejectsWrongSize)5503 TEST(PointwiseTest, RejectsWrongSize) {
5504 const double lhs[2] = {1, 2};
5505 const int rhs[1] = {0};
5506 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5507 EXPECT_EQ("which contains 2 values",
5508 Explain(Pointwise(Gt(), rhs), lhs));
5509
5510 const int rhs2[3] = {0, 1, 2};
5511 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5512 }
5513
TEST(PointwiseTest,RejectsWrongContent)5514 TEST(PointwiseTest, RejectsWrongContent) {
5515 const double lhs[3] = {1, 2, 3};
5516 const int rhs[3] = {2, 6, 4};
5517 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5518 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5519 "where the second/2 is 3",
5520 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5521 }
5522
TEST(PointwiseTest,AcceptsCorrectContent)5523 TEST(PointwiseTest, AcceptsCorrectContent) {
5524 const double lhs[3] = {1, 2, 3};
5525 const int rhs[3] = {2, 4, 6};
5526 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5527 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5528 }
5529
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)5530 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5531 const double lhs[3] = {1, 2, 3};
5532 const int rhs[3] = {2, 4, 6};
5533 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5534 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5535 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5536
5537 // This type works as a tuple<const double&, const int&> can be
5538 // implicitly cast to tuple<double, int>.
5539 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5540 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5541 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5542 }
5543
TEST(UnorderedPointwiseTest,DescribesSelf)5544 TEST(UnorderedPointwiseTest, DescribesSelf) {
5545 vector<int> rhs;
5546 rhs.push_back(1);
5547 rhs.push_back(2);
5548 rhs.push_back(3);
5549 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5550 EXPECT_EQ(
5551 "has 3 elements and there exists some permutation of elements such "
5552 "that:\n"
5553 " - element #0 and 1 are a pair where the first is half of the second, "
5554 "and\n"
5555 " - element #1 and 2 are a pair where the first is half of the second, "
5556 "and\n"
5557 " - element #2 and 3 are a pair where the first is half of the second",
5558 Describe(m));
5559 EXPECT_EQ(
5560 "doesn't have 3 elements, or there exists no permutation of elements "
5561 "such that:\n"
5562 " - element #0 and 1 are a pair where the first is half of the second, "
5563 "and\n"
5564 " - element #1 and 2 are a pair where the first is half of the second, "
5565 "and\n"
5566 " - element #2 and 3 are a pair where the first is half of the second",
5567 DescribeNegation(m));
5568 }
5569
TEST(UnorderedPointwiseTest,MakesCopyOfRhs)5570 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5571 list<signed char> rhs;
5572 rhs.push_back(2);
5573 rhs.push_back(4);
5574
5575 int lhs[] = {2, 1};
5576 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5577 EXPECT_THAT(lhs, m);
5578
5579 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5580 rhs.push_back(6);
5581 EXPECT_THAT(lhs, m);
5582 }
5583
TEST(UnorderedPointwiseTest,WorksForLhsNativeArray)5584 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5585 const int lhs[] = {1, 2, 3};
5586 vector<int> rhs;
5587 rhs.push_back(4);
5588 rhs.push_back(6);
5589 rhs.push_back(2);
5590 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5591 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5592 }
5593
TEST(UnorderedPointwiseTest,WorksForRhsNativeArray)5594 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5595 const int rhs[] = {1, 2, 3};
5596 vector<int> lhs;
5597 lhs.push_back(4);
5598 lhs.push_back(2);
5599 lhs.push_back(6);
5600 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5601 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5602 }
5603
5604 #if GTEST_HAS_STD_INITIALIZER_LIST_
5605
TEST(UnorderedPointwiseTest,WorksForRhsInitializerList)5606 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5607 const vector<int> lhs{2, 4, 6};
5608 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5609 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5610 }
5611
5612 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
5613
TEST(UnorderedPointwiseTest,RejectsWrongSize)5614 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5615 const double lhs[2] = {1, 2};
5616 const int rhs[1] = {0};
5617 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5618 EXPECT_EQ("which has 2 elements",
5619 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5620
5621 const int rhs2[3] = {0, 1, 2};
5622 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5623 }
5624
TEST(UnorderedPointwiseTest,RejectsWrongContent)5625 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5626 const double lhs[3] = {1, 2, 3};
5627 const int rhs[3] = {2, 6, 6};
5628 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5629 EXPECT_EQ("where the following elements don't match any matchers:\n"
5630 "element #1: 2",
5631 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5632 }
5633
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInSameOrder)5634 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5635 const double lhs[3] = {1, 2, 3};
5636 const int rhs[3] = {2, 4, 6};
5637 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5638 }
5639
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInDifferentOrder)5640 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5641 const double lhs[3] = {1, 2, 3};
5642 const int rhs[3] = {6, 4, 2};
5643 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5644 }
5645
TEST(UnorderedPointwiseTest,AllowsMonomorphicInnerMatcher)5646 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5647 const double lhs[3] = {1, 2, 3};
5648 const int rhs[3] = {4, 6, 2};
5649 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5650 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5651
5652 // This type works as a tuple<const double&, const int&> can be
5653 // implicitly cast to tuple<double, int>.
5654 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5655 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5656 }
5657
5658 class SampleVariantIntString {
5659 public:
SampleVariantIntString(int i)5660 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
SampleVariantIntString(const std::string & s)5661 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
5662
5663 template <typename T>
holds_alternative(const SampleVariantIntString & value)5664 friend bool holds_alternative(const SampleVariantIntString& value) {
5665 return value.has_int_ == internal::IsSame<T, int>::value;
5666 }
5667
5668 template <typename T>
get(const SampleVariantIntString & value)5669 friend const T& get(const SampleVariantIntString& value) {
5670 return value.get_impl(static_cast<T*>(NULL));
5671 }
5672
5673 private:
get_impl(int *) const5674 const int& get_impl(int*) const { return i_; }
get_impl(std::string *) const5675 const std::string& get_impl(std::string*) const { return s_; }
5676
5677 int i_;
5678 std::string s_;
5679 bool has_int_;
5680 };
5681
TEST(VariantTest,DescribesSelf)5682 TEST(VariantTest, DescribesSelf) {
5683 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
5684 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
5685 "'.*' and the value is equal to 1"));
5686 }
5687
TEST(VariantTest,ExplainsSelf)5688 TEST(VariantTest, ExplainsSelf) {
5689 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
5690 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
5691 ContainsRegex("whose value 1"));
5692 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
5693 HasSubstr("whose value is not of type '"));
5694 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
5695 "whose value 2 doesn't match");
5696 }
5697
TEST(VariantTest,FullMatch)5698 TEST(VariantTest, FullMatch) {
5699 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
5700 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
5701
5702 m = VariantWith<std::string>(Eq("1"));
5703 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
5704 }
5705
TEST(VariantTest,TypeDoesNotMatch)5706 TEST(VariantTest, TypeDoesNotMatch) {
5707 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
5708 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
5709
5710 m = VariantWith<std::string>(Eq("1"));
5711 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
5712 }
5713
TEST(VariantTest,InnerDoesNotMatch)5714 TEST(VariantTest, InnerDoesNotMatch) {
5715 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
5716 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
5717
5718 m = VariantWith<std::string>(Eq("1"));
5719 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
5720 }
5721
5722 } // namespace gmock_matchers_test
5723 } // namespace testing
5724