1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file tests some commonly used argument matchers.
35 #include "gmock/gmock-matchers.h"
36 #include "gmock/gmock-more-matchers.h"
53 #include "gmock/gmock.h"
54 #include "gtest/gtest.h"
55 #include "gtest/gtest-spi.h"
57 #if GTEST_HAS_STD_FORWARD_LIST_
58 # include <forward_list> // NOLINT
62 # include <type_traits>
66 namespace gmock_matchers_test {
78 using std::stringstream;
81 using testing::AllArgs;
86 using testing::ContainsRegex;
87 using testing::DoubleEq;
88 using testing::DoubleNear;
89 using testing::EndsWith;
91 using testing::ExplainMatchResult;
93 using testing::FloatEq;
94 using testing::FloatNear;
97 using testing::HasSubstr;
98 using testing::IsEmpty;
99 using testing::IsNull;
103 using testing::MakeMatcher;
104 using testing::MakePolymorphicMatcher;
105 using testing::MatchResultListener;
106 using testing::Matcher;
107 using testing::MatcherCast;
108 using testing::MatcherInterface;
109 using testing::Matches;
110 using testing::MatchesRegex;
111 using testing::NanSensitiveDoubleEq;
112 using testing::NanSensitiveDoubleNear;
113 using testing::NanSensitiveFloatEq;
114 using testing::NanSensitiveFloatNear;
117 using testing::NotNull;
119 using testing::Pointee;
120 using testing::Pointwise;
121 using testing::PolymorphicMatcher;
122 using testing::Property;
124 using testing::ResultOf;
125 using testing::SizeIs;
126 using testing::StartsWith;
127 using testing::StrCaseEq;
128 using testing::StrCaseNe;
129 using testing::StrEq;
130 using testing::StrNe;
131 using testing::StringMatchResultListener;
132 using testing::Truly;
133 using testing::TypedEq;
134 using testing::UnorderedPointwise;
135 using testing::Value;
136 using testing::WhenSorted;
137 using testing::WhenSortedBy;
140 using testing::internal::DummyMatchResultListener;
141 using testing::internal::ElementMatcherPair;
142 using testing::internal::ElementMatcherPairs;
143 using testing::internal::ExplainMatchFailureTupleTo;
144 using testing::internal::FloatingEqMatcher;
145 using testing::internal::FormatMatcherDescription;
146 using testing::internal::IsReadableTypeName;
147 using testing::internal::linked_ptr;
148 using testing::internal::MatchMatrix;
149 using testing::internal::RE;
150 using testing::internal::scoped_ptr;
151 using testing::internal::StreamMatchResultListener;
152 using testing::internal::Strings;
153 using testing::internal::linked_ptr;
154 using testing::internal::scoped_ptr;
155 using testing::internal::string;
156 using testing::make_tuple;
157 using testing::tuple;
159 // For testing ExplainMatchResultTo().
160 class GreaterThanMatcher : public MatcherInterface<int> {
162 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
164 virtual void DescribeTo(ostream* os) const {
165 *os << "is > " << rhs_;
168 virtual bool MatchAndExplain(int lhs,
169 MatchResultListener* listener) const {
170 const int diff = lhs - rhs_;
172 *listener << "which is " << diff << " more than " << rhs_;
173 } else if (diff == 0) {
174 *listener << "which is the same as " << rhs_;
176 *listener << "which is " << -diff << " less than " << rhs_;
186 Matcher<int> GreaterThan(int n) {
187 return MakeMatcher(new GreaterThanMatcher(n));
190 std::string OfType(const std::string& type_name) {
192 return " (of type " + type_name + ")";
198 // Returns the description of the given matcher.
199 template <typename T>
200 std::string Describe(const Matcher<T>& m) {
201 return DescribeMatcher<T>(m);
204 // Returns the description of the negation of the given matcher.
205 template <typename T>
206 std::string DescribeNegation(const Matcher<T>& m) {
207 return DescribeMatcher<T>(m, true);
210 // Returns the reason why x matches, or doesn't match, m.
211 template <typename MatcherType, typename Value>
212 std::string Explain(const MatcherType& m, const Value& x) {
213 StringMatchResultListener listener;
214 ExplainMatchResult(m, x, &listener);
215 return listener.str();
218 TEST(MonotonicMatcherTest, IsPrintable) {
220 ss << GreaterThan(5);
221 EXPECT_EQ("is > 5", ss.str());
224 TEST(MatchResultListenerTest, StreamingWorks) {
225 StringMatchResultListener listener;
226 listener << "hi" << 5;
227 EXPECT_EQ("hi5", listener.str());
230 EXPECT_EQ("", listener.str());
233 EXPECT_EQ("42", listener.str());
235 // Streaming shouldn't crash when the underlying ostream is NULL.
236 DummyMatchResultListener dummy;
240 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
241 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
242 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
244 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
247 TEST(MatchResultListenerTest, IsInterestedWorks) {
248 EXPECT_TRUE(StringMatchResultListener().IsInterested());
249 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
251 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
252 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
255 // Makes sure that the MatcherInterface<T> interface doesn't
257 class EvenMatcherImpl : public MatcherInterface<int> {
259 virtual bool MatchAndExplain(int x,
260 MatchResultListener* /* listener */) const {
264 virtual void DescribeTo(ostream* os) const {
265 *os << "is an even number";
268 // We deliberately don't define DescribeNegationTo() and
269 // ExplainMatchResultTo() here, to make sure the definition of these
270 // two methods is optional.
273 // Makes sure that the MatcherInterface API doesn't change.
274 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
278 // Tests implementing a monomorphic matcher using MatchAndExplain().
280 class NewEvenMatcherImpl : public MatcherInterface<int> {
282 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
289 *listener->stream() << " == " << (x % 2);
294 virtual void DescribeTo(ostream* os) const {
295 *os << "is an even number";
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));
307 // Tests default-constructing a matcher.
308 TEST(MatcherTest, CanBeDefaultConstructed) {
312 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
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));
320 // Tests that value can be used in place of Eq(value).
321 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
323 EXPECT_TRUE(m1.Matches(5));
324 EXPECT_FALSE(m1.Matches(6));
327 // Tests that NULL can be used in place of Eq(NULL).
328 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
329 Matcher<int*> m1 = NULL;
330 EXPECT_TRUE(m1.Matches(NULL));
332 EXPECT_FALSE(m1.Matches(&n));
335 // Tests that matchers can be constructed from a variable that is not properly
336 // defined. This should be illegal, but many users rely on this accidentally.
338 virtual ~Undefined() = 0;
339 static const int kInt = 1;
342 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
343 Matcher<int> m1 = Undefined::kInt;
344 EXPECT_TRUE(m1.Matches(1));
345 EXPECT_FALSE(m1.Matches(2));
348 // Test that a matcher parameterized with an abstract class compiles.
349 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
351 // Tests that matchers are copyable.
352 TEST(MatcherTest, IsCopyable) {
353 // Tests the copy constructor.
354 Matcher<bool> m1 = Eq(false);
355 EXPECT_TRUE(m1.Matches(false));
356 EXPECT_FALSE(m1.Matches(true));
358 // Tests the assignment operator.
360 EXPECT_TRUE(m1.Matches(true));
361 EXPECT_FALSE(m1.Matches(false));
364 // Tests that Matcher<T>::DescribeTo() calls
365 // MatcherInterface<T>::DescribeTo().
366 TEST(MatcherTest, CanDescribeItself) {
367 EXPECT_EQ("is an even number",
368 Describe(Matcher<int>(new EvenMatcherImpl)));
371 // Tests Matcher<T>::MatchAndExplain().
372 TEST(MatcherTest, MatchAndExplain) {
373 Matcher<int> m = GreaterThan(0);
374 StringMatchResultListener listener1;
375 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
376 EXPECT_EQ("which is 42 more than 0", listener1.str());
378 StringMatchResultListener listener2;
379 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
380 EXPECT_EQ("which is 9 less than 0", listener2.str());
383 // Tests that a C-string literal can be implicitly converted to a
384 // Matcher<std::string> or Matcher<const std::string&>.
385 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
386 Matcher<std::string> m1 = "hi";
387 EXPECT_TRUE(m1.Matches("hi"));
388 EXPECT_FALSE(m1.Matches("hello"));
390 Matcher<const std::string&> m2 = "hi";
391 EXPECT_TRUE(m2.Matches("hi"));
392 EXPECT_FALSE(m2.Matches("hello"));
395 // Tests that a string object can be implicitly converted to a
396 // Matcher<std::string> or Matcher<const std::string&>.
397 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
398 Matcher<std::string> m1 = std::string("hi");
399 EXPECT_TRUE(m1.Matches("hi"));
400 EXPECT_FALSE(m1.Matches("hello"));
402 Matcher<const std::string&> m2 = std::string("hi");
403 EXPECT_TRUE(m2.Matches("hi"));
404 EXPECT_FALSE(m2.Matches("hello"));
407 #if GTEST_HAS_GLOBAL_STRING
408 // Tests that a ::string object can be implicitly converted to a
409 // Matcher<std::string> or Matcher<const std::string&>.
410 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
411 Matcher<std::string> m1 = ::string("hi");
412 EXPECT_TRUE(m1.Matches("hi"));
413 EXPECT_FALSE(m1.Matches("hello"));
415 Matcher<const std::string&> m2 = ::string("hi");
416 EXPECT_TRUE(m2.Matches("hi"));
417 EXPECT_FALSE(m2.Matches("hello"));
419 #endif // GTEST_HAS_GLOBAL_STRING
421 #if GTEST_HAS_GLOBAL_STRING
422 // Tests that a C-string literal can be implicitly converted to a
423 // Matcher<::string> or Matcher<const ::string&>.
424 TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
425 Matcher< ::string> m1 = "hi";
426 EXPECT_TRUE(m1.Matches("hi"));
427 EXPECT_FALSE(m1.Matches("hello"));
429 Matcher<const ::string&> m2 = "hi";
430 EXPECT_TRUE(m2.Matches("hi"));
431 EXPECT_FALSE(m2.Matches("hello"));
434 // Tests that a std::string object can be implicitly converted to a
435 // Matcher<::string> or Matcher<const ::string&>.
436 TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) {
437 Matcher< ::string> m1 = std::string("hi");
438 EXPECT_TRUE(m1.Matches("hi"));
439 EXPECT_FALSE(m1.Matches("hello"));
441 Matcher<const ::string&> m2 = std::string("hi");
442 EXPECT_TRUE(m2.Matches("hi"));
443 EXPECT_FALSE(m2.Matches("hello"));
446 // Tests that a ::string object can be implicitly converted to a
447 // Matcher<::string> or Matcher<const ::string&>.
448 TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
449 Matcher< ::string> m1 = ::string("hi");
450 EXPECT_TRUE(m1.Matches("hi"));
451 EXPECT_FALSE(m1.Matches("hello"));
453 Matcher<const ::string&> m2 = ::string("hi");
454 EXPECT_TRUE(m2.Matches("hi"));
455 EXPECT_FALSE(m2.Matches("hello"));
457 #endif // GTEST_HAS_GLOBAL_STRING
460 // Tests that a C-string literal can be implicitly converted to a
461 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
462 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
463 Matcher<absl::string_view> m1 = "cats";
464 EXPECT_TRUE(m1.Matches("cats"));
465 EXPECT_FALSE(m1.Matches("dogs"));
467 Matcher<const absl::string_view&> m2 = "cats";
468 EXPECT_TRUE(m2.Matches("cats"));
469 EXPECT_FALSE(m2.Matches("dogs"));
472 // Tests that a std::string object can be implicitly converted to a
473 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
474 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
475 Matcher<absl::string_view> m1 = std::string("cats");
476 EXPECT_TRUE(m1.Matches("cats"));
477 EXPECT_FALSE(m1.Matches("dogs"));
479 Matcher<const absl::string_view&> m2 = std::string("cats");
480 EXPECT_TRUE(m2.Matches("cats"));
481 EXPECT_FALSE(m2.Matches("dogs"));
484 #if GTEST_HAS_GLOBAL_STRING
485 // Tests that a ::string object can be implicitly converted to a
486 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
487 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
488 Matcher<absl::string_view> m1 = ::string("cats");
489 EXPECT_TRUE(m1.Matches("cats"));
490 EXPECT_FALSE(m1.Matches("dogs"));
492 Matcher<const absl::string_view&> m2 = ::string("cats");
493 EXPECT_TRUE(m2.Matches("cats"));
494 EXPECT_FALSE(m2.Matches("dogs"));
496 #endif // GTEST_HAS_GLOBAL_STRING
498 // Tests that a absl::string_view object can be implicitly converted to a
499 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
500 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
501 Matcher<absl::string_view> m1 = absl::string_view("cats");
502 EXPECT_TRUE(m1.Matches("cats"));
503 EXPECT_FALSE(m1.Matches("dogs"));
505 Matcher<const absl::string_view&> m2 = absl::string_view("cats");
506 EXPECT_TRUE(m2.Matches("cats"));
507 EXPECT_FALSE(m2.Matches("dogs"));
509 #endif // GTEST_HAS_ABSL
511 // Tests that MakeMatcher() constructs a Matcher<T> from a
512 // MatcherInterface* without requiring the user to explicitly
514 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
515 const MatcherInterface<int>* dummy_impl = NULL;
516 Matcher<int> m = MakeMatcher(dummy_impl);
519 // Tests that MakePolymorphicMatcher() can construct a polymorphic
520 // matcher from its implementation using the old API.
522 class ReferencesBarOrIsZeroImpl {
524 template <typename T>
525 bool MatchAndExplain(const T& x,
526 MatchResultListener* /* listener */) const {
528 return p == &g_bar || x == 0;
531 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
533 void DescribeNegationTo(ostream* os) const {
534 *os << "doesn't reference g_bar and is not zero";
538 // This function verifies that MakePolymorphicMatcher() returns a
539 // PolymorphicMatcher<T> where T is the argument's type.
540 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
541 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
544 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
545 // Using a polymorphic matcher to match a reference type.
546 Matcher<const int&> m1 = ReferencesBarOrIsZero();
547 EXPECT_TRUE(m1.Matches(0));
548 // Verifies that the identity of a by-reference argument is preserved.
549 EXPECT_TRUE(m1.Matches(g_bar));
550 EXPECT_FALSE(m1.Matches(1));
551 EXPECT_EQ("g_bar or zero", Describe(m1));
553 // Using a polymorphic matcher to match a value type.
554 Matcher<double> m2 = ReferencesBarOrIsZero();
555 EXPECT_TRUE(m2.Matches(0.0));
556 EXPECT_FALSE(m2.Matches(0.1));
557 EXPECT_EQ("g_bar or zero", Describe(m2));
560 // Tests implementing a polymorphic matcher using MatchAndExplain().
562 class PolymorphicIsEvenImpl {
564 void DescribeTo(ostream* os) const { *os << "is even"; }
566 void DescribeNegationTo(ostream* os) const {
570 template <typename T>
571 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
572 // Verifies that we can stream to the listener directly.
573 *listener << "% " << 2;
574 if (listener->stream() != NULL) {
575 // Verifies that we can stream to the listener's underlying stream
577 *listener->stream() << " == " << (x % 2);
583 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
584 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
587 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
588 // Using PolymorphicIsEven() as a Matcher<int>.
589 const Matcher<int> m1 = PolymorphicIsEven();
590 EXPECT_TRUE(m1.Matches(42));
591 EXPECT_FALSE(m1.Matches(43));
592 EXPECT_EQ("is even", Describe(m1));
594 const Matcher<int> not_m1 = Not(m1);
595 EXPECT_EQ("is odd", Describe(not_m1));
597 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
599 // Using PolymorphicIsEven() as a Matcher<char>.
600 const Matcher<char> m2 = PolymorphicIsEven();
601 EXPECT_TRUE(m2.Matches('\x42'));
602 EXPECT_FALSE(m2.Matches('\x43'));
603 EXPECT_EQ("is even", Describe(m2));
605 const Matcher<char> not_m2 = Not(m2);
606 EXPECT_EQ("is odd", Describe(not_m2));
608 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
611 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
612 TEST(MatcherCastTest, FromPolymorphicMatcher) {
613 Matcher<int> m = MatcherCast<int>(Eq(5));
614 EXPECT_TRUE(m.Matches(5));
615 EXPECT_FALSE(m.Matches(6));
618 // For testing casting matchers between compatible types.
621 // An int can be statically (although not implicitly) cast to a
623 explicit IntValue(int a_value) : value_(a_value) {}
625 int value() const { return value_; }
630 // For testing casting matchers between compatible types.
631 bool IsPositiveIntValue(const IntValue& foo) {
632 return foo.value() > 0;
635 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
636 // can be statically converted to U.
637 TEST(MatcherCastTest, FromCompatibleType) {
638 Matcher<double> m1 = Eq(2.0);
639 Matcher<int> m2 = MatcherCast<int>(m1);
640 EXPECT_TRUE(m2.Matches(2));
641 EXPECT_FALSE(m2.Matches(3));
643 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
644 Matcher<int> m4 = MatcherCast<int>(m3);
645 // In the following, the arguments 1 and 0 are statically converted
646 // to IntValue objects, and then tested by the IsPositiveIntValue()
648 EXPECT_TRUE(m4.Matches(1));
649 EXPECT_FALSE(m4.Matches(0));
652 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
653 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
654 Matcher<const int&> m1 = Eq(0);
655 Matcher<int> m2 = MatcherCast<int>(m1);
656 EXPECT_TRUE(m2.Matches(0));
657 EXPECT_FALSE(m2.Matches(1));
660 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
661 TEST(MatcherCastTest, FromReferenceToNonReference) {
662 Matcher<int&> m1 = Eq(0);
663 Matcher<int> m2 = MatcherCast<int>(m1);
664 EXPECT_TRUE(m2.Matches(0));
665 EXPECT_FALSE(m2.Matches(1));
668 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
669 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
670 Matcher<int> m1 = Eq(0);
671 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
672 EXPECT_TRUE(m2.Matches(0));
673 EXPECT_FALSE(m2.Matches(1));
676 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
677 TEST(MatcherCastTest, FromNonReferenceToReference) {
678 Matcher<int> m1 = Eq(0);
679 Matcher<int&> m2 = MatcherCast<int&>(m1);
681 EXPECT_TRUE(m2.Matches(n));
683 EXPECT_FALSE(m2.Matches(n));
686 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
687 TEST(MatcherCastTest, FromSameType) {
688 Matcher<int> m1 = Eq(0);
689 Matcher<int> m2 = MatcherCast<int>(m1);
690 EXPECT_TRUE(m2.Matches(0));
691 EXPECT_FALSE(m2.Matches(1));
694 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
695 // value type of the Matcher.
696 TEST(MatcherCastTest, FromAValue) {
697 Matcher<int> m = MatcherCast<int>(42);
698 EXPECT_TRUE(m.Matches(42));
699 EXPECT_FALSE(m.Matches(239));
702 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
703 // convertible to the value type of the Matcher.
704 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
705 const int kExpected = 'c';
706 Matcher<int> m = MatcherCast<int>('c');
707 EXPECT_TRUE(m.Matches(kExpected));
708 EXPECT_FALSE(m.Matches(kExpected + 1));
711 struct NonImplicitlyConstructibleTypeWithOperatorEq {
712 friend bool operator==(
713 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
717 friend bool operator==(
719 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
724 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
725 // implicitly convertible to the value type of the Matcher, but the value type
726 // of the matcher has operator==() overload accepting m.
727 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
728 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
729 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
730 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
732 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
733 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
734 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
736 // When updating the following lines please also change the comment to
737 // namespace convertible_from_any.
739 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
740 EXPECT_TRUE(m3.Matches(42));
741 EXPECT_FALSE(m3.Matches(239));
744 // ConvertibleFromAny does not work with MSVC. resulting in
745 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
746 // No constructor could take the source type, or constructor overload
747 // resolution was ambiguous
749 #if !defined _MSC_VER
751 // The below ConvertibleFromAny struct is implicitly constructible from anything
752 // and when in the same namespace can interact with other tests. In particular,
753 // if it is in the same namespace as other tests and one removes
754 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
755 // then the corresponding test still compiles (and it should not!) by implicitly
756 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
758 namespace convertible_from_any {
759 // Implicitly convertible from any type.
760 struct ConvertibleFromAny {
761 ConvertibleFromAny(int a_value) : value(a_value) {}
762 template <typename T>
763 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
764 ADD_FAILURE() << "Conversion constructor called";
769 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
770 return a.value == b.value;
773 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
774 return os << a.value;
777 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
778 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
779 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
780 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
783 TEST(MatcherCastTest, FromConvertibleFromAny) {
784 Matcher<ConvertibleFromAny> m =
785 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
786 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
787 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
789 } // namespace convertible_from_any
791 #endif // !defined _MSC_VER
793 struct IntReferenceWrapper {
794 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
798 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
799 return a.value == b.value;
802 TEST(MatcherCastTest, ValueIsNotCopied) {
804 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
805 // Verify that the matcher holds a reference to n, not to its temporary copy.
806 EXPECT_TRUE(m.Matches(n));
814 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
817 class Derived : public Base {
819 Derived() : Base() {}
823 class OtherDerived : public Base {};
825 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
826 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
827 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
828 EXPECT_TRUE(m2.Matches(' '));
829 EXPECT_FALSE(m2.Matches('\n'));
832 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
833 // T and U are arithmetic types and T can be losslessly converted to
835 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
836 Matcher<double> m1 = DoubleEq(1.0);
837 Matcher<float> m2 = SafeMatcherCast<float>(m1);
838 EXPECT_TRUE(m2.Matches(1.0f));
839 EXPECT_FALSE(m2.Matches(2.0f));
841 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
842 EXPECT_TRUE(m3.Matches('a'));
843 EXPECT_FALSE(m3.Matches('b'));
846 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
847 // are pointers or references to a derived and a base class, correspondingly.
848 TEST(SafeMatcherCastTest, FromBaseClass) {
850 Matcher<Base*> m1 = Eq(&d);
851 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
852 EXPECT_TRUE(m2.Matches(&d));
853 EXPECT_FALSE(m2.Matches(&d2));
855 Matcher<Base&> m3 = Ref(d);
856 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
857 EXPECT_TRUE(m4.Matches(d));
858 EXPECT_FALSE(m4.Matches(d2));
861 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
862 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
864 Matcher<const int&> m1 = Ref(n);
865 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
867 EXPECT_TRUE(m2.Matches(n));
868 EXPECT_FALSE(m2.Matches(n1));
871 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
872 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
873 Matcher<int> m1 = Eq(0);
874 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
875 EXPECT_TRUE(m2.Matches(0));
876 EXPECT_FALSE(m2.Matches(1));
879 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
880 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
881 Matcher<int> m1 = Eq(0);
882 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
884 EXPECT_TRUE(m2.Matches(n));
886 EXPECT_FALSE(m2.Matches(n));
889 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
890 TEST(SafeMatcherCastTest, FromSameType) {
891 Matcher<int> m1 = Eq(0);
892 Matcher<int> m2 = SafeMatcherCast<int>(m1);
893 EXPECT_TRUE(m2.Matches(0));
894 EXPECT_FALSE(m2.Matches(1));
897 #if !defined _MSC_VER
899 namespace convertible_from_any {
900 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
901 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
902 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
903 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
906 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
907 Matcher<ConvertibleFromAny> m =
908 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
909 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
910 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
912 } // namespace convertible_from_any
914 #endif // !defined _MSC_VER
916 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
918 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
919 // Verify that the matcher holds a reference to n, not to its temporary copy.
920 EXPECT_TRUE(m.Matches(n));
923 TEST(ExpectThat, TakesLiterals) {
925 EXPECT_THAT(1.0, 1.0);
926 EXPECT_THAT(std::string(), "");
929 TEST(ExpectThat, TakesFunctions) {
931 static void Func() {}
933 void (*func)() = Helper::Func;
934 EXPECT_THAT(func, Helper::Func);
935 EXPECT_THAT(func, &Helper::Func);
938 // Tests that A<T>() matches any value of type T.
939 TEST(ATest, MatchesAnyValue) {
940 // Tests a matcher for a value type.
941 Matcher<double> m1 = A<double>();
942 EXPECT_TRUE(m1.Matches(91.43));
943 EXPECT_TRUE(m1.Matches(-15.32));
945 // Tests a matcher for a reference type.
948 Matcher<int&> m2 = A<int&>();
949 EXPECT_TRUE(m2.Matches(a));
950 EXPECT_TRUE(m2.Matches(b));
953 TEST(ATest, WorksForDerivedClass) {
956 EXPECT_THAT(&base, A<Base*>());
957 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
958 EXPECT_THAT(&derived, A<Base*>());
959 EXPECT_THAT(&derived, A<Derived*>());
962 // Tests that A<T>() describes itself properly.
963 TEST(ATest, CanDescribeSelf) {
964 EXPECT_EQ("is anything", Describe(A<bool>()));
967 // Tests that An<T>() matches any value of type T.
968 TEST(AnTest, MatchesAnyValue) {
969 // Tests a matcher for a value type.
970 Matcher<int> m1 = An<int>();
971 EXPECT_TRUE(m1.Matches(9143));
972 EXPECT_TRUE(m1.Matches(-1532));
974 // Tests a matcher for a reference type.
977 Matcher<int&> m2 = An<int&>();
978 EXPECT_TRUE(m2.Matches(a));
979 EXPECT_TRUE(m2.Matches(b));
982 // Tests that An<T>() describes itself properly.
983 TEST(AnTest, CanDescribeSelf) {
984 EXPECT_EQ("is anything", Describe(An<int>()));
987 // Tests that _ can be used as a matcher for any type and matches any
988 // value of that type.
989 TEST(UnderscoreTest, MatchesAnyValue) {
990 // Uses _ as a matcher for a value type.
992 EXPECT_TRUE(m1.Matches(123));
993 EXPECT_TRUE(m1.Matches(-242));
995 // Uses _ as a matcher for a reference type.
998 Matcher<const bool&> m2 = _;
999 EXPECT_TRUE(m2.Matches(a));
1000 EXPECT_TRUE(m2.Matches(b));
1003 // Tests that _ describes itself properly.
1004 TEST(UnderscoreTest, CanDescribeSelf) {
1006 EXPECT_EQ("is anything", Describe(m));
1009 // Tests that Eq(x) matches any value equal to x.
1010 TEST(EqTest, MatchesEqualValue) {
1011 // 2 C-strings with same content but different addresses.
1012 const char a1[] = "hi";
1013 const char a2[] = "hi";
1015 Matcher<const char*> m1 = Eq(a1);
1016 EXPECT_TRUE(m1.Matches(a1));
1017 EXPECT_FALSE(m1.Matches(a2));
1020 // Tests that Eq(v) describes itself properly.
1024 Unprintable() : c_('a') {}
1026 bool operator==(const Unprintable& /* rhs */) const { return true; }
1031 TEST(EqTest, CanDescribeSelf) {
1032 Matcher<Unprintable> m = Eq(Unprintable());
1033 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
1036 // Tests that Eq(v) can be used to match any type that supports
1037 // comparing with type T, where T is v's type.
1038 TEST(EqTest, IsPolymorphic) {
1039 Matcher<int> m1 = Eq(1);
1040 EXPECT_TRUE(m1.Matches(1));
1041 EXPECT_FALSE(m1.Matches(2));
1043 Matcher<char> m2 = Eq(1);
1044 EXPECT_TRUE(m2.Matches('\1'));
1045 EXPECT_FALSE(m2.Matches('a'));
1048 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
1049 TEST(TypedEqTest, ChecksEqualityForGivenType) {
1050 Matcher<char> m1 = TypedEq<char>('a');
1051 EXPECT_TRUE(m1.Matches('a'));
1052 EXPECT_FALSE(m1.Matches('b'));
1054 Matcher<int> m2 = TypedEq<int>(6);
1055 EXPECT_TRUE(m2.Matches(6));
1056 EXPECT_FALSE(m2.Matches(7));
1059 // Tests that TypedEq(v) describes itself properly.
1060 TEST(TypedEqTest, CanDescribeSelf) {
1061 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
1064 // Tests that TypedEq<T>(v) has type Matcher<T>.
1066 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
1067 // is a "bare" type (i.e. not in the form of const U or U&). If v's
1068 // type is not T, the compiler will generate a message about
1069 // "undefined reference".
1070 template <typename T>
1072 static bool IsTypeOf(const T& /* v */) { return true; }
1074 template <typename T2>
1075 static void IsTypeOf(T2 v);
1078 TEST(TypedEqTest, HasSpecifiedType) {
1079 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
1080 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
1081 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
1084 // Tests that Ge(v) matches anything >= v.
1085 TEST(GeTest, ImplementsGreaterThanOrEqual) {
1086 Matcher<int> m1 = Ge(0);
1087 EXPECT_TRUE(m1.Matches(1));
1088 EXPECT_TRUE(m1.Matches(0));
1089 EXPECT_FALSE(m1.Matches(-1));
1092 // Tests that Ge(v) describes itself properly.
1093 TEST(GeTest, CanDescribeSelf) {
1094 Matcher<int> m = Ge(5);
1095 EXPECT_EQ("is >= 5", Describe(m));
1098 // Tests that Gt(v) matches anything > v.
1099 TEST(GtTest, ImplementsGreaterThan) {
1100 Matcher<double> m1 = Gt(0);
1101 EXPECT_TRUE(m1.Matches(1.0));
1102 EXPECT_FALSE(m1.Matches(0.0));
1103 EXPECT_FALSE(m1.Matches(-1.0));
1106 // Tests that Gt(v) describes itself properly.
1107 TEST(GtTest, CanDescribeSelf) {
1108 Matcher<int> m = Gt(5);
1109 EXPECT_EQ("is > 5", Describe(m));
1112 // Tests that Le(v) matches anything <= v.
1113 TEST(LeTest, ImplementsLessThanOrEqual) {
1114 Matcher<char> m1 = Le('b');
1115 EXPECT_TRUE(m1.Matches('a'));
1116 EXPECT_TRUE(m1.Matches('b'));
1117 EXPECT_FALSE(m1.Matches('c'));
1120 // Tests that Le(v) describes itself properly.
1121 TEST(LeTest, CanDescribeSelf) {
1122 Matcher<int> m = Le(5);
1123 EXPECT_EQ("is <= 5", Describe(m));
1126 // Tests that Lt(v) matches anything < v.
1127 TEST(LtTest, ImplementsLessThan) {
1128 Matcher<const std::string&> m1 = Lt("Hello");
1129 EXPECT_TRUE(m1.Matches("Abc"));
1130 EXPECT_FALSE(m1.Matches("Hello"));
1131 EXPECT_FALSE(m1.Matches("Hello, world!"));
1134 // Tests that Lt(v) describes itself properly.
1135 TEST(LtTest, CanDescribeSelf) {
1136 Matcher<int> m = Lt(5);
1137 EXPECT_EQ("is < 5", Describe(m));
1140 // Tests that Ne(v) matches anything != v.
1141 TEST(NeTest, ImplementsNotEqual) {
1142 Matcher<int> m1 = Ne(0);
1143 EXPECT_TRUE(m1.Matches(1));
1144 EXPECT_TRUE(m1.Matches(-1));
1145 EXPECT_FALSE(m1.Matches(0));
1148 // Tests that Ne(v) describes itself properly.
1149 TEST(NeTest, CanDescribeSelf) {
1150 Matcher<int> m = Ne(5);
1151 EXPECT_EQ("isn't equal to 5", Describe(m));
1154 // Tests that IsNull() matches any NULL pointer of any type.
1155 TEST(IsNullTest, MatchesNullPointer) {
1156 Matcher<int*> m1 = IsNull();
1159 EXPECT_TRUE(m1.Matches(p1));
1160 EXPECT_FALSE(m1.Matches(&n));
1162 Matcher<const char*> m2 = IsNull();
1163 const char* p2 = NULL;
1164 EXPECT_TRUE(m2.Matches(p2));
1165 EXPECT_FALSE(m2.Matches("hi"));
1167 #if !GTEST_OS_SYMBIAN
1168 // Nokia's Symbian compiler generates:
1169 // gmock-matchers.h: ambiguous access to overloaded function
1170 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1171 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1172 // MatcherInterface<void *> *)'
1173 // gmock-matchers.h: (point of instantiation: 'testing::
1174 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1175 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
1176 Matcher<void*> m3 = IsNull();
1178 EXPECT_TRUE(m3.Matches(p3));
1179 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1183 TEST(IsNullTest, LinkedPtr) {
1184 const Matcher<linked_ptr<int> > m = IsNull();
1185 const linked_ptr<int> null_p;
1186 const linked_ptr<int> non_null_p(new int);
1188 EXPECT_TRUE(m.Matches(null_p));
1189 EXPECT_FALSE(m.Matches(non_null_p));
1192 TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1193 const Matcher<const linked_ptr<double>&> m = IsNull();
1194 const linked_ptr<double> null_p;
1195 const linked_ptr<double> non_null_p(new double);
1197 EXPECT_TRUE(m.Matches(null_p));
1198 EXPECT_FALSE(m.Matches(non_null_p));
1201 #if GTEST_LANG_CXX11
1202 TEST(IsNullTest, StdFunction) {
1203 const Matcher<std::function<void()>> m = IsNull();
1205 EXPECT_TRUE(m.Matches(std::function<void()>()));
1206 EXPECT_FALSE(m.Matches([]{}));
1208 #endif // GTEST_LANG_CXX11
1210 // Tests that IsNull() describes itself properly.
1211 TEST(IsNullTest, CanDescribeSelf) {
1212 Matcher<int*> m = IsNull();
1213 EXPECT_EQ("is NULL", Describe(m));
1214 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1217 // Tests that NotNull() matches any non-NULL pointer of any type.
1218 TEST(NotNullTest, MatchesNonNullPointer) {
1219 Matcher<int*> m1 = NotNull();
1222 EXPECT_FALSE(m1.Matches(p1));
1223 EXPECT_TRUE(m1.Matches(&n));
1225 Matcher<const char*> m2 = NotNull();
1226 const char* p2 = NULL;
1227 EXPECT_FALSE(m2.Matches(p2));
1228 EXPECT_TRUE(m2.Matches("hi"));
1231 TEST(NotNullTest, LinkedPtr) {
1232 const Matcher<linked_ptr<int> > m = NotNull();
1233 const linked_ptr<int> null_p;
1234 const linked_ptr<int> non_null_p(new int);
1236 EXPECT_FALSE(m.Matches(null_p));
1237 EXPECT_TRUE(m.Matches(non_null_p));
1240 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1241 const Matcher<const linked_ptr<double>&> m = NotNull();
1242 const linked_ptr<double> null_p;
1243 const linked_ptr<double> non_null_p(new double);
1245 EXPECT_FALSE(m.Matches(null_p));
1246 EXPECT_TRUE(m.Matches(non_null_p));
1249 #if GTEST_LANG_CXX11
1250 TEST(NotNullTest, StdFunction) {
1251 const Matcher<std::function<void()>> m = NotNull();
1253 EXPECT_TRUE(m.Matches([]{}));
1254 EXPECT_FALSE(m.Matches(std::function<void()>()));
1256 #endif // GTEST_LANG_CXX11
1258 // Tests that NotNull() describes itself properly.
1259 TEST(NotNullTest, CanDescribeSelf) {
1260 Matcher<int*> m = NotNull();
1261 EXPECT_EQ("isn't NULL", Describe(m));
1264 // Tests that Ref(variable) matches an argument that references
1266 TEST(RefTest, MatchesSameVariable) {
1269 Matcher<int&> m = Ref(a);
1270 EXPECT_TRUE(m.Matches(a));
1271 EXPECT_FALSE(m.Matches(b));
1274 // Tests that Ref(variable) describes itself properly.
1275 TEST(RefTest, CanDescribeSelf) {
1277 Matcher<int&> m = Ref(n);
1279 ss << "references the variable @" << &n << " 5";
1280 EXPECT_EQ(ss.str(), Describe(m));
1283 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1285 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1288 Matcher<const int&> m = Ref(a);
1289 EXPECT_TRUE(m.Matches(a));
1290 EXPECT_FALSE(m.Matches(b));
1293 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1294 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1295 // of Ref(base), but not vice versa.
1297 TEST(RefTest, IsCovariant) {
1300 Matcher<const Base&> m1 = Ref(base);
1301 EXPECT_TRUE(m1.Matches(base));
1302 EXPECT_FALSE(m1.Matches(base2));
1303 EXPECT_FALSE(m1.Matches(derived));
1306 EXPECT_TRUE(m1.Matches(derived));
1307 EXPECT_FALSE(m1.Matches(base));
1308 EXPECT_FALSE(m1.Matches(base2));
1311 TEST(RefTest, ExplainsResult) {
1313 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1314 StartsWith("which is located @"));
1317 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1318 StartsWith("which is located @"));
1321 // Tests string comparison matchers.
1323 TEST(StrEqTest, MatchesEqualString) {
1324 Matcher<const char*> m = StrEq(std::string("Hello"));
1325 EXPECT_TRUE(m.Matches("Hello"));
1326 EXPECT_FALSE(m.Matches("hello"));
1327 EXPECT_FALSE(m.Matches(NULL));
1329 Matcher<const std::string&> m2 = StrEq("Hello");
1330 EXPECT_TRUE(m2.Matches("Hello"));
1331 EXPECT_FALSE(m2.Matches("Hi"));
1334 Matcher<const absl::string_view&> m3 = StrEq("Hello");
1335 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1336 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1337 EXPECT_FALSE(m3.Matches(absl::string_view()));
1338 #endif // GTEST_HAS_ABSL
1341 TEST(StrEqTest, CanDescribeSelf) {
1342 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1343 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1346 std::string str("01204500800");
1348 Matcher<std::string> m2 = StrEq(str);
1349 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1350 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1351 Matcher<std::string> m3 = StrEq(str);
1352 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1355 TEST(StrNeTest, MatchesUnequalString) {
1356 Matcher<const char*> m = StrNe("Hello");
1357 EXPECT_TRUE(m.Matches(""));
1358 EXPECT_TRUE(m.Matches(NULL));
1359 EXPECT_FALSE(m.Matches("Hello"));
1361 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1362 EXPECT_TRUE(m2.Matches("hello"));
1363 EXPECT_FALSE(m2.Matches("Hello"));
1366 Matcher<const absl::string_view> m3 = StrNe("Hello");
1367 EXPECT_TRUE(m3.Matches(absl::string_view("")));
1368 EXPECT_TRUE(m3.Matches(absl::string_view()));
1369 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1370 #endif // GTEST_HAS_ABSL
1373 TEST(StrNeTest, CanDescribeSelf) {
1374 Matcher<const char*> m = StrNe("Hi");
1375 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1378 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1379 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1380 EXPECT_TRUE(m.Matches("Hello"));
1381 EXPECT_TRUE(m.Matches("hello"));
1382 EXPECT_FALSE(m.Matches("Hi"));
1383 EXPECT_FALSE(m.Matches(NULL));
1385 Matcher<const std::string&> m2 = StrCaseEq("Hello");
1386 EXPECT_TRUE(m2.Matches("hello"));
1387 EXPECT_FALSE(m2.Matches("Hi"));
1390 Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
1391 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1392 EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
1393 EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
1394 EXPECT_FALSE(m3.Matches(absl::string_view()));
1395 #endif // GTEST_HAS_ABSL
1398 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1399 std::string str1("oabocdooeoo");
1400 std::string str2("OABOCDOOEOO");
1401 Matcher<const std::string&> m0 = StrCaseEq(str1);
1402 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1404 str1[3] = str2[3] = '\0';
1405 Matcher<const std::string&> m1 = StrCaseEq(str1);
1406 EXPECT_TRUE(m1.Matches(str2));
1408 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1409 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1410 Matcher<const std::string&> m2 = StrCaseEq(str1);
1411 str1[9] = str2[9] = '\0';
1412 EXPECT_FALSE(m2.Matches(str2));
1414 Matcher<const std::string&> m3 = StrCaseEq(str1);
1415 EXPECT_TRUE(m3.Matches(str2));
1417 EXPECT_FALSE(m3.Matches(str2 + "x"));
1418 str2.append(1, '\0');
1419 EXPECT_FALSE(m3.Matches(str2));
1420 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1423 TEST(StrCaseEqTest, CanDescribeSelf) {
1424 Matcher<std::string> m = StrCaseEq("Hi");
1425 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1428 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1429 Matcher<const char*> m = StrCaseNe("Hello");
1430 EXPECT_TRUE(m.Matches("Hi"));
1431 EXPECT_TRUE(m.Matches(NULL));
1432 EXPECT_FALSE(m.Matches("Hello"));
1433 EXPECT_FALSE(m.Matches("hello"));
1435 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1436 EXPECT_TRUE(m2.Matches(""));
1437 EXPECT_FALSE(m2.Matches("Hello"));
1440 Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
1441 EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
1442 EXPECT_TRUE(m3.Matches(absl::string_view()));
1443 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1444 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1445 #endif // GTEST_HAS_ABSL
1448 TEST(StrCaseNeTest, CanDescribeSelf) {
1449 Matcher<const char*> m = StrCaseNe("Hi");
1450 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1453 // Tests that HasSubstr() works for matching string-typed values.
1454 TEST(HasSubstrTest, WorksForStringClasses) {
1455 const Matcher<std::string> m1 = HasSubstr("foo");
1456 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1457 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1459 const Matcher<const std::string&> m2 = HasSubstr("foo");
1460 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1461 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1464 // Tests that HasSubstr() works for matching C-string-typed values.
1465 TEST(HasSubstrTest, WorksForCStrings) {
1466 const Matcher<char*> m1 = HasSubstr("foo");
1467 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1468 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1469 EXPECT_FALSE(m1.Matches(NULL));
1471 const Matcher<const char*> m2 = HasSubstr("foo");
1472 EXPECT_TRUE(m2.Matches("I love food."));
1473 EXPECT_FALSE(m2.Matches("tofo"));
1474 EXPECT_FALSE(m2.Matches(NULL));
1478 // Tests that HasSubstr() works for matching absl::string_view-typed values.
1479 TEST(HasSubstrTest, WorksForStringViewClasses) {
1480 const Matcher<absl::string_view> m1 = HasSubstr("foo");
1481 EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
1482 EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
1483 EXPECT_FALSE(m1.Matches(absl::string_view()));
1485 const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
1486 EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
1487 EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
1488 EXPECT_FALSE(m2.Matches(absl::string_view()));
1490 const Matcher<const absl::string_view&> m3 = HasSubstr("");
1491 EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
1492 EXPECT_FALSE(m3.Matches(absl::string_view()));
1494 #endif // GTEST_HAS_ABSL
1496 // Tests that HasSubstr(s) describes itself properly.
1497 TEST(HasSubstrTest, CanDescribeSelf) {
1498 Matcher<std::string> m = HasSubstr("foo\n\"");
1499 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1502 TEST(KeyTest, CanDescribeSelf) {
1503 Matcher<const pair<std::string, int>&> m = Key("foo");
1504 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1505 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1508 TEST(KeyTest, ExplainsResult) {
1509 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1510 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1511 Explain(m, make_pair(5, true)));
1512 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1513 Explain(m, make_pair(15, true)));
1516 TEST(KeyTest, MatchesCorrectly) {
1517 pair<int, std::string> p(25, "foo");
1518 EXPECT_THAT(p, Key(25));
1519 EXPECT_THAT(p, Not(Key(42)));
1520 EXPECT_THAT(p, Key(Ge(20)));
1521 EXPECT_THAT(p, Not(Key(Lt(25))));
1524 #if GTEST_LANG_CXX11
1528 struct PairWithGet {
1531 using first_type = int;
1532 using second_type = string;
1534 const int& GetImpl(Tag<0>) const { return member_1; }
1535 const string& GetImpl(Tag<1>) const { return member_2; }
1538 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1539 return value.GetImpl(Tag<I>());
1541 TEST(PairTest, MatchesPairWithGetCorrectly) {
1542 PairWithGet p{25, "foo"};
1543 EXPECT_THAT(p, Key(25));
1544 EXPECT_THAT(p, Not(Key(42)));
1545 EXPECT_THAT(p, Key(Ge(20)));
1546 EXPECT_THAT(p, Not(Key(Lt(25))));
1548 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1549 EXPECT_THAT(v, Contains(Key(29)));
1551 #endif // GTEST_LANG_CXX11
1553 TEST(KeyTest, SafelyCastsInnerMatcher) {
1554 Matcher<int> is_positive = Gt(0);
1555 Matcher<int> is_negative = Lt(0);
1556 pair<char, bool> p('a', true);
1557 EXPECT_THAT(p, Key(is_positive));
1558 EXPECT_THAT(p, Not(Key(is_negative)));
1561 TEST(KeyTest, InsideContainsUsingMap) {
1562 map<int, char> container;
1563 container.insert(make_pair(1, 'a'));
1564 container.insert(make_pair(2, 'b'));
1565 container.insert(make_pair(4, 'c'));
1566 EXPECT_THAT(container, Contains(Key(1)));
1567 EXPECT_THAT(container, Not(Contains(Key(3))));
1570 TEST(KeyTest, InsideContainsUsingMultimap) {
1571 multimap<int, char> container;
1572 container.insert(make_pair(1, 'a'));
1573 container.insert(make_pair(2, 'b'));
1574 container.insert(make_pair(4, 'c'));
1576 EXPECT_THAT(container, Not(Contains(Key(25))));
1577 container.insert(make_pair(25, 'd'));
1578 EXPECT_THAT(container, Contains(Key(25)));
1579 container.insert(make_pair(25, 'e'));
1580 EXPECT_THAT(container, Contains(Key(25)));
1582 EXPECT_THAT(container, Contains(Key(1)));
1583 EXPECT_THAT(container, Not(Contains(Key(3))));
1586 TEST(PairTest, Typing) {
1587 // Test verifies the following type conversions can be compiled.
1588 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1589 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1590 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1592 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1593 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1596 TEST(PairTest, CanDescribeSelf) {
1597 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1598 EXPECT_EQ("has a first field that is equal to \"foo\""
1599 ", and has a second field that is equal to 42",
1601 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1602 ", or has a second field that isn't equal to 42",
1603 DescribeNegation(m1));
1604 // Double and triple negation (1 or 2 times not and description of negation).
1605 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1606 EXPECT_EQ("has a first field that isn't equal to 13"
1607 ", and has a second field that is equal to 42",
1608 DescribeNegation(m2));
1611 TEST(PairTest, CanExplainMatchResultTo) {
1612 // If neither field matches, Pair() should explain about the first
1614 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1615 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1616 Explain(m, make_pair(-1, -2)));
1618 // If the first field matches but the second doesn't, Pair() should
1619 // explain about the second field.
1620 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1621 Explain(m, make_pair(1, -2)));
1623 // If the first field doesn't match but the second does, Pair()
1624 // should explain about the first field.
1625 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1626 Explain(m, make_pair(-1, 2)));
1628 // If both fields match, Pair() should explain about them both.
1629 EXPECT_EQ("whose both fields match, where the first field is a value "
1630 "which is 1 more than 0, and the second field is a value "
1631 "which is 2 more than 0",
1632 Explain(m, make_pair(1, 2)));
1634 // If only the first match has an explanation, only this explanation should
1636 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1637 EXPECT_EQ("whose both fields match, where the first field is a value "
1638 "which is 1 more than 0",
1639 Explain(explain_first, make_pair(1, 0)));
1641 // If only the second match has an explanation, only this explanation should
1643 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1644 EXPECT_EQ("whose both fields match, where the second field is a value "
1645 "which is 1 more than 0",
1646 Explain(explain_second, make_pair(0, 1)));
1649 TEST(PairTest, MatchesCorrectly) {
1650 pair<int, std::string> p(25, "foo");
1652 // Both fields match.
1653 EXPECT_THAT(p, Pair(25, "foo"));
1654 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1656 // 'first' doesnt' match, but 'second' matches.
1657 EXPECT_THAT(p, Not(Pair(42, "foo")));
1658 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1660 // 'first' matches, but 'second' doesn't match.
1661 EXPECT_THAT(p, Not(Pair(25, "bar")));
1662 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1664 // Neither field matches.
1665 EXPECT_THAT(p, Not(Pair(13, "bar")));
1666 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1669 TEST(PairTest, SafelyCastsInnerMatchers) {
1670 Matcher<int> is_positive = Gt(0);
1671 Matcher<int> is_negative = Lt(0);
1672 pair<char, bool> p('a', true);
1673 EXPECT_THAT(p, Pair(is_positive, _));
1674 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1675 EXPECT_THAT(p, Pair(_, is_positive));
1676 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1679 TEST(PairTest, InsideContainsUsingMap) {
1680 map<int, char> container;
1681 container.insert(make_pair(1, 'a'));
1682 container.insert(make_pair(2, 'b'));
1683 container.insert(make_pair(4, 'c'));
1684 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1685 EXPECT_THAT(container, Contains(Pair(1, _)));
1686 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1687 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1690 #if GTEST_LANG_CXX11
1691 TEST(PairTest, UseGetInsteadOfMembers) {
1692 PairWithGet pair{7, "ABC"};
1693 EXPECT_THAT(pair, Pair(7, "ABC"));
1694 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1695 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1697 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1698 EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not(""))));
1700 #endif // GTEST_LANG_CXX11
1702 // Tests StartsWith(s).
1704 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1705 const Matcher<const char*> m1 = StartsWith(std::string(""));
1706 EXPECT_TRUE(m1.Matches("Hi"));
1707 EXPECT_TRUE(m1.Matches(""));
1708 EXPECT_FALSE(m1.Matches(NULL));
1710 const Matcher<const std::string&> m2 = StartsWith("Hi");
1711 EXPECT_TRUE(m2.Matches("Hi"));
1712 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1713 EXPECT_TRUE(m2.Matches("High"));
1714 EXPECT_FALSE(m2.Matches("H"));
1715 EXPECT_FALSE(m2.Matches(" Hi"));
1718 TEST(StartsWithTest, CanDescribeSelf) {
1719 Matcher<const std::string> m = StartsWith("Hi");
1720 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1723 // Tests EndsWith(s).
1725 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1726 const Matcher<const char*> m1 = EndsWith("");
1727 EXPECT_TRUE(m1.Matches("Hi"));
1728 EXPECT_TRUE(m1.Matches(""));
1729 EXPECT_FALSE(m1.Matches(NULL));
1731 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1732 EXPECT_TRUE(m2.Matches("Hi"));
1733 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1734 EXPECT_TRUE(m2.Matches("Super Hi"));
1735 EXPECT_FALSE(m2.Matches("i"));
1736 EXPECT_FALSE(m2.Matches("Hi "));
1738 #if GTEST_HAS_GLOBAL_STRING
1739 const Matcher<const ::string&> m3 = EndsWith(::string("Hi"));
1740 EXPECT_TRUE(m3.Matches("Hi"));
1741 EXPECT_TRUE(m3.Matches("Wow Hi Hi"));
1742 EXPECT_TRUE(m3.Matches("Super Hi"));
1743 EXPECT_FALSE(m3.Matches("i"));
1744 EXPECT_FALSE(m3.Matches("Hi "));
1745 #endif // GTEST_HAS_GLOBAL_STRING
1748 const Matcher<const absl::string_view&> m4 = EndsWith("");
1749 EXPECT_TRUE(m4.Matches("Hi"));
1750 EXPECT_TRUE(m4.Matches(""));
1751 // Default-constructed absl::string_view should not match anything, in order
1752 // to distinguish it from an empty string.
1753 EXPECT_FALSE(m4.Matches(absl::string_view()));
1754 #endif // GTEST_HAS_ABSL
1757 TEST(EndsWithTest, CanDescribeSelf) {
1758 Matcher<const std::string> m = EndsWith("Hi");
1759 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1762 // Tests MatchesRegex().
1764 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1765 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1766 EXPECT_TRUE(m1.Matches("az"));
1767 EXPECT_TRUE(m1.Matches("abcz"));
1768 EXPECT_FALSE(m1.Matches(NULL));
1770 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1771 EXPECT_TRUE(m2.Matches("azbz"));
1772 EXPECT_FALSE(m2.Matches("az1"));
1773 EXPECT_FALSE(m2.Matches("1az"));
1776 const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
1777 EXPECT_TRUE(m3.Matches(absl::string_view("az")));
1778 EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
1779 EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
1780 // Default-constructed absl::string_view should not match anything, in order
1781 // to distinguish it from an empty string.
1782 EXPECT_FALSE(m3.Matches(absl::string_view()));
1783 const Matcher<const absl::string_view&> m4 = MatchesRegex("");
1784 EXPECT_FALSE(m4.Matches(absl::string_view()));
1785 #endif // GTEST_HAS_ABSL
1788 TEST(MatchesRegexTest, CanDescribeSelf) {
1789 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1790 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1792 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1793 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1796 Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
1797 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1798 #endif // GTEST_HAS_ABSL
1801 // Tests ContainsRegex().
1803 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1804 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1805 EXPECT_TRUE(m1.Matches("az"));
1806 EXPECT_TRUE(m1.Matches("0abcz1"));
1807 EXPECT_FALSE(m1.Matches(NULL));
1809 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1810 EXPECT_TRUE(m2.Matches("azbz"));
1811 EXPECT_TRUE(m2.Matches("az1"));
1812 EXPECT_FALSE(m2.Matches("1a"));
1815 const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
1816 EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
1817 EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
1818 EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
1819 // Default-constructed absl::string_view should not match anything, in order
1820 // to distinguish it from an empty string.
1821 EXPECT_FALSE(m3.Matches(absl::string_view()));
1822 const Matcher<const absl::string_view&> m4 = ContainsRegex("");
1823 EXPECT_FALSE(m4.Matches(absl::string_view()));
1824 #endif // GTEST_HAS_ABSL
1827 TEST(ContainsRegexTest, CanDescribeSelf) {
1828 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1829 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1831 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1832 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1835 Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
1836 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1837 #endif // GTEST_HAS_ABSL
1840 // Tests for wide strings.
1841 #if GTEST_HAS_STD_WSTRING
1842 TEST(StdWideStrEqTest, MatchesEqual) {
1843 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1844 EXPECT_TRUE(m.Matches(L"Hello"));
1845 EXPECT_FALSE(m.Matches(L"hello"));
1846 EXPECT_FALSE(m.Matches(NULL));
1848 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1849 EXPECT_TRUE(m2.Matches(L"Hello"));
1850 EXPECT_FALSE(m2.Matches(L"Hi"));
1852 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1853 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1854 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1856 ::std::wstring str(L"01204500800");
1858 Matcher<const ::std::wstring&> m4 = StrEq(str);
1859 EXPECT_TRUE(m4.Matches(str));
1860 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1861 Matcher<const ::std::wstring&> m5 = StrEq(str);
1862 EXPECT_TRUE(m5.Matches(str));
1865 TEST(StdWideStrEqTest, CanDescribeSelf) {
1866 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1867 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1870 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1871 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1874 ::std::wstring str(L"01204500800");
1876 Matcher<const ::std::wstring&> m4 = StrEq(str);
1877 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1878 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1879 Matcher<const ::std::wstring&> m5 = StrEq(str);
1880 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1883 TEST(StdWideStrNeTest, MatchesUnequalString) {
1884 Matcher<const wchar_t*> m = StrNe(L"Hello");
1885 EXPECT_TRUE(m.Matches(L""));
1886 EXPECT_TRUE(m.Matches(NULL));
1887 EXPECT_FALSE(m.Matches(L"Hello"));
1889 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1890 EXPECT_TRUE(m2.Matches(L"hello"));
1891 EXPECT_FALSE(m2.Matches(L"Hello"));
1894 TEST(StdWideStrNeTest, CanDescribeSelf) {
1895 Matcher<const wchar_t*> m = StrNe(L"Hi");
1896 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1899 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1900 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1901 EXPECT_TRUE(m.Matches(L"Hello"));
1902 EXPECT_TRUE(m.Matches(L"hello"));
1903 EXPECT_FALSE(m.Matches(L"Hi"));
1904 EXPECT_FALSE(m.Matches(NULL));
1906 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1907 EXPECT_TRUE(m2.Matches(L"hello"));
1908 EXPECT_FALSE(m2.Matches(L"Hi"));
1911 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1912 ::std::wstring str1(L"oabocdooeoo");
1913 ::std::wstring str2(L"OABOCDOOEOO");
1914 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1915 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1917 str1[3] = str2[3] = L'\0';
1918 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1919 EXPECT_TRUE(m1.Matches(str2));
1921 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1922 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1923 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1924 str1[9] = str2[9] = L'\0';
1925 EXPECT_FALSE(m2.Matches(str2));
1927 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1928 EXPECT_TRUE(m3.Matches(str2));
1930 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1931 str2.append(1, L'\0');
1932 EXPECT_FALSE(m3.Matches(str2));
1933 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1936 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1937 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1938 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1941 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1942 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1943 EXPECT_TRUE(m.Matches(L"Hi"));
1944 EXPECT_TRUE(m.Matches(NULL));
1945 EXPECT_FALSE(m.Matches(L"Hello"));
1946 EXPECT_FALSE(m.Matches(L"hello"));
1948 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1949 EXPECT_TRUE(m2.Matches(L""));
1950 EXPECT_FALSE(m2.Matches(L"Hello"));
1953 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1954 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1955 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1958 // Tests that HasSubstr() works for matching wstring-typed values.
1959 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1960 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1961 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1962 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1964 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1965 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1966 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1969 // Tests that HasSubstr() works for matching C-wide-string-typed values.
1970 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1971 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1972 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1973 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1974 EXPECT_FALSE(m1.Matches(NULL));
1976 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1977 EXPECT_TRUE(m2.Matches(L"I love food."));
1978 EXPECT_FALSE(m2.Matches(L"tofo"));
1979 EXPECT_FALSE(m2.Matches(NULL));
1982 // Tests that HasSubstr(s) describes itself properly.
1983 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1984 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1985 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1988 // Tests StartsWith(s).
1990 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1991 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1992 EXPECT_TRUE(m1.Matches(L"Hi"));
1993 EXPECT_TRUE(m1.Matches(L""));
1994 EXPECT_FALSE(m1.Matches(NULL));
1996 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1997 EXPECT_TRUE(m2.Matches(L"Hi"));
1998 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1999 EXPECT_TRUE(m2.Matches(L"High"));
2000 EXPECT_FALSE(m2.Matches(L"H"));
2001 EXPECT_FALSE(m2.Matches(L" Hi"));
2004 TEST(StdWideStartsWithTest, CanDescribeSelf) {
2005 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2006 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2009 // Tests EndsWith(s).
2011 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2012 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2013 EXPECT_TRUE(m1.Matches(L"Hi"));
2014 EXPECT_TRUE(m1.Matches(L""));
2015 EXPECT_FALSE(m1.Matches(NULL));
2017 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2018 EXPECT_TRUE(m2.Matches(L"Hi"));
2019 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2020 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2021 EXPECT_FALSE(m2.Matches(L"i"));
2022 EXPECT_FALSE(m2.Matches(L"Hi "));
2025 TEST(StdWideEndsWithTest, CanDescribeSelf) {
2026 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2027 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2030 #endif // GTEST_HAS_STD_WSTRING
2032 #if GTEST_HAS_GLOBAL_WSTRING
2033 TEST(GlobalWideStrEqTest, MatchesEqual) {
2034 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
2035 EXPECT_TRUE(m.Matches(L"Hello"));
2036 EXPECT_FALSE(m.Matches(L"hello"));
2037 EXPECT_FALSE(m.Matches(NULL));
2039 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
2040 EXPECT_TRUE(m2.Matches(L"Hello"));
2041 EXPECT_FALSE(m2.Matches(L"Hi"));
2043 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
2044 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
2045 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
2047 ::wstring str(L"01204500800");
2049 Matcher<const ::wstring&> m4 = StrEq(str);
2050 EXPECT_TRUE(m4.Matches(str));
2051 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
2052 Matcher<const ::wstring&> m5 = StrEq(str);
2053 EXPECT_TRUE(m5.Matches(str));
2056 TEST(GlobalWideStrEqTest, CanDescribeSelf) {
2057 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
2058 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
2061 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
2062 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
2065 ::wstring str(L"01204500800");
2067 Matcher<const ::wstring&> m4 = StrEq(str);
2068 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
2069 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
2070 Matcher<const ::wstring&> m5 = StrEq(str);
2071 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
2074 TEST(GlobalWideStrNeTest, MatchesUnequalString) {
2075 Matcher<const wchar_t*> m = StrNe(L"Hello");
2076 EXPECT_TRUE(m.Matches(L""));
2077 EXPECT_TRUE(m.Matches(NULL));
2078 EXPECT_FALSE(m.Matches(L"Hello"));
2080 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
2081 EXPECT_TRUE(m2.Matches(L"hello"));
2082 EXPECT_FALSE(m2.Matches(L"Hello"));
2085 TEST(GlobalWideStrNeTest, CanDescribeSelf) {
2086 Matcher<const wchar_t*> m = StrNe(L"Hi");
2087 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
2090 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2091 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
2092 EXPECT_TRUE(m.Matches(L"Hello"));
2093 EXPECT_TRUE(m.Matches(L"hello"));
2094 EXPECT_FALSE(m.Matches(L"Hi"));
2095 EXPECT_FALSE(m.Matches(NULL));
2097 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
2098 EXPECT_TRUE(m2.Matches(L"hello"));
2099 EXPECT_FALSE(m2.Matches(L"Hi"));
2102 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
2103 ::wstring str1(L"oabocdooeoo");
2104 ::wstring str2(L"OABOCDOOEOO");
2105 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
2106 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
2108 str1[3] = str2[3] = L'\0';
2109 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
2110 EXPECT_TRUE(m1.Matches(str2));
2112 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
2113 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
2114 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
2115 str1[9] = str2[9] = L'\0';
2116 EXPECT_FALSE(m2.Matches(str2));
2118 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
2119 EXPECT_TRUE(m3.Matches(str2));
2121 EXPECT_FALSE(m3.Matches(str2 + L"x"));
2122 str2.append(1, L'\0');
2123 EXPECT_FALSE(m3.Matches(str2));
2124 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
2127 TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
2128 Matcher< ::wstring> m = StrCaseEq(L"Hi");
2129 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2132 TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2133 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2134 EXPECT_TRUE(m.Matches(L"Hi"));
2135 EXPECT_TRUE(m.Matches(NULL));
2136 EXPECT_FALSE(m.Matches(L"Hello"));
2137 EXPECT_FALSE(m.Matches(L"hello"));
2139 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
2140 EXPECT_TRUE(m2.Matches(L""));
2141 EXPECT_FALSE(m2.Matches(L"Hello"));
2144 TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
2145 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2146 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2149 // Tests that HasSubstr() works for matching wstring-typed values.
2150 TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
2151 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
2152 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
2153 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
2155 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
2156 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
2157 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
2160 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2161 TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
2162 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2163 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2164 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
2165 EXPECT_FALSE(m1.Matches(NULL));
2167 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2168 EXPECT_TRUE(m2.Matches(L"I love food."));
2169 EXPECT_FALSE(m2.Matches(L"tofo"));
2170 EXPECT_FALSE(m2.Matches(NULL));
2173 // Tests that HasSubstr(s) describes itself properly.
2174 TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
2175 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
2176 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2179 // Tests StartsWith(s).
2181 TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
2182 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
2183 EXPECT_TRUE(m1.Matches(L"Hi"));
2184 EXPECT_TRUE(m1.Matches(L""));
2185 EXPECT_FALSE(m1.Matches(NULL));
2187 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
2188 EXPECT_TRUE(m2.Matches(L"Hi"));
2189 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2190 EXPECT_TRUE(m2.Matches(L"High"));
2191 EXPECT_FALSE(m2.Matches(L"H"));
2192 EXPECT_FALSE(m2.Matches(L" Hi"));
2195 TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
2196 Matcher<const ::wstring> m = StartsWith(L"Hi");
2197 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2200 // Tests EndsWith(s).
2202 TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
2203 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2204 EXPECT_TRUE(m1.Matches(L"Hi"));
2205 EXPECT_TRUE(m1.Matches(L""));
2206 EXPECT_FALSE(m1.Matches(NULL));
2208 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
2209 EXPECT_TRUE(m2.Matches(L"Hi"));
2210 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2211 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2212 EXPECT_FALSE(m2.Matches(L"i"));
2213 EXPECT_FALSE(m2.Matches(L"Hi "));
2216 TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
2217 Matcher<const ::wstring> m = EndsWith(L"Hi");
2218 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2221 #endif // GTEST_HAS_GLOBAL_WSTRING
2224 typedef ::testing::tuple<long, int> Tuple2; // NOLINT
2226 // Tests that Eq() matches a 2-tuple where the first field == the
2228 TEST(Eq2Test, MatchesEqualArguments) {
2229 Matcher<const Tuple2&> m = Eq();
2230 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2231 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2234 // Tests that Eq() describes itself properly.
2235 TEST(Eq2Test, CanDescribeSelf) {
2236 Matcher<const Tuple2&> m = Eq();
2237 EXPECT_EQ("are an equal pair", Describe(m));
2240 // Tests that Ge() matches a 2-tuple where the first field >= the
2242 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2243 Matcher<const Tuple2&> m = Ge();
2244 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2245 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2246 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2249 // Tests that Ge() describes itself properly.
2250 TEST(Ge2Test, CanDescribeSelf) {
2251 Matcher<const Tuple2&> m = Ge();
2252 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2255 // Tests that Gt() matches a 2-tuple where the first field > the
2257 TEST(Gt2Test, MatchesGreaterThanArguments) {
2258 Matcher<const Tuple2&> m = Gt();
2259 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2260 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2261 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2264 // Tests that Gt() describes itself properly.
2265 TEST(Gt2Test, CanDescribeSelf) {
2266 Matcher<const Tuple2&> m = Gt();
2267 EXPECT_EQ("are a pair where the first > the second", Describe(m));
2270 // Tests that Le() matches a 2-tuple where the first field <= the
2272 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2273 Matcher<const Tuple2&> m = Le();
2274 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2275 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2276 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2279 // Tests that Le() describes itself properly.
2280 TEST(Le2Test, CanDescribeSelf) {
2281 Matcher<const Tuple2&> m = Le();
2282 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2285 // Tests that Lt() matches a 2-tuple where the first field < the
2287 TEST(Lt2Test, MatchesLessThanArguments) {
2288 Matcher<const Tuple2&> m = Lt();
2289 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2290 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2291 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2294 // Tests that Lt() describes itself properly.
2295 TEST(Lt2Test, CanDescribeSelf) {
2296 Matcher<const Tuple2&> m = Lt();
2297 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2300 // Tests that Ne() matches a 2-tuple where the first field != the
2302 TEST(Ne2Test, MatchesUnequalArguments) {
2303 Matcher<const Tuple2&> m = Ne();
2304 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2305 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2306 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2309 // Tests that Ne() describes itself properly.
2310 TEST(Ne2Test, CanDescribeSelf) {
2311 Matcher<const Tuple2&> m = Ne();
2312 EXPECT_EQ("are an unequal pair", Describe(m));
2315 // Tests that FloatEq() matches a 2-tuple where
2316 // FloatEq(first field) matches the second field.
2317 TEST(FloatEq2Test, MatchesEqualArguments) {
2318 typedef ::testing::tuple<float, float> Tpl;
2319 Matcher<const Tpl&> m = FloatEq();
2320 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2321 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2322 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2325 // Tests that FloatEq() describes itself properly.
2326 TEST(FloatEq2Test, CanDescribeSelf) {
2327 Matcher<const ::testing::tuple<float, float>&> m = FloatEq();
2328 EXPECT_EQ("are an almost-equal pair", Describe(m));
2331 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2332 // NanSensitiveFloatEq(first field) matches the second field.
2333 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2334 typedef ::testing::tuple<float, float> Tpl;
2335 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2336 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2337 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2338 std::numeric_limits<float>::quiet_NaN())));
2339 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2340 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2341 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2344 // Tests that NanSensitiveFloatEq() describes itself properly.
2345 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2346 Matcher<const ::testing::tuple<float, float>&> m = NanSensitiveFloatEq();
2347 EXPECT_EQ("are an almost-equal pair", Describe(m));
2350 // Tests that DoubleEq() matches a 2-tuple where
2351 // DoubleEq(first field) matches the second field.
2352 TEST(DoubleEq2Test, MatchesEqualArguments) {
2353 typedef ::testing::tuple<double, double> Tpl;
2354 Matcher<const Tpl&> m = DoubleEq();
2355 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2356 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2357 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2360 // Tests that DoubleEq() describes itself properly.
2361 TEST(DoubleEq2Test, CanDescribeSelf) {
2362 Matcher<const ::testing::tuple<double, double>&> m = DoubleEq();
2363 EXPECT_EQ("are an almost-equal pair", Describe(m));
2366 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2367 // NanSensitiveDoubleEq(first field) matches the second field.
2368 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2369 typedef ::testing::tuple<double, double> Tpl;
2370 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2371 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2372 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2373 std::numeric_limits<double>::quiet_NaN())));
2374 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2375 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2376 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2379 // Tests that DoubleEq() describes itself properly.
2380 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2381 Matcher<const ::testing::tuple<double, double>&> m = NanSensitiveDoubleEq();
2382 EXPECT_EQ("are an almost-equal pair", Describe(m));
2385 // Tests that FloatEq() matches a 2-tuple where
2386 // FloatNear(first field, max_abs_error) matches the second field.
2387 TEST(FloatNear2Test, MatchesEqualArguments) {
2388 typedef ::testing::tuple<float, float> Tpl;
2389 Matcher<const Tpl&> m = FloatNear(0.5f);
2390 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2391 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2392 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2395 // Tests that FloatNear() describes itself properly.
2396 TEST(FloatNear2Test, CanDescribeSelf) {
2397 Matcher<const ::testing::tuple<float, float>&> m = FloatNear(0.5f);
2398 EXPECT_EQ("are an almost-equal pair", Describe(m));
2401 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2402 // NanSensitiveFloatNear(first field) matches the second field.
2403 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2404 typedef ::testing::tuple<float, float> Tpl;
2405 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2406 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2407 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2408 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2409 std::numeric_limits<float>::quiet_NaN())));
2410 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2411 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2412 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2415 // Tests that NanSensitiveFloatNear() describes itself properly.
2416 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2417 Matcher<const ::testing::tuple<float, float>&> m =
2418 NanSensitiveFloatNear(0.5f);
2419 EXPECT_EQ("are an almost-equal pair", Describe(m));
2422 // Tests that FloatEq() matches a 2-tuple where
2423 // DoubleNear(first field, max_abs_error) matches the second field.
2424 TEST(DoubleNear2Test, MatchesEqualArguments) {
2425 typedef ::testing::tuple<double, double> Tpl;
2426 Matcher<const Tpl&> m = DoubleNear(0.5);
2427 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2428 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2429 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2432 // Tests that DoubleNear() describes itself properly.
2433 TEST(DoubleNear2Test, CanDescribeSelf) {
2434 Matcher<const ::testing::tuple<double, double>&> m = DoubleNear(0.5);
2435 EXPECT_EQ("are an almost-equal pair", Describe(m));
2438 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2439 // NanSensitiveDoubleNear(first field) matches the second field.
2440 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2441 typedef ::testing::tuple<double, double> Tpl;
2442 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2443 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2444 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2445 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2446 std::numeric_limits<double>::quiet_NaN())));
2447 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2448 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2449 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2452 // Tests that NanSensitiveDoubleNear() describes itself properly.
2453 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2454 Matcher<const ::testing::tuple<double, double>&> m =
2455 NanSensitiveDoubleNear(0.5f);
2456 EXPECT_EQ("are an almost-equal pair", Describe(m));
2459 // Tests that Not(m) matches any value that doesn't match m.
2460 TEST(NotTest, NegatesMatcher) {
2463 EXPECT_TRUE(m.Matches(3));
2464 EXPECT_FALSE(m.Matches(2));
2467 // Tests that Not(m) describes itself properly.
2468 TEST(NotTest, CanDescribeSelf) {
2469 Matcher<int> m = Not(Eq(5));
2470 EXPECT_EQ("isn't equal to 5", Describe(m));
2473 // Tests that monomorphic matchers are safely cast by the Not matcher.
2474 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2475 // greater_than_5 is a monomorphic matcher.
2476 Matcher<int> greater_than_5 = Gt(5);
2478 Matcher<const int&> m = Not(greater_than_5);
2479 Matcher<int&> m2 = Not(greater_than_5);
2480 Matcher<int&> m3 = Not(m);
2483 // Helper to allow easy testing of AllOf matchers with num parameters.
2484 void AllOfMatches(int num, const Matcher<int>& m) {
2485 SCOPED_TRACE(Describe(m));
2486 EXPECT_TRUE(m.Matches(0));
2487 for (int i = 1; i <= num; ++i) {
2488 EXPECT_FALSE(m.Matches(i));
2490 EXPECT_TRUE(m.Matches(num + 1));
2493 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2494 // the given matchers.
2495 TEST(AllOfTest, MatchesWhenAllMatch) {
2497 m = AllOf(Le(2), Ge(1));
2498 EXPECT_TRUE(m.Matches(1));
2499 EXPECT_TRUE(m.Matches(2));
2500 EXPECT_FALSE(m.Matches(0));
2501 EXPECT_FALSE(m.Matches(3));
2503 m = AllOf(Gt(0), Ne(1), Ne(2));
2504 EXPECT_TRUE(m.Matches(3));
2505 EXPECT_FALSE(m.Matches(2));
2506 EXPECT_FALSE(m.Matches(1));
2507 EXPECT_FALSE(m.Matches(0));
2509 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2510 EXPECT_TRUE(m.Matches(4));
2511 EXPECT_FALSE(m.Matches(3));
2512 EXPECT_FALSE(m.Matches(2));
2513 EXPECT_FALSE(m.Matches(1));
2514 EXPECT_FALSE(m.Matches(0));
2516 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2517 EXPECT_TRUE(m.Matches(0));
2518 EXPECT_TRUE(m.Matches(1));
2519 EXPECT_FALSE(m.Matches(3));
2521 // The following tests for varying number of sub-matchers. Due to the way
2522 // the sub-matchers are handled it is enough to test every sub-matcher once
2523 // with sub-matchers using the same matcher type. Varying matcher types are
2524 // checked for above.
2525 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2526 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2527 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2528 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2529 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2530 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2531 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2533 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2535 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2539 #if GTEST_LANG_CXX11
2540 // Tests the variadic version of the AllOfMatcher.
2541 TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2542 // Make sure AllOf is defined in the right namespace and does not depend on
2544 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2545 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2546 Ne(9), Ne(10), Ne(11));
2547 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2548 AllOfMatches(11, m);
2549 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2550 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2551 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2552 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2553 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2554 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2555 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2559 #endif // GTEST_LANG_CXX11
2561 // Tests that AllOf(m1, ..., mn) describes itself properly.
2562 TEST(AllOfTest, CanDescribeSelf) {
2564 m = AllOf(Le(2), Ge(1));
2565 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2567 m = AllOf(Gt(0), Ne(1), Ne(2));
2568 EXPECT_EQ("(is > 0) and "
2569 "((isn't equal to 1) and "
2570 "(isn't equal to 2))",
2574 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2575 EXPECT_EQ("((is > 0) and "
2576 "(isn't equal to 1)) and "
2577 "((isn't equal to 2) and "
2578 "(isn't equal to 3))",
2582 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2583 EXPECT_EQ("((is >= 0) and "
2585 "((isn't equal to 3) and "
2586 "((isn't equal to 5) and "
2587 "(isn't equal to 7)))",
2591 // Tests that AllOf(m1, ..., mn) describes its negation properly.
2592 TEST(AllOfTest, CanDescribeNegation) {
2594 m = AllOf(Le(2), Ge(1));
2595 EXPECT_EQ("(isn't <= 2) or "
2597 DescribeNegation(m));
2599 m = AllOf(Gt(0), Ne(1), Ne(2));
2600 EXPECT_EQ("(isn't > 0) or "
2601 "((is equal to 1) or "
2603 DescribeNegation(m));
2606 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2607 EXPECT_EQ("((isn't > 0) or "
2608 "(is equal to 1)) or "
2609 "((is equal to 2) or "
2611 DescribeNegation(m));
2614 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2615 EXPECT_EQ("((isn't >= 0) or "
2617 "((is equal to 3) or "
2618 "((is equal to 5) or "
2619 "(is equal to 7)))",
2620 DescribeNegation(m));
2623 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
2624 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2625 // greater_than_5 and less_than_10 are monomorphic matchers.
2626 Matcher<int> greater_than_5 = Gt(5);
2627 Matcher<int> less_than_10 = Lt(10);
2629 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2630 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2631 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2633 // Tests that BothOf works when composing itself.
2634 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2635 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2638 TEST(AllOfTest, ExplainsResult) {
2641 // Successful match. Both matchers need to explain. The second
2642 // matcher doesn't give an explanation, so only the first matcher's
2643 // explanation is printed.
2644 m = AllOf(GreaterThan(10), Lt(30));
2645 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2647 // Successful match. Both matchers need to explain.
2648 m = AllOf(GreaterThan(10), GreaterThan(20));
2649 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2652 // Successful match. All matchers need to explain. The second
2653 // matcher doesn't given an explanation.
2654 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2655 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2658 // Successful match. All matchers need to explain.
2659 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2660 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2661 "and which is 10 more than 30",
2664 // Failed match. The first matcher, which failed, needs to
2666 m = AllOf(GreaterThan(10), GreaterThan(20));
2667 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2669 // Failed match. The second matcher, which failed, needs to
2670 // explain. Since it doesn't given an explanation, nothing is
2672 m = AllOf(GreaterThan(10), Lt(30));
2673 EXPECT_EQ("", Explain(m, 40));
2675 // Failed match. The second matcher, which failed, needs to
2677 m = AllOf(GreaterThan(10), GreaterThan(20));
2678 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2681 // Helper to allow easy testing of AnyOf matchers with num parameters.
2682 static void AnyOfMatches(int num, const Matcher<int>& m) {
2683 SCOPED_TRACE(Describe(m));
2684 EXPECT_FALSE(m.Matches(0));
2685 for (int i = 1; i <= num; ++i) {
2686 EXPECT_TRUE(m.Matches(i));
2688 EXPECT_FALSE(m.Matches(num + 1));
2691 #if GTEST_LANG_CXX11
2692 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2693 SCOPED_TRACE(Describe(m));
2694 EXPECT_FALSE(m.Matches(std::to_string(0)));
2696 for (int i = 1; i <= num; ++i) {
2697 EXPECT_TRUE(m.Matches(std::to_string(i)));
2699 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2703 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2704 // least one of the given matchers.
2705 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2707 m = AnyOf(Le(1), Ge(3));
2708 EXPECT_TRUE(m.Matches(1));
2709 EXPECT_TRUE(m.Matches(4));
2710 EXPECT_FALSE(m.Matches(2));
2712 m = AnyOf(Lt(0), Eq(1), Eq(2));
2713 EXPECT_TRUE(m.Matches(-1));
2714 EXPECT_TRUE(m.Matches(1));
2715 EXPECT_TRUE(m.Matches(2));
2716 EXPECT_FALSE(m.Matches(0));
2718 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2719 EXPECT_TRUE(m.Matches(-1));
2720 EXPECT_TRUE(m.Matches(1));
2721 EXPECT_TRUE(m.Matches(2));
2722 EXPECT_TRUE(m.Matches(3));
2723 EXPECT_FALSE(m.Matches(0));
2725 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2726 EXPECT_TRUE(m.Matches(0));
2727 EXPECT_TRUE(m.Matches(11));
2728 EXPECT_TRUE(m.Matches(3));
2729 EXPECT_FALSE(m.Matches(2));
2731 // The following tests for varying number of sub-matchers. Due to the way
2732 // the sub-matchers are handled it is enough to test every sub-matcher once
2733 // with sub-matchers using the same matcher type. Varying matcher types are
2734 // checked for above.
2735 AnyOfMatches(2, AnyOf(1, 2));
2736 AnyOfMatches(3, AnyOf(1, 2, 3));
2737 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2738 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2739 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2740 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2741 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2742 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2743 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2746 #if GTEST_LANG_CXX11
2747 // Tests the variadic version of the AnyOfMatcher.
2748 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2749 // Also make sure AnyOf is defined in the right namespace and does not depend
2751 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2753 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2754 AnyOfMatches(11, m);
2755 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2756 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2757 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2758 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2759 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2761 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2762 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2763 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2764 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2765 "43", "44", "45", "46", "47", "48", "49", "50"));
2768 // Tests the variadic version of the ElementsAreMatcher
2769 TEST(ElementsAreTest, HugeMatcher) {
2770 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2772 EXPECT_THAT(test_vector,
2773 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2774 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2777 // Tests the variadic version of the UnorderedElementsAreMatcher
2778 TEST(ElementsAreTest, HugeMatcherStr) {
2779 vector<string> test_vector{
2780 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2782 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2786 // Tests the variadic version of the UnorderedElementsAreMatcher
2787 TEST(ElementsAreTest, HugeMatcherUnordered) {
2788 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2790 EXPECT_THAT(test_vector, UnorderedElementsAre(
2791 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2792 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2795 #endif // GTEST_LANG_CXX11
2797 // Tests that AnyOf(m1, ..., mn) describes itself properly.
2798 TEST(AnyOfTest, CanDescribeSelf) {
2800 m = AnyOf(Le(1), Ge(3));
2801 EXPECT_EQ("(is <= 1) or (is >= 3)",
2804 m = AnyOf(Lt(0), Eq(1), Eq(2));
2805 EXPECT_EQ("(is < 0) or "
2806 "((is equal to 1) or (is equal to 2))",
2809 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2810 EXPECT_EQ("((is < 0) or "
2811 "(is equal to 1)) or "
2812 "((is equal to 2) or "
2816 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2817 EXPECT_EQ("((is <= 0) or "
2819 "((is equal to 3) or "
2820 "((is equal to 5) or "
2821 "(is equal to 7)))",
2825 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
2826 TEST(AnyOfTest, CanDescribeNegation) {
2828 m = AnyOf(Le(1), Ge(3));
2829 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2830 DescribeNegation(m));
2832 m = AnyOf(Lt(0), Eq(1), Eq(2));
2833 EXPECT_EQ("(isn't < 0) and "
2834 "((isn't equal to 1) and (isn't equal to 2))",
2835 DescribeNegation(m));
2837 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2838 EXPECT_EQ("((isn't < 0) and "
2839 "(isn't equal to 1)) and "
2840 "((isn't equal to 2) and "
2841 "(isn't equal to 3))",
2842 DescribeNegation(m));
2844 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2845 EXPECT_EQ("((isn't <= 0) and "
2846 "(isn't > 10)) and "
2847 "((isn't equal to 3) and "
2848 "((isn't equal to 5) and "
2849 "(isn't equal to 7)))",
2850 DescribeNegation(m));
2853 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2854 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2855 // greater_than_5 and less_than_10 are monomorphic matchers.
2856 Matcher<int> greater_than_5 = Gt(5);
2857 Matcher<int> less_than_10 = Lt(10);
2859 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2860 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2861 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2863 // Tests that EitherOf works when composing itself.
2864 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2865 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2868 TEST(AnyOfTest, ExplainsResult) {
2871 // Failed match. Both matchers need to explain. The second
2872 // matcher doesn't give an explanation, so only the first matcher's
2873 // explanation is printed.
2874 m = AnyOf(GreaterThan(10), Lt(0));
2875 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2877 // Failed match. Both matchers need to explain.
2878 m = AnyOf(GreaterThan(10), GreaterThan(20));
2879 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2882 // Failed match. All matchers need to explain. The second
2883 // matcher doesn't given an explanation.
2884 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2885 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2888 // Failed match. All matchers need to explain.
2889 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2890 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2891 "and which is 25 less than 30",
2894 // Successful match. The first matcher, which succeeded, needs to
2896 m = AnyOf(GreaterThan(10), GreaterThan(20));
2897 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2899 // Successful match. The second matcher, which succeeded, needs to
2900 // explain. Since it doesn't given an explanation, nothing is
2902 m = AnyOf(GreaterThan(10), Lt(30));
2903 EXPECT_EQ("", Explain(m, 0));
2905 // Successful match. The second matcher, which succeeded, needs to
2907 m = AnyOf(GreaterThan(30), GreaterThan(20));
2908 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2911 // The following predicate function and predicate functor are for
2912 // testing the Truly(predicate) matcher.
2914 // Returns non-zero if the input is positive. Note that the return
2915 // type of this function is not bool. It's OK as Truly() accepts any
2916 // unary function or functor whose return type can be implicitly
2917 // converted to bool.
2918 int IsPositive(double x) {
2919 return x > 0 ? 1 : 0;
2922 // This functor returns true if the input is greater than the given
2924 class IsGreaterThan {
2926 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2928 bool operator()(int n) const { return n > threshold_; }
2934 // For testing Truly().
2937 // This predicate returns true iff the argument references foo and has
2939 bool ReferencesFooAndIsZero(const int& n) {
2940 return (&n == &foo) && (n == 0);
2943 // Tests that Truly(predicate) matches what satisfies the given
2945 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2946 Matcher<double> m = Truly(IsPositive);
2947 EXPECT_TRUE(m.Matches(2.0));
2948 EXPECT_FALSE(m.Matches(-1.5));
2951 // Tests that Truly(predicate_functor) works too.
2952 TEST(TrulyTest, CanBeUsedWithFunctor) {
2953 Matcher<int> m = Truly(IsGreaterThan(5));
2954 EXPECT_TRUE(m.Matches(6));
2955 EXPECT_FALSE(m.Matches(4));
2958 // A class that can be implicitly converted to bool.
2959 class ConvertibleToBool {
2961 explicit ConvertibleToBool(int number) : number_(number) {}
2962 operator bool() const { return number_ != 0; }
2968 ConvertibleToBool IsNotZero(int number) {
2969 return ConvertibleToBool(number);
2972 // Tests that the predicate used in Truly() may return a class that's
2973 // implicitly convertible to bool, even when the class has no
2975 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2976 Matcher<int> m = Truly(IsNotZero);
2977 EXPECT_TRUE(m.Matches(1));
2978 EXPECT_FALSE(m.Matches(0));
2981 // Tests that Truly(predicate) can describe itself properly.
2982 TEST(TrulyTest, CanDescribeSelf) {
2983 Matcher<double> m = Truly(IsPositive);
2984 EXPECT_EQ("satisfies the given predicate",
2988 // Tests that Truly(predicate) works when the matcher takes its
2989 // argument by reference.
2990 TEST(TrulyTest, WorksForByRefArguments) {
2991 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2992 EXPECT_TRUE(m.Matches(foo));
2994 EXPECT_FALSE(m.Matches(n));
2997 // Tests that Matches(m) is a predicate satisfied by whatever that
2998 // matches matcher m.
2999 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
3000 EXPECT_TRUE(Matches(Ge(0))(1));
3001 EXPECT_FALSE(Matches(Eq('a'))('b'));
3004 // Tests that Matches(m) works when the matcher takes its argument by
3006 TEST(MatchesTest, WorksOnByRefArguments) {
3008 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
3009 EXPECT_FALSE(Matches(Ref(m))(n));
3012 // Tests that a Matcher on non-reference type can be used in
3014 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3015 Matcher<int> eq5 = Eq(5);
3016 EXPECT_TRUE(Matches(eq5)(5));
3017 EXPECT_FALSE(Matches(eq5)(2));
3020 // Tests Value(value, matcher). Since Value() is a simple wrapper for
3021 // Matches(), which has been tested already, we don't spend a lot of
3022 // effort on testing Value().
3023 TEST(ValueTest, WorksWithPolymorphicMatcher) {
3024 EXPECT_TRUE(Value("hi", StartsWith("h")));
3025 EXPECT_FALSE(Value(5, Gt(10)));
3028 TEST(ValueTest, WorksWithMonomorphicMatcher) {
3029 const Matcher<int> is_zero = Eq(0);
3030 EXPECT_TRUE(Value(0, is_zero));
3031 EXPECT_FALSE(Value('a', is_zero));
3034 const Matcher<const int&> ref_n = Ref(n);
3035 EXPECT_TRUE(Value(n, ref_n));
3036 EXPECT_FALSE(Value(1, ref_n));
3039 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3040 StringMatchResultListener listener1;
3041 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3042 EXPECT_EQ("% 2 == 0", listener1.str());
3044 StringMatchResultListener listener2;
3045 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3046 EXPECT_EQ("", listener2.str());
3049 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3050 const Matcher<int> is_even = PolymorphicIsEven();
3051 StringMatchResultListener listener1;
3052 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3053 EXPECT_EQ("% 2 == 0", listener1.str());
3055 const Matcher<const double&> is_zero = Eq(0);
3056 StringMatchResultListener listener2;
3057 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3058 EXPECT_EQ("", listener2.str());
3061 MATCHER_P(Really, inner_matcher, "") {
3062 return ExplainMatchResult(inner_matcher, arg, result_listener);
3065 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3066 EXPECT_THAT(0, Really(Eq(0)));
3069 TEST(DescribeMatcherTest, WorksWithValue) {
3070 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3071 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3074 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
3075 const Matcher<int> monomorphic = Le(0);
3076 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
3077 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
3080 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3081 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
3082 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
3085 TEST(AllArgsTest, WorksForTuple) {
3086 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
3087 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
3090 TEST(AllArgsTest, WorksForNonTuple) {
3091 EXPECT_THAT(42, AllArgs(Gt(0)));
3092 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3095 class AllArgsHelper {
3099 MOCK_METHOD2(Helper, int(char x, int y));
3102 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
3105 TEST(AllArgsTest, WorksInWithClause) {
3106 AllArgsHelper helper;
3107 ON_CALL(helper, Helper(_, _))
3108 .With(AllArgs(Lt()))
3109 .WillByDefault(Return(1));
3110 EXPECT_CALL(helper, Helper(_, _));
3111 EXPECT_CALL(helper, Helper(_, _))
3112 .With(AllArgs(Gt()))
3113 .WillOnce(Return(2));
3115 EXPECT_EQ(1, helper.Helper('\1', 2));
3116 EXPECT_EQ(2, helper.Helper('a', 1));
3119 class OptionalMatchersHelper {
3121 OptionalMatchersHelper() {}
3123 MOCK_METHOD0(NoArgs, int());
3125 MOCK_METHOD1(OneArg, int(int y));
3127 MOCK_METHOD2(TwoArgs, int(char x, int y));
3129 MOCK_METHOD1(Overloaded, int(char x));
3130 MOCK_METHOD2(Overloaded, int(char x, int y));
3133 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
3136 TEST(AllArgsTest, WorksWithoutMatchers) {
3137 OptionalMatchersHelper helper;
3139 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3140 ON_CALL(helper, OneArg).WillByDefault(Return(20));
3141 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3143 EXPECT_EQ(10, helper.NoArgs());
3144 EXPECT_EQ(20, helper.OneArg(1));
3145 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3147 EXPECT_CALL(helper, NoArgs).Times(1);
3148 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
3149 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
3150 EXPECT_CALL(helper, TwoArgs).Times(0);
3152 EXPECT_EQ(10, helper.NoArgs());
3153 EXPECT_EQ(100, helper.OneArg(1));
3154 EXPECT_EQ(200, helper.OneArg(17));
3157 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3158 // matches the matcher.
3159 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3160 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3161 ASSERT_THAT("Foo", EndsWith("oo"));
3162 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3163 EXPECT_THAT("Hello", StartsWith("Hell"));
3166 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3167 // doesn't match the matcher.
3168 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3169 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3170 // which cannot reference auto variables.
3171 static unsigned short n; // NOLINT
3174 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
3175 // functions declared in the namespace scope from within nested classes.
3176 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
3177 // namespace-level functions invoked inside them need to be explicitly
3179 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
3181 "Expected: is > 10\n"
3182 " Actual: 5" + OfType("unsigned short"));
3184 EXPECT_NONFATAL_FAILURE(
3185 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
3187 "Expected: (is <= 7) and (is >= 5)\n"
3188 " Actual: 0" + OfType("unsigned short"));
3191 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3192 // has a reference type.
3193 TEST(MatcherAssertionTest, WorksForByRefArguments) {
3194 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3195 // reference auto variables.
3198 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3199 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
3201 "Expected: does not reference the variable @");
3202 // Tests the "Actual" part.
3203 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
3204 "Actual: 0" + OfType("int") + ", which is located @");
3207 #if !GTEST_OS_SYMBIAN
3208 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3211 // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
3212 // Symbian compiler: it tries to compile
3213 // template<T, U> class MatcherCastImpl { ...
3214 // virtual bool MatchAndExplain(T x, ...) const {
3215 // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
3216 // with U == string and T == const char*
3217 // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
3218 // the compiler silently crashes with no output.
3219 // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
3220 // the code compiles but the converted string is bogus.
3221 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3222 Matcher<const char*> starts_with_he = StartsWith("he");
3223 ASSERT_THAT("hello", starts_with_he);
3225 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
3226 ASSERT_THAT("book", ends_with_ok);
3227 const std::string bad = "bad";
3228 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3230 "Expected: ends with \"ok\"\n"
3231 " Actual: \"bad\"");
3232 Matcher<int> is_greater_than_5 = Gt(5);
3233 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3235 "Expected: is > 5\n"
3236 " Actual: 5" + OfType("int"));
3238 #endif // !GTEST_OS_SYMBIAN
3240 // Tests floating-point matchers.
3241 template <typename RawType>
3242 class FloatingPointTest : public testing::Test {
3244 typedef testing::internal::FloatingPoint<RawType> Floating;
3245 typedef typename Floating::Bits Bits;
3248 : max_ulps_(Floating::kMaxUlps),
3249 zero_bits_(Floating(0).bits()),
3250 one_bits_(Floating(1).bits()),
3251 infinity_bits_(Floating(Floating::Infinity()).bits()),
3252 close_to_positive_zero_(
3253 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3254 close_to_negative_zero_(
3255 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3256 further_from_negative_zero_(-Floating::ReinterpretBits(
3257 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
3258 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3259 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
3260 infinity_(Floating::Infinity()),
3262 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3263 further_from_infinity_(
3264 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
3265 max_(Floating::Max()),
3266 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3267 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3271 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3274 // A battery of tests for FloatingEqMatcher::Matches.
3275 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3277 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3278 Matcher<RawType> m1 = matcher_maker(0.0);
3279 EXPECT_TRUE(m1.Matches(-0.0));
3280 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3281 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3282 EXPECT_FALSE(m1.Matches(1.0));
3284 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3285 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3287 Matcher<RawType> m3 = matcher_maker(1.0);
3288 EXPECT_TRUE(m3.Matches(close_to_one_));
3289 EXPECT_FALSE(m3.Matches(further_from_one_));
3291 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3292 EXPECT_FALSE(m3.Matches(0.0));
3294 Matcher<RawType> m4 = matcher_maker(-infinity_);
3295 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3297 Matcher<RawType> m5 = matcher_maker(infinity_);
3298 EXPECT_TRUE(m5.Matches(close_to_infinity_));
3300 // This is interesting as the representations of infinity_ and nan1_
3301 // are only 1 DLP apart.
3302 EXPECT_FALSE(m5.Matches(nan1_));
3304 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3306 Matcher<const RawType&> m6 = matcher_maker(0.0);
3307 EXPECT_TRUE(m6.Matches(-0.0));
3308 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3309 EXPECT_FALSE(m6.Matches(1.0));
3311 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3313 Matcher<RawType&> m7 = matcher_maker(0.0);
3315 EXPECT_TRUE(m7.Matches(x));
3317 EXPECT_FALSE(m7.Matches(x));
3320 // Pre-calculated numbers to be used by the tests.
3322 const Bits max_ulps_;
3324 const Bits zero_bits_; // The bits that represent 0.0.
3325 const Bits one_bits_; // The bits that represent 1.0.
3326 const Bits infinity_bits_; // The bits that represent +infinity.
3328 // Some numbers close to 0.0.
3329 const RawType close_to_positive_zero_;
3330 const RawType close_to_negative_zero_;
3331 const RawType further_from_negative_zero_;
3333 // Some numbers close to 1.0.
3334 const RawType close_to_one_;
3335 const RawType further_from_one_;
3337 // Some numbers close to +infinity.
3338 const RawType infinity_;
3339 const RawType close_to_infinity_;
3340 const RawType further_from_infinity_;
3342 // Maximum representable value that's not infinity.
3346 const RawType nan1_;
3347 const RawType nan2_;
3350 // Tests floating-point matchers with fixed epsilons.
3351 template <typename RawType>
3352 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3354 typedef FloatingPointTest<RawType> ParentType;
3356 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3357 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3358 void TestNearMatches(
3359 testing::internal::FloatingEqMatcher<RawType>
3360 (*matcher_maker)(RawType, RawType)) {
3361 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3362 EXPECT_TRUE(m1.Matches(0.0));
3363 EXPECT_TRUE(m1.Matches(-0.0));
3364 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3365 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3366 EXPECT_FALSE(m1.Matches(1.0));
3368 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3369 EXPECT_TRUE(m2.Matches(0.0));
3370 EXPECT_TRUE(m2.Matches(-0.0));
3371 EXPECT_TRUE(m2.Matches(1.0));
3372 EXPECT_TRUE(m2.Matches(-1.0));
3373 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3374 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3376 // Check that inf matches inf, regardless of the of the specified max
3378 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3379 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3380 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3381 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3383 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3384 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3385 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3386 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3388 // Test various overflow scenarios.
3389 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3390 EXPECT_TRUE(m5.Matches(ParentType::max_));
3391 EXPECT_FALSE(m5.Matches(-ParentType::max_));
3393 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3394 EXPECT_FALSE(m6.Matches(ParentType::max_));
3395 EXPECT_TRUE(m6.Matches(-ParentType::max_));
3397 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3398 EXPECT_TRUE(m7.Matches(ParentType::max_));
3399 EXPECT_FALSE(m7.Matches(-ParentType::max_));
3401 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3402 EXPECT_FALSE(m8.Matches(ParentType::max_));
3403 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3405 // The difference between max() and -max() normally overflows to infinity,
3406 // but it should still match if the max_abs_error is also infinity.
3407 Matcher<RawType> m9 = matcher_maker(
3408 ParentType::max_, ParentType::infinity_);
3409 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3411 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3413 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3414 EXPECT_TRUE(m10.Matches(-0.0));
3415 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3416 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3418 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3420 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3422 EXPECT_TRUE(m11.Matches(x));
3424 EXPECT_TRUE(m11.Matches(x));
3426 EXPECT_TRUE(m11.Matches(x));
3428 EXPECT_FALSE(m11.Matches(x));
3430 EXPECT_FALSE(m11.Matches(x));
3434 // Instantiate FloatingPointTest for testing floats.
3435 typedef FloatingPointTest<float> FloatTest;
3437 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3438 TestMatches(&FloatEq);
3441 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3442 TestMatches(&NanSensitiveFloatEq);
3445 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3446 // FloatEq never matches NaN.
3447 Matcher<float> m = FloatEq(nan1_);
3448 EXPECT_FALSE(m.Matches(nan1_));
3449 EXPECT_FALSE(m.Matches(nan2_));
3450 EXPECT_FALSE(m.Matches(1.0));
3453 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3454 // NanSensitiveFloatEq will match NaN.
3455 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3456 EXPECT_TRUE(m.Matches(nan1_));
3457 EXPECT_TRUE(m.Matches(nan2_));
3458 EXPECT_FALSE(m.Matches(1.0));
3461 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3462 Matcher<float> m1 = FloatEq(2.0f);
3463 EXPECT_EQ("is approximately 2", Describe(m1));
3464 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3466 Matcher<float> m2 = FloatEq(0.5f);
3467 EXPECT_EQ("is approximately 0.5", Describe(m2));
3468 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3470 Matcher<float> m3 = FloatEq(nan1_);
3471 EXPECT_EQ("never matches", Describe(m3));
3472 EXPECT_EQ("is anything", DescribeNegation(m3));
3475 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3476 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3477 EXPECT_EQ("is approximately 2", Describe(m1));
3478 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3480 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3481 EXPECT_EQ("is approximately 0.5", Describe(m2));
3482 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3484 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3485 EXPECT_EQ("is NaN", Describe(m3));
3486 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3489 // Instantiate FloatingPointTest for testing floats with a user-specified
3490 // max absolute error.
3491 typedef FloatingPointNearTest<float> FloatNearTest;
3493 TEST_F(FloatNearTest, FloatNearMatches) {
3494 TestNearMatches(&FloatNear);
3497 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3498 TestNearMatches(&NanSensitiveFloatNear);
3501 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3502 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3503 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3505 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3507 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3508 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3510 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3512 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3513 EXPECT_EQ("never matches", Describe(m3));
3514 EXPECT_EQ("is anything", DescribeNegation(m3));
3517 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3518 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3519 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3521 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3523 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3524 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3526 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3528 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3529 EXPECT_EQ("is NaN", Describe(m3));
3530 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3533 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3534 // FloatNear never matches NaN.
3535 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3536 EXPECT_FALSE(m.Matches(nan1_));
3537 EXPECT_FALSE(m.Matches(nan2_));
3538 EXPECT_FALSE(m.Matches(1.0));
3541 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3542 // NanSensitiveFloatNear will match NaN.
3543 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3544 EXPECT_TRUE(m.Matches(nan1_));
3545 EXPECT_TRUE(m.Matches(nan2_));
3546 EXPECT_FALSE(m.Matches(1.0));
3549 // Instantiate FloatingPointTest for testing doubles.
3550 typedef FloatingPointTest<double> DoubleTest;
3552 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3553 TestMatches(&DoubleEq);
3556 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3557 TestMatches(&NanSensitiveDoubleEq);
3560 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3561 // DoubleEq never matches NaN.
3562 Matcher<double> m = DoubleEq(nan1_);
3563 EXPECT_FALSE(m.Matches(nan1_));
3564 EXPECT_FALSE(m.Matches(nan2_));
3565 EXPECT_FALSE(m.Matches(1.0));
3568 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3569 // NanSensitiveDoubleEq will match NaN.
3570 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3571 EXPECT_TRUE(m.Matches(nan1_));
3572 EXPECT_TRUE(m.Matches(nan2_));
3573 EXPECT_FALSE(m.Matches(1.0));
3576 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3577 Matcher<double> m1 = DoubleEq(2.0);
3578 EXPECT_EQ("is approximately 2", Describe(m1));
3579 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3581 Matcher<double> m2 = DoubleEq(0.5);
3582 EXPECT_EQ("is approximately 0.5", Describe(m2));
3583 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3585 Matcher<double> m3 = DoubleEq(nan1_);
3586 EXPECT_EQ("never matches", Describe(m3));
3587 EXPECT_EQ("is anything", DescribeNegation(m3));
3590 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3591 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3592 EXPECT_EQ("is approximately 2", Describe(m1));
3593 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3595 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3596 EXPECT_EQ("is approximately 0.5", Describe(m2));
3597 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3599 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3600 EXPECT_EQ("is NaN", Describe(m3));
3601 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3604 // Instantiate FloatingPointTest for testing floats with a user-specified
3605 // max absolute error.
3606 typedef FloatingPointNearTest<double> DoubleNearTest;
3608 TEST_F(DoubleNearTest, DoubleNearMatches) {
3609 TestNearMatches(&DoubleNear);
3612 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3613 TestNearMatches(&NanSensitiveDoubleNear);
3616 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3617 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3618 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3620 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3622 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3623 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3625 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3627 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3628 EXPECT_EQ("never matches", Describe(m3));
3629 EXPECT_EQ("is anything", DescribeNegation(m3));
3632 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3633 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3634 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3635 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3637 const std::string explanation =
3638 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3639 // Different C++ implementations may print floating-point numbers
3640 // slightly differently.
3641 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3642 explanation == "which is 1.2e-010 from 2.1") // MSVC
3643 << " where explanation is \"" << explanation << "\".";
3646 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3647 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3648 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3650 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3652 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3653 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3655 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3657 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3658 EXPECT_EQ("is NaN", Describe(m3));
3659 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3662 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3663 // DoubleNear never matches NaN.
3664 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3665 EXPECT_FALSE(m.Matches(nan1_));
3666 EXPECT_FALSE(m.Matches(nan2_));
3667 EXPECT_FALSE(m.Matches(1.0));
3670 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3671 // NanSensitiveDoubleNear will match NaN.
3672 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3673 EXPECT_TRUE(m.Matches(nan1_));
3674 EXPECT_TRUE(m.Matches(nan2_));
3675 EXPECT_FALSE(m.Matches(1.0));
3678 TEST(PointeeTest, RawPointer) {
3679 const Matcher<int*> m = Pointee(Ge(0));
3682 EXPECT_TRUE(m.Matches(&n));
3684 EXPECT_FALSE(m.Matches(&n));
3685 EXPECT_FALSE(m.Matches(NULL));
3688 TEST(PointeeTest, RawPointerToConst) {
3689 const Matcher<const double*> m = Pointee(Ge(0));
3692 EXPECT_TRUE(m.Matches(&x));
3694 EXPECT_FALSE(m.Matches(&x));
3695 EXPECT_FALSE(m.Matches(NULL));
3698 TEST(PointeeTest, ReferenceToConstRawPointer) {
3699 const Matcher<int* const &> m = Pointee(Ge(0));
3702 EXPECT_TRUE(m.Matches(&n));
3704 EXPECT_FALSE(m.Matches(&n));
3705 EXPECT_FALSE(m.Matches(NULL));
3708 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3709 const Matcher<double* &> m = Pointee(Ge(0));
3713 EXPECT_TRUE(m.Matches(p));
3715 EXPECT_FALSE(m.Matches(p));
3717 EXPECT_FALSE(m.Matches(p));
3720 MATCHER_P(FieldIIs, inner_matcher, "") {
3721 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3725 TEST(WhenDynamicCastToTest, SameType) {
3729 // Right type. A pointer is passed down.
3730 Base* as_base_ptr = &derived;
3731 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3732 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3733 EXPECT_THAT(as_base_ptr,
3734 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3737 TEST(WhenDynamicCastToTest, WrongTypes) {
3740 OtherDerived other_derived;
3742 // Wrong types. NULL is passed.
3743 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3744 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3745 Base* as_base_ptr = &derived;
3746 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3747 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3748 as_base_ptr = &other_derived;
3749 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3750 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3753 TEST(WhenDynamicCastToTest, AlreadyNull) {
3755 Base* as_base_ptr = NULL;
3756 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3759 struct AmbiguousCastTypes {
3760 class VirtualDerived : public virtual Base {};
3761 class DerivedSub1 : public VirtualDerived {};
3762 class DerivedSub2 : public VirtualDerived {};
3763 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3766 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3767 AmbiguousCastTypes::DerivedSub1 sub1;
3768 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3769 // Multiply derived from Base. dynamic_cast<> returns NULL.
3771 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3772 EXPECT_THAT(as_base_ptr,
3773 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3774 as_base_ptr = &sub1;
3777 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3780 TEST(WhenDynamicCastToTest, Describe) {
3781 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3782 const std::string prefix =
3783 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3784 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3785 EXPECT_EQ(prefix + "does not point to a value that is anything",
3786 DescribeNegation(matcher));
3789 TEST(WhenDynamicCastToTest, Explain) {
3790 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3792 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3794 EXPECT_TRUE(matcher.Matches(&derived));
3795 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3797 // With references, the matcher itself can fail. Test for that one.
3798 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3799 EXPECT_THAT(Explain(ref_matcher, derived),
3800 HasSubstr("which cannot be dynamic_cast"));
3803 TEST(WhenDynamicCastToTest, GoodReference) {
3806 Base& as_base_ref = derived;
3807 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3808 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3811 TEST(WhenDynamicCastToTest, BadReference) {
3813 Base& as_base_ref = derived;
3814 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3816 #endif // GTEST_HAS_RTTI
3818 // Minimal const-propagating pointer.
3819 template <typename T>
3820 class ConstPropagatingPtr {
3822 typedef T element_type;
3824 ConstPropagatingPtr() : val_() {}
3825 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3826 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3828 T* get() { return val_; }
3829 T& operator*() { return *val_; }
3830 // Most smart pointers return non-const T* and T& from the next methods.
3831 const T* get() const { return val_; }
3832 const T& operator*() const { return *val_; }
3838 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3839 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3841 const ConstPropagatingPtr<int> co(&three);
3842 ConstPropagatingPtr<int> o(&three);
3843 EXPECT_TRUE(m.Matches(o));
3844 EXPECT_TRUE(m.Matches(co));
3846 EXPECT_FALSE(m.Matches(o));
3847 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3850 TEST(PointeeTest, NeverMatchesNull) {
3851 const Matcher<const char*> m = Pointee(_);
3852 EXPECT_FALSE(m.Matches(NULL));
3855 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3856 TEST(PointeeTest, MatchesAgainstAValue) {
3857 const Matcher<int*> m = Pointee(5);
3860 EXPECT_TRUE(m.Matches(&n));
3862 EXPECT_FALSE(m.Matches(&n));
3863 EXPECT_FALSE(m.Matches(NULL));
3866 TEST(PointeeTest, CanDescribeSelf) {
3867 const Matcher<int*> m = Pointee(Gt(3));
3868 EXPECT_EQ("points to a value that is > 3", Describe(m));
3869 EXPECT_EQ("does not point to a value that is > 3",
3870 DescribeNegation(m));
3873 TEST(PointeeTest, CanExplainMatchResult) {
3874 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3876 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL)));
3878 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3879 long n = 3; // NOLINT
3880 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3884 TEST(PointeeTest, AlwaysExplainsPointee) {
3885 const Matcher<int*> m = Pointee(0);
3887 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3890 // An uncopyable class.
3893 Uncopyable() : value_(-1) {}
3894 explicit Uncopyable(int a_value) : value_(a_value) {}
3896 int value() const { return value_; }
3897 void set_value(int i) { value_ = i; }
3901 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3904 // Returns true iff x.value() is positive.
3905 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3907 MATCHER_P(UncopyableIs, inner_matcher, "") {
3908 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3911 // A user-defined struct for testing Field().
3913 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3914 AStruct(const AStruct& rhs)
3915 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3917 int x; // A non-const field.
3918 const double y; // A const field.
3919 Uncopyable z; // An uncopyable field.
3920 const char* p; // A pointer field.
3923 GTEST_DISALLOW_ASSIGN_(AStruct);
3926 // A derived struct for testing Field().
3927 struct DerivedStruct : public AStruct {
3931 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3934 // Tests that Field(&Foo::field, ...) works when field is non-const.
3935 TEST(FieldTest, WorksForNonConstField) {
3936 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3937 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
3940 EXPECT_TRUE(m.Matches(a));
3941 EXPECT_TRUE(m_with_name.Matches(a));
3943 EXPECT_FALSE(m.Matches(a));
3944 EXPECT_FALSE(m_with_name.Matches(a));
3947 // Tests that Field(&Foo::field, ...) works when field is const.
3948 TEST(FieldTest, WorksForConstField) {
3951 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3952 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
3953 EXPECT_TRUE(m.Matches(a));
3954 EXPECT_TRUE(m_with_name.Matches(a));
3955 m = Field(&AStruct::y, Le(0.0));
3956 m_with_name = Field("y", &AStruct::y, Le(0.0));
3957 EXPECT_FALSE(m.Matches(a));
3958 EXPECT_FALSE(m_with_name.Matches(a));
3961 // Tests that Field(&Foo::field, ...) works when field is not copyable.
3962 TEST(FieldTest, WorksForUncopyableField) {
3965 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3966 EXPECT_TRUE(m.Matches(a));
3967 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3968 EXPECT_FALSE(m.Matches(a));
3971 // Tests that Field(&Foo::field, ...) works when field is a pointer.
3972 TEST(FieldTest, WorksForPointerField) {
3973 // Matching against NULL.
3974 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3976 EXPECT_TRUE(m.Matches(a));
3978 EXPECT_FALSE(m.Matches(a));
3980 // Matching a pointer that is not NULL.
3981 m = Field(&AStruct::p, StartsWith("hi"));
3983 EXPECT_TRUE(m.Matches(a));
3985 EXPECT_FALSE(m.Matches(a));
3988 // Tests that Field() works when the object is passed by reference.
3989 TEST(FieldTest, WorksForByRefArgument) {
3990 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3993 EXPECT_TRUE(m.Matches(a));
3995 EXPECT_FALSE(m.Matches(a));
3998 // Tests that Field(&Foo::field, ...) works when the argument's type
3999 // is a sub-type of Foo.
4000 TEST(FieldTest, WorksForArgumentOfSubType) {
4001 // Note that the matcher expects DerivedStruct but we say AStruct
4003 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
4006 EXPECT_TRUE(m.Matches(d));
4008 EXPECT_FALSE(m.Matches(d));
4011 // Tests that Field(&Foo::field, m) works when field's type and m's
4012 // argument type are compatible but not the same.
4013 TEST(FieldTest, WorksForCompatibleMatcherType) {
4014 // The field is an int, but the inner matcher expects a signed char.
4015 Matcher<const AStruct&> m = Field(&AStruct::x,
4016 Matcher<signed char>(Ge(0)));
4019 EXPECT_TRUE(m.Matches(a));
4021 EXPECT_FALSE(m.Matches(a));
4024 // Tests that Field() can describe itself.
4025 TEST(FieldTest, CanDescribeSelf) {
4026 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4028 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4029 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4032 TEST(FieldTest, CanDescribeSelfWithFieldName) {
4033 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4035 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4036 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4037 DescribeNegation(m));
4040 // Tests that Field() can explain the match result.
4041 TEST(FieldTest, CanExplainMatchResult) {
4042 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4046 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4048 m = Field(&AStruct::x, GreaterThan(0));
4050 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4054 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4055 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4059 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4061 m = Field("field_name", &AStruct::x, GreaterThan(0));
4062 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4063 ", which is 1 more than 0",
4067 // Tests that Field() works when the argument is a pointer to const.
4068 TEST(FieldForPointerTest, WorksForPointerToConst) {
4069 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4072 EXPECT_TRUE(m.Matches(&a));
4074 EXPECT_FALSE(m.Matches(&a));
4077 // Tests that Field() works when the argument is a pointer to non-const.
4078 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4079 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
4082 EXPECT_TRUE(m.Matches(&a));
4084 EXPECT_FALSE(m.Matches(&a));
4087 // Tests that Field() works when the argument is a reference to a const pointer.
4088 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4089 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
4092 EXPECT_TRUE(m.Matches(&a));
4094 EXPECT_FALSE(m.Matches(&a));
4097 // Tests that Field() does not match the NULL pointer.
4098 TEST(FieldForPointerTest, DoesNotMatchNull) {
4099 Matcher<const AStruct*> m = Field(&AStruct::x, _);
4100 EXPECT_FALSE(m.Matches(NULL));
4103 // Tests that Field(&Foo::field, ...) works when the argument's type
4104 // is a sub-type of const Foo*.
4105 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4106 // Note that the matcher expects DerivedStruct but we say AStruct
4108 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
4111 EXPECT_TRUE(m.Matches(&d));
4113 EXPECT_FALSE(m.Matches(&d));
4116 // Tests that Field() can describe itself when used to match a pointer.
4117 TEST(FieldForPointerTest, CanDescribeSelf) {
4118 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4120 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4121 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4124 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4125 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4127 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4128 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4129 DescribeNegation(m));
4132 // Tests that Field() can explain the result of matching a pointer.
4133 TEST(FieldForPointerTest, CanExplainMatchResult) {
4134 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4138 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
4139 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4142 m = Field(&AStruct::x, GreaterThan(0));
4143 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4144 ", which is 1 more than 0", Explain(m, &a));
4147 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4148 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4152 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
4154 "which points to an object whose field `field_name` is 1" + OfType("int"),
4157 m = Field("field_name", &AStruct::x, GreaterThan(0));
4158 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4159 OfType("int") + ", which is 1 more than 0",
4163 // A user-defined class for testing Property().
4168 // A getter that returns a non-reference.
4169 int n() const { return n_; }
4171 void set_n(int new_n) { n_ = new_n; }
4173 // A getter that returns a reference to const.
4174 const std::string& s() const { return s_; }
4176 #if GTEST_LANG_CXX11
4177 const std::string& s_ref() const & { return s_; }
4180 void set_s(const std::string& new_s) { s_ = new_s; }
4182 // A getter that returns a reference to non-const.
4183 double& x() const { return x_; }
4192 double AClass::x_ = 0.0;
4194 // A derived class for testing Property().
4195 class DerivedClass : public AClass {
4197 int k() const { return k_; }
4202 // Tests that Property(&Foo::property, ...) works when property()
4203 // returns a non-reference.
4204 TEST(PropertyTest, WorksForNonReferenceProperty) {
4205 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4206 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4210 EXPECT_TRUE(m.Matches(a));
4211 EXPECT_TRUE(m_with_name.Matches(a));
4214 EXPECT_FALSE(m.Matches(a));
4215 EXPECT_FALSE(m_with_name.Matches(a));
4218 // Tests that Property(&Foo::property, ...) works when property()
4219 // returns a reference to const.
4220 TEST(PropertyTest, WorksForReferenceToConstProperty) {
4221 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
4222 Matcher<const AClass&> m_with_name =
4223 Property("s", &AClass::s, StartsWith("hi"));
4227 EXPECT_TRUE(m.Matches(a));
4228 EXPECT_TRUE(m_with_name.Matches(a));
4231 EXPECT_FALSE(m.Matches(a));
4232 EXPECT_FALSE(m_with_name.Matches(a));
4235 #if GTEST_LANG_CXX11
4236 // Tests that Property(&Foo::property, ...) works when property() is
4238 TEST(PropertyTest, WorksForRefQualifiedProperty) {
4239 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4240 Matcher<const AClass&> m_with_name =
4241 Property("s", &AClass::s_ref, StartsWith("hi"));
4245 EXPECT_TRUE(m.Matches(a));
4246 EXPECT_TRUE(m_with_name.Matches(a));
4249 EXPECT_FALSE(m.Matches(a));
4250 EXPECT_FALSE(m_with_name.Matches(a));
4254 // Tests that Property(&Foo::property, ...) works when property()
4255 // returns a reference to non-const.
4256 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4260 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4261 EXPECT_FALSE(m.Matches(a));
4263 m = Property(&AClass::x, Not(Ref(x)));
4264 EXPECT_TRUE(m.Matches(a));
4267 // Tests that Property(&Foo::property, ...) works when the argument is
4269 TEST(PropertyTest, WorksForByValueArgument) {
4270 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4274 EXPECT_TRUE(m.Matches(a));
4277 EXPECT_FALSE(m.Matches(a));
4280 // Tests that Property(&Foo::property, ...) works when the argument's
4281 // type is a sub-type of Foo.
4282 TEST(PropertyTest, WorksForArgumentOfSubType) {
4283 // The matcher expects a DerivedClass, but inside the Property() we
4285 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4289 EXPECT_TRUE(m.Matches(d));
4292 EXPECT_FALSE(m.Matches(d));
4295 // Tests that Property(&Foo::property, m) works when property()'s type
4296 // and m's argument type are compatible but different.
4297 TEST(PropertyTest, WorksForCompatibleMatcherType) {
4298 // n() returns an int but the inner matcher expects a signed char.
4299 Matcher<const AClass&> m = Property(&AClass::n,
4300 Matcher<signed char>(Ge(0)));
4302 Matcher<const AClass&> m_with_name =
4303 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4306 EXPECT_TRUE(m.Matches(a));
4307 EXPECT_TRUE(m_with_name.Matches(a));
4309 EXPECT_FALSE(m.Matches(a));
4310 EXPECT_FALSE(m_with_name.Matches(a));
4313 // Tests that Property() can describe itself.
4314 TEST(PropertyTest, CanDescribeSelf) {
4315 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4317 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4318 EXPECT_EQ("is an object whose given property isn't >= 0",
4319 DescribeNegation(m));
4322 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4323 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4325 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4326 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4327 DescribeNegation(m));
4330 // Tests that Property() can explain the match result.
4331 TEST(PropertyTest, CanExplainMatchResult) {
4332 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4336 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4338 m = Property(&AClass::n, GreaterThan(0));
4340 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4344 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4345 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4349 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4351 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4352 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4353 ", which is 1 more than 0",
4357 // Tests that Property() works when the argument is a pointer to const.
4358 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4359 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4363 EXPECT_TRUE(m.Matches(&a));
4366 EXPECT_FALSE(m.Matches(&a));
4369 // Tests that Property() works when the argument is a pointer to non-const.
4370 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4371 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4375 EXPECT_TRUE(m.Matches(&a));
4378 EXPECT_FALSE(m.Matches(&a));
4381 // Tests that Property() works when the argument is a reference to a
4383 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4384 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4388 EXPECT_TRUE(m.Matches(&a));
4391 EXPECT_FALSE(m.Matches(&a));
4394 // Tests that Property() does not match the NULL pointer.
4395 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4396 Matcher<const AClass*> m = Property(&AClass::x, _);
4397 EXPECT_FALSE(m.Matches(NULL));
4400 // Tests that Property(&Foo::property, ...) works when the argument's
4401 // type is a sub-type of const Foo*.
4402 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4403 // The matcher expects a DerivedClass, but inside the Property() we
4405 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4409 EXPECT_TRUE(m.Matches(&d));
4412 EXPECT_FALSE(m.Matches(&d));
4415 // Tests that Property() can describe itself when used to match a pointer.
4416 TEST(PropertyForPointerTest, CanDescribeSelf) {
4417 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4419 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4420 EXPECT_EQ("is an object whose given property isn't >= 0",
4421 DescribeNegation(m));
4424 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4425 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4427 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4428 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4429 DescribeNegation(m));
4432 // Tests that Property() can explain the result of matching a pointer.
4433 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4434 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4438 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
4440 "which points to an object whose given property is 1" + OfType("int"),
4443 m = Property(&AClass::n, GreaterThan(0));
4444 EXPECT_EQ("which points to an object whose given property is 1" +
4445 OfType("int") + ", which is 1 more than 0",
4449 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4450 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4454 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
4455 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4459 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4460 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4461 OfType("int") + ", which is 1 more than 0",
4467 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4468 // function pointer.
4469 std::string IntToStringFunction(int input) {
4470 return input == 1 ? "foo" : "bar";
4473 TEST(ResultOfTest, WorksForFunctionPointers) {
4474 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4476 EXPECT_TRUE(matcher.Matches(1));
4477 EXPECT_FALSE(matcher.Matches(2));
4480 // Tests that ResultOf() can describe itself.
4481 TEST(ResultOfTest, CanDescribeItself) {
4482 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4484 EXPECT_EQ("is mapped by the given callable to a value that "
4485 "is equal to \"foo\"", Describe(matcher));
4486 EXPECT_EQ("is mapped by the given callable to a value that "
4487 "isn't equal to \"foo\"", DescribeNegation(matcher));
4490 // Tests that ResultOf() can explain the match result.
4491 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4493 TEST(ResultOfTest, CanExplainMatchResult) {
4494 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4495 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4496 Explain(matcher, 36));
4498 matcher = ResultOf(&IntFunction, GreaterThan(85));
4499 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4500 ", which is 5 more than 85", Explain(matcher, 36));
4503 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4504 // returns a non-reference.
4505 TEST(ResultOfTest, WorksForNonReferenceResults) {
4506 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4508 EXPECT_TRUE(matcher.Matches(42));
4509 EXPECT_FALSE(matcher.Matches(36));
4512 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4513 // returns a reference to non-const.
4514 double& DoubleFunction(double& input) { return input; } // NOLINT
4516 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
4520 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4523 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4525 EXPECT_TRUE(matcher.Matches(x));
4526 EXPECT_FALSE(matcher.Matches(x2));
4528 // Test that ResultOf works with uncopyable objects
4531 Matcher<Uncopyable&> matcher2 =
4532 ResultOf(&RefUncopyableFunction, Ref(obj));
4534 EXPECT_TRUE(matcher2.Matches(obj));
4535 EXPECT_FALSE(matcher2.Matches(obj2));
4538 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4539 // returns a reference to const.
4540 const std::string& StringFunction(const std::string& input) { return input; }
4542 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4543 std::string s = "foo";
4545 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4547 EXPECT_TRUE(matcher.Matches(s));
4548 EXPECT_FALSE(matcher.Matches(s2));
4551 // Tests that ResultOf(f, m) works when f(x) and m's
4552 // argument types are compatible but different.
4553 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4554 // IntFunction() returns int but the inner matcher expects a signed char.
4555 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4557 EXPECT_TRUE(matcher.Matches(36));
4558 EXPECT_FALSE(matcher.Matches(42));
4561 // Tests that the program aborts when ResultOf is passed
4562 // a NULL function pointer.
4563 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4564 EXPECT_DEATH_IF_SUPPORTED(
4565 ResultOf(static_cast<std::string (*)(int dummy)>(NULL),
4566 Eq(std::string("foo"))),
4567 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4570 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4571 // function reference.
4572 TEST(ResultOfTest, WorksForFunctionReferences) {
4573 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4574 EXPECT_TRUE(matcher.Matches(1));
4575 EXPECT_FALSE(matcher.Matches(2));
4578 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4580 struct Functor : public ::std::unary_function<int, std::string> {
4581 result_type operator()(argument_type input) const {
4582 return IntToStringFunction(input);
4586 TEST(ResultOfTest, WorksForFunctors) {
4587 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4589 EXPECT_TRUE(matcher.Matches(1));
4590 EXPECT_FALSE(matcher.Matches(2));
4593 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4594 // functor with more than one operator() defined. ResultOf() must work
4595 // for each defined operator().
4596 struct PolymorphicFunctor {
4597 typedef int result_type;
4598 int operator()(int n) { return n; }
4599 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
4600 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4603 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4604 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4606 EXPECT_TRUE(matcher_int.Matches(10));
4607 EXPECT_FALSE(matcher_int.Matches(2));
4609 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4611 EXPECT_TRUE(matcher_string.Matches("long string"));
4612 EXPECT_FALSE(matcher_string.Matches("shrt"));
4615 #if GTEST_LANG_CXX11
4616 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4617 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4620 EXPECT_TRUE(matcher.Matches(&n));
4621 EXPECT_FALSE(matcher.Matches(nullptr));
4624 TEST(ResultOfTest, WorksForLambdas) {
4625 Matcher<int> matcher =
4626 ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx");
4627 EXPECT_TRUE(matcher.Matches(3));
4628 EXPECT_FALSE(matcher.Matches(1));
4632 const int* ReferencingFunction(const int& n) { return &n; }
4634 struct ReferencingFunctor {
4635 typedef const int* result_type;
4636 result_type operator()(const int& n) { return &n; }
4639 TEST(ResultOfTest, WorksForReferencingCallables) {
4642 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4643 EXPECT_TRUE(matcher2.Matches(n));
4644 EXPECT_FALSE(matcher2.Matches(n2));
4646 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4647 EXPECT_TRUE(matcher3.Matches(n));
4648 EXPECT_FALSE(matcher3.Matches(n2));
4651 class DivisibleByImpl {
4653 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4655 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4656 template <typename T>
4657 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4658 *listener << "which is " << (n % divider_) << " modulo "
4660 return (n % divider_) == 0;
4663 void DescribeTo(ostream* os) const {
4664 *os << "is divisible by " << divider_;
4667 void DescribeNegationTo(ostream* os) const {
4668 *os << "is not divisible by " << divider_;
4671 void set_divider(int a_divider) { divider_ = a_divider; }
4672 int divider() const { return divider_; }
4678 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4679 return MakePolymorphicMatcher(DivisibleByImpl(n));
4682 // Tests that when AllOf() fails, only the first failing matcher is
4683 // asked to explain why.
4684 TEST(ExplainMatchResultTest, AllOf_False_False) {
4685 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4686 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4689 // Tests that when AllOf() fails, only the first failing matcher is
4690 // asked to explain why.
4691 TEST(ExplainMatchResultTest, AllOf_False_True) {
4692 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4693 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4696 // Tests that when AllOf() fails, only the first failing matcher is
4697 // asked to explain why.
4698 TEST(ExplainMatchResultTest, AllOf_True_False) {
4699 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4700 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4703 // Tests that when AllOf() succeeds, all matchers are asked to explain
4705 TEST(ExplainMatchResultTest, AllOf_True_True) {
4706 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4707 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4710 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4711 const Matcher<int> m = AllOf(Ge(2), Le(3));
4712 EXPECT_EQ("", Explain(m, 2));
4715 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4716 const Matcher<int> m = GreaterThan(5);
4717 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4720 // The following two tests verify that values without a public copy
4721 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4722 // with the help of ByRef().
4726 explicit NotCopyable(int a_value) : value_(a_value) {}
4728 int value() const { return value_; }
4730 bool operator==(const NotCopyable& rhs) const {
4731 return value() == rhs.value();
4734 bool operator>=(const NotCopyable& rhs) const {
4735 return value() >= rhs.value();
4740 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4743 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4744 const NotCopyable const_value1(1);
4745 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4747 const NotCopyable n1(1), n2(2);
4748 EXPECT_TRUE(m.Matches(n1));
4749 EXPECT_FALSE(m.Matches(n2));
4752 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4753 NotCopyable value2(2);
4754 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4756 NotCopyable n1(1), n2(2);
4757 EXPECT_FALSE(m.Matches(n1));
4758 EXPECT_TRUE(m.Matches(n2));
4761 TEST(IsEmptyTest, ImplementsIsEmpty) {
4762 vector<int> container;
4763 EXPECT_THAT(container, IsEmpty());
4764 container.push_back(0);
4765 EXPECT_THAT(container, Not(IsEmpty()));
4766 container.push_back(1);
4767 EXPECT_THAT(container, Not(IsEmpty()));
4770 TEST(IsEmptyTest, WorksWithString) {
4772 EXPECT_THAT(text, IsEmpty());
4774 EXPECT_THAT(text, Not(IsEmpty()));
4775 text = std::string("\0", 1);
4776 EXPECT_THAT(text, Not(IsEmpty()));
4779 TEST(IsEmptyTest, CanDescribeSelf) {
4780 Matcher<vector<int> > m = IsEmpty();
4781 EXPECT_EQ("is empty", Describe(m));
4782 EXPECT_EQ("isn't empty", DescribeNegation(m));
4785 TEST(IsEmptyTest, ExplainsResult) {
4786 Matcher<vector<int> > m = IsEmpty();
4787 vector<int> container;
4788 EXPECT_EQ("", Explain(m, container));
4789 container.push_back(0);
4790 EXPECT_EQ("whose size is 1", Explain(m, container));
4793 TEST(IsTrueTest, IsTrueIsFalse) {
4794 EXPECT_THAT(true, IsTrue());
4795 EXPECT_THAT(false, IsFalse());
4796 EXPECT_THAT(true, Not(IsFalse()));
4797 EXPECT_THAT(false, Not(IsTrue()));
4798 EXPECT_THAT(0, Not(IsTrue()));
4799 EXPECT_THAT(0, IsFalse());
4800 EXPECT_THAT(NULL, Not(IsTrue()));
4801 EXPECT_THAT(NULL, IsFalse());
4802 EXPECT_THAT(-1, IsTrue());
4803 EXPECT_THAT(-1, Not(IsFalse()));
4804 EXPECT_THAT(1, IsTrue());
4805 EXPECT_THAT(1, Not(IsFalse()));
4806 EXPECT_THAT(2, IsTrue());
4807 EXPECT_THAT(2, Not(IsFalse()));
4809 EXPECT_THAT(a, IsTrue());
4810 EXPECT_THAT(a, Not(IsFalse()));
4811 EXPECT_THAT(&a, IsTrue());
4812 EXPECT_THAT(&a, Not(IsFalse()));
4813 EXPECT_THAT(false, Not(IsTrue()));
4814 EXPECT_THAT(true, Not(IsFalse()));
4815 #if GTEST_LANG_CXX11
4816 EXPECT_THAT(std::true_type(), IsTrue());
4817 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4818 EXPECT_THAT(std::false_type(), IsFalse());
4819 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4820 EXPECT_THAT(nullptr, Not(IsTrue()));
4821 EXPECT_THAT(nullptr, IsFalse());
4822 std::unique_ptr<int> null_unique;
4823 std::unique_ptr<int> nonnull_unique(new int(0));
4824 EXPECT_THAT(null_unique, Not(IsTrue()));
4825 EXPECT_THAT(null_unique, IsFalse());
4826 EXPECT_THAT(nonnull_unique, IsTrue());
4827 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4828 #endif // GTEST_LANG_CXX11
4831 TEST(SizeIsTest, ImplementsSizeIs) {
4832 vector<int> container;
4833 EXPECT_THAT(container, SizeIs(0));
4834 EXPECT_THAT(container, Not(SizeIs(1)));
4835 container.push_back(0);
4836 EXPECT_THAT(container, Not(SizeIs(0)));
4837 EXPECT_THAT(container, SizeIs(1));
4838 container.push_back(0);
4839 EXPECT_THAT(container, Not(SizeIs(0)));
4840 EXPECT_THAT(container, SizeIs(2));
4843 TEST(SizeIsTest, WorksWithMap) {
4844 map<std::string, int> container;
4845 EXPECT_THAT(container, SizeIs(0));
4846 EXPECT_THAT(container, Not(SizeIs(1)));
4847 container.insert(make_pair("foo", 1));
4848 EXPECT_THAT(container, Not(SizeIs(0)));
4849 EXPECT_THAT(container, SizeIs(1));
4850 container.insert(make_pair("bar", 2));
4851 EXPECT_THAT(container, Not(SizeIs(0)));
4852 EXPECT_THAT(container, SizeIs(2));
4855 TEST(SizeIsTest, WorksWithReferences) {
4856 vector<int> container;
4857 Matcher<const vector<int>&> m = SizeIs(1);
4858 EXPECT_THAT(container, Not(m));
4859 container.push_back(0);
4860 EXPECT_THAT(container, m);
4863 TEST(SizeIsTest, CanDescribeSelf) {
4864 Matcher<vector<int> > m = SizeIs(2);
4865 EXPECT_EQ("size is equal to 2", Describe(m));
4866 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4869 TEST(SizeIsTest, ExplainsResult) {
4870 Matcher<vector<int> > m1 = SizeIs(2);
4871 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4872 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4873 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4874 vector<int> container;
4875 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4876 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4877 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4878 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4879 Explain(m4, container));
4880 container.push_back(0);
4881 container.push_back(0);
4882 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4883 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4884 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4885 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4886 Explain(m4, container));
4889 #if GTEST_HAS_TYPED_TEST
4890 // Tests ContainerEq with different container types, and
4891 // different element types.
4893 template <typename T>
4894 class ContainerEqTest : public testing::Test {};
4896 typedef testing::Types<
4901 ContainerEqTestTypes;
4903 TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4905 // Tests that the filled container is equal to itself.
4906 TYPED_TEST(ContainerEqTest, EqualsSelf) {
4907 static const int vals[] = {1, 1, 2, 3, 5, 8};
4908 TypeParam my_set(vals, vals + 6);
4909 const Matcher<TypeParam> m = ContainerEq(my_set);
4910 EXPECT_TRUE(m.Matches(my_set));
4911 EXPECT_EQ("", Explain(m, my_set));
4914 // Tests that missing values are reported.
4915 TYPED_TEST(ContainerEqTest, ValueMissing) {
4916 static const int vals[] = {1, 1, 2, 3, 5, 8};
4917 static const int test_vals[] = {2, 1, 8, 5};
4918 TypeParam my_set(vals, vals + 6);
4919 TypeParam test_set(test_vals, test_vals + 4);
4920 const Matcher<TypeParam> m = ContainerEq(my_set);
4921 EXPECT_FALSE(m.Matches(test_set));
4922 EXPECT_EQ("which doesn't have these expected elements: 3",
4923 Explain(m, test_set));
4926 // Tests that added values are reported.
4927 TYPED_TEST(ContainerEqTest, ValueAdded) {
4928 static const int vals[] = {1, 1, 2, 3, 5, 8};
4929 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4930 TypeParam my_set(vals, vals + 6);
4931 TypeParam test_set(test_vals, test_vals + 6);
4932 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4933 EXPECT_FALSE(m.Matches(test_set));
4934 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4937 // Tests that added and missing values are reported together.
4938 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4939 static const int vals[] = {1, 1, 2, 3, 5, 8};
4940 static const int test_vals[] = {1, 2, 3, 8, 46};
4941 TypeParam my_set(vals, vals + 6);
4942 TypeParam test_set(test_vals, test_vals + 5);
4943 const Matcher<TypeParam> m = ContainerEq(my_set);
4944 EXPECT_FALSE(m.Matches(test_set));
4945 EXPECT_EQ("which has these unexpected elements: 46,\n"
4946 "and doesn't have these expected elements: 5",
4947 Explain(m, test_set));
4950 // Tests duplicated value -- expect no explanation.
4951 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4952 static const int vals[] = {1, 1, 2, 3, 5, 8};
4953 static const int test_vals[] = {1, 2, 3, 5, 8};
4954 TypeParam my_set(vals, vals + 6);
4955 TypeParam test_set(test_vals, test_vals + 5);
4956 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4957 // Depending on the container, match may be true or false
4958 // But in any case there should be no explanation.
4959 EXPECT_EQ("", Explain(m, test_set));
4961 #endif // GTEST_HAS_TYPED_TEST
4963 // Tests that mutliple missing values are reported.
4964 // Using just vector here, so order is predictable.
4965 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4966 static const int vals[] = {1, 1, 2, 3, 5, 8};
4967 static const int test_vals[] = {2, 1, 5};
4968 vector<int> my_set(vals, vals + 6);
4969 vector<int> test_set(test_vals, test_vals + 3);
4970 const Matcher<vector<int> > m = ContainerEq(my_set);
4971 EXPECT_FALSE(m.Matches(test_set));
4972 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4973 Explain(m, test_set));
4976 // Tests that added values are reported.
4977 // Using just vector here, so order is predictable.
4978 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4979 static const int vals[] = {1, 1, 2, 3, 5, 8};
4980 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4981 list<size_t> my_set(vals, vals + 6);
4982 list<size_t> test_set(test_vals, test_vals + 7);
4983 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4984 EXPECT_FALSE(m.Matches(test_set));
4985 EXPECT_EQ("which has these unexpected elements: 92, 46",
4986 Explain(m, test_set));
4989 // Tests that added and missing values are reported together.
4990 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4991 static const int vals[] = {1, 1, 2, 3, 5, 8};
4992 static const int test_vals[] = {1, 2, 3, 92, 46};
4993 list<size_t> my_set(vals, vals + 6);
4994 list<size_t> test_set(test_vals, test_vals + 5);
4995 const Matcher<const list<size_t> > m = ContainerEq(my_set);
4996 EXPECT_FALSE(m.Matches(test_set));
4997 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4998 "and doesn't have these expected elements: 5, 8",
4999 Explain(m, test_set));
5002 // Tests to see that duplicate elements are detected,
5003 // but (as above) not reported in the explanation.
5004 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
5005 static const int vals[] = {1, 1, 2, 3, 5, 8};
5006 static const int test_vals[] = {1, 2, 3, 5, 8};
5007 vector<int> my_set(vals, vals + 6);
5008 vector<int> test_set(test_vals, test_vals + 5);
5009 const Matcher<vector<int> > m = ContainerEq(my_set);
5010 EXPECT_TRUE(m.Matches(my_set));
5011 EXPECT_FALSE(m.Matches(test_set));
5012 // There is nothing to report when both sets contain all the same values.
5013 EXPECT_EQ("", Explain(m, test_set));
5016 // Tests that ContainerEq works for non-trivial associative containers,
5018 TEST(ContainerEqExtraTest, WorksForMaps) {
5019 map<int, std::string> my_map;
5023 map<int, std::string> test_map;
5027 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
5028 EXPECT_TRUE(m.Matches(my_map));
5029 EXPECT_FALSE(m.Matches(test_map));
5031 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
5032 "and doesn't have these expected elements: (0, \"a\")",
5033 Explain(m, test_map));
5036 TEST(ContainerEqExtraTest, WorksForNativeArray) {
5037 int a1[] = {1, 2, 3};
5038 int a2[] = {1, 2, 3};
5039 int b[] = {1, 2, 4};
5041 EXPECT_THAT(a1, ContainerEq(a2));
5042 EXPECT_THAT(a1, Not(ContainerEq(b)));
5045 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5046 const char a1[][3] = {"hi", "lo"};
5047 const char a2[][3] = {"hi", "lo"};
5048 const char b[][3] = {"lo", "hi"};
5050 // Tests using ContainerEq() in the first dimension.
5051 EXPECT_THAT(a1, ContainerEq(a2));
5052 EXPECT_THAT(a1, Not(ContainerEq(b)));
5054 // Tests using ContainerEq() in the second dimension.
5055 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5056 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5059 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5060 const int a1[] = {1, 2, 3};
5061 const int a2[] = {1, 2, 3};
5062 const int b[] = {1, 2, 3, 4};
5064 const int* const p1 = a1;
5065 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
5066 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
5068 const int c[] = {1, 3, 2};
5069 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
5072 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5073 std::string a1[][3] = {
5074 {"hi", "hello", "ciao"},
5075 {"bye", "see you", "ciao"}
5078 std::string a2[][3] = {
5079 {"hi", "hello", "ciao"},
5080 {"bye", "see you", "ciao"}
5083 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5090 TEST(WhenSortedByTest, WorksForEmptyContainer) {
5091 const vector<int> numbers;
5092 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
5093 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
5096 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
5097 vector<unsigned> numbers;
5098 numbers.push_back(3);
5099 numbers.push_back(1);
5100 numbers.push_back(2);
5101 numbers.push_back(2);
5102 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
5103 ElementsAre(3, 2, 2, 1)));
5104 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
5105 ElementsAre(1, 2, 2, 3))));
5108 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
5109 list<std::string> words;
5110 words.push_back("say");
5111 words.push_back("hello");
5112 words.push_back("world");
5113 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
5114 ElementsAre("hello", "say", "world")));
5115 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
5116 ElementsAre("say", "hello", "world"))));
5119 TEST(WhenSortedByTest, WorksForNativeArray) {
5120 const int numbers[] = {1, 3, 2, 4};
5121 const int sorted_numbers[] = {1, 2, 3, 4};
5122 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
5123 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
5124 ElementsAreArray(sorted_numbers)));
5125 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5128 TEST(WhenSortedByTest, CanDescribeSelf) {
5129 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
5130 EXPECT_EQ("(when sorted) has 2 elements where\n"
5131 "element #0 is equal to 1,\n"
5132 "element #1 is equal to 2",
5134 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5135 "element #0 isn't equal to 1, or\n"
5136 "element #1 isn't equal to 2",
5137 DescribeNegation(m));
5140 TEST(WhenSortedByTest, ExplainsMatchResult) {
5141 const int a[] = {2, 1};
5142 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5143 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
5144 EXPECT_EQ("which is { 1, 2 } when sorted",
5145 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
5148 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5149 // need to test it as exhaustively as we test the latter.
5151 TEST(WhenSortedTest, WorksForEmptyContainer) {
5152 const vector<int> numbers;
5153 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5154 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5157 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
5158 list<std::string> words;
5159 words.push_back("3");
5160 words.push_back("1");
5161 words.push_back("2");
5162 words.push_back("2");
5163 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
5164 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5167 TEST(WhenSortedTest, WorksForMapTypes) {
5168 map<std::string, int> word_counts;
5169 word_counts["and"] = 1;
5170 word_counts["the"] = 1;
5171 word_counts["buffalo"] = 2;
5172 EXPECT_THAT(word_counts,
5173 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5175 EXPECT_THAT(word_counts,
5176 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5177 Pair("buffalo", 2)))));
5180 TEST(WhenSortedTest, WorksForMultiMapTypes) {
5181 multimap<int, int> ifib;
5182 ifib.insert(make_pair(8, 6));
5183 ifib.insert(make_pair(2, 3));
5184 ifib.insert(make_pair(1, 1));
5185 ifib.insert(make_pair(3, 4));
5186 ifib.insert(make_pair(1, 2));
5187 ifib.insert(make_pair(5, 5));
5188 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5194 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5202 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5206 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5207 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5210 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5214 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5215 EXPECT_THAT(d, WhenSorted(vector_match));
5216 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5217 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5220 // Deliberately bare pseudo-container.
5221 // Offers only begin() and end() accessors, yielding InputIterator.
5222 template <typename T>
5227 typedef ConstIter const_iterator;
5228 typedef T value_type;
5230 template <typename InIter>
5231 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5233 const_iterator begin() const {
5234 return const_iterator(this, remainder_.begin());
5236 const_iterator end() const {
5237 return const_iterator(this, remainder_.end());
5241 class ConstIter : public std::iterator<std::input_iterator_tag,
5245 const value_type&> {
5247 ConstIter(const Streamlike* s,
5248 typename std::list<value_type>::iterator pos)
5249 : s_(s), pos_(pos) {}
5251 const value_type& operator*() const { return *pos_; }
5252 const value_type* operator->() const { return &*pos_; }
5253 ConstIter& operator++() {
5254 s_->remainder_.erase(pos_++);
5258 // *iter++ is required to work (see std::istreambuf_iterator).
5259 // (void)iter++ is also required to work.
5260 class PostIncrProxy {
5262 explicit PostIncrProxy(const value_type& value) : value_(value) {}
5263 value_type operator*() const { return value_; }
5267 PostIncrProxy operator++(int) {
5268 PostIncrProxy proxy(**this);
5273 friend bool operator==(const ConstIter& a, const ConstIter& b) {
5274 return a.s_ == b.s_ && a.pos_ == b.pos_;
5276 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5281 const Streamlike* s_;
5282 typename std::list<value_type>::iterator pos_;
5285 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5287 typedef typename std::list<value_type>::const_iterator Iter;
5288 const char* sep = "";
5289 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5297 mutable std::list<value_type> remainder_; // modified by iteration
5300 TEST(StreamlikeTest, Iteration) {
5301 const int a[5] = {2, 1, 4, 5, 3};
5302 Streamlike<int> s(a, a + 5);
5303 Streamlike<int>::const_iterator it = s.begin();
5305 while (it != s.end()) {
5306 SCOPED_TRACE(ip - a);
5307 EXPECT_EQ(*ip++, *it++);
5311 #if GTEST_HAS_STD_FORWARD_LIST_
5312 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5313 std::forward_list<int> container;
5314 EXPECT_THAT(container, BeginEndDistanceIs(0));
5315 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5316 container.push_front(0);
5317 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5318 EXPECT_THAT(container, BeginEndDistanceIs(1));
5319 container.push_front(0);
5320 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5321 EXPECT_THAT(container, BeginEndDistanceIs(2));
5323 #endif // GTEST_HAS_STD_FORWARD_LIST_
5325 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5326 const int a[5] = {1, 2, 3, 4, 5};
5327 Streamlike<int> s(a, a + 5);
5328 EXPECT_THAT(s, BeginEndDistanceIs(5));
5331 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5332 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5333 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5334 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5335 DescribeNegation(m));
5338 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5339 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5340 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5341 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5342 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5343 vector<int> container;
5344 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5345 Explain(m1, container));
5346 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5347 Explain(m2, container));
5348 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5349 Explain(m3, container));
5351 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5353 Explain(m4, container));
5354 container.push_back(0);
5355 container.push_back(0);
5356 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5357 Explain(m1, container));
5358 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5359 Explain(m2, container));
5360 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5361 Explain(m3, container));
5363 "whose distance between begin() and end() 2 matches, which is 1 more "
5365 Explain(m4, container));
5368 TEST(WhenSortedTest, WorksForStreamlike) {
5369 // Streamlike 'container' provides only minimal iterator support.
5370 // Its iterators are tagged with input_iterator_tag.
5371 const int a[5] = {2, 1, 4, 5, 3};
5372 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5373 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5374 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5377 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5378 const int a[] = {2, 1, 4, 5, 3};
5379 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5380 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5381 EXPECT_THAT(s, WhenSorted(vector_match));
5382 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5385 TEST(IsSupersetOfTest, WorksForNativeArray) {
5386 const int subset[] = {1, 4};
5387 const int superset[] = {1, 2, 4};
5388 const int disjoint[] = {1, 0, 3};
5389 EXPECT_THAT(subset, IsSupersetOf(subset));
5390 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5391 EXPECT_THAT(superset, IsSupersetOf(subset));
5392 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5393 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5396 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5397 const int not_enough[] = {1, 2};
5398 const int enough[] = {1, 1, 2};
5399 const int expected[] = {1, 1};
5400 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5401 EXPECT_THAT(enough, IsSupersetOf(expected));
5404 TEST(IsSupersetOfTest, WorksForEmpty) {
5405 vector<int> numbers;
5406 vector<int> expected;
5407 EXPECT_THAT(numbers, IsSupersetOf(expected));
5408 expected.push_back(1);
5409 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5411 numbers.push_back(1);
5412 numbers.push_back(2);
5413 EXPECT_THAT(numbers, IsSupersetOf(expected));
5414 expected.push_back(1);
5415 EXPECT_THAT(numbers, IsSupersetOf(expected));
5416 expected.push_back(2);
5417 EXPECT_THAT(numbers, IsSupersetOf(expected));
5418 expected.push_back(3);
5419 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5422 TEST(IsSupersetOfTest, WorksForStreamlike) {
5423 const int a[5] = {1, 2, 3, 4, 5};
5424 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5426 vector<int> expected;
5427 expected.push_back(1);
5428 expected.push_back(2);
5429 expected.push_back(5);
5430 EXPECT_THAT(s, IsSupersetOf(expected));
5432 expected.push_back(0);
5433 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5436 TEST(IsSupersetOfTest, TakesStlContainer) {
5437 const int actual[] = {3, 1, 2};
5439 ::std::list<int> expected;
5440 expected.push_back(1);
5441 expected.push_back(3);
5442 EXPECT_THAT(actual, IsSupersetOf(expected));
5444 expected.push_back(4);
5445 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5448 TEST(IsSupersetOfTest, Describe) {
5449 typedef std::vector<int> IntVec;
5451 expected.push_back(111);
5452 expected.push_back(222);
5453 expected.push_back(333);
5455 Describe<IntVec>(IsSupersetOf(expected)),
5456 Eq("a surjection from elements to requirements exists such that:\n"
5457 " - an element is equal to 111\n"
5458 " - an element is equal to 222\n"
5459 " - an element is equal to 333"));
5462 TEST(IsSupersetOfTest, DescribeNegation) {
5463 typedef std::vector<int> IntVec;
5465 expected.push_back(111);
5466 expected.push_back(222);
5467 expected.push_back(333);
5469 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5470 Eq("no surjection from elements to requirements exists such that:\n"
5471 " - an element is equal to 111\n"
5472 " - an element is equal to 222\n"
5473 " - an element is equal to 333"));
5476 TEST(IsSupersetOfTest, MatchAndExplain) {
5480 std::vector<int> expected;
5481 expected.push_back(1);
5482 expected.push_back(2);
5483 StringMatchResultListener listener;
5484 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5486 EXPECT_THAT(listener.str(),
5487 Eq("where the following matchers don't match any elements:\n"
5488 "matcher #0: is equal to 1"));
5492 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5494 EXPECT_THAT(listener.str(), Eq("where:\n"
5495 " - element #0 is matched by matcher #1,\n"
5496 " - element #2 is matched by matcher #0"));
5499 #if GTEST_HAS_STD_INITIALIZER_LIST_
5500 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5501 const int numbers[] = {1, 3, 6, 2, 4, 5};
5502 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5503 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5507 TEST(IsSubsetOfTest, WorksForNativeArray) {
5508 const int subset[] = {1, 4};
5509 const int superset[] = {1, 2, 4};
5510 const int disjoint[] = {1, 0, 3};
5511 EXPECT_THAT(subset, IsSubsetOf(subset));
5512 EXPECT_THAT(subset, IsSubsetOf(superset));
5513 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5514 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5515 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5518 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5519 const int not_enough[] = {1, 2};
5520 const int enough[] = {1, 1, 2};
5521 const int actual[] = {1, 1};
5522 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5523 EXPECT_THAT(actual, IsSubsetOf(enough));
5526 TEST(IsSubsetOfTest, WorksForEmpty) {
5527 vector<int> numbers;
5528 vector<int> expected;
5529 EXPECT_THAT(numbers, IsSubsetOf(expected));
5530 expected.push_back(1);
5531 EXPECT_THAT(numbers, IsSubsetOf(expected));
5533 numbers.push_back(1);
5534 numbers.push_back(2);
5535 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5536 expected.push_back(1);
5537 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5538 expected.push_back(2);
5539 EXPECT_THAT(numbers, IsSubsetOf(expected));
5540 expected.push_back(3);
5541 EXPECT_THAT(numbers, IsSubsetOf(expected));
5544 TEST(IsSubsetOfTest, WorksForStreamlike) {
5545 const int a[5] = {1, 2};
5546 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5548 vector<int> expected;
5549 expected.push_back(1);
5550 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5551 expected.push_back(2);
5552 expected.push_back(5);
5553 EXPECT_THAT(s, IsSubsetOf(expected));
5556 TEST(IsSubsetOfTest, TakesStlContainer) {
5557 const int actual[] = {3, 1, 2};
5559 ::std::list<int> expected;
5560 expected.push_back(1);
5561 expected.push_back(3);
5562 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5564 expected.push_back(2);
5565 expected.push_back(4);
5566 EXPECT_THAT(actual, IsSubsetOf(expected));
5569 TEST(IsSubsetOfTest, Describe) {
5570 typedef std::vector<int> IntVec;
5572 expected.push_back(111);
5573 expected.push_back(222);
5574 expected.push_back(333);
5577 Describe<IntVec>(IsSubsetOf(expected)),
5578 Eq("an injection from elements to requirements exists such that:\n"
5579 " - an element is equal to 111\n"
5580 " - an element is equal to 222\n"
5581 " - an element is equal to 333"));
5584 TEST(IsSubsetOfTest, DescribeNegation) {
5585 typedef std::vector<int> IntVec;
5587 expected.push_back(111);
5588 expected.push_back(222);
5589 expected.push_back(333);
5591 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5592 Eq("no injection from elements to requirements exists such that:\n"
5593 " - an element is equal to 111\n"
5594 " - an element is equal to 222\n"
5595 " - an element is equal to 333"));
5598 TEST(IsSubsetOfTest, MatchAndExplain) {
5602 std::vector<int> expected;
5603 expected.push_back(1);
5604 expected.push_back(2);
5605 StringMatchResultListener listener;
5606 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5608 EXPECT_THAT(listener.str(),
5609 Eq("where the following elements don't match any matchers:\n"
5612 expected.push_back(3);
5614 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5616 EXPECT_THAT(listener.str(), Eq("where:\n"
5617 " - element #0 is matched by matcher #1,\n"
5618 " - element #1 is matched by matcher #2"));
5621 #if GTEST_HAS_STD_INITIALIZER_LIST_
5622 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5623 const int numbers[] = {1, 2, 3};
5624 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5625 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5629 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5632 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5633 const int a[5] = {1, 2, 3, 4, 5};
5634 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5635 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5636 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5639 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5640 const int a[5] = {1, 2, 3, 4, 5};
5641 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5643 vector<int> expected;
5644 expected.push_back(1);
5645 expected.push_back(2);
5646 expected.push_back(3);
5647 expected.push_back(4);
5648 expected.push_back(5);
5649 EXPECT_THAT(s, ElementsAreArray(expected));
5652 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5655 TEST(ElementsAreTest, WorksWithUncopyable) {
5657 objs[0].set_value(-3);
5658 objs[1].set_value(1);
5659 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5662 TEST(ElementsAreTest, TakesStlContainer) {
5663 const int actual[] = {3, 1, 2};
5665 ::std::list<int> expected;
5666 expected.push_back(3);
5667 expected.push_back(1);
5668 expected.push_back(2);
5669 EXPECT_THAT(actual, ElementsAreArray(expected));
5671 expected.push_back(4);
5672 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5675 // Tests for UnorderedElementsAreArray()
5677 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5678 const int a[] = {0, 1, 2, 3, 4};
5679 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5681 StringMatchResultListener listener;
5682 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5683 s, &listener)) << listener.str();
5684 } while (std::next_permutation(s.begin(), s.end()));
5687 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5688 const bool a[] = {0, 1, 0, 1, 1};
5689 const bool b[] = {1, 0, 1, 1, 0};
5690 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
5691 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
5692 StringMatchResultListener listener;
5693 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5694 actual, &listener)) << listener.str();
5697 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5698 // Streamlike 'container' provides only minimal iterator support.
5699 // Its iterators are tagged with input_iterator_tag, and it has no
5700 // size() or empty() methods.
5701 const int a[5] = {2, 1, 4, 5, 3};
5702 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5704 ::std::vector<int> expected;
5705 expected.push_back(1);
5706 expected.push_back(2);
5707 expected.push_back(3);
5708 expected.push_back(4);
5709 expected.push_back(5);
5710 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5712 expected.push_back(6);
5713 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5716 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5717 const int actual[] = {3, 1, 2};
5719 ::std::list<int> expected;
5720 expected.push_back(1);
5721 expected.push_back(2);
5722 expected.push_back(3);
5723 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5725 expected.push_back(4);
5726 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5729 #if GTEST_HAS_STD_INITIALIZER_LIST_
5731 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5732 const int a[5] = {2, 1, 4, 5, 3};
5733 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5734 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5737 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5738 const std::string a[5] = {"a", "b", "c", "d", "e"};
5739 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5740 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5743 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5744 const int a[5] = {2, 1, 4, 5, 3};
5745 EXPECT_THAT(a, UnorderedElementsAreArray(
5746 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5747 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5748 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5751 TEST(UnorderedElementsAreArrayTest,
5752 TakesInitializerListOfDifferentTypedMatchers) {
5753 const int a[5] = {2, 1, 4, 5, 3};
5754 // The compiler cannot infer the type of the initializer list if its
5755 // elements have different types. We must explicitly specify the
5756 // unified element type in this case.
5757 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5758 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5759 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5760 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5763 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
5765 class UnorderedElementsAreTest : public testing::Test {
5767 typedef std::vector<int> IntVec;
5770 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5772 objs[0].set_value(-3);
5773 objs[1].set_value(1);
5775 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5778 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5779 const int a[] = {1, 2, 3};
5780 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5782 StringMatchResultListener listener;
5783 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5784 s, &listener)) << listener.str();
5785 } while (std::next_permutation(s.begin(), s.end()));
5788 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5789 const int a[] = {1, 2, 3};
5790 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5791 std::vector<Matcher<int> > mv;
5795 // The element with value '3' matches nothing: fail fast.
5796 StringMatchResultListener listener;
5797 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5798 s, &listener)) << listener.str();
5801 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5802 // Streamlike 'container' provides only minimal iterator support.
5803 // Its iterators are tagged with input_iterator_tag, and it has no
5804 // size() or empty() methods.
5805 const int a[5] = {2, 1, 4, 5, 3};
5806 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5808 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5809 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5812 // One naive implementation of the matcher runs in O(N!) time, which is too
5813 // slow for many real-world inputs. This test shows that our matcher can match
5814 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5815 // iterations and obviously effectively incomputable.
5816 // [ RUN ] UnorderedElementsAreTest.Performance
5817 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
5818 TEST_F(UnorderedElementsAreTest, Performance) {
5820 std::vector<Matcher<int> > mv;
5821 for (int i = 0; i < 100; ++i) {
5826 StringMatchResultListener listener;
5827 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5828 s, &listener)) << listener.str();
5831 // Another variant of 'Performance' with similar expectations.
5832 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5833 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
5834 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5836 std::vector<Matcher<int> > mv;
5837 for (int i = 0; i < 100; ++i) {
5845 StringMatchResultListener listener;
5846 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5847 s, &listener)) << listener.str();
5850 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5853 StringMatchResultListener listener;
5854 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5855 v, &listener)) << listener.str();
5856 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5859 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5861 StringMatchResultListener listener;
5862 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5863 v, &listener)) << listener.str();
5864 EXPECT_THAT(listener.str(), Eq(""));
5867 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5871 StringMatchResultListener listener;
5872 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5873 v, &listener)) << listener.str();
5876 Eq("where the following matchers don't match any elements:\n"
5877 "matcher #1: is equal to 2"));
5880 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5884 StringMatchResultListener listener;
5885 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5886 v, &listener)) << listener.str();
5889 Eq("where the following elements don't match any matchers:\n"
5893 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5897 StringMatchResultListener listener;
5898 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5899 v, &listener)) << listener.str();
5903 " the following matchers don't match any elements:\n"
5904 "matcher #0: is equal to 1\n"
5907 " the following elements don't match any matchers:\n"
5911 // Test helper for formatting element, matcher index pairs in expectations.
5912 static std::string EMString(int element, int matcher) {
5914 ss << "(element #" << element << ", matcher #" << matcher << ")";
5918 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
5919 // A situation where all elements and matchers have a match
5920 // associated with them, but the max matching is not perfect.
5921 std::vector<std::string> v;
5925 StringMatchResultListener listener;
5926 EXPECT_FALSE(ExplainMatchResult(
5927 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5930 std::string prefix =
5931 "where no permutation of the elements can satisfy all matchers, "
5932 "and the closest match is 2 of 3 matchers with the "
5935 // We have to be a bit loose here, because there are 4 valid max matches.
5938 AnyOf(prefix + "{\n " + EMString(0, 0) +
5939 ",\n " + EMString(1, 2) + "\n}",
5940 prefix + "{\n " + EMString(0, 1) +
5941 ",\n " + EMString(1, 2) + "\n}",
5942 prefix + "{\n " + EMString(0, 0) +
5943 ",\n " + EMString(2, 2) + "\n}",
5944 prefix + "{\n " + EMString(0, 1) +
5945 ",\n " + EMString(2, 2) + "\n}"));
5948 TEST_F(UnorderedElementsAreTest, Describe) {
5949 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5952 Describe<IntVec>(UnorderedElementsAre(345)),
5953 Eq("has 1 element and that element is equal to 345"));
5955 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5956 Eq("has 3 elements and there exists some permutation "
5957 "of elements such that:\n"
5958 " - element #0 is equal to 111, and\n"
5959 " - element #1 is equal to 222, and\n"
5960 " - element #2 is equal to 333"));
5963 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5964 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5967 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5968 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5970 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5971 Eq("doesn't have 3 elements, or there exists no permutation "
5972 "of elements such that:\n"
5973 " - element #0 is equal to 123, and\n"
5974 " - element #1 is equal to 234, and\n"
5975 " - element #2 is equal to 345"));
5980 // Used as a check on the more complex max flow method used in the
5981 // real testing::internal::FindMaxBipartiteMatching. This method is
5982 // compatible but runs in worst-case factorial time, so we only
5983 // use it in testing for small problem sizes.
5984 template <typename Graph>
5985 class BacktrackingMaxBPMState {
5987 // Does not take ownership of 'g'.
5988 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5990 ElementMatcherPairs Compute() {
5991 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5992 return best_so_far_;
5994 lhs_used_.assign(graph_->LhsSize(), kUnused);
5995 rhs_used_.assign(graph_->RhsSize(), kUnused);
5996 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5999 if (best_so_far_.size() == graph_->RhsSize())
6002 return best_so_far_;
6006 static const size_t kUnused = static_cast<size_t>(-1);
6008 void PushMatch(size_t lhs, size_t rhs) {
6009 matches_.push_back(ElementMatcherPair(lhs, rhs));
6010 lhs_used_[lhs] = rhs;
6011 rhs_used_[rhs] = lhs;
6012 if (matches_.size() > best_so_far_.size()) {
6013 best_so_far_ = matches_;
6018 const ElementMatcherPair& back = matches_.back();
6019 lhs_used_[back.first] = kUnused;
6020 rhs_used_[back.second] = kUnused;
6021 matches_.pop_back();
6024 bool RecurseInto(size_t irhs) {
6025 if (rhs_used_[irhs] != kUnused) {
6028 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
6029 if (lhs_used_[ilhs] != kUnused) {
6032 if (!graph_->HasEdge(ilhs, irhs)) {
6035 PushMatch(ilhs, irhs);
6036 if (best_so_far_.size() == graph_->RhsSize()) {
6039 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6040 if (!RecurseInto(mi)) return false;
6047 const Graph* graph_; // not owned
6048 std::vector<size_t> lhs_used_;
6049 std::vector<size_t> rhs_used_;
6050 ElementMatcherPairs matches_;
6051 ElementMatcherPairs best_so_far_;
6054 template <typename Graph>
6055 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6059 // Implement a simple backtracking algorithm to determine if it is possible
6060 // to find one element per matcher, without reusing elements.
6061 template <typename Graph>
6063 FindBacktrackingMaxBPM(const Graph& g) {
6064 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6067 class BacktrackingBPMTest : public ::testing::Test { };
6069 // Tests the MaxBipartiteMatching algorithm with square matrices.
6070 // The single int param is the # of nodes on each of the left and right sides.
6071 class BipartiteTest : public ::testing::TestWithParam<int> { };
6073 // Verify all match graphs up to some moderate number of edges.
6074 TEST_P(BipartiteTest, Exhaustive) {
6075 int nodes = GetParam();
6076 MatchMatrix graph(nodes, nodes);
6078 ElementMatcherPairs matches =
6079 internal::FindMaxBipartiteMatching(graph);
6080 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6081 << "graph: " << graph.DebugString();
6082 // Check that all elements of matches are in the graph.
6083 // Check that elements of first and second are unique.
6084 std::vector<bool> seen_element(graph.LhsSize());
6085 std::vector<bool> seen_matcher(graph.RhsSize());
6086 SCOPED_TRACE(PrintToString(matches));
6087 for (size_t i = 0; i < matches.size(); ++i) {
6088 size_t ilhs = matches[i].first;
6089 size_t irhs = matches[i].second;
6090 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
6091 EXPECT_FALSE(seen_element[ilhs]);
6092 EXPECT_FALSE(seen_matcher[irhs]);
6093 seen_element[ilhs] = true;
6094 seen_matcher[irhs] = true;
6096 } while (graph.NextGraph());
6099 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
6100 ::testing::Range(0, 5));
6102 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
6103 class BipartiteNonSquareTest
6104 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6107 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6115 MatchMatrix g(4, 3);
6116 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
6117 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
6118 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
6120 EXPECT_THAT(FindBacktrackingMaxBPM(g),
6121 ElementsAre(Pair(3, 0),
6122 Pair(AnyOf(1, 2), 1),
6123 Pair(0, 2))) << g.DebugString();
6126 // Verify a few nonsquare matrices.
6127 TEST_P(BipartiteNonSquareTest, Exhaustive) {
6128 size_t nlhs = GetParam().first;
6129 size_t nrhs = GetParam().second;
6130 MatchMatrix graph(nlhs, nrhs);
6132 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6133 internal::FindMaxBipartiteMatching(graph).size())
6134 << "graph: " << graph.DebugString()
6135 << "\nbacktracking: "
6136 << PrintToString(FindBacktrackingMaxBPM(graph))
6138 << PrintToString(internal::FindMaxBipartiteMatching(graph));
6139 } while (graph.NextGraph());
6142 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
6144 std::make_pair(1, 2),
6145 std::make_pair(2, 1),
6146 std::make_pair(3, 2),
6147 std::make_pair(2, 3),
6148 std::make_pair(4, 1),
6149 std::make_pair(1, 4),
6150 std::make_pair(4, 3),
6151 std::make_pair(3, 4)));
6153 class BipartiteRandomTest
6154 : public ::testing::TestWithParam<std::pair<int, int> > {
6157 // Verifies a large sample of larger graphs.
6158 TEST_P(BipartiteRandomTest, LargerNets) {
6159 int nodes = GetParam().first;
6160 int iters = GetParam().second;
6161 MatchMatrix graph(nodes, nodes);
6163 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
6165 seed = static_cast<testing::internal::Int32>(time(NULL));
6168 for (; iters > 0; --iters, ++seed) {
6169 srand(static_cast<int>(seed));
6171 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6172 internal::FindMaxBipartiteMatching(graph).size())
6173 << " graph: " << graph.DebugString()
6174 << "\nTo reproduce the failure, rerun the test with the flag"
6175 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6179 // Test argument is a std::pair<int, int> representing (nodes, iters).
6180 INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
6182 std::make_pair(5, 10000),
6183 std::make_pair(6, 5000),
6184 std::make_pair(7, 2000),
6185 std::make_pair(8, 500),
6186 std::make_pair(9, 100)));
6188 // Tests IsReadableTypeName().
6190 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6191 EXPECT_TRUE(IsReadableTypeName("int"));
6192 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6193 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6194 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6197 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6198 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6199 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6200 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6203 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6205 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6206 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6209 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6210 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6213 // Tests FormatMatcherDescription().
6215 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6216 EXPECT_EQ("is even",
6217 FormatMatcherDescription(false, "IsEven", Strings()));
6218 EXPECT_EQ("not (is even)",
6219 FormatMatcherDescription(true, "IsEven", Strings()));
6221 const char* params[] = {"5"};
6222 EXPECT_EQ("equals 5",
6223 FormatMatcherDescription(false, "Equals",
6224 Strings(params, params + 1)));
6226 const char* params2[] = {"5", "8"};
6227 EXPECT_EQ("is in range (5, 8)",
6228 FormatMatcherDescription(false, "IsInRange",
6229 Strings(params2, params2 + 2)));
6232 // Tests PolymorphicMatcher::mutable_impl().
6233 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6234 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6235 DivisibleByImpl& impl = m.mutable_impl();
6236 EXPECT_EQ(42, impl.divider());
6238 impl.set_divider(0);
6239 EXPECT_EQ(0, m.mutable_impl().divider());
6242 // Tests PolymorphicMatcher::impl().
6243 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6244 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6245 const DivisibleByImpl& impl = m.impl();
6246 EXPECT_EQ(42, impl.divider());
6249 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6251 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6252 make_tuple('a', 10), &ss1);
6253 EXPECT_EQ("", ss1.str()); // Successful match.
6256 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6257 make_tuple(2, 'b'), &ss2);
6258 EXPECT_EQ(" Expected arg #0: is > 5\n"
6259 " Actual: 2, which is 3 less than 5\n"
6260 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6261 " Actual: 'b' (98, 0x62)\n",
6262 ss2.str()); // Failed match where both arguments need explanation.
6265 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6266 make_tuple(2, 'a'), &ss3);
6267 EXPECT_EQ(" Expected arg #0: is > 5\n"
6268 " Actual: 2, which is 3 less than 5\n",
6269 ss3.str()); // Failed match where only one argument needs
6275 TEST(EachTest, ExplainsMatchResultCorrectly) {
6276 set<int> a; // empty
6278 Matcher<set<int> > m = Each(2);
6279 EXPECT_EQ("", Explain(m, a));
6281 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6283 const int b[1] = {1};
6284 EXPECT_EQ("", Explain(n, b));
6287 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6292 m = Each(GreaterThan(0));
6293 EXPECT_EQ("", Explain(m, a));
6295 m = Each(GreaterThan(10));
6296 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6300 TEST(EachTest, DescribesItselfCorrectly) {
6301 Matcher<vector<int> > m = Each(1);
6302 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6304 Matcher<vector<int> > m2 = Not(m);
6305 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6308 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6309 vector<int> some_vector;
6310 EXPECT_THAT(some_vector, Each(1));
6311 some_vector.push_back(3);
6312 EXPECT_THAT(some_vector, Not(Each(1)));
6313 EXPECT_THAT(some_vector, Each(3));
6314 some_vector.push_back(1);
6315 some_vector.push_back(2);
6316 EXPECT_THAT(some_vector, Not(Each(3)));
6317 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6319 vector<std::string> another_vector;
6320 another_vector.push_back("fee");
6321 EXPECT_THAT(another_vector, Each(std::string("fee")));
6322 another_vector.push_back("fie");
6323 another_vector.push_back("foe");
6324 another_vector.push_back("fum");
6325 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6328 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6329 map<const char*, int> my_map;
6330 const char* bar = "a string";
6332 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6334 map<std::string, int> another_map;
6335 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6336 another_map["fee"] = 1;
6337 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6338 another_map["fie"] = 2;
6339 another_map["foe"] = 3;
6340 another_map["fum"] = 4;
6341 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6342 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6343 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6346 TEST(EachTest, AcceptsMatcher) {
6347 const int a[] = {1, 2, 3};
6348 EXPECT_THAT(a, Each(Gt(0)));
6349 EXPECT_THAT(a, Not(Each(Gt(1))));
6352 TEST(EachTest, WorksForNativeArrayAsTuple) {
6353 const int a[] = {1, 2};
6354 const int* const pointer = a;
6355 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
6356 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
6359 // For testing Pointwise().
6360 class IsHalfOfMatcher {
6362 template <typename T1, typename T2>
6363 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
6364 MatchResultListener* listener) const {
6365 if (get<0>(a_pair) == get<1>(a_pair)/2) {
6366 *listener << "where the second is " << get<1>(a_pair);
6369 *listener << "where the second/2 is " << get<1>(a_pair)/2;
6374 void DescribeTo(ostream* os) const {
6375 *os << "are a pair where the first is half of the second";
6378 void DescribeNegationTo(ostream* os) const {
6379 *os << "are a pair where the first isn't half of the second";
6383 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6384 return MakePolymorphicMatcher(IsHalfOfMatcher());
6387 TEST(PointwiseTest, DescribesSelf) {
6392 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6393 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6394 "in { 1, 2, 3 } are a pair where the first is half of the second",
6396 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6397 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6398 "where the first isn't half of the second",
6399 DescribeNegation(m));
6402 TEST(PointwiseTest, MakesCopyOfRhs) {
6403 list<signed char> rhs;
6408 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6409 EXPECT_THAT(lhs, m);
6411 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6413 EXPECT_THAT(lhs, m);
6416 TEST(PointwiseTest, WorksForLhsNativeArray) {
6417 const int lhs[] = {1, 2, 3};
6422 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6423 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6426 TEST(PointwiseTest, WorksForRhsNativeArray) {
6427 const int rhs[] = {1, 2, 3};
6432 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6433 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6436 // Test is effective only with sanitizers.
6437 TEST(PointwiseTest, WorksForVectorOfBool) {
6438 vector<bool> rhs(3, false);
6440 vector<bool> lhs = rhs;
6441 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6443 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6446 #if GTEST_HAS_STD_INITIALIZER_LIST_
6448 TEST(PointwiseTest, WorksForRhsInitializerList) {
6449 const vector<int> lhs{2, 4, 6};
6450 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6451 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6454 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
6456 TEST(PointwiseTest, RejectsWrongSize) {
6457 const double lhs[2] = {1, 2};
6458 const int rhs[1] = {0};
6459 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6460 EXPECT_EQ("which contains 2 values",
6461 Explain(Pointwise(Gt(), rhs), lhs));
6463 const int rhs2[3] = {0, 1, 2};
6464 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6467 TEST(PointwiseTest, RejectsWrongContent) {
6468 const double lhs[3] = {1, 2, 3};
6469 const int rhs[3] = {2, 6, 4};
6470 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6471 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6472 "where the second/2 is 3",
6473 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6476 TEST(PointwiseTest, AcceptsCorrectContent) {
6477 const double lhs[3] = {1, 2, 3};
6478 const int rhs[3] = {2, 4, 6};
6479 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6480 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6483 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6484 const double lhs[3] = {1, 2, 3};
6485 const int rhs[3] = {2, 4, 6};
6486 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
6487 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6488 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6490 // This type works as a tuple<const double&, const int&> can be
6491 // implicitly cast to tuple<double, int>.
6492 const Matcher<tuple<double, int> > m2 = IsHalfOf();
6493 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6494 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6497 TEST(UnorderedPointwiseTest, DescribesSelf) {
6502 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6504 "has 3 elements and there exists some permutation of elements such "
6506 " - element #0 and 1 are a pair where the first is half of the second, "
6508 " - element #1 and 2 are a pair where the first is half of the second, "
6510 " - element #2 and 3 are a pair where the first is half of the second",
6513 "doesn't have 3 elements, or there exists no permutation of elements "
6515 " - element #0 and 1 are a pair where the first is half of the second, "
6517 " - element #1 and 2 are a pair where the first is half of the second, "
6519 " - element #2 and 3 are a pair where the first is half of the second",
6520 DescribeNegation(m));
6523 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6524 list<signed char> rhs;
6529 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6530 EXPECT_THAT(lhs, m);
6532 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6534 EXPECT_THAT(lhs, m);
6537 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6538 const int lhs[] = {1, 2, 3};
6543 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6544 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6547 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6548 const int rhs[] = {1, 2, 3};
6553 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6554 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6557 #if GTEST_HAS_STD_INITIALIZER_LIST_
6559 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6560 const vector<int> lhs{2, 4, 6};
6561 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6562 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6565 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
6567 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6568 const double lhs[2] = {1, 2};
6569 const int rhs[1] = {0};
6570 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6571 EXPECT_EQ("which has 2 elements",
6572 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6574 const int rhs2[3] = {0, 1, 2};
6575 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6578 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6579 const double lhs[3] = {1, 2, 3};
6580 const int rhs[3] = {2, 6, 6};
6581 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6582 EXPECT_EQ("where the following elements don't match any matchers:\n"
6584 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6587 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6588 const double lhs[3] = {1, 2, 3};
6589 const int rhs[3] = {2, 4, 6};
6590 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6593 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6594 const double lhs[3] = {1, 2, 3};
6595 const int rhs[3] = {6, 4, 2};
6596 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6599 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6600 const double lhs[3] = {1, 2, 3};
6601 const int rhs[3] = {4, 6, 2};
6602 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
6603 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6605 // This type works as a tuple<const double&, const int&> can be
6606 // implicitly cast to tuple<double, int>.
6607 const Matcher<tuple<double, int> > m2 = IsHalfOf();
6608 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6611 // Sample optional type implementation with minimal requirements for use with
6612 // Optional matcher.
6613 class SampleOptionalInt {
6615 typedef int value_type;
6616 explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {}
6617 SampleOptionalInt() : value_(0), has_value_(false) {}
6618 operator bool() const {
6621 const int& operator*() const {
6629 TEST(OptionalTest, DescribesSelf) {
6630 const Matcher<SampleOptionalInt> m = Optional(Eq(1));
6631 EXPECT_EQ("value is equal to 1", Describe(m));
6634 TEST(OptionalTest, ExplainsSelf) {
6635 const Matcher<SampleOptionalInt> m = Optional(Eq(1));
6636 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1)));
6637 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2)));
6640 TEST(OptionalTest, MatchesNonEmptyOptional) {
6641 const Matcher<SampleOptionalInt> m1 = Optional(1);
6642 const Matcher<SampleOptionalInt> m2 = Optional(Eq(2));
6643 const Matcher<SampleOptionalInt> m3 = Optional(Lt(3));
6644 SampleOptionalInt opt(1);
6645 EXPECT_TRUE(m1.Matches(opt));
6646 EXPECT_FALSE(m2.Matches(opt));
6647 EXPECT_TRUE(m3.Matches(opt));
6650 TEST(OptionalTest, DoesNotMatchNullopt) {
6651 const Matcher<SampleOptionalInt> m = Optional(1);
6652 SampleOptionalInt empty;
6653 EXPECT_FALSE(m.Matches(empty));
6656 class SampleVariantIntString {
6658 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6659 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6661 template <typename T>
6662 friend bool holds_alternative(const SampleVariantIntString& value) {
6663 return value.has_int_ == internal::IsSame<T, int>::value;
6666 template <typename T>
6667 friend const T& get(const SampleVariantIntString& value) {
6668 return value.get_impl(static_cast<T*>(NULL));
6672 const int& get_impl(int*) const { return i_; }
6673 const std::string& get_impl(std::string*) const { return s_; }
6680 TEST(VariantTest, DescribesSelf) {
6681 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6682 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6683 "'.*' and the value is equal to 1"));
6686 TEST(VariantTest, ExplainsSelf) {
6687 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6688 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6689 ContainsRegex("whose value 1"));
6690 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6691 HasSubstr("whose value is not of type '"));
6692 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6693 "whose value 2 doesn't match");
6696 TEST(VariantTest, FullMatch) {
6697 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6698 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6700 m = VariantWith<std::string>(Eq("1"));
6701 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6704 TEST(VariantTest, TypeDoesNotMatch) {
6705 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6706 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6708 m = VariantWith<std::string>(Eq("1"));
6709 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6712 TEST(VariantTest, InnerDoesNotMatch) {
6713 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6714 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6716 m = VariantWith<std::string>(Eq("1"));
6717 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6720 class SampleAnyType {
6722 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6723 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6725 template <typename T>
6726 friend const T* any_cast(const SampleAnyType* any) {
6727 return any->get_impl(static_cast<T*>(NULL));
6735 const int* get_impl(int*) const { return index_ == 0 ? &i_ : NULL; }
6736 const std::string* get_impl(std::string*) const {
6737 return index_ == 1 ? &s_ : NULL;
6741 TEST(AnyWithTest, FullMatch) {
6742 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6743 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6746 TEST(AnyWithTest, TestBadCastType) {
6747 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6748 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6751 #if GTEST_LANG_CXX11
6752 TEST(AnyWithTest, TestUseInContainers) {
6753 std::vector<SampleAnyType> a;
6758 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6760 std::vector<SampleAnyType> b;
6761 b.emplace_back("hello");
6762 b.emplace_back("merhaba");
6763 b.emplace_back("salut");
6764 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6765 AnyWith<std::string>("merhaba"),
6766 AnyWith<std::string>("salut")}));
6768 #endif // GTEST_LANG_CXX11
6769 TEST(AnyWithTest, TestCompare) {
6770 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6773 TEST(AnyWithTest, DescribesSelf) {
6774 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6775 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6776 "'.*' and the value is equal to 1"));
6779 TEST(AnyWithTest, ExplainsSelf) {
6780 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6782 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6783 EXPECT_THAT(Explain(m, SampleAnyType("A")),
6784 HasSubstr("whose value is not of type '"));
6785 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6788 #if GTEST_LANG_CXX11
6790 TEST(PointeeTest, WorksOnMoveOnlyType) {
6791 std::unique_ptr<int> p(new int(3));
6792 EXPECT_THAT(p, Pointee(Eq(3)));
6793 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6796 TEST(NotTest, WorksOnMoveOnlyType) {
6797 std::unique_ptr<int> p(new int(3));
6798 EXPECT_THAT(p, Pointee(Eq(3)));
6799 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6802 #endif // GTEST_LANG_CXX11
6804 } // namespace gmock_matchers_test
6805 } // namespace testing