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 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
36 // possible loss of data and C4100, unreferenced local parameter
38 # pragma warning(push)
39 # pragma warning(disable:4244)
40 # pragma warning(disable:4100)
43 #include "gmock/gmock-matchers.h"
51 #include <forward_list>
62 #include <type_traits>
63 #include <unordered_map>
64 #include <unordered_set>
68 #include "gmock/gmock-more-matchers.h"
69 #include "gmock/gmock.h"
70 #include "gtest/gtest-spi.h"
71 #include "gtest/gtest.h"
74 namespace gmock_matchers_test {
87 using std::stringstream;
89 using testing::internal::DummyMatchResultListener;
90 using testing::internal::ElementMatcherPair;
91 using testing::internal::ElementMatcherPairs;
92 using testing::internal::ElementsAreArrayMatcher;
93 using testing::internal::ExplainMatchFailureTupleTo;
94 using testing::internal::FloatingEqMatcher;
95 using testing::internal::FormatMatcherDescription;
96 using testing::internal::IsReadableTypeName;
97 using testing::internal::MatchMatrix;
98 using testing::internal::PredicateFormatterFromMatcher;
99 using testing::internal::RE;
100 using testing::internal::StreamMatchResultListener;
101 using testing::internal::Strings;
103 // Helper for testing container-valued matchers in mock method context. It is
104 // important to test matchers in this context, since it requires additional type
105 // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
106 struct ContainerHelper {
107 MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
110 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
111 std::vector<std::unique_ptr<int>> pointers;
112 for (int i : ints) pointers.emplace_back(new int(i));
116 // For testing ExplainMatchResultTo().
117 template <typename T = int>
118 class GreaterThanMatcher : public MatcherInterface<T> {
120 explicit GreaterThanMatcher(T rhs) : rhs_(rhs) {}
122 void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
124 bool MatchAndExplain(T lhs, MatchResultListener* listener) const override {
126 *listener << "which is " << (lhs - rhs_) << " more than " << rhs_;
127 } else if (lhs == rhs_) {
128 *listener << "which is the same as " << rhs_;
130 *listener << "which is " << (rhs_ - lhs) << " less than " << rhs_;
140 template <typename T>
141 Matcher<T> GreaterThan(T n) {
142 return MakeMatcher(new GreaterThanMatcher<T>(n));
145 std::string OfType(const std::string& type_name) {
147 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
153 // Returns the description of the given matcher.
154 template <typename T>
155 std::string Describe(const Matcher<T>& m) {
156 return DescribeMatcher<T>(m);
159 // Returns the description of the negation of the given matcher.
160 template <typename T>
161 std::string DescribeNegation(const Matcher<T>& m) {
162 return DescribeMatcher<T>(m, true);
165 // Returns the reason why x matches, or doesn't match, m.
166 template <typename MatcherType, typename Value>
167 std::string Explain(const MatcherType& m, const Value& x) {
168 StringMatchResultListener listener;
169 ExplainMatchResult(m, x, &listener);
170 return listener.str();
173 TEST(MonotonicMatcherTest, IsPrintable) {
175 ss << GreaterThan(5);
176 EXPECT_EQ("is > 5", ss.str());
179 TEST(MatchResultListenerTest, StreamingWorks) {
180 StringMatchResultListener listener;
181 listener << "hi" << 5;
182 EXPECT_EQ("hi5", listener.str());
185 EXPECT_EQ("", listener.str());
188 EXPECT_EQ("42", listener.str());
190 // Streaming shouldn't crash when the underlying ostream is NULL.
191 DummyMatchResultListener dummy;
195 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
196 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
197 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
199 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
202 TEST(MatchResultListenerTest, IsInterestedWorks) {
203 EXPECT_TRUE(StringMatchResultListener().IsInterested());
204 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
206 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
207 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
210 // Makes sure that the MatcherInterface<T> interface doesn't
212 class EvenMatcherImpl : public MatcherInterface<int> {
214 bool MatchAndExplain(int x,
215 MatchResultListener* /* listener */) const override {
219 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
221 // We deliberately don't define DescribeNegationTo() and
222 // ExplainMatchResultTo() here, to make sure the definition of these
223 // two methods is optional.
226 // Makes sure that the MatcherInterface API doesn't change.
227 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
231 // Tests implementing a monomorphic matcher using MatchAndExplain().
233 class NewEvenMatcherImpl : public MatcherInterface<int> {
235 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
236 const bool match = x % 2 == 0;
237 // Verifies that we can stream to a listener directly.
238 *listener << "value % " << 2;
239 if (listener->stream() != nullptr) {
240 // Verifies that we can stream to a listener's underlying stream
242 *listener->stream() << " == " << (x % 2);
247 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
250 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
251 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
252 EXPECT_TRUE(m.Matches(2));
253 EXPECT_FALSE(m.Matches(3));
254 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
255 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
258 // Tests default-constructing a matcher.
259 TEST(MatcherTest, CanBeDefaultConstructed) {
263 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
264 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
265 const MatcherInterface<int>* impl = new EvenMatcherImpl;
266 Matcher<int> m(impl);
267 EXPECT_TRUE(m.Matches(4));
268 EXPECT_FALSE(m.Matches(5));
271 // Tests that value can be used in place of Eq(value).
272 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
274 EXPECT_TRUE(m1.Matches(5));
275 EXPECT_FALSE(m1.Matches(6));
278 // Tests that NULL can be used in place of Eq(NULL).
279 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
280 Matcher<int*> m1 = nullptr;
281 EXPECT_TRUE(m1.Matches(nullptr));
283 EXPECT_FALSE(m1.Matches(&n));
286 // Tests that matchers can be constructed from a variable that is not properly
287 // defined. This should be illegal, but many users rely on this accidentally.
289 virtual ~Undefined() = 0;
290 static const int kInt = 1;
293 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
294 Matcher<int> m1 = Undefined::kInt;
295 EXPECT_TRUE(m1.Matches(1));
296 EXPECT_FALSE(m1.Matches(2));
299 // Test that a matcher parameterized with an abstract class compiles.
300 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
302 // Tests that matchers are copyable.
303 TEST(MatcherTest, IsCopyable) {
304 // Tests the copy constructor.
305 Matcher<bool> m1 = Eq(false);
306 EXPECT_TRUE(m1.Matches(false));
307 EXPECT_FALSE(m1.Matches(true));
309 // Tests the assignment operator.
311 EXPECT_TRUE(m1.Matches(true));
312 EXPECT_FALSE(m1.Matches(false));
315 // Tests that Matcher<T>::DescribeTo() calls
316 // MatcherInterface<T>::DescribeTo().
317 TEST(MatcherTest, CanDescribeItself) {
318 EXPECT_EQ("is an even number",
319 Describe(Matcher<int>(new EvenMatcherImpl)));
322 // Tests Matcher<T>::MatchAndExplain().
323 TEST(MatcherTest, MatchAndExplain) {
324 Matcher<int> m = GreaterThan(0);
325 StringMatchResultListener listener1;
326 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
327 EXPECT_EQ("which is 42 more than 0", listener1.str());
329 StringMatchResultListener listener2;
330 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
331 EXPECT_EQ("which is 9 less than 0", listener2.str());
334 // Tests that a C-string literal can be implicitly converted to a
335 // Matcher<std::string> or Matcher<const std::string&>.
336 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
337 Matcher<std::string> m1 = "hi";
338 EXPECT_TRUE(m1.Matches("hi"));
339 EXPECT_FALSE(m1.Matches("hello"));
341 Matcher<const std::string&> m2 = "hi";
342 EXPECT_TRUE(m2.Matches("hi"));
343 EXPECT_FALSE(m2.Matches("hello"));
346 // Tests that a string object can be implicitly converted to a
347 // Matcher<std::string> or Matcher<const std::string&>.
348 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
349 Matcher<std::string> m1 = std::string("hi");
350 EXPECT_TRUE(m1.Matches("hi"));
351 EXPECT_FALSE(m1.Matches("hello"));
353 Matcher<const std::string&> m2 = std::string("hi");
354 EXPECT_TRUE(m2.Matches("hi"));
355 EXPECT_FALSE(m2.Matches("hello"));
358 #if GTEST_INTERNAL_HAS_STRING_VIEW
359 // Tests that a C-string literal can be implicitly converted to a
360 // Matcher<StringView> or Matcher<const StringView&>.
361 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
362 Matcher<internal::StringView> m1 = "cats";
363 EXPECT_TRUE(m1.Matches("cats"));
364 EXPECT_FALSE(m1.Matches("dogs"));
366 Matcher<const internal::StringView&> m2 = "cats";
367 EXPECT_TRUE(m2.Matches("cats"));
368 EXPECT_FALSE(m2.Matches("dogs"));
371 // Tests that a std::string object can be implicitly converted to a
372 // Matcher<StringView> or Matcher<const StringView&>.
373 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
374 Matcher<internal::StringView> m1 = std::string("cats");
375 EXPECT_TRUE(m1.Matches("cats"));
376 EXPECT_FALSE(m1.Matches("dogs"));
378 Matcher<const internal::StringView&> m2 = std::string("cats");
379 EXPECT_TRUE(m2.Matches("cats"));
380 EXPECT_FALSE(m2.Matches("dogs"));
383 // Tests that a StringView object can be implicitly converted to a
384 // Matcher<StringView> or Matcher<const StringView&>.
385 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
386 Matcher<internal::StringView> m1 = internal::StringView("cats");
387 EXPECT_TRUE(m1.Matches("cats"));
388 EXPECT_FALSE(m1.Matches("dogs"));
390 Matcher<const internal::StringView&> m2 = internal::StringView("cats");
391 EXPECT_TRUE(m2.Matches("cats"));
392 EXPECT_FALSE(m2.Matches("dogs"));
394 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
396 // Tests that a std::reference_wrapper<std::string> object can be implicitly
397 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
398 TEST(StringMatcherTest,
399 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
400 std::string value = "cats";
401 Matcher<std::string> m1 = Eq(std::ref(value));
402 EXPECT_TRUE(m1.Matches("cats"));
403 EXPECT_FALSE(m1.Matches("dogs"));
405 Matcher<const std::string&> m2 = Eq(std::ref(value));
406 EXPECT_TRUE(m2.Matches("cats"));
407 EXPECT_FALSE(m2.Matches("dogs"));
410 // Tests that MakeMatcher() constructs a Matcher<T> from a
411 // MatcherInterface* without requiring the user to explicitly
413 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
414 const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
415 Matcher<int> m = MakeMatcher(dummy_impl);
418 // Tests that MakePolymorphicMatcher() can construct a polymorphic
419 // matcher from its implementation using the old API.
421 class ReferencesBarOrIsZeroImpl {
423 template <typename T>
424 bool MatchAndExplain(const T& x,
425 MatchResultListener* /* listener */) const {
427 return p == &g_bar || x == 0;
430 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
432 void DescribeNegationTo(ostream* os) const {
433 *os << "doesn't reference g_bar and is not zero";
437 // This function verifies that MakePolymorphicMatcher() returns a
438 // PolymorphicMatcher<T> where T is the argument's type.
439 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
440 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
443 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
444 // Using a polymorphic matcher to match a reference type.
445 Matcher<const int&> m1 = ReferencesBarOrIsZero();
446 EXPECT_TRUE(m1.Matches(0));
447 // Verifies that the identity of a by-reference argument is preserved.
448 EXPECT_TRUE(m1.Matches(g_bar));
449 EXPECT_FALSE(m1.Matches(1));
450 EXPECT_EQ("g_bar or zero", Describe(m1));
452 // Using a polymorphic matcher to match a value type.
453 Matcher<double> m2 = ReferencesBarOrIsZero();
454 EXPECT_TRUE(m2.Matches(0.0));
455 EXPECT_FALSE(m2.Matches(0.1));
456 EXPECT_EQ("g_bar or zero", Describe(m2));
459 // Tests implementing a polymorphic matcher using MatchAndExplain().
461 class PolymorphicIsEvenImpl {
463 void DescribeTo(ostream* os) const { *os << "is even"; }
465 void DescribeNegationTo(ostream* os) const {
469 template <typename T>
470 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
471 // Verifies that we can stream to the listener directly.
472 *listener << "% " << 2;
473 if (listener->stream() != nullptr) {
474 // Verifies that we can stream to the listener's underlying stream
476 *listener->stream() << " == " << (x % 2);
482 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
483 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
486 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
487 // Using PolymorphicIsEven() as a Matcher<int>.
488 const Matcher<int> m1 = PolymorphicIsEven();
489 EXPECT_TRUE(m1.Matches(42));
490 EXPECT_FALSE(m1.Matches(43));
491 EXPECT_EQ("is even", Describe(m1));
493 const Matcher<int> not_m1 = Not(m1);
494 EXPECT_EQ("is odd", Describe(not_m1));
496 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
498 // Using PolymorphicIsEven() as a Matcher<char>.
499 const Matcher<char> m2 = PolymorphicIsEven();
500 EXPECT_TRUE(m2.Matches('\x42'));
501 EXPECT_FALSE(m2.Matches('\x43'));
502 EXPECT_EQ("is even", Describe(m2));
504 const Matcher<char> not_m2 = Not(m2);
505 EXPECT_EQ("is odd", Describe(not_m2));
507 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
510 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
511 TEST(MatcherCastTest, FromPolymorphicMatcher) {
512 Matcher<int> m = MatcherCast<int>(Eq(5));
513 EXPECT_TRUE(m.Matches(5));
514 EXPECT_FALSE(m.Matches(6));
517 // For testing casting matchers between compatible types.
520 // An int can be statically (although not implicitly) cast to a
522 explicit IntValue(int a_value) : value_(a_value) {}
524 int value() const { return value_; }
529 // For testing casting matchers between compatible types.
530 bool IsPositiveIntValue(const IntValue& foo) {
531 return foo.value() > 0;
534 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
535 // can be statically converted to U.
536 TEST(MatcherCastTest, FromCompatibleType) {
537 Matcher<double> m1 = Eq(2.0);
538 Matcher<int> m2 = MatcherCast<int>(m1);
539 EXPECT_TRUE(m2.Matches(2));
540 EXPECT_FALSE(m2.Matches(3));
542 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
543 Matcher<int> m4 = MatcherCast<int>(m3);
544 // In the following, the arguments 1 and 0 are statically converted
545 // to IntValue objects, and then tested by the IsPositiveIntValue()
547 EXPECT_TRUE(m4.Matches(1));
548 EXPECT_FALSE(m4.Matches(0));
551 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
552 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
553 Matcher<const int&> m1 = Eq(0);
554 Matcher<int> m2 = MatcherCast<int>(m1);
555 EXPECT_TRUE(m2.Matches(0));
556 EXPECT_FALSE(m2.Matches(1));
559 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
560 TEST(MatcherCastTest, FromReferenceToNonReference) {
561 Matcher<int&> m1 = Eq(0);
562 Matcher<int> m2 = MatcherCast<int>(m1);
563 EXPECT_TRUE(m2.Matches(0));
564 EXPECT_FALSE(m2.Matches(1));
567 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
568 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
569 Matcher<int> m1 = Eq(0);
570 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
571 EXPECT_TRUE(m2.Matches(0));
572 EXPECT_FALSE(m2.Matches(1));
575 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
576 TEST(MatcherCastTest, FromNonReferenceToReference) {
577 Matcher<int> m1 = Eq(0);
578 Matcher<int&> m2 = MatcherCast<int&>(m1);
580 EXPECT_TRUE(m2.Matches(n));
582 EXPECT_FALSE(m2.Matches(n));
585 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
586 TEST(MatcherCastTest, FromSameType) {
587 Matcher<int> m1 = Eq(0);
588 Matcher<int> m2 = MatcherCast<int>(m1);
589 EXPECT_TRUE(m2.Matches(0));
590 EXPECT_FALSE(m2.Matches(1));
593 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
594 // value type of the Matcher.
595 TEST(MatcherCastTest, FromAValue) {
596 Matcher<int> m = MatcherCast<int>(42);
597 EXPECT_TRUE(m.Matches(42));
598 EXPECT_FALSE(m.Matches(239));
601 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
602 // convertible to the value type of the Matcher.
603 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
604 const int kExpected = 'c';
605 Matcher<int> m = MatcherCast<int>('c');
606 EXPECT_TRUE(m.Matches(kExpected));
607 EXPECT_FALSE(m.Matches(kExpected + 1));
610 struct NonImplicitlyConstructibleTypeWithOperatorEq {
611 friend bool operator==(
612 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
616 friend bool operator==(
618 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
623 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
624 // implicitly convertible to the value type of the Matcher, but the value type
625 // of the matcher has operator==() overload accepting m.
626 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
627 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
628 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
629 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
631 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
632 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
633 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
635 // When updating the following lines please also change the comment to
636 // namespace convertible_from_any.
638 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
639 EXPECT_TRUE(m3.Matches(42));
640 EXPECT_FALSE(m3.Matches(239));
643 // ConvertibleFromAny does not work with MSVC. resulting in
644 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
645 // No constructor could take the source type, or constructor overload
646 // resolution was ambiguous
648 #if !defined _MSC_VER
650 // The below ConvertibleFromAny struct is implicitly constructible from anything
651 // and when in the same namespace can interact with other tests. In particular,
652 // if it is in the same namespace as other tests and one removes
653 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
654 // then the corresponding test still compiles (and it should not!) by implicitly
655 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
657 namespace convertible_from_any {
658 // Implicitly convertible from any type.
659 struct ConvertibleFromAny {
660 ConvertibleFromAny(int a_value) : value(a_value) {}
661 template <typename T>
662 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
663 ADD_FAILURE() << "Conversion constructor called";
668 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
669 return a.value == b.value;
672 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
673 return os << a.value;
676 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
677 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
678 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
679 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
682 TEST(MatcherCastTest, FromConvertibleFromAny) {
683 Matcher<ConvertibleFromAny> m =
684 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
685 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
686 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
688 } // namespace convertible_from_any
690 #endif // !defined _MSC_VER
692 struct IntReferenceWrapper {
693 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
697 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
698 return a.value == b.value;
701 TEST(MatcherCastTest, ValueIsNotCopied) {
703 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
704 // Verify that the matcher holds a reference to n, not to its temporary copy.
705 EXPECT_TRUE(m.Matches(n));
713 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
716 class Derived : public Base {
718 Derived() : Base() {}
722 class OtherDerived : public Base {};
724 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
725 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
726 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
727 EXPECT_TRUE(m2.Matches(' '));
728 EXPECT_FALSE(m2.Matches('\n'));
731 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
732 // T and U are arithmetic types and T can be losslessly converted to
734 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
735 Matcher<double> m1 = DoubleEq(1.0);
736 Matcher<float> m2 = SafeMatcherCast<float>(m1);
737 EXPECT_TRUE(m2.Matches(1.0f));
738 EXPECT_FALSE(m2.Matches(2.0f));
740 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
741 EXPECT_TRUE(m3.Matches('a'));
742 EXPECT_FALSE(m3.Matches('b'));
745 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
746 // are pointers or references to a derived and a base class, correspondingly.
747 TEST(SafeMatcherCastTest, FromBaseClass) {
749 Matcher<Base*> m1 = Eq(&d);
750 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
751 EXPECT_TRUE(m2.Matches(&d));
752 EXPECT_FALSE(m2.Matches(&d2));
754 Matcher<Base&> m3 = Ref(d);
755 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
756 EXPECT_TRUE(m4.Matches(d));
757 EXPECT_FALSE(m4.Matches(d2));
760 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
761 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
763 Matcher<const int&> m1 = Ref(n);
764 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
766 EXPECT_TRUE(m2.Matches(n));
767 EXPECT_FALSE(m2.Matches(n1));
770 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
771 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
772 Matcher<std::unique_ptr<int>> m1 = IsNull();
773 Matcher<const std::unique_ptr<int>&> m2 =
774 SafeMatcherCast<const std::unique_ptr<int>&>(m1);
775 EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
776 EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
779 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
780 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
781 Matcher<int> m1 = Eq(0);
782 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
784 EXPECT_TRUE(m2.Matches(n));
786 EXPECT_FALSE(m2.Matches(n));
789 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
790 TEST(SafeMatcherCastTest, FromSameType) {
791 Matcher<int> m1 = Eq(0);
792 Matcher<int> m2 = SafeMatcherCast<int>(m1);
793 EXPECT_TRUE(m2.Matches(0));
794 EXPECT_FALSE(m2.Matches(1));
797 #if !defined _MSC_VER
799 namespace convertible_from_any {
800 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
801 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
802 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
803 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
806 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
807 Matcher<ConvertibleFromAny> m =
808 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
809 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
810 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
812 } // namespace convertible_from_any
814 #endif // !defined _MSC_VER
816 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
818 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
819 // Verify that the matcher holds a reference to n, not to its temporary copy.
820 EXPECT_TRUE(m.Matches(n));
823 TEST(ExpectThat, TakesLiterals) {
825 EXPECT_THAT(1.0, 1.0);
826 EXPECT_THAT(std::string(), "");
829 TEST(ExpectThat, TakesFunctions) {
831 static void Func() {}
833 void (*func)() = Helper::Func;
834 EXPECT_THAT(func, Helper::Func);
835 EXPECT_THAT(func, &Helper::Func);
838 // Tests that A<T>() matches any value of type T.
839 TEST(ATest, MatchesAnyValue) {
840 // Tests a matcher for a value type.
841 Matcher<double> m1 = A<double>();
842 EXPECT_TRUE(m1.Matches(91.43));
843 EXPECT_TRUE(m1.Matches(-15.32));
845 // Tests a matcher for a reference type.
848 Matcher<int&> m2 = A<int&>();
849 EXPECT_TRUE(m2.Matches(a));
850 EXPECT_TRUE(m2.Matches(b));
853 TEST(ATest, WorksForDerivedClass) {
856 EXPECT_THAT(&base, A<Base*>());
857 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
858 EXPECT_THAT(&derived, A<Base*>());
859 EXPECT_THAT(&derived, A<Derived*>());
862 // Tests that A<T>() describes itself properly.
863 TEST(ATest, CanDescribeSelf) {
864 EXPECT_EQ("is anything", Describe(A<bool>()));
867 // Tests that An<T>() matches any value of type T.
868 TEST(AnTest, MatchesAnyValue) {
869 // Tests a matcher for a value type.
870 Matcher<int> m1 = An<int>();
871 EXPECT_TRUE(m1.Matches(9143));
872 EXPECT_TRUE(m1.Matches(-1532));
874 // Tests a matcher for a reference type.
877 Matcher<int&> m2 = An<int&>();
878 EXPECT_TRUE(m2.Matches(a));
879 EXPECT_TRUE(m2.Matches(b));
882 // Tests that An<T>() describes itself properly.
883 TEST(AnTest, CanDescribeSelf) {
884 EXPECT_EQ("is anything", Describe(An<int>()));
887 // Tests that _ can be used as a matcher for any type and matches any
888 // value of that type.
889 TEST(UnderscoreTest, MatchesAnyValue) {
890 // Uses _ as a matcher for a value type.
892 EXPECT_TRUE(m1.Matches(123));
893 EXPECT_TRUE(m1.Matches(-242));
895 // Uses _ as a matcher for a reference type.
898 Matcher<const bool&> m2 = _;
899 EXPECT_TRUE(m2.Matches(a));
900 EXPECT_TRUE(m2.Matches(b));
903 // Tests that _ describes itself properly.
904 TEST(UnderscoreTest, CanDescribeSelf) {
906 EXPECT_EQ("is anything", Describe(m));
909 // Tests that Eq(x) matches any value equal to x.
910 TEST(EqTest, MatchesEqualValue) {
911 // 2 C-strings with same content but different addresses.
912 const char a1[] = "hi";
913 const char a2[] = "hi";
915 Matcher<const char*> m1 = Eq(a1);
916 EXPECT_TRUE(m1.Matches(a1));
917 EXPECT_FALSE(m1.Matches(a2));
920 // Tests that Eq(v) describes itself properly.
924 Unprintable() : c_('a') {}
926 bool operator==(const Unprintable& /* rhs */) const { return true; }
927 // -Wunused-private-field: dummy accessor for `c_`.
928 char dummy_c() { return c_; }
933 TEST(EqTest, CanDescribeSelf) {
934 Matcher<Unprintable> m = Eq(Unprintable());
935 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
938 // Tests that Eq(v) can be used to match any type that supports
939 // comparing with type T, where T is v's type.
940 TEST(EqTest, IsPolymorphic) {
941 Matcher<int> m1 = Eq(1);
942 EXPECT_TRUE(m1.Matches(1));
943 EXPECT_FALSE(m1.Matches(2));
945 Matcher<char> m2 = Eq(1);
946 EXPECT_TRUE(m2.Matches('\1'));
947 EXPECT_FALSE(m2.Matches('a'));
950 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
951 TEST(TypedEqTest, ChecksEqualityForGivenType) {
952 Matcher<char> m1 = TypedEq<char>('a');
953 EXPECT_TRUE(m1.Matches('a'));
954 EXPECT_FALSE(m1.Matches('b'));
956 Matcher<int> m2 = TypedEq<int>(6);
957 EXPECT_TRUE(m2.Matches(6));
958 EXPECT_FALSE(m2.Matches(7));
961 // Tests that TypedEq(v) describes itself properly.
962 TEST(TypedEqTest, CanDescribeSelf) {
963 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
966 // Tests that TypedEq<T>(v) has type Matcher<T>.
968 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
969 // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
970 // not T, the compiler will generate a message about "undefined reference".
971 template <typename T>
973 static bool IsTypeOf(const T& /* v */) { return true; }
975 template <typename T2>
976 static void IsTypeOf(T2 v);
979 TEST(TypedEqTest, HasSpecifiedType) {
980 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
981 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
982 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
985 // Tests that Ge(v) matches anything >= v.
986 TEST(GeTest, ImplementsGreaterThanOrEqual) {
987 Matcher<int> m1 = Ge(0);
988 EXPECT_TRUE(m1.Matches(1));
989 EXPECT_TRUE(m1.Matches(0));
990 EXPECT_FALSE(m1.Matches(-1));
993 // Tests that Ge(v) describes itself properly.
994 TEST(GeTest, CanDescribeSelf) {
995 Matcher<int> m = Ge(5);
996 EXPECT_EQ("is >= 5", Describe(m));
999 // Tests that Gt(v) matches anything > v.
1000 TEST(GtTest, ImplementsGreaterThan) {
1001 Matcher<double> m1 = Gt(0);
1002 EXPECT_TRUE(m1.Matches(1.0));
1003 EXPECT_FALSE(m1.Matches(0.0));
1004 EXPECT_FALSE(m1.Matches(-1.0));
1007 // Tests that Gt(v) describes itself properly.
1008 TEST(GtTest, CanDescribeSelf) {
1009 Matcher<int> m = Gt(5);
1010 EXPECT_EQ("is > 5", Describe(m));
1013 // Tests that Le(v) matches anything <= v.
1014 TEST(LeTest, ImplementsLessThanOrEqual) {
1015 Matcher<char> m1 = Le('b');
1016 EXPECT_TRUE(m1.Matches('a'));
1017 EXPECT_TRUE(m1.Matches('b'));
1018 EXPECT_FALSE(m1.Matches('c'));
1021 // Tests that Le(v) describes itself properly.
1022 TEST(LeTest, CanDescribeSelf) {
1023 Matcher<int> m = Le(5);
1024 EXPECT_EQ("is <= 5", Describe(m));
1027 // Tests that Lt(v) matches anything < v.
1028 TEST(LtTest, ImplementsLessThan) {
1029 Matcher<const std::string&> m1 = Lt("Hello");
1030 EXPECT_TRUE(m1.Matches("Abc"));
1031 EXPECT_FALSE(m1.Matches("Hello"));
1032 EXPECT_FALSE(m1.Matches("Hello, world!"));
1035 // Tests that Lt(v) describes itself properly.
1036 TEST(LtTest, CanDescribeSelf) {
1037 Matcher<int> m = Lt(5);
1038 EXPECT_EQ("is < 5", Describe(m));
1041 // Tests that Ne(v) matches anything != v.
1042 TEST(NeTest, ImplementsNotEqual) {
1043 Matcher<int> m1 = Ne(0);
1044 EXPECT_TRUE(m1.Matches(1));
1045 EXPECT_TRUE(m1.Matches(-1));
1046 EXPECT_FALSE(m1.Matches(0));
1049 // Tests that Ne(v) describes itself properly.
1050 TEST(NeTest, CanDescribeSelf) {
1051 Matcher<int> m = Ne(5);
1052 EXPECT_EQ("isn't equal to 5", Describe(m));
1057 explicit MoveOnly(int i) : i_(i) {}
1058 MoveOnly(const MoveOnly&) = delete;
1059 MoveOnly(MoveOnly&&) = default;
1060 MoveOnly& operator=(const MoveOnly&) = delete;
1061 MoveOnly& operator=(MoveOnly&&) = default;
1063 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
1064 bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
1065 bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
1066 bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
1067 bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
1068 bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
1075 MOCK_METHOD1(Call, void(MoveOnly));
1078 // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
1079 #if defined(_MSC_VER) && (_MSC_VER < 1910)
1080 TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
1082 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1087 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1088 helper.Call(MoveOnly(0));
1089 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1090 helper.Call(MoveOnly(1));
1091 EXPECT_CALL(helper, Call(Le(ByRef(m))));
1092 helper.Call(MoveOnly(0));
1093 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1094 helper.Call(MoveOnly(-1));
1095 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1096 helper.Call(MoveOnly(0));
1097 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1098 helper.Call(MoveOnly(1));
1101 // Tests that IsNull() matches any NULL pointer of any type.
1102 TEST(IsNullTest, MatchesNullPointer) {
1103 Matcher<int*> m1 = IsNull();
1106 EXPECT_TRUE(m1.Matches(p1));
1107 EXPECT_FALSE(m1.Matches(&n));
1109 Matcher<const char*> m2 = IsNull();
1110 const char* p2 = nullptr;
1111 EXPECT_TRUE(m2.Matches(p2));
1112 EXPECT_FALSE(m2.Matches("hi"));
1114 Matcher<void*> m3 = IsNull();
1116 EXPECT_TRUE(m3.Matches(p3));
1117 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1120 TEST(IsNullTest, StdFunction) {
1121 const Matcher<std::function<void()>> m = IsNull();
1123 EXPECT_TRUE(m.Matches(std::function<void()>()));
1124 EXPECT_FALSE(m.Matches([]{}));
1127 // Tests that IsNull() describes itself properly.
1128 TEST(IsNullTest, CanDescribeSelf) {
1129 Matcher<int*> m = IsNull();
1130 EXPECT_EQ("is NULL", Describe(m));
1131 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1134 // Tests that NotNull() matches any non-NULL pointer of any type.
1135 TEST(NotNullTest, MatchesNonNullPointer) {
1136 Matcher<int*> m1 = NotNull();
1139 EXPECT_FALSE(m1.Matches(p1));
1140 EXPECT_TRUE(m1.Matches(&n));
1142 Matcher<const char*> m2 = NotNull();
1143 const char* p2 = nullptr;
1144 EXPECT_FALSE(m2.Matches(p2));
1145 EXPECT_TRUE(m2.Matches("hi"));
1148 TEST(NotNullTest, LinkedPtr) {
1149 const Matcher<std::shared_ptr<int>> m = NotNull();
1150 const std::shared_ptr<int> null_p;
1151 const std::shared_ptr<int> non_null_p(new int);
1153 EXPECT_FALSE(m.Matches(null_p));
1154 EXPECT_TRUE(m.Matches(non_null_p));
1157 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1158 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1159 const std::shared_ptr<double> null_p;
1160 const std::shared_ptr<double> non_null_p(new double);
1162 EXPECT_FALSE(m.Matches(null_p));
1163 EXPECT_TRUE(m.Matches(non_null_p));
1166 TEST(NotNullTest, StdFunction) {
1167 const Matcher<std::function<void()>> m = NotNull();
1169 EXPECT_TRUE(m.Matches([]{}));
1170 EXPECT_FALSE(m.Matches(std::function<void()>()));
1173 // Tests that NotNull() describes itself properly.
1174 TEST(NotNullTest, CanDescribeSelf) {
1175 Matcher<int*> m = NotNull();
1176 EXPECT_EQ("isn't NULL", Describe(m));
1179 // Tests that Ref(variable) matches an argument that references
1181 TEST(RefTest, MatchesSameVariable) {
1184 Matcher<int&> m = Ref(a);
1185 EXPECT_TRUE(m.Matches(a));
1186 EXPECT_FALSE(m.Matches(b));
1189 // Tests that Ref(variable) describes itself properly.
1190 TEST(RefTest, CanDescribeSelf) {
1192 Matcher<int&> m = Ref(n);
1194 ss << "references the variable @" << &n << " 5";
1195 EXPECT_EQ(ss.str(), Describe(m));
1198 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1200 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1203 Matcher<const int&> m = Ref(a);
1204 EXPECT_TRUE(m.Matches(a));
1205 EXPECT_FALSE(m.Matches(b));
1208 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1209 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1210 // of Ref(base), but not vice versa.
1212 TEST(RefTest, IsCovariant) {
1215 Matcher<const Base&> m1 = Ref(base);
1216 EXPECT_TRUE(m1.Matches(base));
1217 EXPECT_FALSE(m1.Matches(base2));
1218 EXPECT_FALSE(m1.Matches(derived));
1221 EXPECT_TRUE(m1.Matches(derived));
1222 EXPECT_FALSE(m1.Matches(base));
1223 EXPECT_FALSE(m1.Matches(base2));
1226 TEST(RefTest, ExplainsResult) {
1228 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1229 StartsWith("which is located @"));
1232 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1233 StartsWith("which is located @"));
1236 // Tests string comparison matchers.
1238 template <typename T = std::string>
1239 std::string FromStringLike(internal::StringLike<T> str) {
1240 return std::string(str);
1243 TEST(StringLike, TestConversions) {
1244 EXPECT_EQ("foo", FromStringLike("foo"));
1245 EXPECT_EQ("foo", FromStringLike(std::string("foo")));
1246 #if GTEST_INTERNAL_HAS_STRING_VIEW
1247 EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
1248 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1250 // Non deducible types.
1251 EXPECT_EQ("", FromStringLike({}));
1252 EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
1253 const char buf[] = "foo";
1254 EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
1257 TEST(StrEqTest, MatchesEqualString) {
1258 Matcher<const char*> m = StrEq(std::string("Hello"));
1259 EXPECT_TRUE(m.Matches("Hello"));
1260 EXPECT_FALSE(m.Matches("hello"));
1261 EXPECT_FALSE(m.Matches(nullptr));
1263 Matcher<const std::string&> m2 = StrEq("Hello");
1264 EXPECT_TRUE(m2.Matches("Hello"));
1265 EXPECT_FALSE(m2.Matches("Hi"));
1267 #if GTEST_INTERNAL_HAS_STRING_VIEW
1268 Matcher<const internal::StringView&> m3 =
1269 StrEq(internal::StringView("Hello"));
1270 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1271 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1272 EXPECT_FALSE(m3.Matches(internal::StringView()));
1274 Matcher<const internal::StringView&> m_empty = StrEq("");
1275 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1276 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1277 EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
1278 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1281 TEST(StrEqTest, CanDescribeSelf) {
1282 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1283 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1286 std::string str("01204500800");
1288 Matcher<std::string> m2 = StrEq(str);
1289 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1290 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1291 Matcher<std::string> m3 = StrEq(str);
1292 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1295 TEST(StrNeTest, MatchesUnequalString) {
1296 Matcher<const char*> m = StrNe("Hello");
1297 EXPECT_TRUE(m.Matches(""));
1298 EXPECT_TRUE(m.Matches(nullptr));
1299 EXPECT_FALSE(m.Matches("Hello"));
1301 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1302 EXPECT_TRUE(m2.Matches("hello"));
1303 EXPECT_FALSE(m2.Matches("Hello"));
1305 #if GTEST_INTERNAL_HAS_STRING_VIEW
1306 Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
1307 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1308 EXPECT_TRUE(m3.Matches(internal::StringView()));
1309 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1310 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1313 TEST(StrNeTest, CanDescribeSelf) {
1314 Matcher<const char*> m = StrNe("Hi");
1315 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1318 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1319 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1320 EXPECT_TRUE(m.Matches("Hello"));
1321 EXPECT_TRUE(m.Matches("hello"));
1322 EXPECT_FALSE(m.Matches("Hi"));
1323 EXPECT_FALSE(m.Matches(nullptr));
1325 Matcher<const std::string&> m2 = StrCaseEq("Hello");
1326 EXPECT_TRUE(m2.Matches("hello"));
1327 EXPECT_FALSE(m2.Matches("Hi"));
1329 #if GTEST_INTERNAL_HAS_STRING_VIEW
1330 Matcher<const internal::StringView&> m3 =
1331 StrCaseEq(internal::StringView("Hello"));
1332 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1333 EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
1334 EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
1335 EXPECT_FALSE(m3.Matches(internal::StringView()));
1336 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1339 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1340 std::string str1("oabocdooeoo");
1341 std::string str2("OABOCDOOEOO");
1342 Matcher<const std::string&> m0 = StrCaseEq(str1);
1343 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1345 str1[3] = str2[3] = '\0';
1346 Matcher<const std::string&> m1 = StrCaseEq(str1);
1347 EXPECT_TRUE(m1.Matches(str2));
1349 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1350 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1351 Matcher<const std::string&> m2 = StrCaseEq(str1);
1352 str1[9] = str2[9] = '\0';
1353 EXPECT_FALSE(m2.Matches(str2));
1355 Matcher<const std::string&> m3 = StrCaseEq(str1);
1356 EXPECT_TRUE(m3.Matches(str2));
1358 EXPECT_FALSE(m3.Matches(str2 + "x"));
1359 str2.append(1, '\0');
1360 EXPECT_FALSE(m3.Matches(str2));
1361 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1364 TEST(StrCaseEqTest, CanDescribeSelf) {
1365 Matcher<std::string> m = StrCaseEq("Hi");
1366 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1369 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1370 Matcher<const char*> m = StrCaseNe("Hello");
1371 EXPECT_TRUE(m.Matches("Hi"));
1372 EXPECT_TRUE(m.Matches(nullptr));
1373 EXPECT_FALSE(m.Matches("Hello"));
1374 EXPECT_FALSE(m.Matches("hello"));
1376 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1377 EXPECT_TRUE(m2.Matches(""));
1378 EXPECT_FALSE(m2.Matches("Hello"));
1380 #if GTEST_INTERNAL_HAS_STRING_VIEW
1381 Matcher<const internal::StringView> m3 =
1382 StrCaseNe(internal::StringView("Hello"));
1383 EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
1384 EXPECT_TRUE(m3.Matches(internal::StringView()));
1385 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1386 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1387 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1390 TEST(StrCaseNeTest, CanDescribeSelf) {
1391 Matcher<const char*> m = StrCaseNe("Hi");
1392 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1395 // Tests that HasSubstr() works for matching string-typed values.
1396 TEST(HasSubstrTest, WorksForStringClasses) {
1397 const Matcher<std::string> m1 = HasSubstr("foo");
1398 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1399 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1401 const Matcher<const std::string&> m2 = HasSubstr("foo");
1402 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1403 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1405 const Matcher<std::string> m_empty = HasSubstr("");
1406 EXPECT_TRUE(m_empty.Matches(std::string()));
1407 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1410 // Tests that HasSubstr() works for matching C-string-typed values.
1411 TEST(HasSubstrTest, WorksForCStrings) {
1412 const Matcher<char*> m1 = HasSubstr("foo");
1413 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1414 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1415 EXPECT_FALSE(m1.Matches(nullptr));
1417 const Matcher<const char*> m2 = HasSubstr("foo");
1418 EXPECT_TRUE(m2.Matches("I love food."));
1419 EXPECT_FALSE(m2.Matches("tofo"));
1420 EXPECT_FALSE(m2.Matches(nullptr));
1422 const Matcher<const char*> m_empty = HasSubstr("");
1423 EXPECT_TRUE(m_empty.Matches("not empty"));
1424 EXPECT_TRUE(m_empty.Matches(""));
1425 EXPECT_FALSE(m_empty.Matches(nullptr));
1428 #if GTEST_INTERNAL_HAS_STRING_VIEW
1429 // Tests that HasSubstr() works for matching StringView-typed values.
1430 TEST(HasSubstrTest, WorksForStringViewClasses) {
1431 const Matcher<internal::StringView> m1 =
1432 HasSubstr(internal::StringView("foo"));
1433 EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
1434 EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
1435 EXPECT_FALSE(m1.Matches(internal::StringView()));
1437 const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
1438 EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
1439 EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
1440 EXPECT_FALSE(m2.Matches(internal::StringView()));
1442 const Matcher<const internal::StringView&> m3 = HasSubstr("");
1443 EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
1444 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1445 EXPECT_TRUE(m3.Matches(internal::StringView()));
1447 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1449 // Tests that HasSubstr(s) describes itself properly.
1450 TEST(HasSubstrTest, CanDescribeSelf) {
1451 Matcher<std::string> m = HasSubstr("foo\n\"");
1452 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1455 TEST(KeyTest, CanDescribeSelf) {
1456 Matcher<const pair<std::string, int>&> m = Key("foo");
1457 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1458 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1461 TEST(KeyTest, ExplainsResult) {
1462 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1463 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1464 Explain(m, make_pair(5, true)));
1465 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1466 Explain(m, make_pair(15, true)));
1469 TEST(KeyTest, MatchesCorrectly) {
1470 pair<int, std::string> p(25, "foo");
1471 EXPECT_THAT(p, Key(25));
1472 EXPECT_THAT(p, Not(Key(42)));
1473 EXPECT_THAT(p, Key(Ge(20)));
1474 EXPECT_THAT(p, Not(Key(Lt(25))));
1477 TEST(KeyTest, WorksWithMoveOnly) {
1478 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1479 EXPECT_THAT(p, Key(Eq(nullptr)));
1485 struct PairWithGet {
1487 std::string member_2;
1488 using first_type = int;
1489 using second_type = std::string;
1491 const int& GetImpl(Tag<0>) const { return member_1; }
1492 const std::string& GetImpl(Tag<1>) const { return member_2; }
1495 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1496 return value.GetImpl(Tag<I>());
1498 TEST(PairTest, MatchesPairWithGetCorrectly) {
1499 PairWithGet p{25, "foo"};
1500 EXPECT_THAT(p, Key(25));
1501 EXPECT_THAT(p, Not(Key(42)));
1502 EXPECT_THAT(p, Key(Ge(20)));
1503 EXPECT_THAT(p, Not(Key(Lt(25))));
1505 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1506 EXPECT_THAT(v, Contains(Key(29)));
1509 TEST(KeyTest, SafelyCastsInnerMatcher) {
1510 Matcher<int> is_positive = Gt(0);
1511 Matcher<int> is_negative = Lt(0);
1512 pair<char, bool> p('a', true);
1513 EXPECT_THAT(p, Key(is_positive));
1514 EXPECT_THAT(p, Not(Key(is_negative)));
1517 TEST(KeyTest, InsideContainsUsingMap) {
1518 map<int, char> container;
1519 container.insert(make_pair(1, 'a'));
1520 container.insert(make_pair(2, 'b'));
1521 container.insert(make_pair(4, 'c'));
1522 EXPECT_THAT(container, Contains(Key(1)));
1523 EXPECT_THAT(container, Not(Contains(Key(3))));
1526 TEST(KeyTest, InsideContainsUsingMultimap) {
1527 multimap<int, char> container;
1528 container.insert(make_pair(1, 'a'));
1529 container.insert(make_pair(2, 'b'));
1530 container.insert(make_pair(4, 'c'));
1532 EXPECT_THAT(container, Not(Contains(Key(25))));
1533 container.insert(make_pair(25, 'd'));
1534 EXPECT_THAT(container, Contains(Key(25)));
1535 container.insert(make_pair(25, 'e'));
1536 EXPECT_THAT(container, Contains(Key(25)));
1538 EXPECT_THAT(container, Contains(Key(1)));
1539 EXPECT_THAT(container, Not(Contains(Key(3))));
1542 TEST(PairTest, Typing) {
1543 // Test verifies the following type conversions can be compiled.
1544 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1545 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1546 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1548 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1549 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1552 TEST(PairTest, CanDescribeSelf) {
1553 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1554 EXPECT_EQ("has a first field that is equal to \"foo\""
1555 ", and has a second field that is equal to 42",
1557 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1558 ", or has a second field that isn't equal to 42",
1559 DescribeNegation(m1));
1560 // Double and triple negation (1 or 2 times not and description of negation).
1561 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1562 EXPECT_EQ("has a first field that isn't equal to 13"
1563 ", and has a second field that is equal to 42",
1564 DescribeNegation(m2));
1567 TEST(PairTest, CanExplainMatchResultTo) {
1568 // If neither field matches, Pair() should explain about the first
1570 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1571 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1572 Explain(m, make_pair(-1, -2)));
1574 // If the first field matches but the second doesn't, Pair() should
1575 // explain about the second field.
1576 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1577 Explain(m, make_pair(1, -2)));
1579 // If the first field doesn't match but the second does, Pair()
1580 // should explain about the first field.
1581 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1582 Explain(m, make_pair(-1, 2)));
1584 // If both fields match, Pair() should explain about them both.
1585 EXPECT_EQ("whose both fields match, where the first field is a value "
1586 "which is 1 more than 0, and the second field is a value "
1587 "which is 2 more than 0",
1588 Explain(m, make_pair(1, 2)));
1590 // If only the first match has an explanation, only this explanation should
1592 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1593 EXPECT_EQ("whose both fields match, where the first field is a value "
1594 "which is 1 more than 0",
1595 Explain(explain_first, make_pair(1, 0)));
1597 // If only the second match has an explanation, only this explanation should
1599 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1600 EXPECT_EQ("whose both fields match, where the second field is a value "
1601 "which is 1 more than 0",
1602 Explain(explain_second, make_pair(0, 1)));
1605 TEST(PairTest, MatchesCorrectly) {
1606 pair<int, std::string> p(25, "foo");
1608 // Both fields match.
1609 EXPECT_THAT(p, Pair(25, "foo"));
1610 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1612 // 'first' doesnt' match, but 'second' matches.
1613 EXPECT_THAT(p, Not(Pair(42, "foo")));
1614 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1616 // 'first' matches, but 'second' doesn't match.
1617 EXPECT_THAT(p, Not(Pair(25, "bar")));
1618 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1620 // Neither field matches.
1621 EXPECT_THAT(p, Not(Pair(13, "bar")));
1622 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1625 TEST(PairTest, WorksWithMoveOnly) {
1626 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1627 p.second.reset(new int(7));
1628 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1631 TEST(PairTest, SafelyCastsInnerMatchers) {
1632 Matcher<int> is_positive = Gt(0);
1633 Matcher<int> is_negative = Lt(0);
1634 pair<char, bool> p('a', true);
1635 EXPECT_THAT(p, Pair(is_positive, _));
1636 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1637 EXPECT_THAT(p, Pair(_, is_positive));
1638 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1641 TEST(PairTest, InsideContainsUsingMap) {
1642 map<int, char> container;
1643 container.insert(make_pair(1, 'a'));
1644 container.insert(make_pair(2, 'b'));
1645 container.insert(make_pair(4, 'c'));
1646 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1647 EXPECT_THAT(container, Contains(Pair(1, _)));
1648 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1649 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1652 TEST(FieldsAreTest, MatchesCorrectly) {
1653 std::tuple<int, std::string, double> p(25, "foo", .5);
1655 // All fields match.
1656 EXPECT_THAT(p, FieldsAre(25, "foo", .5));
1657 EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
1659 // Some don't match.
1660 EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
1661 EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
1662 EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
1665 TEST(FieldsAreTest, CanDescribeSelf) {
1666 Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
1668 "has field #0 that is equal to \"foo\""
1669 ", and has field #1 that is equal to 42",
1672 "has field #0 that isn't equal to \"foo\""
1673 ", or has field #1 that isn't equal to 42",
1674 DescribeNegation(m1));
1677 TEST(FieldsAreTest, CanExplainMatchResultTo) {
1678 // The first one that fails is the one that gives the error.
1679 Matcher<std::tuple<int, int, int>> m =
1680 FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
1682 EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
1683 Explain(m, std::make_tuple(-1, -2, -3)));
1684 EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
1685 Explain(m, std::make_tuple(1, -2, -3)));
1686 EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
1687 Explain(m, std::make_tuple(1, 2, -3)));
1689 // If they all match, we get a long explanation of success.
1691 "whose all elements match, "
1692 "where field #0 is a value which is 1 more than 0"
1693 ", and field #1 is a value which is 2 more than 0"
1694 ", and field #2 is a value which is 3 more than 0",
1695 Explain(m, std::make_tuple(1, 2, 3)));
1697 // Only print those that have an explanation.
1698 m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
1700 "whose all elements match, "
1701 "where field #0 is a value which is 1 more than 0"
1702 ", and field #2 is a value which is 3 more than 0",
1703 Explain(m, std::make_tuple(1, 0, 3)));
1705 // If only one has an explanation, then print that one.
1706 m = FieldsAre(0, GreaterThan(0), 0);
1708 "whose all elements match, "
1709 "where field #1 is a value which is 1 more than 0",
1710 Explain(m, std::make_tuple(0, 1, 0)));
1713 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
1714 TEST(FieldsAreTest, StructuredBindings) {
1715 // testing::FieldsAre can also match aggregates and such with C++17 and up.
1720 EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
1722 // Test all the supported arities.
1726 EXPECT_THAT(MyVarType1{}, FieldsAre(0));
1730 EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
1734 EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
1738 EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
1742 EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
1744 int a, b, c, d, e, f;
1746 EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
1748 int a, b, c, d, e, f, g;
1750 EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
1752 int a, b, c, d, e, f, g, h;
1754 EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
1756 int a, b, c, d, e, f, g, h, i;
1758 EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
1759 struct MyVarType10 {
1760 int a, b, c, d, e, f, g, h, i, j;
1762 EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1763 struct MyVarType11 {
1764 int a, b, c, d, e, f, g, h, i, j, k;
1766 EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1767 struct MyVarType12 {
1768 int a, b, c, d, e, f, g, h, i, j, k, l;
1770 EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1771 struct MyVarType13 {
1772 int a, b, c, d, e, f, g, h, i, j, k, l, m;
1774 EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1775 struct MyVarType14 {
1776 int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
1778 EXPECT_THAT(MyVarType14{},
1779 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1780 struct MyVarType15 {
1781 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
1783 EXPECT_THAT(MyVarType15{},
1784 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1785 struct MyVarType16 {
1786 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
1788 EXPECT_THAT(MyVarType16{},
1789 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1793 TEST(ContainsTest, WorksWithMoveOnly) {
1794 ContainerHelper helper;
1795 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1796 helper.Call(MakeUniquePtrs({1, 2}));
1799 TEST(PairTest, UseGetInsteadOfMembers) {
1800 PairWithGet pair{7, "ABC"};
1801 EXPECT_THAT(pair, Pair(7, "ABC"));
1802 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1803 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1805 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1807 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1810 // Tests StartsWith(s).
1812 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1813 const Matcher<const char*> m1 = StartsWith(std::string(""));
1814 EXPECT_TRUE(m1.Matches("Hi"));
1815 EXPECT_TRUE(m1.Matches(""));
1816 EXPECT_FALSE(m1.Matches(nullptr));
1818 const Matcher<const std::string&> m2 = StartsWith("Hi");
1819 EXPECT_TRUE(m2.Matches("Hi"));
1820 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1821 EXPECT_TRUE(m2.Matches("High"));
1822 EXPECT_FALSE(m2.Matches("H"));
1823 EXPECT_FALSE(m2.Matches(" Hi"));
1825 #if GTEST_INTERNAL_HAS_STRING_VIEW
1826 const Matcher<internal::StringView> m_empty =
1827 StartsWith(internal::StringView(""));
1828 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1829 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1830 EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
1831 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1834 TEST(StartsWithTest, CanDescribeSelf) {
1835 Matcher<const std::string> m = StartsWith("Hi");
1836 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1839 // Tests EndsWith(s).
1841 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1842 const Matcher<const char*> m1 = EndsWith("");
1843 EXPECT_TRUE(m1.Matches("Hi"));
1844 EXPECT_TRUE(m1.Matches(""));
1845 EXPECT_FALSE(m1.Matches(nullptr));
1847 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1848 EXPECT_TRUE(m2.Matches("Hi"));
1849 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1850 EXPECT_TRUE(m2.Matches("Super Hi"));
1851 EXPECT_FALSE(m2.Matches("i"));
1852 EXPECT_FALSE(m2.Matches("Hi "));
1854 #if GTEST_INTERNAL_HAS_STRING_VIEW
1855 const Matcher<const internal::StringView&> m4 =
1856 EndsWith(internal::StringView(""));
1857 EXPECT_TRUE(m4.Matches("Hi"));
1858 EXPECT_TRUE(m4.Matches(""));
1859 EXPECT_TRUE(m4.Matches(internal::StringView()));
1860 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1861 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1864 TEST(EndsWithTest, CanDescribeSelf) {
1865 Matcher<const std::string> m = EndsWith("Hi");
1866 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1869 // Tests MatchesRegex().
1871 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1872 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1873 EXPECT_TRUE(m1.Matches("az"));
1874 EXPECT_TRUE(m1.Matches("abcz"));
1875 EXPECT_FALSE(m1.Matches(nullptr));
1877 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1878 EXPECT_TRUE(m2.Matches("azbz"));
1879 EXPECT_FALSE(m2.Matches("az1"));
1880 EXPECT_FALSE(m2.Matches("1az"));
1882 #if GTEST_INTERNAL_HAS_STRING_VIEW
1883 const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
1884 EXPECT_TRUE(m3.Matches(internal::StringView("az")));
1885 EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
1886 EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
1887 EXPECT_FALSE(m3.Matches(internal::StringView()));
1888 const Matcher<const internal::StringView&> m4 =
1889 MatchesRegex(internal::StringView(""));
1890 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1891 EXPECT_TRUE(m4.Matches(internal::StringView()));
1892 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1895 TEST(MatchesRegexTest, CanDescribeSelf) {
1896 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1897 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1899 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1900 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1902 #if GTEST_INTERNAL_HAS_STRING_VIEW
1903 Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
1904 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1905 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1908 // Tests ContainsRegex().
1910 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1911 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1912 EXPECT_TRUE(m1.Matches("az"));
1913 EXPECT_TRUE(m1.Matches("0abcz1"));
1914 EXPECT_FALSE(m1.Matches(nullptr));
1916 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1917 EXPECT_TRUE(m2.Matches("azbz"));
1918 EXPECT_TRUE(m2.Matches("az1"));
1919 EXPECT_FALSE(m2.Matches("1a"));
1921 #if GTEST_INTERNAL_HAS_STRING_VIEW
1922 const Matcher<const internal::StringView&> m3 =
1923 ContainsRegex(new RE("a.*z"));
1924 EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
1925 EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
1926 EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
1927 EXPECT_FALSE(m3.Matches(internal::StringView()));
1928 const Matcher<const internal::StringView&> m4 =
1929 ContainsRegex(internal::StringView(""));
1930 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1931 EXPECT_TRUE(m4.Matches(internal::StringView()));
1932 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1935 TEST(ContainsRegexTest, CanDescribeSelf) {
1936 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1937 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1939 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1940 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1942 #if GTEST_INTERNAL_HAS_STRING_VIEW
1943 Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
1944 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1945 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1948 // Tests for wide strings.
1949 #if GTEST_HAS_STD_WSTRING
1950 TEST(StdWideStrEqTest, MatchesEqual) {
1951 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1952 EXPECT_TRUE(m.Matches(L"Hello"));
1953 EXPECT_FALSE(m.Matches(L"hello"));
1954 EXPECT_FALSE(m.Matches(nullptr));
1956 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1957 EXPECT_TRUE(m2.Matches(L"Hello"));
1958 EXPECT_FALSE(m2.Matches(L"Hi"));
1960 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1961 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1962 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1964 ::std::wstring str(L"01204500800");
1966 Matcher<const ::std::wstring&> m4 = StrEq(str);
1967 EXPECT_TRUE(m4.Matches(str));
1968 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1969 Matcher<const ::std::wstring&> m5 = StrEq(str);
1970 EXPECT_TRUE(m5.Matches(str));
1973 TEST(StdWideStrEqTest, CanDescribeSelf) {
1974 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1975 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1978 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1979 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1982 ::std::wstring str(L"01204500800");
1984 Matcher<const ::std::wstring&> m4 = StrEq(str);
1985 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1986 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1987 Matcher<const ::std::wstring&> m5 = StrEq(str);
1988 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1991 TEST(StdWideStrNeTest, MatchesUnequalString) {
1992 Matcher<const wchar_t*> m = StrNe(L"Hello");
1993 EXPECT_TRUE(m.Matches(L""));
1994 EXPECT_TRUE(m.Matches(nullptr));
1995 EXPECT_FALSE(m.Matches(L"Hello"));
1997 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1998 EXPECT_TRUE(m2.Matches(L"hello"));
1999 EXPECT_FALSE(m2.Matches(L"Hello"));
2002 TEST(StdWideStrNeTest, CanDescribeSelf) {
2003 Matcher<const wchar_t*> m = StrNe(L"Hi");
2004 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
2007 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2008 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
2009 EXPECT_TRUE(m.Matches(L"Hello"));
2010 EXPECT_TRUE(m.Matches(L"hello"));
2011 EXPECT_FALSE(m.Matches(L"Hi"));
2012 EXPECT_FALSE(m.Matches(nullptr));
2014 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
2015 EXPECT_TRUE(m2.Matches(L"hello"));
2016 EXPECT_FALSE(m2.Matches(L"Hi"));
2019 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
2020 ::std::wstring str1(L"oabocdooeoo");
2021 ::std::wstring str2(L"OABOCDOOEOO");
2022 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
2023 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
2025 str1[3] = str2[3] = L'\0';
2026 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
2027 EXPECT_TRUE(m1.Matches(str2));
2029 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
2030 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
2031 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
2032 str1[9] = str2[9] = L'\0';
2033 EXPECT_FALSE(m2.Matches(str2));
2035 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
2036 EXPECT_TRUE(m3.Matches(str2));
2038 EXPECT_FALSE(m3.Matches(str2 + L"x"));
2039 str2.append(1, L'\0');
2040 EXPECT_FALSE(m3.Matches(str2));
2041 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
2044 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2045 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
2046 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2049 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2050 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2051 EXPECT_TRUE(m.Matches(L"Hi"));
2052 EXPECT_TRUE(m.Matches(nullptr));
2053 EXPECT_FALSE(m.Matches(L"Hello"));
2054 EXPECT_FALSE(m.Matches(L"hello"));
2056 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
2057 EXPECT_TRUE(m2.Matches(L""));
2058 EXPECT_FALSE(m2.Matches(L"Hello"));
2061 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2062 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2063 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2066 // Tests that HasSubstr() works for matching wstring-typed values.
2067 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2068 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
2069 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
2070 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
2072 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
2073 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
2074 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
2077 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2078 TEST(StdWideHasSubstrTest, WorksForCStrings) {
2079 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2080 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2081 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
2082 EXPECT_FALSE(m1.Matches(nullptr));
2084 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2085 EXPECT_TRUE(m2.Matches(L"I love food."));
2086 EXPECT_FALSE(m2.Matches(L"tofo"));
2087 EXPECT_FALSE(m2.Matches(nullptr));
2090 // Tests that HasSubstr(s) describes itself properly.
2091 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2092 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
2093 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2096 // Tests StartsWith(s).
2098 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2099 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
2100 EXPECT_TRUE(m1.Matches(L"Hi"));
2101 EXPECT_TRUE(m1.Matches(L""));
2102 EXPECT_FALSE(m1.Matches(nullptr));
2104 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
2105 EXPECT_TRUE(m2.Matches(L"Hi"));
2106 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2107 EXPECT_TRUE(m2.Matches(L"High"));
2108 EXPECT_FALSE(m2.Matches(L"H"));
2109 EXPECT_FALSE(m2.Matches(L" Hi"));
2112 TEST(StdWideStartsWithTest, CanDescribeSelf) {
2113 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2114 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2117 // Tests EndsWith(s).
2119 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2120 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2121 EXPECT_TRUE(m1.Matches(L"Hi"));
2122 EXPECT_TRUE(m1.Matches(L""));
2123 EXPECT_FALSE(m1.Matches(nullptr));
2125 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2126 EXPECT_TRUE(m2.Matches(L"Hi"));
2127 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2128 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2129 EXPECT_FALSE(m2.Matches(L"i"));
2130 EXPECT_FALSE(m2.Matches(L"Hi "));
2133 TEST(StdWideEndsWithTest, CanDescribeSelf) {
2134 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2135 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2138 #endif // GTEST_HAS_STD_WSTRING
2140 typedef ::std::tuple<long, int> Tuple2; // NOLINT
2142 // Tests that Eq() matches a 2-tuple where the first field == the
2144 TEST(Eq2Test, MatchesEqualArguments) {
2145 Matcher<const Tuple2&> m = Eq();
2146 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2147 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2150 // Tests that Eq() describes itself properly.
2151 TEST(Eq2Test, CanDescribeSelf) {
2152 Matcher<const Tuple2&> m = Eq();
2153 EXPECT_EQ("are an equal pair", Describe(m));
2156 // Tests that Ge() matches a 2-tuple where the first field >= the
2158 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2159 Matcher<const Tuple2&> m = Ge();
2160 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2161 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2162 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2165 // Tests that Ge() describes itself properly.
2166 TEST(Ge2Test, CanDescribeSelf) {
2167 Matcher<const Tuple2&> m = Ge();
2168 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2171 // Tests that Gt() matches a 2-tuple where the first field > the
2173 TEST(Gt2Test, MatchesGreaterThanArguments) {
2174 Matcher<const Tuple2&> m = Gt();
2175 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2176 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2177 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2180 // Tests that Gt() describes itself properly.
2181 TEST(Gt2Test, CanDescribeSelf) {
2182 Matcher<const Tuple2&> m = Gt();
2183 EXPECT_EQ("are a pair where the first > the second", Describe(m));
2186 // Tests that Le() matches a 2-tuple where the first field <= the
2188 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2189 Matcher<const Tuple2&> m = Le();
2190 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2191 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2192 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2195 // Tests that Le() describes itself properly.
2196 TEST(Le2Test, CanDescribeSelf) {
2197 Matcher<const Tuple2&> m = Le();
2198 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2201 // Tests that Lt() matches a 2-tuple where the first field < the
2203 TEST(Lt2Test, MatchesLessThanArguments) {
2204 Matcher<const Tuple2&> m = Lt();
2205 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2206 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2207 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2210 // Tests that Lt() describes itself properly.
2211 TEST(Lt2Test, CanDescribeSelf) {
2212 Matcher<const Tuple2&> m = Lt();
2213 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2216 // Tests that Ne() matches a 2-tuple where the first field != the
2218 TEST(Ne2Test, MatchesUnequalArguments) {
2219 Matcher<const Tuple2&> m = Ne();
2220 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2221 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2222 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2225 // Tests that Ne() describes itself properly.
2226 TEST(Ne2Test, CanDescribeSelf) {
2227 Matcher<const Tuple2&> m = Ne();
2228 EXPECT_EQ("are an unequal pair", Describe(m));
2231 TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2232 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2233 Matcher<Pointers> matcher = Eq();
2235 // Tested values don't matter; the point is that matcher does not copy the
2237 EXPECT_TRUE(matcher.Matches(pointers));
2240 // Tests that IsNan() matches a NaN, with float.
2241 TEST(IsNan, FloatMatchesNan) {
2242 float quiet_nan = std::numeric_limits<float>::quiet_NaN();
2243 float other_nan = std::nanf("1");
2244 float real_value = 1.0f;
2246 Matcher<float> m = IsNan();
2247 EXPECT_TRUE(m.Matches(quiet_nan));
2248 EXPECT_TRUE(m.Matches(other_nan));
2249 EXPECT_FALSE(m.Matches(real_value));
2251 Matcher<float&> m_ref = IsNan();
2252 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2253 EXPECT_TRUE(m_ref.Matches(other_nan));
2254 EXPECT_FALSE(m_ref.Matches(real_value));
2256 Matcher<const float&> m_cref = IsNan();
2257 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2258 EXPECT_TRUE(m_cref.Matches(other_nan));
2259 EXPECT_FALSE(m_cref.Matches(real_value));
2262 // Tests that IsNan() matches a NaN, with double.
2263 TEST(IsNan, DoubleMatchesNan) {
2264 double quiet_nan = std::numeric_limits<double>::quiet_NaN();
2265 double other_nan = std::nan("1");
2266 double real_value = 1.0;
2268 Matcher<double> m = IsNan();
2269 EXPECT_TRUE(m.Matches(quiet_nan));
2270 EXPECT_TRUE(m.Matches(other_nan));
2271 EXPECT_FALSE(m.Matches(real_value));
2273 Matcher<double&> m_ref = IsNan();
2274 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2275 EXPECT_TRUE(m_ref.Matches(other_nan));
2276 EXPECT_FALSE(m_ref.Matches(real_value));
2278 Matcher<const double&> m_cref = IsNan();
2279 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2280 EXPECT_TRUE(m_cref.Matches(other_nan));
2281 EXPECT_FALSE(m_cref.Matches(real_value));
2284 // Tests that IsNan() matches a NaN, with long double.
2285 TEST(IsNan, LongDoubleMatchesNan) {
2286 long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
2287 long double other_nan = std::nan("1");
2288 long double real_value = 1.0;
2290 Matcher<long double> m = IsNan();
2291 EXPECT_TRUE(m.Matches(quiet_nan));
2292 EXPECT_TRUE(m.Matches(other_nan));
2293 EXPECT_FALSE(m.Matches(real_value));
2295 Matcher<long double&> m_ref = IsNan();
2296 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2297 EXPECT_TRUE(m_ref.Matches(other_nan));
2298 EXPECT_FALSE(m_ref.Matches(real_value));
2300 Matcher<const long double&> m_cref = IsNan();
2301 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2302 EXPECT_TRUE(m_cref.Matches(other_nan));
2303 EXPECT_FALSE(m_cref.Matches(real_value));
2306 // Tests that IsNan() works with Not.
2307 TEST(IsNan, NotMatchesNan) {
2308 Matcher<float> mf = Not(IsNan());
2309 EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2310 EXPECT_FALSE(mf.Matches(std::nanf("1")));
2311 EXPECT_TRUE(mf.Matches(1.0));
2313 Matcher<double> md = Not(IsNan());
2314 EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2315 EXPECT_FALSE(md.Matches(std::nan("1")));
2316 EXPECT_TRUE(md.Matches(1.0));
2318 Matcher<long double> mld = Not(IsNan());
2319 EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2320 EXPECT_FALSE(mld.Matches(std::nanl("1")));
2321 EXPECT_TRUE(mld.Matches(1.0));
2324 // Tests that IsNan() can describe itself.
2325 TEST(IsNan, CanDescribeSelf) {
2326 Matcher<float> mf = IsNan();
2327 EXPECT_EQ("is NaN", Describe(mf));
2329 Matcher<double> md = IsNan();
2330 EXPECT_EQ("is NaN", Describe(md));
2332 Matcher<long double> mld = IsNan();
2333 EXPECT_EQ("is NaN", Describe(mld));
2336 // Tests that IsNan() can describe itself with Not.
2337 TEST(IsNan, CanDescribeSelfWithNot) {
2338 Matcher<float> mf = Not(IsNan());
2339 EXPECT_EQ("isn't NaN", Describe(mf));
2341 Matcher<double> md = Not(IsNan());
2342 EXPECT_EQ("isn't NaN", Describe(md));
2344 Matcher<long double> mld = Not(IsNan());
2345 EXPECT_EQ("isn't NaN", Describe(mld));
2348 // Tests that FloatEq() matches a 2-tuple where
2349 // FloatEq(first field) matches the second field.
2350 TEST(FloatEq2Test, MatchesEqualArguments) {
2351 typedef ::std::tuple<float, float> Tpl;
2352 Matcher<const Tpl&> m = FloatEq();
2353 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2354 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2355 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2358 // Tests that FloatEq() describes itself properly.
2359 TEST(FloatEq2Test, CanDescribeSelf) {
2360 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2361 EXPECT_EQ("are an almost-equal pair", Describe(m));
2364 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2365 // NanSensitiveFloatEq(first field) matches the second field.
2366 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2367 typedef ::std::tuple<float, float> Tpl;
2368 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2369 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2370 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2371 std::numeric_limits<float>::quiet_NaN())));
2372 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2373 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2374 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2377 // Tests that NanSensitiveFloatEq() describes itself properly.
2378 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2379 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2380 EXPECT_EQ("are an almost-equal pair", Describe(m));
2383 // Tests that DoubleEq() matches a 2-tuple where
2384 // DoubleEq(first field) matches the second field.
2385 TEST(DoubleEq2Test, MatchesEqualArguments) {
2386 typedef ::std::tuple<double, double> Tpl;
2387 Matcher<const Tpl&> m = DoubleEq();
2388 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2389 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2390 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2393 // Tests that DoubleEq() describes itself properly.
2394 TEST(DoubleEq2Test, CanDescribeSelf) {
2395 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2396 EXPECT_EQ("are an almost-equal pair", Describe(m));
2399 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2400 // NanSensitiveDoubleEq(first field) matches the second field.
2401 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2402 typedef ::std::tuple<double, double> Tpl;
2403 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2404 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2405 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2406 std::numeric_limits<double>::quiet_NaN())));
2407 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2408 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2409 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2412 // Tests that DoubleEq() describes itself properly.
2413 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2414 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2415 EXPECT_EQ("are an almost-equal pair", Describe(m));
2418 // Tests that FloatEq() matches a 2-tuple where
2419 // FloatNear(first field, max_abs_error) matches the second field.
2420 TEST(FloatNear2Test, MatchesEqualArguments) {
2421 typedef ::std::tuple<float, float> Tpl;
2422 Matcher<const Tpl&> m = FloatNear(0.5f);
2423 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2424 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2425 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2428 // Tests that FloatNear() describes itself properly.
2429 TEST(FloatNear2Test, CanDescribeSelf) {
2430 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2431 EXPECT_EQ("are an almost-equal pair", Describe(m));
2434 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2435 // NanSensitiveFloatNear(first field) matches the second field.
2436 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2437 typedef ::std::tuple<float, float> Tpl;
2438 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2439 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2440 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2441 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2442 std::numeric_limits<float>::quiet_NaN())));
2443 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2444 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2445 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2448 // Tests that NanSensitiveFloatNear() describes itself properly.
2449 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2450 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2451 EXPECT_EQ("are an almost-equal pair", Describe(m));
2454 // Tests that FloatEq() matches a 2-tuple where
2455 // DoubleNear(first field, max_abs_error) matches the second field.
2456 TEST(DoubleNear2Test, MatchesEqualArguments) {
2457 typedef ::std::tuple<double, double> Tpl;
2458 Matcher<const Tpl&> m = DoubleNear(0.5);
2459 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2460 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2461 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2464 // Tests that DoubleNear() describes itself properly.
2465 TEST(DoubleNear2Test, CanDescribeSelf) {
2466 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2467 EXPECT_EQ("are an almost-equal pair", Describe(m));
2470 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2471 // NanSensitiveDoubleNear(first field) matches the second field.
2472 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2473 typedef ::std::tuple<double, double> Tpl;
2474 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2475 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2476 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2477 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2478 std::numeric_limits<double>::quiet_NaN())));
2479 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2480 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2481 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2484 // Tests that NanSensitiveDoubleNear() describes itself properly.
2485 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2486 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2487 EXPECT_EQ("are an almost-equal pair", Describe(m));
2490 // Tests that Not(m) matches any value that doesn't match m.
2491 TEST(NotTest, NegatesMatcher) {
2494 EXPECT_TRUE(m.Matches(3));
2495 EXPECT_FALSE(m.Matches(2));
2498 // Tests that Not(m) describes itself properly.
2499 TEST(NotTest, CanDescribeSelf) {
2500 Matcher<int> m = Not(Eq(5));
2501 EXPECT_EQ("isn't equal to 5", Describe(m));
2504 // Tests that monomorphic matchers are safely cast by the Not matcher.
2505 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2506 // greater_than_5 is a monomorphic matcher.
2507 Matcher<int> greater_than_5 = Gt(5);
2509 Matcher<const int&> m = Not(greater_than_5);
2510 Matcher<int&> m2 = Not(greater_than_5);
2511 Matcher<int&> m3 = Not(m);
2514 // Helper to allow easy testing of AllOf matchers with num parameters.
2515 void AllOfMatches(int num, const Matcher<int>& m) {
2516 SCOPED_TRACE(Describe(m));
2517 EXPECT_TRUE(m.Matches(0));
2518 for (int i = 1; i <= num; ++i) {
2519 EXPECT_FALSE(m.Matches(i));
2521 EXPECT_TRUE(m.Matches(num + 1));
2524 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2525 // the given matchers.
2526 TEST(AllOfTest, MatchesWhenAllMatch) {
2528 m = AllOf(Le(2), Ge(1));
2529 EXPECT_TRUE(m.Matches(1));
2530 EXPECT_TRUE(m.Matches(2));
2531 EXPECT_FALSE(m.Matches(0));
2532 EXPECT_FALSE(m.Matches(3));
2534 m = AllOf(Gt(0), Ne(1), Ne(2));
2535 EXPECT_TRUE(m.Matches(3));
2536 EXPECT_FALSE(m.Matches(2));
2537 EXPECT_FALSE(m.Matches(1));
2538 EXPECT_FALSE(m.Matches(0));
2540 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2541 EXPECT_TRUE(m.Matches(4));
2542 EXPECT_FALSE(m.Matches(3));
2543 EXPECT_FALSE(m.Matches(2));
2544 EXPECT_FALSE(m.Matches(1));
2545 EXPECT_FALSE(m.Matches(0));
2547 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2548 EXPECT_TRUE(m.Matches(0));
2549 EXPECT_TRUE(m.Matches(1));
2550 EXPECT_FALSE(m.Matches(3));
2552 // The following tests for varying number of sub-matchers. Due to the way
2553 // the sub-matchers are handled it is enough to test every sub-matcher once
2554 // with sub-matchers using the same matcher type. Varying matcher types are
2555 // checked for above.
2556 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2557 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2558 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2559 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2560 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2561 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2562 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2564 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2566 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2569 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2570 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2571 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2572 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2573 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2574 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2579 // Tests that AllOf(m1, ..., mn) describes itself properly.
2580 TEST(AllOfTest, CanDescribeSelf) {
2582 m = AllOf(Le(2), Ge(1));
2583 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2585 m = AllOf(Gt(0), Ne(1), Ne(2));
2586 std::string expected_descr1 =
2587 "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2588 EXPECT_EQ(expected_descr1, Describe(m));
2590 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2591 std::string expected_descr2 =
2592 "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2594 EXPECT_EQ(expected_descr2, Describe(m));
2596 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2597 std::string expected_descr3 =
2598 "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2599 "and (isn't equal to 7)";
2600 EXPECT_EQ(expected_descr3, Describe(m));
2603 // Tests that AllOf(m1, ..., mn) describes its negation properly.
2604 TEST(AllOfTest, CanDescribeNegation) {
2606 m = AllOf(Le(2), Ge(1));
2607 std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2608 EXPECT_EQ(expected_descr4, DescribeNegation(m));
2610 m = AllOf(Gt(0), Ne(1), Ne(2));
2611 std::string expected_descr5 =
2612 "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2613 EXPECT_EQ(expected_descr5, DescribeNegation(m));
2615 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2616 std::string expected_descr6 =
2617 "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2618 EXPECT_EQ(expected_descr6, DescribeNegation(m));
2620 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2621 std::string expected_desr7 =
2622 "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2624 EXPECT_EQ(expected_desr7, DescribeNegation(m));
2626 m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2628 AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2629 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2630 AllOfMatches(11, m);
2633 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
2634 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2635 // greater_than_5 and less_than_10 are monomorphic matchers.
2636 Matcher<int> greater_than_5 = Gt(5);
2637 Matcher<int> less_than_10 = Lt(10);
2639 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2640 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2641 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2643 // Tests that BothOf works when composing itself.
2644 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2645 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2648 TEST(AllOfTest, ExplainsResult) {
2651 // Successful match. Both matchers need to explain. The second
2652 // matcher doesn't give an explanation, so only the first matcher's
2653 // explanation is printed.
2654 m = AllOf(GreaterThan(10), Lt(30));
2655 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2657 // Successful match. Both matchers need to explain.
2658 m = AllOf(GreaterThan(10), GreaterThan(20));
2659 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2662 // Successful match. All matchers need to explain. The second
2663 // matcher doesn't given an explanation.
2664 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2665 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2668 // Successful match. All matchers need to explain.
2669 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2670 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2671 "and which is 10 more than 30",
2674 // Failed match. The first matcher, which failed, needs to
2676 m = AllOf(GreaterThan(10), GreaterThan(20));
2677 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2679 // Failed match. The second matcher, which failed, needs to
2680 // explain. Since it doesn't given an explanation, nothing is
2682 m = AllOf(GreaterThan(10), Lt(30));
2683 EXPECT_EQ("", Explain(m, 40));
2685 // Failed match. The second matcher, which failed, needs to
2687 m = AllOf(GreaterThan(10), GreaterThan(20));
2688 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2691 // Helper to allow easy testing of AnyOf matchers with num parameters.
2692 static void AnyOfMatches(int num, const Matcher<int>& m) {
2693 SCOPED_TRACE(Describe(m));
2694 EXPECT_FALSE(m.Matches(0));
2695 for (int i = 1; i <= num; ++i) {
2696 EXPECT_TRUE(m.Matches(i));
2698 EXPECT_FALSE(m.Matches(num + 1));
2701 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2702 SCOPED_TRACE(Describe(m));
2703 EXPECT_FALSE(m.Matches(std::to_string(0)));
2705 for (int i = 1; i <= num; ++i) {
2706 EXPECT_TRUE(m.Matches(std::to_string(i)));
2708 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2711 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2712 // least one of the given matchers.
2713 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2715 m = AnyOf(Le(1), Ge(3));
2716 EXPECT_TRUE(m.Matches(1));
2717 EXPECT_TRUE(m.Matches(4));
2718 EXPECT_FALSE(m.Matches(2));
2720 m = AnyOf(Lt(0), Eq(1), Eq(2));
2721 EXPECT_TRUE(m.Matches(-1));
2722 EXPECT_TRUE(m.Matches(1));
2723 EXPECT_TRUE(m.Matches(2));
2724 EXPECT_FALSE(m.Matches(0));
2726 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2727 EXPECT_TRUE(m.Matches(-1));
2728 EXPECT_TRUE(m.Matches(1));
2729 EXPECT_TRUE(m.Matches(2));
2730 EXPECT_TRUE(m.Matches(3));
2731 EXPECT_FALSE(m.Matches(0));
2733 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2734 EXPECT_TRUE(m.Matches(0));
2735 EXPECT_TRUE(m.Matches(11));
2736 EXPECT_TRUE(m.Matches(3));
2737 EXPECT_FALSE(m.Matches(2));
2739 // The following tests for varying number of sub-matchers. Due to the way
2740 // the sub-matchers are handled it is enough to test every sub-matcher once
2741 // with sub-matchers using the same matcher type. Varying matcher types are
2742 // checked for above.
2743 AnyOfMatches(2, AnyOf(1, 2));
2744 AnyOfMatches(3, AnyOf(1, 2, 3));
2745 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2746 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2747 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2748 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2749 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2750 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2751 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2754 // Tests the variadic version of the AnyOfMatcher.
2755 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2756 // Also make sure AnyOf is defined in the right namespace and does not depend
2758 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2760 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2761 AnyOfMatches(11, m);
2762 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2763 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2764 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2765 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2766 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2768 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2769 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2770 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2771 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2772 "43", "44", "45", "46", "47", "48", "49", "50"));
2775 TEST(ConditionalTest, MatchesFirstIfCondition) {
2776 Matcher<std::string> eq_red = Eq("red");
2777 Matcher<std::string> ne_red = Ne("red");
2778 Matcher<std::string> m = Conditional(true, eq_red, ne_red);
2779 EXPECT_TRUE(m.Matches("red"));
2780 EXPECT_FALSE(m.Matches("green"));
2782 StringMatchResultListener listener;
2783 StringMatchResultListener expected;
2784 EXPECT_FALSE(m.MatchAndExplain("green", &listener));
2785 EXPECT_FALSE(eq_red.MatchAndExplain("green", &expected));
2786 EXPECT_THAT(listener.str(), Eq(expected.str()));
2789 TEST(ConditionalTest, MatchesSecondIfCondition) {
2790 Matcher<std::string> eq_red = Eq("red");
2791 Matcher<std::string> ne_red = Ne("red");
2792 Matcher<std::string> m = Conditional(false, eq_red, ne_red);
2793 EXPECT_FALSE(m.Matches("red"));
2794 EXPECT_TRUE(m.Matches("green"));
2796 StringMatchResultListener listener;
2797 StringMatchResultListener expected;
2798 EXPECT_FALSE(m.MatchAndExplain("red", &listener));
2799 EXPECT_FALSE(ne_red.MatchAndExplain("red", &expected));
2800 EXPECT_THAT(listener.str(), Eq(expected.str()));
2803 // Tests the variadic version of the ElementsAreMatcher
2804 TEST(ElementsAreTest, HugeMatcher) {
2805 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2807 EXPECT_THAT(test_vector,
2808 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2809 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2812 // Tests the variadic version of the UnorderedElementsAreMatcher
2813 TEST(ElementsAreTest, HugeMatcherStr) {
2814 vector<std::string> test_vector{
2815 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2817 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2821 // Tests the variadic version of the UnorderedElementsAreMatcher
2822 TEST(ElementsAreTest, HugeMatcherUnordered) {
2823 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2825 EXPECT_THAT(test_vector, UnorderedElementsAre(
2826 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2827 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2831 // Tests that AnyOf(m1, ..., mn) describes itself properly.
2832 TEST(AnyOfTest, CanDescribeSelf) {
2834 m = AnyOf(Le(1), Ge(3));
2836 EXPECT_EQ("(is <= 1) or (is >= 3)",
2839 m = AnyOf(Lt(0), Eq(1), Eq(2));
2840 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
2842 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2843 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
2846 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2848 "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2853 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
2854 TEST(AnyOfTest, CanDescribeNegation) {
2856 m = AnyOf(Le(1), Ge(3));
2857 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2858 DescribeNegation(m));
2860 m = AnyOf(Lt(0), Eq(1), Eq(2));
2861 EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
2862 DescribeNegation(m));
2864 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2866 "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2868 DescribeNegation(m));
2870 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2872 "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2873 "to 5) and (isn't equal to 7)",
2874 DescribeNegation(m));
2877 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2878 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2879 // greater_than_5 and less_than_10 are monomorphic matchers.
2880 Matcher<int> greater_than_5 = Gt(5);
2881 Matcher<int> less_than_10 = Lt(10);
2883 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2884 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2885 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2887 // Tests that EitherOf works when composing itself.
2888 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2889 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2892 TEST(AnyOfTest, ExplainsResult) {
2895 // Failed match. Both matchers need to explain. The second
2896 // matcher doesn't give an explanation, so only the first matcher's
2897 // explanation is printed.
2898 m = AnyOf(GreaterThan(10), Lt(0));
2899 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2901 // Failed match. Both matchers need to explain.
2902 m = AnyOf(GreaterThan(10), GreaterThan(20));
2903 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2906 // Failed match. All matchers need to explain. The second
2907 // matcher doesn't given an explanation.
2908 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2909 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2912 // Failed match. All matchers need to explain.
2913 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2914 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2915 "and which is 25 less than 30",
2918 // Successful match. The first matcher, which succeeded, needs to
2920 m = AnyOf(GreaterThan(10), GreaterThan(20));
2921 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2923 // Successful match. The second matcher, which succeeded, needs to
2924 // explain. Since it doesn't given an explanation, nothing is
2926 m = AnyOf(GreaterThan(10), Lt(30));
2927 EXPECT_EQ("", Explain(m, 0));
2929 // Successful match. The second matcher, which succeeded, needs to
2931 m = AnyOf(GreaterThan(30), GreaterThan(20));
2932 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2935 // The following predicate function and predicate functor are for
2936 // testing the Truly(predicate) matcher.
2938 // Returns non-zero if the input is positive. Note that the return
2939 // type of this function is not bool. It's OK as Truly() accepts any
2940 // unary function or functor whose return type can be implicitly
2941 // converted to bool.
2942 int IsPositive(double x) {
2943 return x > 0 ? 1 : 0;
2946 // This functor returns true if the input is greater than the given
2948 class IsGreaterThan {
2950 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2952 bool operator()(int n) const { return n > threshold_; }
2958 // For testing Truly().
2961 // This predicate returns true if and only if the argument references foo and
2962 // has a zero value.
2963 bool ReferencesFooAndIsZero(const int& n) {
2964 return (&n == &foo) && (n == 0);
2967 // Tests that Truly(predicate) matches what satisfies the given
2969 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2970 Matcher<double> m = Truly(IsPositive);
2971 EXPECT_TRUE(m.Matches(2.0));
2972 EXPECT_FALSE(m.Matches(-1.5));
2975 // Tests that Truly(predicate_functor) works too.
2976 TEST(TrulyTest, CanBeUsedWithFunctor) {
2977 Matcher<int> m = Truly(IsGreaterThan(5));
2978 EXPECT_TRUE(m.Matches(6));
2979 EXPECT_FALSE(m.Matches(4));
2982 // A class that can be implicitly converted to bool.
2983 class ConvertibleToBool {
2985 explicit ConvertibleToBool(int number) : number_(number) {}
2986 operator bool() const { return number_ != 0; }
2992 ConvertibleToBool IsNotZero(int number) {
2993 return ConvertibleToBool(number);
2996 // Tests that the predicate used in Truly() may return a class that's
2997 // implicitly convertible to bool, even when the class has no
2999 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
3000 Matcher<int> m = Truly(IsNotZero);
3001 EXPECT_TRUE(m.Matches(1));
3002 EXPECT_FALSE(m.Matches(0));
3005 // Tests that Truly(predicate) can describe itself properly.
3006 TEST(TrulyTest, CanDescribeSelf) {
3007 Matcher<double> m = Truly(IsPositive);
3008 EXPECT_EQ("satisfies the given predicate",
3012 // Tests that Truly(predicate) works when the matcher takes its
3013 // argument by reference.
3014 TEST(TrulyTest, WorksForByRefArguments) {
3015 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
3016 EXPECT_TRUE(m.Matches(foo));
3018 EXPECT_FALSE(m.Matches(n));
3021 // Tests that Truly(predicate) provides a helpful reason when it fails.
3022 TEST(TrulyTest, ExplainsFailures) {
3023 StringMatchResultListener listener;
3024 EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
3025 EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
3028 // Tests that Matches(m) is a predicate satisfied by whatever that
3029 // matches matcher m.
3030 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
3031 EXPECT_TRUE(Matches(Ge(0))(1));
3032 EXPECT_FALSE(Matches(Eq('a'))('b'));
3035 // Tests that Matches(m) works when the matcher takes its argument by
3037 TEST(MatchesTest, WorksOnByRefArguments) {
3039 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
3040 EXPECT_FALSE(Matches(Ref(m))(n));
3043 // Tests that a Matcher on non-reference type can be used in
3045 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3046 Matcher<int> eq5 = Eq(5);
3047 EXPECT_TRUE(Matches(eq5)(5));
3048 EXPECT_FALSE(Matches(eq5)(2));
3051 // Tests Value(value, matcher). Since Value() is a simple wrapper for
3052 // Matches(), which has been tested already, we don't spend a lot of
3053 // effort on testing Value().
3054 TEST(ValueTest, WorksWithPolymorphicMatcher) {
3055 EXPECT_TRUE(Value("hi", StartsWith("h")));
3056 EXPECT_FALSE(Value(5, Gt(10)));
3059 TEST(ValueTest, WorksWithMonomorphicMatcher) {
3060 const Matcher<int> is_zero = Eq(0);
3061 EXPECT_TRUE(Value(0, is_zero));
3062 EXPECT_FALSE(Value('a', is_zero));
3065 const Matcher<const int&> ref_n = Ref(n);
3066 EXPECT_TRUE(Value(n, ref_n));
3067 EXPECT_FALSE(Value(1, ref_n));
3070 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3071 StringMatchResultListener listener1;
3072 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3073 EXPECT_EQ("% 2 == 0", listener1.str());
3075 StringMatchResultListener listener2;
3076 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3077 EXPECT_EQ("", listener2.str());
3080 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3081 const Matcher<int> is_even = PolymorphicIsEven();
3082 StringMatchResultListener listener1;
3083 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3084 EXPECT_EQ("% 2 == 0", listener1.str());
3086 const Matcher<const double&> is_zero = Eq(0);
3087 StringMatchResultListener listener2;
3088 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3089 EXPECT_EQ("", listener2.str());
3092 MATCHER(ConstructNoArg, "") { return true; }
3093 MATCHER_P(Construct1Arg, arg1, "") { return true; }
3094 MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
3096 TEST(MatcherConstruct, ExplicitVsImplicit) {
3098 // No arg constructor can be constructed with empty brace.
3099 ConstructNoArgMatcher m = {};
3102 ConstructNoArgMatcher m2;
3106 // The one arg constructor has an explicit constructor.
3107 // This is to prevent the implicit conversion.
3108 using M = Construct1ArgMatcherP<int>;
3109 EXPECT_TRUE((std::is_constructible<M, int>::value));
3110 EXPECT_FALSE((std::is_convertible<int, M>::value));
3113 // Multiple arg matchers can be constructed with an implicit construction.
3114 Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
3119 MATCHER_P(Really, inner_matcher, "") {
3120 return ExplainMatchResult(inner_matcher, arg, result_listener);
3123 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3124 EXPECT_THAT(0, Really(Eq(0)));
3127 TEST(DescribeMatcherTest, WorksWithValue) {
3128 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3129 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3132 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
3133 const Matcher<int> monomorphic = Le(0);
3134 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
3135 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
3138 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3139 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
3140 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
3143 TEST(AllArgsTest, WorksForTuple) {
3144 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
3145 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
3148 TEST(AllArgsTest, WorksForNonTuple) {
3149 EXPECT_THAT(42, AllArgs(Gt(0)));
3150 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3153 class AllArgsHelper {
3157 MOCK_METHOD2(Helper, int(char x, int y));
3160 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
3163 TEST(AllArgsTest, WorksInWithClause) {
3164 AllArgsHelper helper;
3165 ON_CALL(helper, Helper(_, _))
3166 .With(AllArgs(Lt()))
3167 .WillByDefault(Return(1));
3168 EXPECT_CALL(helper, Helper(_, _));
3169 EXPECT_CALL(helper, Helper(_, _))
3170 .With(AllArgs(Gt()))
3171 .WillOnce(Return(2));
3173 EXPECT_EQ(1, helper.Helper('\1', 2));
3174 EXPECT_EQ(2, helper.Helper('a', 1));
3177 class OptionalMatchersHelper {
3179 OptionalMatchersHelper() {}
3181 MOCK_METHOD0(NoArgs, int());
3183 MOCK_METHOD1(OneArg, int(int y));
3185 MOCK_METHOD2(TwoArgs, int(char x, int y));
3187 MOCK_METHOD1(Overloaded, int(char x));
3188 MOCK_METHOD2(Overloaded, int(char x, int y));
3191 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
3194 TEST(AllArgsTest, WorksWithoutMatchers) {
3195 OptionalMatchersHelper helper;
3197 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3198 ON_CALL(helper, OneArg).WillByDefault(Return(20));
3199 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3201 EXPECT_EQ(10, helper.NoArgs());
3202 EXPECT_EQ(20, helper.OneArg(1));
3203 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3205 EXPECT_CALL(helper, NoArgs).Times(1);
3206 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
3207 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
3208 EXPECT_CALL(helper, TwoArgs).Times(0);
3210 EXPECT_EQ(10, helper.NoArgs());
3211 EXPECT_EQ(100, helper.OneArg(1));
3212 EXPECT_EQ(200, helper.OneArg(17));
3215 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3216 // matches the matcher.
3217 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3218 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3219 ASSERT_THAT("Foo", EndsWith("oo"));
3220 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3221 EXPECT_THAT("Hello", StartsWith("Hell"));
3224 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3225 // doesn't match the matcher.
3226 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3227 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3228 // which cannot reference auto variables.
3229 static unsigned short n; // NOLINT
3232 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
3234 "Expected: is > 10\n"
3235 " Actual: 5" + OfType("unsigned short"));
3237 EXPECT_NONFATAL_FAILURE(
3238 EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
3240 "Expected: (is <= 7) and (is >= 5)\n"
3241 " Actual: 0" + OfType("unsigned short"));
3244 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3245 // has a reference type.
3246 TEST(MatcherAssertionTest, WorksForByRefArguments) {
3247 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3248 // reference auto variables.
3251 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3252 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3254 "Expected: does not reference the variable @");
3255 // Tests the "Actual" part.
3256 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3257 "Actual: 0" + OfType("int") + ", which is located @");
3260 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3262 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3263 Matcher<const char*> starts_with_he = StartsWith("he");
3264 ASSERT_THAT("hello", starts_with_he);
3266 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
3267 ASSERT_THAT("book", ends_with_ok);
3268 const std::string bad = "bad";
3269 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3271 "Expected: ends with \"ok\"\n"
3272 " Actual: \"bad\"");
3273 Matcher<int> is_greater_than_5 = Gt(5);
3274 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3276 "Expected: is > 5\n"
3277 " Actual: 5" + OfType("int"));
3280 // Tests floating-point matchers.
3281 template <typename RawType>
3282 class FloatingPointTest : public testing::Test {
3284 typedef testing::internal::FloatingPoint<RawType> Floating;
3285 typedef typename Floating::Bits Bits;
3288 : max_ulps_(Floating::kMaxUlps),
3289 zero_bits_(Floating(0).bits()),
3290 one_bits_(Floating(1).bits()),
3291 infinity_bits_(Floating(Floating::Infinity()).bits()),
3292 close_to_positive_zero_(
3293 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3294 close_to_negative_zero_(
3295 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3296 further_from_negative_zero_(-Floating::ReinterpretBits(
3297 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
3298 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3299 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
3300 infinity_(Floating::Infinity()),
3302 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3303 further_from_infinity_(
3304 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
3305 max_(Floating::Max()),
3306 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3307 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3311 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3314 // A battery of tests for FloatingEqMatcher::Matches.
3315 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3317 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3318 Matcher<RawType> m1 = matcher_maker(0.0);
3319 EXPECT_TRUE(m1.Matches(-0.0));
3320 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3321 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3322 EXPECT_FALSE(m1.Matches(1.0));
3324 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3325 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3327 Matcher<RawType> m3 = matcher_maker(1.0);
3328 EXPECT_TRUE(m3.Matches(close_to_one_));
3329 EXPECT_FALSE(m3.Matches(further_from_one_));
3331 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3332 EXPECT_FALSE(m3.Matches(0.0));
3334 Matcher<RawType> m4 = matcher_maker(-infinity_);
3335 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3337 Matcher<RawType> m5 = matcher_maker(infinity_);
3338 EXPECT_TRUE(m5.Matches(close_to_infinity_));
3340 // This is interesting as the representations of infinity_ and nan1_
3341 // are only 1 DLP apart.
3342 EXPECT_FALSE(m5.Matches(nan1_));
3344 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3346 Matcher<const RawType&> m6 = matcher_maker(0.0);
3347 EXPECT_TRUE(m6.Matches(-0.0));
3348 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3349 EXPECT_FALSE(m6.Matches(1.0));
3351 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3353 Matcher<RawType&> m7 = matcher_maker(0.0);
3355 EXPECT_TRUE(m7.Matches(x));
3357 EXPECT_FALSE(m7.Matches(x));
3360 // Pre-calculated numbers to be used by the tests.
3362 const Bits max_ulps_;
3364 const Bits zero_bits_; // The bits that represent 0.0.
3365 const Bits one_bits_; // The bits that represent 1.0.
3366 const Bits infinity_bits_; // The bits that represent +infinity.
3368 // Some numbers close to 0.0.
3369 const RawType close_to_positive_zero_;
3370 const RawType close_to_negative_zero_;
3371 const RawType further_from_negative_zero_;
3373 // Some numbers close to 1.0.
3374 const RawType close_to_one_;
3375 const RawType further_from_one_;
3377 // Some numbers close to +infinity.
3378 const RawType infinity_;
3379 const RawType close_to_infinity_;
3380 const RawType further_from_infinity_;
3382 // Maximum representable value that's not infinity.
3386 const RawType nan1_;
3387 const RawType nan2_;
3390 // Tests floating-point matchers with fixed epsilons.
3391 template <typename RawType>
3392 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3394 typedef FloatingPointTest<RawType> ParentType;
3396 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3397 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3398 void TestNearMatches(
3399 testing::internal::FloatingEqMatcher<RawType>
3400 (*matcher_maker)(RawType, RawType)) {
3401 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3402 EXPECT_TRUE(m1.Matches(0.0));
3403 EXPECT_TRUE(m1.Matches(-0.0));
3404 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3405 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3406 EXPECT_FALSE(m1.Matches(1.0));
3408 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3409 EXPECT_TRUE(m2.Matches(0.0));
3410 EXPECT_TRUE(m2.Matches(-0.0));
3411 EXPECT_TRUE(m2.Matches(1.0));
3412 EXPECT_TRUE(m2.Matches(-1.0));
3413 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3414 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3416 // Check that inf matches inf, regardless of the of the specified max
3418 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3419 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3420 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3421 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3423 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3424 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3425 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3426 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3428 // Test various overflow scenarios.
3429 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3430 EXPECT_TRUE(m5.Matches(ParentType::max_));
3431 EXPECT_FALSE(m5.Matches(-ParentType::max_));
3433 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3434 EXPECT_FALSE(m6.Matches(ParentType::max_));
3435 EXPECT_TRUE(m6.Matches(-ParentType::max_));
3437 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3438 EXPECT_TRUE(m7.Matches(ParentType::max_));
3439 EXPECT_FALSE(m7.Matches(-ParentType::max_));
3441 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3442 EXPECT_FALSE(m8.Matches(ParentType::max_));
3443 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3445 // The difference between max() and -max() normally overflows to infinity,
3446 // but it should still match if the max_abs_error is also infinity.
3447 Matcher<RawType> m9 = matcher_maker(
3448 ParentType::max_, ParentType::infinity_);
3449 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3451 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3453 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3454 EXPECT_TRUE(m10.Matches(-0.0));
3455 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3456 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3458 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3460 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3462 EXPECT_TRUE(m11.Matches(x));
3464 EXPECT_TRUE(m11.Matches(x));
3466 EXPECT_TRUE(m11.Matches(x));
3468 EXPECT_FALSE(m11.Matches(x));
3470 EXPECT_FALSE(m11.Matches(x));
3474 // Instantiate FloatingPointTest for testing floats.
3475 typedef FloatingPointTest<float> FloatTest;
3477 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3478 TestMatches(&FloatEq);
3481 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3482 TestMatches(&NanSensitiveFloatEq);
3485 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3486 // FloatEq never matches NaN.
3487 Matcher<float> m = FloatEq(nan1_);
3488 EXPECT_FALSE(m.Matches(nan1_));
3489 EXPECT_FALSE(m.Matches(nan2_));
3490 EXPECT_FALSE(m.Matches(1.0));
3493 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3494 // NanSensitiveFloatEq will match NaN.
3495 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3496 EXPECT_TRUE(m.Matches(nan1_));
3497 EXPECT_TRUE(m.Matches(nan2_));
3498 EXPECT_FALSE(m.Matches(1.0));
3501 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3502 Matcher<float> m1 = FloatEq(2.0f);
3503 EXPECT_EQ("is approximately 2", Describe(m1));
3504 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3506 Matcher<float> m2 = FloatEq(0.5f);
3507 EXPECT_EQ("is approximately 0.5", Describe(m2));
3508 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3510 Matcher<float> m3 = FloatEq(nan1_);
3511 EXPECT_EQ("never matches", Describe(m3));
3512 EXPECT_EQ("is anything", DescribeNegation(m3));
3515 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3516 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3517 EXPECT_EQ("is approximately 2", Describe(m1));
3518 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3520 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3521 EXPECT_EQ("is approximately 0.5", Describe(m2));
3522 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3524 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3525 EXPECT_EQ("is NaN", Describe(m3));
3526 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3529 // Instantiate FloatingPointTest for testing floats with a user-specified
3530 // max absolute error.
3531 typedef FloatingPointNearTest<float> FloatNearTest;
3533 TEST_F(FloatNearTest, FloatNearMatches) {
3534 TestNearMatches(&FloatNear);
3537 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3538 TestNearMatches(&NanSensitiveFloatNear);
3541 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3542 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3543 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3545 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3547 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3548 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3550 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3552 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3553 EXPECT_EQ("never matches", Describe(m3));
3554 EXPECT_EQ("is anything", DescribeNegation(m3));
3557 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3558 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3559 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3561 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3563 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3564 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3566 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3568 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3569 EXPECT_EQ("is NaN", Describe(m3));
3570 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3573 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3574 // FloatNear never matches NaN.
3575 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3576 EXPECT_FALSE(m.Matches(nan1_));
3577 EXPECT_FALSE(m.Matches(nan2_));
3578 EXPECT_FALSE(m.Matches(1.0));
3581 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3582 // NanSensitiveFloatNear will match NaN.
3583 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3584 EXPECT_TRUE(m.Matches(nan1_));
3585 EXPECT_TRUE(m.Matches(nan2_));
3586 EXPECT_FALSE(m.Matches(1.0));
3589 // Instantiate FloatingPointTest for testing doubles.
3590 typedef FloatingPointTest<double> DoubleTest;
3592 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3593 TestMatches(&DoubleEq);
3596 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3597 TestMatches(&NanSensitiveDoubleEq);
3600 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3601 // DoubleEq never matches NaN.
3602 Matcher<double> m = DoubleEq(nan1_);
3603 EXPECT_FALSE(m.Matches(nan1_));
3604 EXPECT_FALSE(m.Matches(nan2_));
3605 EXPECT_FALSE(m.Matches(1.0));
3608 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3609 // NanSensitiveDoubleEq will match NaN.
3610 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3611 EXPECT_TRUE(m.Matches(nan1_));
3612 EXPECT_TRUE(m.Matches(nan2_));
3613 EXPECT_FALSE(m.Matches(1.0));
3616 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3617 Matcher<double> m1 = DoubleEq(2.0);
3618 EXPECT_EQ("is approximately 2", Describe(m1));
3619 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3621 Matcher<double> m2 = DoubleEq(0.5);
3622 EXPECT_EQ("is approximately 0.5", Describe(m2));
3623 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3625 Matcher<double> m3 = DoubleEq(nan1_);
3626 EXPECT_EQ("never matches", Describe(m3));
3627 EXPECT_EQ("is anything", DescribeNegation(m3));
3630 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3631 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3632 EXPECT_EQ("is approximately 2", Describe(m1));
3633 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3635 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3636 EXPECT_EQ("is approximately 0.5", Describe(m2));
3637 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3639 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3640 EXPECT_EQ("is NaN", Describe(m3));
3641 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3644 // Instantiate FloatingPointTest for testing floats with a user-specified
3645 // max absolute error.
3646 typedef FloatingPointNearTest<double> DoubleNearTest;
3648 TEST_F(DoubleNearTest, DoubleNearMatches) {
3649 TestNearMatches(&DoubleNear);
3652 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3653 TestNearMatches(&NanSensitiveDoubleNear);
3656 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3657 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3658 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3660 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3662 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3663 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3665 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3667 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3668 EXPECT_EQ("never matches", Describe(m3));
3669 EXPECT_EQ("is anything", DescribeNegation(m3));
3672 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3673 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3674 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3675 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3677 const std::string explanation =
3678 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3679 // Different C++ implementations may print floating-point numbers
3680 // slightly differently.
3681 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3682 explanation == "which is 1.2e-010 from 2.1") // MSVC
3683 << " where explanation is \"" << explanation << "\".";
3686 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3687 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3688 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3690 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3692 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3693 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3695 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3697 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3698 EXPECT_EQ("is NaN", Describe(m3));
3699 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3702 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3703 // DoubleNear never matches NaN.
3704 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3705 EXPECT_FALSE(m.Matches(nan1_));
3706 EXPECT_FALSE(m.Matches(nan2_));
3707 EXPECT_FALSE(m.Matches(1.0));
3710 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3711 // NanSensitiveDoubleNear will match NaN.
3712 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3713 EXPECT_TRUE(m.Matches(nan1_));
3714 EXPECT_TRUE(m.Matches(nan2_));
3715 EXPECT_FALSE(m.Matches(1.0));
3718 TEST(PointeeTest, RawPointer) {
3719 const Matcher<int*> m = Pointee(Ge(0));
3722 EXPECT_TRUE(m.Matches(&n));
3724 EXPECT_FALSE(m.Matches(&n));
3725 EXPECT_FALSE(m.Matches(nullptr));
3728 TEST(PointeeTest, RawPointerToConst) {
3729 const Matcher<const double*> m = Pointee(Ge(0));
3732 EXPECT_TRUE(m.Matches(&x));
3734 EXPECT_FALSE(m.Matches(&x));
3735 EXPECT_FALSE(m.Matches(nullptr));
3738 TEST(PointeeTest, ReferenceToConstRawPointer) {
3739 const Matcher<int* const &> m = Pointee(Ge(0));
3742 EXPECT_TRUE(m.Matches(&n));
3744 EXPECT_FALSE(m.Matches(&n));
3745 EXPECT_FALSE(m.Matches(nullptr));
3748 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3749 const Matcher<double* &> m = Pointee(Ge(0));
3753 EXPECT_TRUE(m.Matches(p));
3755 EXPECT_FALSE(m.Matches(p));
3757 EXPECT_FALSE(m.Matches(p));
3760 TEST(PointeeTest, SmartPointer) {
3761 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
3763 std::unique_ptr<int> n(new int(1));
3764 EXPECT_TRUE(m.Matches(n));
3767 TEST(PointeeTest, SmartPointerToConst) {
3768 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
3770 // There's no implicit conversion from unique_ptr<int> to const
3771 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3773 std::unique_ptr<const int> n(new int(1));
3774 EXPECT_TRUE(m.Matches(n));
3777 TEST(PointerTest, RawPointer) {
3779 const Matcher<int*> m = Pointer(Eq(&n));
3781 EXPECT_TRUE(m.Matches(&n));
3784 EXPECT_FALSE(m.Matches(p));
3785 EXPECT_FALSE(m.Matches(nullptr));
3788 TEST(PointerTest, RawPointerToConst) {
3790 const Matcher<const int*> m = Pointer(Eq(&n));
3792 EXPECT_TRUE(m.Matches(&n));
3795 EXPECT_FALSE(m.Matches(p));
3796 EXPECT_FALSE(m.Matches(nullptr));
3799 TEST(PointerTest, SmartPointer) {
3800 std::unique_ptr<int> n(new int(10));
3801 int* raw_n = n.get();
3802 const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
3804 EXPECT_TRUE(m.Matches(n));
3807 TEST(PointerTest, SmartPointerToConst) {
3808 std::unique_ptr<const int> n(new int(10));
3809 const int* raw_n = n.get();
3810 const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
3812 // There's no implicit conversion from unique_ptr<int> to const
3813 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3815 std::unique_ptr<const int> p(new int(10));
3816 EXPECT_FALSE(m.Matches(p));
3819 TEST(AddressTest, NonConst) {
3821 const Matcher<int> m = Address(Eq(&n));
3823 EXPECT_TRUE(m.Matches(n));
3827 EXPECT_FALSE(m.Matches(other));
3831 EXPECT_TRUE(m.Matches(n_ref));
3834 TEST(AddressTest, Const) {
3836 const Matcher<int> m = Address(Eq(&n));
3838 EXPECT_TRUE(m.Matches(n));
3842 EXPECT_FALSE(m.Matches(other));
3845 TEST(AddressTest, MatcherDoesntCopy) {
3846 std::unique_ptr<int> n(new int(1));
3847 const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
3849 EXPECT_TRUE(m.Matches(n));
3852 TEST(AddressTest, Describe) {
3853 Matcher<int> matcher = Address(_);
3854 EXPECT_EQ("has address that is anything", Describe(matcher));
3855 EXPECT_EQ("does not have address that is anything",
3856 DescribeNegation(matcher));
3859 MATCHER_P(FieldIIs, inner_matcher, "") {
3860 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3864 TEST(WhenDynamicCastToTest, SameType) {
3868 // Right type. A pointer is passed down.
3869 Base* as_base_ptr = &derived;
3870 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3871 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3872 EXPECT_THAT(as_base_ptr,
3873 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3876 TEST(WhenDynamicCastToTest, WrongTypes) {
3879 OtherDerived other_derived;
3881 // Wrong types. NULL is passed.
3882 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3883 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3884 Base* as_base_ptr = &derived;
3885 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3886 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3887 as_base_ptr = &other_derived;
3888 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3889 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3892 TEST(WhenDynamicCastToTest, AlreadyNull) {
3894 Base* as_base_ptr = nullptr;
3895 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3898 struct AmbiguousCastTypes {
3899 class VirtualDerived : public virtual Base {};
3900 class DerivedSub1 : public VirtualDerived {};
3901 class DerivedSub2 : public VirtualDerived {};
3902 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3905 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3906 AmbiguousCastTypes::DerivedSub1 sub1;
3907 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3908 // Multiply derived from Base. dynamic_cast<> returns NULL.
3910 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3911 EXPECT_THAT(as_base_ptr,
3912 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3913 as_base_ptr = &sub1;
3916 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3919 TEST(WhenDynamicCastToTest, Describe) {
3920 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3921 const std::string prefix =
3922 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3923 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3924 EXPECT_EQ(prefix + "does not point to a value that is anything",
3925 DescribeNegation(matcher));
3928 TEST(WhenDynamicCastToTest, Explain) {
3929 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3930 Base* null = nullptr;
3931 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3933 EXPECT_TRUE(matcher.Matches(&derived));
3934 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3936 // With references, the matcher itself can fail. Test for that one.
3937 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3938 EXPECT_THAT(Explain(ref_matcher, derived),
3939 HasSubstr("which cannot be dynamic_cast"));
3942 TEST(WhenDynamicCastToTest, GoodReference) {
3945 Base& as_base_ref = derived;
3946 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3947 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3950 TEST(WhenDynamicCastToTest, BadReference) {
3952 Base& as_base_ref = derived;
3953 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3955 #endif // GTEST_HAS_RTTI
3957 // Minimal const-propagating pointer.
3958 template <typename T>
3959 class ConstPropagatingPtr {
3961 typedef T element_type;
3963 ConstPropagatingPtr() : val_() {}
3964 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3965 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3967 T* get() { return val_; }
3968 T& operator*() { return *val_; }
3969 // Most smart pointers return non-const T* and T& from the next methods.
3970 const T* get() const { return val_; }
3971 const T& operator*() const { return *val_; }
3977 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3978 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3980 const ConstPropagatingPtr<int> co(&three);
3981 ConstPropagatingPtr<int> o(&three);
3982 EXPECT_TRUE(m.Matches(o));
3983 EXPECT_TRUE(m.Matches(co));
3985 EXPECT_FALSE(m.Matches(o));
3986 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3989 TEST(PointeeTest, NeverMatchesNull) {
3990 const Matcher<const char*> m = Pointee(_);
3991 EXPECT_FALSE(m.Matches(nullptr));
3994 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3995 TEST(PointeeTest, MatchesAgainstAValue) {
3996 const Matcher<int*> m = Pointee(5);
3999 EXPECT_TRUE(m.Matches(&n));
4001 EXPECT_FALSE(m.Matches(&n));
4002 EXPECT_FALSE(m.Matches(nullptr));
4005 TEST(PointeeTest, CanDescribeSelf) {
4006 const Matcher<int*> m = Pointee(Gt(3));
4007 EXPECT_EQ("points to a value that is > 3", Describe(m));
4008 EXPECT_EQ("does not point to a value that is > 3",
4009 DescribeNegation(m));
4012 TEST(PointeeTest, CanExplainMatchResult) {
4013 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
4015 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
4017 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
4018 long n = 3; // NOLINT
4019 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
4023 TEST(PointeeTest, AlwaysExplainsPointee) {
4024 const Matcher<int*> m = Pointee(0);
4026 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
4029 // An uncopyable class.
4032 Uncopyable() : value_(-1) {}
4033 explicit Uncopyable(int a_value) : value_(a_value) {}
4035 int value() const { return value_; }
4036 void set_value(int i) { value_ = i; }
4040 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
4043 // Returns true if and only if x.value() is positive.
4044 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
4046 MATCHER_P(UncopyableIs, inner_matcher, "") {
4047 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
4050 // A user-defined struct for testing Field().
4052 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
4053 AStruct(const AStruct& rhs)
4054 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
4056 int x; // A non-const field.
4057 const double y; // A const field.
4058 Uncopyable z; // An uncopyable field.
4059 const char* p; // A pointer field.
4062 // A derived struct for testing Field().
4063 struct DerivedStruct : public AStruct {
4067 // Tests that Field(&Foo::field, ...) works when field is non-const.
4068 TEST(FieldTest, WorksForNonConstField) {
4069 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
4070 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
4073 EXPECT_TRUE(m.Matches(a));
4074 EXPECT_TRUE(m_with_name.Matches(a));
4076 EXPECT_FALSE(m.Matches(a));
4077 EXPECT_FALSE(m_with_name.Matches(a));
4080 // Tests that Field(&Foo::field, ...) works when field is const.
4081 TEST(FieldTest, WorksForConstField) {
4084 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
4085 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
4086 EXPECT_TRUE(m.Matches(a));
4087 EXPECT_TRUE(m_with_name.Matches(a));
4088 m = Field(&AStruct::y, Le(0.0));
4089 m_with_name = Field("y", &AStruct::y, Le(0.0));
4090 EXPECT_FALSE(m.Matches(a));
4091 EXPECT_FALSE(m_with_name.Matches(a));
4094 // Tests that Field(&Foo::field, ...) works when field is not copyable.
4095 TEST(FieldTest, WorksForUncopyableField) {
4098 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
4099 EXPECT_TRUE(m.Matches(a));
4100 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
4101 EXPECT_FALSE(m.Matches(a));
4104 // Tests that Field(&Foo::field, ...) works when field is a pointer.
4105 TEST(FieldTest, WorksForPointerField) {
4106 // Matching against NULL.
4107 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
4109 EXPECT_TRUE(m.Matches(a));
4111 EXPECT_FALSE(m.Matches(a));
4113 // Matching a pointer that is not NULL.
4114 m = Field(&AStruct::p, StartsWith("hi"));
4116 EXPECT_TRUE(m.Matches(a));
4118 EXPECT_FALSE(m.Matches(a));
4121 // Tests that Field() works when the object is passed by reference.
4122 TEST(FieldTest, WorksForByRefArgument) {
4123 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4126 EXPECT_TRUE(m.Matches(a));
4128 EXPECT_FALSE(m.Matches(a));
4131 // Tests that Field(&Foo::field, ...) works when the argument's type
4132 // is a sub-type of Foo.
4133 TEST(FieldTest, WorksForArgumentOfSubType) {
4134 // Note that the matcher expects DerivedStruct but we say AStruct
4136 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
4139 EXPECT_TRUE(m.Matches(d));
4141 EXPECT_FALSE(m.Matches(d));
4144 // Tests that Field(&Foo::field, m) works when field's type and m's
4145 // argument type are compatible but not the same.
4146 TEST(FieldTest, WorksForCompatibleMatcherType) {
4147 // The field is an int, but the inner matcher expects a signed char.
4148 Matcher<const AStruct&> m = Field(&AStruct::x,
4149 Matcher<signed char>(Ge(0)));
4152 EXPECT_TRUE(m.Matches(a));
4154 EXPECT_FALSE(m.Matches(a));
4157 // Tests that Field() can describe itself.
4158 TEST(FieldTest, CanDescribeSelf) {
4159 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4161 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4162 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4165 TEST(FieldTest, CanDescribeSelfWithFieldName) {
4166 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4168 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4169 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4170 DescribeNegation(m));
4173 // Tests that Field() can explain the match result.
4174 TEST(FieldTest, CanExplainMatchResult) {
4175 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4179 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4181 m = Field(&AStruct::x, GreaterThan(0));
4183 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4187 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4188 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4192 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4194 m = Field("field_name", &AStruct::x, GreaterThan(0));
4195 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4196 ", which is 1 more than 0",
4200 // Tests that Field() works when the argument is a pointer to const.
4201 TEST(FieldForPointerTest, WorksForPointerToConst) {
4202 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4205 EXPECT_TRUE(m.Matches(&a));
4207 EXPECT_FALSE(m.Matches(&a));
4210 // Tests that Field() works when the argument is a pointer to non-const.
4211 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4212 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
4215 EXPECT_TRUE(m.Matches(&a));
4217 EXPECT_FALSE(m.Matches(&a));
4220 // Tests that Field() works when the argument is a reference to a const pointer.
4221 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4222 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
4225 EXPECT_TRUE(m.Matches(&a));
4227 EXPECT_FALSE(m.Matches(&a));
4230 // Tests that Field() does not match the NULL pointer.
4231 TEST(FieldForPointerTest, DoesNotMatchNull) {
4232 Matcher<const AStruct*> m = Field(&AStruct::x, _);
4233 EXPECT_FALSE(m.Matches(nullptr));
4236 // Tests that Field(&Foo::field, ...) works when the argument's type
4237 // is a sub-type of const Foo*.
4238 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4239 // Note that the matcher expects DerivedStruct but we say AStruct
4241 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
4244 EXPECT_TRUE(m.Matches(&d));
4246 EXPECT_FALSE(m.Matches(&d));
4249 // Tests that Field() can describe itself when used to match a pointer.
4250 TEST(FieldForPointerTest, CanDescribeSelf) {
4251 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4253 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4254 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4257 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4258 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4260 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4261 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4262 DescribeNegation(m));
4265 // Tests that Field() can explain the result of matching a pointer.
4266 TEST(FieldForPointerTest, CanExplainMatchResult) {
4267 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4271 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4272 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4275 m = Field(&AStruct::x, GreaterThan(0));
4276 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4277 ", which is 1 more than 0", Explain(m, &a));
4280 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4281 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4285 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4287 "which points to an object whose field `field_name` is 1" + OfType("int"),
4290 m = Field("field_name", &AStruct::x, GreaterThan(0));
4291 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4292 OfType("int") + ", which is 1 more than 0",
4296 // A user-defined class for testing Property().
4301 // A getter that returns a non-reference.
4302 int n() const { return n_; }
4304 void set_n(int new_n) { n_ = new_n; }
4306 // A getter that returns a reference to const.
4307 const std::string& s() const { return s_; }
4309 const std::string& s_ref() const & { return s_; }
4311 void set_s(const std::string& new_s) { s_ = new_s; }
4313 // A getter that returns a reference to non-const.
4314 double& x() const { return x_; }
4323 double AClass::x_ = 0.0;
4325 // A derived class for testing Property().
4326 class DerivedClass : public AClass {
4328 int k() const { return k_; }
4333 // Tests that Property(&Foo::property, ...) works when property()
4334 // returns a non-reference.
4335 TEST(PropertyTest, WorksForNonReferenceProperty) {
4336 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4337 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4341 EXPECT_TRUE(m.Matches(a));
4342 EXPECT_TRUE(m_with_name.Matches(a));
4345 EXPECT_FALSE(m.Matches(a));
4346 EXPECT_FALSE(m_with_name.Matches(a));
4349 // Tests that Property(&Foo::property, ...) works when property()
4350 // returns a reference to const.
4351 TEST(PropertyTest, WorksForReferenceToConstProperty) {
4352 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
4353 Matcher<const AClass&> m_with_name =
4354 Property("s", &AClass::s, StartsWith("hi"));
4358 EXPECT_TRUE(m.Matches(a));
4359 EXPECT_TRUE(m_with_name.Matches(a));
4362 EXPECT_FALSE(m.Matches(a));
4363 EXPECT_FALSE(m_with_name.Matches(a));
4366 // Tests that Property(&Foo::property, ...) works when property() is
4368 TEST(PropertyTest, WorksForRefQualifiedProperty) {
4369 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4370 Matcher<const AClass&> m_with_name =
4371 Property("s", &AClass::s_ref, StartsWith("hi"));
4375 EXPECT_TRUE(m.Matches(a));
4376 EXPECT_TRUE(m_with_name.Matches(a));
4379 EXPECT_FALSE(m.Matches(a));
4380 EXPECT_FALSE(m_with_name.Matches(a));
4383 // Tests that Property(&Foo::property, ...) works when property()
4384 // returns a reference to non-const.
4385 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4389 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4390 EXPECT_FALSE(m.Matches(a));
4392 m = Property(&AClass::x, Not(Ref(x)));
4393 EXPECT_TRUE(m.Matches(a));
4396 // Tests that Property(&Foo::property, ...) works when the argument is
4398 TEST(PropertyTest, WorksForByValueArgument) {
4399 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4403 EXPECT_TRUE(m.Matches(a));
4406 EXPECT_FALSE(m.Matches(a));
4409 // Tests that Property(&Foo::property, ...) works when the argument's
4410 // type is a sub-type of Foo.
4411 TEST(PropertyTest, WorksForArgumentOfSubType) {
4412 // The matcher expects a DerivedClass, but inside the Property() we
4414 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4418 EXPECT_TRUE(m.Matches(d));
4421 EXPECT_FALSE(m.Matches(d));
4424 // Tests that Property(&Foo::property, m) works when property()'s type
4425 // and m's argument type are compatible but different.
4426 TEST(PropertyTest, WorksForCompatibleMatcherType) {
4427 // n() returns an int but the inner matcher expects a signed char.
4428 Matcher<const AClass&> m = Property(&AClass::n,
4429 Matcher<signed char>(Ge(0)));
4431 Matcher<const AClass&> m_with_name =
4432 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4435 EXPECT_TRUE(m.Matches(a));
4436 EXPECT_TRUE(m_with_name.Matches(a));
4438 EXPECT_FALSE(m.Matches(a));
4439 EXPECT_FALSE(m_with_name.Matches(a));
4442 // Tests that Property() can describe itself.
4443 TEST(PropertyTest, CanDescribeSelf) {
4444 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4446 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4447 EXPECT_EQ("is an object whose given property isn't >= 0",
4448 DescribeNegation(m));
4451 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4452 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4454 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4455 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4456 DescribeNegation(m));
4459 // Tests that Property() can explain the match result.
4460 TEST(PropertyTest, CanExplainMatchResult) {
4461 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4465 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4467 m = Property(&AClass::n, GreaterThan(0));
4469 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4473 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4474 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4478 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4480 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4481 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4482 ", which is 1 more than 0",
4486 // Tests that Property() works when the argument is a pointer to const.
4487 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4488 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4492 EXPECT_TRUE(m.Matches(&a));
4495 EXPECT_FALSE(m.Matches(&a));
4498 // Tests that Property() works when the argument is a pointer to non-const.
4499 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4500 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4504 EXPECT_TRUE(m.Matches(&a));
4507 EXPECT_FALSE(m.Matches(&a));
4510 // Tests that Property() works when the argument is a reference to a
4512 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4513 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4517 EXPECT_TRUE(m.Matches(&a));
4520 EXPECT_FALSE(m.Matches(&a));
4523 // Tests that Property() does not match the NULL pointer.
4524 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4525 Matcher<const AClass*> m = Property(&AClass::x, _);
4526 EXPECT_FALSE(m.Matches(nullptr));
4529 // Tests that Property(&Foo::property, ...) works when the argument's
4530 // type is a sub-type of const Foo*.
4531 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4532 // The matcher expects a DerivedClass, but inside the Property() we
4534 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4538 EXPECT_TRUE(m.Matches(&d));
4541 EXPECT_FALSE(m.Matches(&d));
4544 // Tests that Property() can describe itself when used to match a pointer.
4545 TEST(PropertyForPointerTest, CanDescribeSelf) {
4546 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4548 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4549 EXPECT_EQ("is an object whose given property isn't >= 0",
4550 DescribeNegation(m));
4553 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4554 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4556 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4557 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4558 DescribeNegation(m));
4561 // Tests that Property() can explain the result of matching a pointer.
4562 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4563 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4567 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4569 "which points to an object whose given property is 1" + OfType("int"),
4572 m = Property(&AClass::n, GreaterThan(0));
4573 EXPECT_EQ("which points to an object whose given property is 1" +
4574 OfType("int") + ", which is 1 more than 0",
4578 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4579 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4583 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4584 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4588 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4589 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4590 OfType("int") + ", which is 1 more than 0",
4596 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4597 // function pointer.
4598 std::string IntToStringFunction(int input) {
4599 return input == 1 ? "foo" : "bar";
4602 TEST(ResultOfTest, WorksForFunctionPointers) {
4603 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4605 EXPECT_TRUE(matcher.Matches(1));
4606 EXPECT_FALSE(matcher.Matches(2));
4609 // Tests that ResultOf() can describe itself.
4610 TEST(ResultOfTest, CanDescribeItself) {
4611 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4613 EXPECT_EQ("is mapped by the given callable to a value that "
4614 "is equal to \"foo\"", Describe(matcher));
4615 EXPECT_EQ("is mapped by the given callable to a value that "
4616 "isn't equal to \"foo\"", DescribeNegation(matcher));
4619 // Tests that ResultOf() can explain the match result.
4620 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4622 TEST(ResultOfTest, CanExplainMatchResult) {
4623 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4624 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4625 Explain(matcher, 36));
4627 matcher = ResultOf(&IntFunction, GreaterThan(85));
4628 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4629 ", which is 5 more than 85", Explain(matcher, 36));
4632 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4633 // returns a non-reference.
4634 TEST(ResultOfTest, WorksForNonReferenceResults) {
4635 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4637 EXPECT_TRUE(matcher.Matches(42));
4638 EXPECT_FALSE(matcher.Matches(36));
4641 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4642 // returns a reference to non-const.
4643 double& DoubleFunction(double& input) { return input; } // NOLINT
4645 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
4649 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4652 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4654 EXPECT_TRUE(matcher.Matches(x));
4655 EXPECT_FALSE(matcher.Matches(x2));
4657 // Test that ResultOf works with uncopyable objects
4660 Matcher<Uncopyable&> matcher2 =
4661 ResultOf(&RefUncopyableFunction, Ref(obj));
4663 EXPECT_TRUE(matcher2.Matches(obj));
4664 EXPECT_FALSE(matcher2.Matches(obj2));
4667 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4668 // returns a reference to const.
4669 const std::string& StringFunction(const std::string& input) { return input; }
4671 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4672 std::string s = "foo";
4674 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4676 EXPECT_TRUE(matcher.Matches(s));
4677 EXPECT_FALSE(matcher.Matches(s2));
4680 // Tests that ResultOf(f, m) works when f(x) and m's
4681 // argument types are compatible but different.
4682 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4683 // IntFunction() returns int but the inner matcher expects a signed char.
4684 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4686 EXPECT_TRUE(matcher.Matches(36));
4687 EXPECT_FALSE(matcher.Matches(42));
4690 // Tests that the program aborts when ResultOf is passed
4691 // a NULL function pointer.
4692 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4693 EXPECT_DEATH_IF_SUPPORTED(
4694 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4695 Eq(std::string("foo"))),
4696 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4699 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4700 // function reference.
4701 TEST(ResultOfTest, WorksForFunctionReferences) {
4702 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4703 EXPECT_TRUE(matcher.Matches(1));
4704 EXPECT_FALSE(matcher.Matches(2));
4707 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4710 std::string operator()(int input) const {
4711 return IntToStringFunction(input);
4715 TEST(ResultOfTest, WorksForFunctors) {
4716 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4718 EXPECT_TRUE(matcher.Matches(1));
4719 EXPECT_FALSE(matcher.Matches(2));
4722 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4723 // functor with more than one operator() defined. ResultOf() must work
4724 // for each defined operator().
4725 struct PolymorphicFunctor {
4726 typedef int result_type;
4727 int operator()(int n) { return n; }
4728 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
4729 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4732 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4733 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4735 EXPECT_TRUE(matcher_int.Matches(10));
4736 EXPECT_FALSE(matcher_int.Matches(2));
4738 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4740 EXPECT_TRUE(matcher_string.Matches("long string"));
4741 EXPECT_FALSE(matcher_string.Matches("shrt"));
4744 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4745 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4748 EXPECT_TRUE(matcher.Matches(&n));
4749 EXPECT_FALSE(matcher.Matches(nullptr));
4752 TEST(ResultOfTest, WorksForLambdas) {
4753 Matcher<int> matcher = ResultOf(
4755 return std::string(static_cast<size_t>(str_len), 'x');
4758 EXPECT_TRUE(matcher.Matches(3));
4759 EXPECT_FALSE(matcher.Matches(1));
4762 TEST(ResultOfTest, WorksForNonCopyableArguments) {
4763 Matcher<std::unique_ptr<int>> matcher = ResultOf(
4764 [](const std::unique_ptr<int>& str_len) {
4765 return std::string(static_cast<size_t>(*str_len), 'x');
4768 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4769 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4772 const int* ReferencingFunction(const int& n) { return &n; }
4774 struct ReferencingFunctor {
4775 typedef const int* result_type;
4776 result_type operator()(const int& n) { return &n; }
4779 TEST(ResultOfTest, WorksForReferencingCallables) {
4782 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4783 EXPECT_TRUE(matcher2.Matches(n));
4784 EXPECT_FALSE(matcher2.Matches(n2));
4786 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4787 EXPECT_TRUE(matcher3.Matches(n));
4788 EXPECT_FALSE(matcher3.Matches(n2));
4791 class DivisibleByImpl {
4793 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4795 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4796 template <typename T>
4797 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4798 *listener << "which is " << (n % divider_) << " modulo "
4800 return (n % divider_) == 0;
4803 void DescribeTo(ostream* os) const {
4804 *os << "is divisible by " << divider_;
4807 void DescribeNegationTo(ostream* os) const {
4808 *os << "is not divisible by " << divider_;
4811 void set_divider(int a_divider) { divider_ = a_divider; }
4812 int divider() const { return divider_; }
4818 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4819 return MakePolymorphicMatcher(DivisibleByImpl(n));
4822 // Tests that when AllOf() fails, only the first failing matcher is
4823 // asked to explain why.
4824 TEST(ExplainMatchResultTest, AllOf_False_False) {
4825 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4826 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4829 // Tests that when AllOf() fails, only the first failing matcher is
4830 // asked to explain why.
4831 TEST(ExplainMatchResultTest, AllOf_False_True) {
4832 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4833 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4836 // Tests that when AllOf() fails, only the first failing matcher is
4837 // asked to explain why.
4838 TEST(ExplainMatchResultTest, AllOf_True_False) {
4839 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4840 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4843 // Tests that when AllOf() succeeds, all matchers are asked to explain
4845 TEST(ExplainMatchResultTest, AllOf_True_True) {
4846 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4847 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4850 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4851 const Matcher<int> m = AllOf(Ge(2), Le(3));
4852 EXPECT_EQ("", Explain(m, 2));
4855 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4856 const Matcher<int> m = GreaterThan(5);
4857 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4860 // The following two tests verify that values without a public copy
4861 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4862 // with the help of ByRef().
4866 explicit NotCopyable(int a_value) : value_(a_value) {}
4868 int value() const { return value_; }
4870 bool operator==(const NotCopyable& rhs) const {
4871 return value() == rhs.value();
4874 bool operator>=(const NotCopyable& rhs) const {
4875 return value() >= rhs.value();
4880 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4883 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4884 const NotCopyable const_value1(1);
4885 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4887 const NotCopyable n1(1), n2(2);
4888 EXPECT_TRUE(m.Matches(n1));
4889 EXPECT_FALSE(m.Matches(n2));
4892 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4893 NotCopyable value2(2);
4894 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4896 NotCopyable n1(1), n2(2);
4897 EXPECT_FALSE(m.Matches(n1));
4898 EXPECT_TRUE(m.Matches(n2));
4901 TEST(IsEmptyTest, ImplementsIsEmpty) {
4902 vector<int> container;
4903 EXPECT_THAT(container, IsEmpty());
4904 container.push_back(0);
4905 EXPECT_THAT(container, Not(IsEmpty()));
4906 container.push_back(1);
4907 EXPECT_THAT(container, Not(IsEmpty()));
4910 TEST(IsEmptyTest, WorksWithString) {
4912 EXPECT_THAT(text, IsEmpty());
4914 EXPECT_THAT(text, Not(IsEmpty()));
4915 text = std::string("\0", 1);
4916 EXPECT_THAT(text, Not(IsEmpty()));
4919 TEST(IsEmptyTest, CanDescribeSelf) {
4920 Matcher<vector<int> > m = IsEmpty();
4921 EXPECT_EQ("is empty", Describe(m));
4922 EXPECT_EQ("isn't empty", DescribeNegation(m));
4925 TEST(IsEmptyTest, ExplainsResult) {
4926 Matcher<vector<int> > m = IsEmpty();
4927 vector<int> container;
4928 EXPECT_EQ("", Explain(m, container));
4929 container.push_back(0);
4930 EXPECT_EQ("whose size is 1", Explain(m, container));
4933 TEST(IsEmptyTest, WorksWithMoveOnly) {
4934 ContainerHelper helper;
4935 EXPECT_CALL(helper, Call(IsEmpty()));
4939 TEST(IsTrueTest, IsTrueIsFalse) {
4940 EXPECT_THAT(true, IsTrue());
4941 EXPECT_THAT(false, IsFalse());
4942 EXPECT_THAT(true, Not(IsFalse()));
4943 EXPECT_THAT(false, Not(IsTrue()));
4944 EXPECT_THAT(0, Not(IsTrue()));
4945 EXPECT_THAT(0, IsFalse());
4946 EXPECT_THAT(nullptr, Not(IsTrue()));
4947 EXPECT_THAT(nullptr, IsFalse());
4948 EXPECT_THAT(-1, IsTrue());
4949 EXPECT_THAT(-1, Not(IsFalse()));
4950 EXPECT_THAT(1, IsTrue());
4951 EXPECT_THAT(1, Not(IsFalse()));
4952 EXPECT_THAT(2, IsTrue());
4953 EXPECT_THAT(2, Not(IsFalse()));
4955 EXPECT_THAT(a, IsTrue());
4956 EXPECT_THAT(a, Not(IsFalse()));
4957 EXPECT_THAT(&a, IsTrue());
4958 EXPECT_THAT(&a, Not(IsFalse()));
4959 EXPECT_THAT(false, Not(IsTrue()));
4960 EXPECT_THAT(true, Not(IsFalse()));
4961 EXPECT_THAT(std::true_type(), IsTrue());
4962 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4963 EXPECT_THAT(std::false_type(), IsFalse());
4964 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4965 EXPECT_THAT(nullptr, Not(IsTrue()));
4966 EXPECT_THAT(nullptr, IsFalse());
4967 std::unique_ptr<int> null_unique;
4968 std::unique_ptr<int> nonnull_unique(new int(0));
4969 EXPECT_THAT(null_unique, Not(IsTrue()));
4970 EXPECT_THAT(null_unique, IsFalse());
4971 EXPECT_THAT(nonnull_unique, IsTrue());
4972 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4975 TEST(SizeIsTest, ImplementsSizeIs) {
4976 vector<int> container;
4977 EXPECT_THAT(container, SizeIs(0));
4978 EXPECT_THAT(container, Not(SizeIs(1)));
4979 container.push_back(0);
4980 EXPECT_THAT(container, Not(SizeIs(0)));
4981 EXPECT_THAT(container, SizeIs(1));
4982 container.push_back(0);
4983 EXPECT_THAT(container, Not(SizeIs(0)));
4984 EXPECT_THAT(container, SizeIs(2));
4987 TEST(SizeIsTest, WorksWithMap) {
4988 map<std::string, int> container;
4989 EXPECT_THAT(container, SizeIs(0));
4990 EXPECT_THAT(container, Not(SizeIs(1)));
4991 container.insert(make_pair("foo", 1));
4992 EXPECT_THAT(container, Not(SizeIs(0)));
4993 EXPECT_THAT(container, SizeIs(1));
4994 container.insert(make_pair("bar", 2));
4995 EXPECT_THAT(container, Not(SizeIs(0)));
4996 EXPECT_THAT(container, SizeIs(2));
4999 TEST(SizeIsTest, WorksWithReferences) {
5000 vector<int> container;
5001 Matcher<const vector<int>&> m = SizeIs(1);
5002 EXPECT_THAT(container, Not(m));
5003 container.push_back(0);
5004 EXPECT_THAT(container, m);
5007 TEST(SizeIsTest, WorksWithMoveOnly) {
5008 ContainerHelper helper;
5009 EXPECT_CALL(helper, Call(SizeIs(3)));
5010 helper.Call(MakeUniquePtrs({1, 2, 3}));
5013 // SizeIs should work for any type that provides a size() member function.
5014 // For example, a size_type member type should not need to be provided.
5015 struct MinimalistCustomType {
5016 int size() const { return 1; }
5018 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
5019 MinimalistCustomType container;
5020 EXPECT_THAT(container, SizeIs(1));
5021 EXPECT_THAT(container, Not(SizeIs(0)));
5024 TEST(SizeIsTest, CanDescribeSelf) {
5025 Matcher<vector<int> > m = SizeIs(2);
5026 EXPECT_EQ("size is equal to 2", Describe(m));
5027 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
5030 TEST(SizeIsTest, ExplainsResult) {
5031 Matcher<vector<int> > m1 = SizeIs(2);
5032 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
5033 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
5034 Matcher<vector<int> > m4 = SizeIs(Gt(1u));
5035 vector<int> container;
5036 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
5037 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
5038 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
5039 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
5040 container.push_back(0);
5041 container.push_back(0);
5042 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
5043 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
5044 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
5045 EXPECT_EQ("whose size 2 matches", Explain(m4, container));
5048 #if GTEST_HAS_TYPED_TEST
5049 // Tests ContainerEq with different container types, and
5050 // different element types.
5052 template <typename T>
5053 class ContainerEqTest : public testing::Test {};
5055 typedef testing::Types<
5060 ContainerEqTestTypes;
5062 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
5064 // Tests that the filled container is equal to itself.
5065 TYPED_TEST(ContainerEqTest, EqualsSelf) {
5066 static const int vals[] = {1, 1, 2, 3, 5, 8};
5067 TypeParam my_set(vals, vals + 6);
5068 const Matcher<TypeParam> m = ContainerEq(my_set);
5069 EXPECT_TRUE(m.Matches(my_set));
5070 EXPECT_EQ("", Explain(m, my_set));
5073 // Tests that missing values are reported.
5074 TYPED_TEST(ContainerEqTest, ValueMissing) {
5075 static const int vals[] = {1, 1, 2, 3, 5, 8};
5076 static const int test_vals[] = {2, 1, 8, 5};
5077 TypeParam my_set(vals, vals + 6);
5078 TypeParam test_set(test_vals, test_vals + 4);
5079 const Matcher<TypeParam> m = ContainerEq(my_set);
5080 EXPECT_FALSE(m.Matches(test_set));
5081 EXPECT_EQ("which doesn't have these expected elements: 3",
5082 Explain(m, test_set));
5085 // Tests that added values are reported.
5086 TYPED_TEST(ContainerEqTest, ValueAdded) {
5087 static const int vals[] = {1, 1, 2, 3, 5, 8};
5088 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
5089 TypeParam my_set(vals, vals + 6);
5090 TypeParam test_set(test_vals, test_vals + 6);
5091 const Matcher<const TypeParam&> m = ContainerEq(my_set);
5092 EXPECT_FALSE(m.Matches(test_set));
5093 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
5096 // Tests that added and missing values are reported together.
5097 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
5098 static const int vals[] = {1, 1, 2, 3, 5, 8};
5099 static const int test_vals[] = {1, 2, 3, 8, 46};
5100 TypeParam my_set(vals, vals + 6);
5101 TypeParam test_set(test_vals, test_vals + 5);
5102 const Matcher<TypeParam> m = ContainerEq(my_set);
5103 EXPECT_FALSE(m.Matches(test_set));
5104 EXPECT_EQ("which has these unexpected elements: 46,\n"
5105 "and doesn't have these expected elements: 5",
5106 Explain(m, test_set));
5109 // Tests duplicated value -- expect no explanation.
5110 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
5111 static const int vals[] = {1, 1, 2, 3, 5, 8};
5112 static const int test_vals[] = {1, 2, 3, 5, 8};
5113 TypeParam my_set(vals, vals + 6);
5114 TypeParam test_set(test_vals, test_vals + 5);
5115 const Matcher<const TypeParam&> m = ContainerEq(my_set);
5116 // Depending on the container, match may be true or false
5117 // But in any case there should be no explanation.
5118 EXPECT_EQ("", Explain(m, test_set));
5120 #endif // GTEST_HAS_TYPED_TEST
5122 // Tests that multiple missing values are reported.
5123 // Using just vector here, so order is predictable.
5124 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
5125 static const int vals[] = {1, 1, 2, 3, 5, 8};
5126 static const int test_vals[] = {2, 1, 5};
5127 vector<int> my_set(vals, vals + 6);
5128 vector<int> test_set(test_vals, test_vals + 3);
5129 const Matcher<vector<int> > m = ContainerEq(my_set);
5130 EXPECT_FALSE(m.Matches(test_set));
5131 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
5132 Explain(m, test_set));
5135 // Tests that added values are reported.
5136 // Using just vector here, so order is predictable.
5137 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
5138 static const int vals[] = {1, 1, 2, 3, 5, 8};
5139 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
5140 list<size_t> my_set(vals, vals + 6);
5141 list<size_t> test_set(test_vals, test_vals + 7);
5142 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
5143 EXPECT_FALSE(m.Matches(test_set));
5144 EXPECT_EQ("which has these unexpected elements: 92, 46",
5145 Explain(m, test_set));
5148 // Tests that added and missing values are reported together.
5149 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
5150 static const int vals[] = {1, 1, 2, 3, 5, 8};
5151 static const int test_vals[] = {1, 2, 3, 92, 46};
5152 list<size_t> my_set(vals, vals + 6);
5153 list<size_t> test_set(test_vals, test_vals + 5);
5154 const Matcher<const list<size_t> > m = ContainerEq(my_set);
5155 EXPECT_FALSE(m.Matches(test_set));
5156 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
5157 "and doesn't have these expected elements: 5, 8",
5158 Explain(m, test_set));
5161 // Tests to see that duplicate elements are detected,
5162 // but (as above) not reported in the explanation.
5163 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
5164 static const int vals[] = {1, 1, 2, 3, 5, 8};
5165 static const int test_vals[] = {1, 2, 3, 5, 8};
5166 vector<int> my_set(vals, vals + 6);
5167 vector<int> test_set(test_vals, test_vals + 5);
5168 const Matcher<vector<int> > m = ContainerEq(my_set);
5169 EXPECT_TRUE(m.Matches(my_set));
5170 EXPECT_FALSE(m.Matches(test_set));
5171 // There is nothing to report when both sets contain all the same values.
5172 EXPECT_EQ("", Explain(m, test_set));
5175 // Tests that ContainerEq works for non-trivial associative containers,
5177 TEST(ContainerEqExtraTest, WorksForMaps) {
5178 map<int, std::string> my_map;
5182 map<int, std::string> test_map;
5186 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
5187 EXPECT_TRUE(m.Matches(my_map));
5188 EXPECT_FALSE(m.Matches(test_map));
5190 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
5191 "and doesn't have these expected elements: (0, \"a\")",
5192 Explain(m, test_map));
5195 TEST(ContainerEqExtraTest, WorksForNativeArray) {
5196 int a1[] = {1, 2, 3};
5197 int a2[] = {1, 2, 3};
5198 int b[] = {1, 2, 4};
5200 EXPECT_THAT(a1, ContainerEq(a2));
5201 EXPECT_THAT(a1, Not(ContainerEq(b)));
5204 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5205 const char a1[][3] = {"hi", "lo"};
5206 const char a2[][3] = {"hi", "lo"};
5207 const char b[][3] = {"lo", "hi"};
5209 // Tests using ContainerEq() in the first dimension.
5210 EXPECT_THAT(a1, ContainerEq(a2));
5211 EXPECT_THAT(a1, Not(ContainerEq(b)));
5213 // Tests using ContainerEq() in the second dimension.
5214 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5215 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5218 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5219 const int a1[] = {1, 2, 3};
5220 const int a2[] = {1, 2, 3};
5221 const int b[] = {1, 2, 3, 4};
5223 const int* const p1 = a1;
5224 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
5225 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
5227 const int c[] = {1, 3, 2};
5228 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
5231 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5232 std::string a1[][3] = {
5233 {"hi", "hello", "ciao"},
5234 {"bye", "see you", "ciao"}
5237 std::string a2[][3] = {
5238 {"hi", "hello", "ciao"},
5239 {"bye", "see you", "ciao"}
5242 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5249 TEST(WhenSortedByTest, WorksForEmptyContainer) {
5250 const vector<int> numbers;
5251 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
5252 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
5255 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
5256 vector<unsigned> numbers;
5257 numbers.push_back(3);
5258 numbers.push_back(1);
5259 numbers.push_back(2);
5260 numbers.push_back(2);
5261 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
5262 ElementsAre(3, 2, 2, 1)));
5263 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
5264 ElementsAre(1, 2, 2, 3))));
5267 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
5268 list<std::string> words;
5269 words.push_back("say");
5270 words.push_back("hello");
5271 words.push_back("world");
5272 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
5273 ElementsAre("hello", "say", "world")));
5274 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
5275 ElementsAre("say", "hello", "world"))));
5278 TEST(WhenSortedByTest, WorksForNativeArray) {
5279 const int numbers[] = {1, 3, 2, 4};
5280 const int sorted_numbers[] = {1, 2, 3, 4};
5281 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
5282 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
5283 ElementsAreArray(sorted_numbers)));
5284 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5287 TEST(WhenSortedByTest, CanDescribeSelf) {
5288 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
5289 EXPECT_EQ("(when sorted) has 2 elements where\n"
5290 "element #0 is equal to 1,\n"
5291 "element #1 is equal to 2",
5293 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5294 "element #0 isn't equal to 1, or\n"
5295 "element #1 isn't equal to 2",
5296 DescribeNegation(m));
5299 TEST(WhenSortedByTest, ExplainsMatchResult) {
5300 const int a[] = {2, 1};
5301 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5302 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
5303 EXPECT_EQ("which is { 1, 2 } when sorted",
5304 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
5307 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5308 // need to test it as exhaustively as we test the latter.
5310 TEST(WhenSortedTest, WorksForEmptyContainer) {
5311 const vector<int> numbers;
5312 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5313 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5316 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
5317 list<std::string> words;
5318 words.push_back("3");
5319 words.push_back("1");
5320 words.push_back("2");
5321 words.push_back("2");
5322 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
5323 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5326 TEST(WhenSortedTest, WorksForMapTypes) {
5327 map<std::string, int> word_counts;
5328 word_counts["and"] = 1;
5329 word_counts["the"] = 1;
5330 word_counts["buffalo"] = 2;
5331 EXPECT_THAT(word_counts,
5332 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5334 EXPECT_THAT(word_counts,
5335 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5336 Pair("buffalo", 2)))));
5339 TEST(WhenSortedTest, WorksForMultiMapTypes) {
5340 multimap<int, int> ifib;
5341 ifib.insert(make_pair(8, 6));
5342 ifib.insert(make_pair(2, 3));
5343 ifib.insert(make_pair(1, 1));
5344 ifib.insert(make_pair(3, 4));
5345 ifib.insert(make_pair(1, 2));
5346 ifib.insert(make_pair(5, 5));
5347 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5353 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5361 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5365 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5366 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5369 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5373 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5374 EXPECT_THAT(d, WhenSorted(vector_match));
5375 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5376 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5379 // Deliberately bare pseudo-container.
5380 // Offers only begin() and end() accessors, yielding InputIterator.
5381 template <typename T>
5386 typedef ConstIter const_iterator;
5387 typedef T value_type;
5389 template <typename InIter>
5390 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5392 const_iterator begin() const {
5393 return const_iterator(this, remainder_.begin());
5395 const_iterator end() const {
5396 return const_iterator(this, remainder_.end());
5400 class ConstIter : public std::iterator<std::input_iterator_tag,
5404 const value_type&> {
5406 ConstIter(const Streamlike* s,
5407 typename std::list<value_type>::iterator pos)
5408 : s_(s), pos_(pos) {}
5410 const value_type& operator*() const { return *pos_; }
5411 const value_type* operator->() const { return &*pos_; }
5412 ConstIter& operator++() {
5413 s_->remainder_.erase(pos_++);
5417 // *iter++ is required to work (see std::istreambuf_iterator).
5418 // (void)iter++ is also required to work.
5419 class PostIncrProxy {
5421 explicit PostIncrProxy(const value_type& value) : value_(value) {}
5422 value_type operator*() const { return value_; }
5426 PostIncrProxy operator++(int) {
5427 PostIncrProxy proxy(**this);
5432 friend bool operator==(const ConstIter& a, const ConstIter& b) {
5433 return a.s_ == b.s_ && a.pos_ == b.pos_;
5435 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5440 const Streamlike* s_;
5441 typename std::list<value_type>::iterator pos_;
5444 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5446 typedef typename std::list<value_type>::const_iterator Iter;
5447 const char* sep = "";
5448 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5456 mutable std::list<value_type> remainder_; // modified by iteration
5459 TEST(StreamlikeTest, Iteration) {
5460 const int a[5] = {2, 1, 4, 5, 3};
5461 Streamlike<int> s(a, a + 5);
5462 Streamlike<int>::const_iterator it = s.begin();
5464 while (it != s.end()) {
5465 SCOPED_TRACE(ip - a);
5466 EXPECT_EQ(*ip++, *it++);
5470 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5471 std::forward_list<int> container;
5472 EXPECT_THAT(container, BeginEndDistanceIs(0));
5473 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5474 container.push_front(0);
5475 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5476 EXPECT_THAT(container, BeginEndDistanceIs(1));
5477 container.push_front(0);
5478 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5479 EXPECT_THAT(container, BeginEndDistanceIs(2));
5482 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5483 const int a[5] = {1, 2, 3, 4, 5};
5484 Streamlike<int> s(a, a + 5);
5485 EXPECT_THAT(s, BeginEndDistanceIs(5));
5488 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5489 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5490 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5491 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5492 DescribeNegation(m));
5495 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5496 ContainerHelper helper;
5497 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5498 helper.Call(MakeUniquePtrs({1, 2}));
5501 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5502 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5503 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5504 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5505 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5506 vector<int> container;
5507 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5508 Explain(m1, container));
5509 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5510 Explain(m2, container));
5511 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5512 Explain(m3, container));
5514 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5516 Explain(m4, container));
5517 container.push_back(0);
5518 container.push_back(0);
5519 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5520 Explain(m1, container));
5521 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5522 Explain(m2, container));
5523 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5524 Explain(m3, container));
5526 "whose distance between begin() and end() 2 matches, which is 1 more "
5528 Explain(m4, container));
5531 TEST(WhenSortedTest, WorksForStreamlike) {
5532 // Streamlike 'container' provides only minimal iterator support.
5533 // Its iterators are tagged with input_iterator_tag.
5534 const int a[5] = {2, 1, 4, 5, 3};
5535 Streamlike<int> s(std::begin(a), std::end(a));
5536 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5537 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5540 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5541 const int a[] = {2, 1, 4, 5, 3};
5542 Streamlike<int> s(std::begin(a), std::end(a));
5543 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5544 EXPECT_THAT(s, WhenSorted(vector_match));
5545 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5548 TEST(IsSupersetOfTest, WorksForNativeArray) {
5549 const int subset[] = {1, 4};
5550 const int superset[] = {1, 2, 4};
5551 const int disjoint[] = {1, 0, 3};
5552 EXPECT_THAT(subset, IsSupersetOf(subset));
5553 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5554 EXPECT_THAT(superset, IsSupersetOf(subset));
5555 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5556 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5559 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5560 const int not_enough[] = {1, 2};
5561 const int enough[] = {1, 1, 2};
5562 const int expected[] = {1, 1};
5563 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5564 EXPECT_THAT(enough, IsSupersetOf(expected));
5567 TEST(IsSupersetOfTest, WorksForEmpty) {
5568 vector<int> numbers;
5569 vector<int> expected;
5570 EXPECT_THAT(numbers, IsSupersetOf(expected));
5571 expected.push_back(1);
5572 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5574 numbers.push_back(1);
5575 numbers.push_back(2);
5576 EXPECT_THAT(numbers, IsSupersetOf(expected));
5577 expected.push_back(1);
5578 EXPECT_THAT(numbers, IsSupersetOf(expected));
5579 expected.push_back(2);
5580 EXPECT_THAT(numbers, IsSupersetOf(expected));
5581 expected.push_back(3);
5582 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5585 TEST(IsSupersetOfTest, WorksForStreamlike) {
5586 const int a[5] = {1, 2, 3, 4, 5};
5587 Streamlike<int> s(std::begin(a), std::end(a));
5589 vector<int> expected;
5590 expected.push_back(1);
5591 expected.push_back(2);
5592 expected.push_back(5);
5593 EXPECT_THAT(s, IsSupersetOf(expected));
5595 expected.push_back(0);
5596 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5599 TEST(IsSupersetOfTest, TakesStlContainer) {
5600 const int actual[] = {3, 1, 2};
5602 ::std::list<int> expected;
5603 expected.push_back(1);
5604 expected.push_back(3);
5605 EXPECT_THAT(actual, IsSupersetOf(expected));
5607 expected.push_back(4);
5608 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5611 TEST(IsSupersetOfTest, Describe) {
5612 typedef std::vector<int> IntVec;
5614 expected.push_back(111);
5615 expected.push_back(222);
5616 expected.push_back(333);
5618 Describe<IntVec>(IsSupersetOf(expected)),
5619 Eq("a surjection from elements to requirements exists such that:\n"
5620 " - an element is equal to 111\n"
5621 " - an element is equal to 222\n"
5622 " - an element is equal to 333"));
5625 TEST(IsSupersetOfTest, DescribeNegation) {
5626 typedef std::vector<int> IntVec;
5628 expected.push_back(111);
5629 expected.push_back(222);
5630 expected.push_back(333);
5632 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5633 Eq("no surjection from elements to requirements exists such that:\n"
5634 " - an element is equal to 111\n"
5635 " - an element is equal to 222\n"
5636 " - an element is equal to 333"));
5639 TEST(IsSupersetOfTest, MatchAndExplain) {
5643 std::vector<int> expected;
5644 expected.push_back(1);
5645 expected.push_back(2);
5646 StringMatchResultListener listener;
5647 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5649 EXPECT_THAT(listener.str(),
5650 Eq("where the following matchers don't match any elements:\n"
5651 "matcher #0: is equal to 1"));
5655 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5657 EXPECT_THAT(listener.str(), Eq("where:\n"
5658 " - element #0 is matched by matcher #1,\n"
5659 " - element #2 is matched by matcher #0"));
5662 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5663 const int numbers[] = {1, 3, 6, 2, 4, 5};
5664 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5665 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5668 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5669 ContainerHelper helper;
5670 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5671 helper.Call(MakeUniquePtrs({1, 2}));
5672 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5673 helper.Call(MakeUniquePtrs({2}));
5676 TEST(IsSubsetOfTest, WorksForNativeArray) {
5677 const int subset[] = {1, 4};
5678 const int superset[] = {1, 2, 4};
5679 const int disjoint[] = {1, 0, 3};
5680 EXPECT_THAT(subset, IsSubsetOf(subset));
5681 EXPECT_THAT(subset, IsSubsetOf(superset));
5682 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5683 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5684 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5687 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5688 const int not_enough[] = {1, 2};
5689 const int enough[] = {1, 1, 2};
5690 const int actual[] = {1, 1};
5691 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5692 EXPECT_THAT(actual, IsSubsetOf(enough));
5695 TEST(IsSubsetOfTest, WorksForEmpty) {
5696 vector<int> numbers;
5697 vector<int> expected;
5698 EXPECT_THAT(numbers, IsSubsetOf(expected));
5699 expected.push_back(1);
5700 EXPECT_THAT(numbers, IsSubsetOf(expected));
5702 numbers.push_back(1);
5703 numbers.push_back(2);
5704 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5705 expected.push_back(1);
5706 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5707 expected.push_back(2);
5708 EXPECT_THAT(numbers, IsSubsetOf(expected));
5709 expected.push_back(3);
5710 EXPECT_THAT(numbers, IsSubsetOf(expected));
5713 TEST(IsSubsetOfTest, WorksForStreamlike) {
5714 const int a[5] = {1, 2};
5715 Streamlike<int> s(std::begin(a), std::end(a));
5717 vector<int> expected;
5718 expected.push_back(1);
5719 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5720 expected.push_back(2);
5721 expected.push_back(5);
5722 EXPECT_THAT(s, IsSubsetOf(expected));
5725 TEST(IsSubsetOfTest, TakesStlContainer) {
5726 const int actual[] = {3, 1, 2};
5728 ::std::list<int> expected;
5729 expected.push_back(1);
5730 expected.push_back(3);
5731 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5733 expected.push_back(2);
5734 expected.push_back(4);
5735 EXPECT_THAT(actual, IsSubsetOf(expected));
5738 TEST(IsSubsetOfTest, Describe) {
5739 typedef std::vector<int> IntVec;
5741 expected.push_back(111);
5742 expected.push_back(222);
5743 expected.push_back(333);
5746 Describe<IntVec>(IsSubsetOf(expected)),
5747 Eq("an injection from elements to requirements exists such that:\n"
5748 " - an element is equal to 111\n"
5749 " - an element is equal to 222\n"
5750 " - an element is equal to 333"));
5753 TEST(IsSubsetOfTest, DescribeNegation) {
5754 typedef std::vector<int> IntVec;
5756 expected.push_back(111);
5757 expected.push_back(222);
5758 expected.push_back(333);
5760 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5761 Eq("no injection from elements to requirements exists such that:\n"
5762 " - an element is equal to 111\n"
5763 " - an element is equal to 222\n"
5764 " - an element is equal to 333"));
5767 TEST(IsSubsetOfTest, MatchAndExplain) {
5771 std::vector<int> expected;
5772 expected.push_back(1);
5773 expected.push_back(2);
5774 StringMatchResultListener listener;
5775 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5777 EXPECT_THAT(listener.str(),
5778 Eq("where the following elements don't match any matchers:\n"
5781 expected.push_back(3);
5783 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5785 EXPECT_THAT(listener.str(), Eq("where:\n"
5786 " - element #0 is matched by matcher #1,\n"
5787 " - element #1 is matched by matcher #2"));
5790 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5791 const int numbers[] = {1, 2, 3};
5792 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5793 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5796 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5797 ContainerHelper helper;
5798 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5799 helper.Call(MakeUniquePtrs({1}));
5800 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5801 helper.Call(MakeUniquePtrs({2}));
5804 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5807 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5808 const int a[5] = {1, 2, 3, 4, 5};
5809 Streamlike<int> s(std::begin(a), std::end(a));
5810 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5811 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5814 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5815 const int a[5] = {1, 2, 3, 4, 5};
5816 Streamlike<int> s(std::begin(a), std::end(a));
5818 vector<int> expected;
5819 expected.push_back(1);
5820 expected.push_back(2);
5821 expected.push_back(3);
5822 expected.push_back(4);
5823 expected.push_back(5);
5824 EXPECT_THAT(s, ElementsAreArray(expected));
5827 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5830 TEST(ElementsAreTest, WorksWithUncopyable) {
5832 objs[0].set_value(-3);
5833 objs[1].set_value(1);
5834 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5837 TEST(ElementsAreTest, WorksWithMoveOnly) {
5838 ContainerHelper helper;
5839 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5840 helper.Call(MakeUniquePtrs({1, 2}));
5842 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5843 helper.Call(MakeUniquePtrs({3, 4}));
5846 TEST(ElementsAreTest, TakesStlContainer) {
5847 const int actual[] = {3, 1, 2};
5849 ::std::list<int> expected;
5850 expected.push_back(3);
5851 expected.push_back(1);
5852 expected.push_back(2);
5853 EXPECT_THAT(actual, ElementsAreArray(expected));
5855 expected.push_back(4);
5856 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5859 // Tests for UnorderedElementsAreArray()
5861 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5862 const int a[] = {0, 1, 2, 3, 4};
5863 std::vector<int> s(std::begin(a), std::end(a));
5865 StringMatchResultListener listener;
5866 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5867 s, &listener)) << listener.str();
5868 } while (std::next_permutation(s.begin(), s.end()));
5871 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5872 const bool a[] = {0, 1, 0, 1, 1};
5873 const bool b[] = {1, 0, 1, 1, 0};
5874 std::vector<bool> expected(std::begin(a), std::end(a));
5875 std::vector<bool> actual(std::begin(b), std::end(b));
5876 StringMatchResultListener listener;
5877 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5878 actual, &listener)) << listener.str();
5881 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5882 // Streamlike 'container' provides only minimal iterator support.
5883 // Its iterators are tagged with input_iterator_tag, and it has no
5884 // size() or empty() methods.
5885 const int a[5] = {2, 1, 4, 5, 3};
5886 Streamlike<int> s(std::begin(a), std::end(a));
5888 ::std::vector<int> expected;
5889 expected.push_back(1);
5890 expected.push_back(2);
5891 expected.push_back(3);
5892 expected.push_back(4);
5893 expected.push_back(5);
5894 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5896 expected.push_back(6);
5897 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5900 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5901 const int actual[] = {3, 1, 2};
5903 ::std::list<int> expected;
5904 expected.push_back(1);
5905 expected.push_back(2);
5906 expected.push_back(3);
5907 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5909 expected.push_back(4);
5910 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5914 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5915 const int a[5] = {2, 1, 4, 5, 3};
5916 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5917 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5920 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5921 const std::string a[5] = {"a", "b", "c", "d", "e"};
5922 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5923 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5926 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5927 const int a[5] = {2, 1, 4, 5, 3};
5928 EXPECT_THAT(a, UnorderedElementsAreArray(
5929 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5930 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5931 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5934 TEST(UnorderedElementsAreArrayTest,
5935 TakesInitializerListOfDifferentTypedMatchers) {
5936 const int a[5] = {2, 1, 4, 5, 3};
5937 // The compiler cannot infer the type of the initializer list if its
5938 // elements have different types. We must explicitly specify the
5939 // unified element type in this case.
5940 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5941 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5942 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5943 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5947 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5948 ContainerHelper helper;
5950 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5951 helper.Call(MakeUniquePtrs({2, 1}));
5954 class UnorderedElementsAreTest : public testing::Test {
5956 typedef std::vector<int> IntVec;
5959 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5961 objs[0].set_value(-3);
5962 objs[1].set_value(1);
5964 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5967 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5968 const int a[] = {1, 2, 3};
5969 std::vector<int> s(std::begin(a), std::end(a));
5971 StringMatchResultListener listener;
5972 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5973 s, &listener)) << listener.str();
5974 } while (std::next_permutation(s.begin(), s.end()));
5977 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5978 const int a[] = {1, 2, 3};
5979 std::vector<int> s(std::begin(a), std::end(a));
5980 std::vector<Matcher<int> > mv;
5984 // The element with value '3' matches nothing: fail fast.
5985 StringMatchResultListener listener;
5986 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5987 s, &listener)) << listener.str();
5990 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5991 // Streamlike 'container' provides only minimal iterator support.
5992 // Its iterators are tagged with input_iterator_tag, and it has no
5993 // size() or empty() methods.
5994 const int a[5] = {2, 1, 4, 5, 3};
5995 Streamlike<int> s(std::begin(a), std::end(a));
5997 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5998 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
6001 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
6002 ContainerHelper helper;
6003 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
6004 helper.Call(MakeUniquePtrs({2, 1}));
6007 // One naive implementation of the matcher runs in O(N!) time, which is too
6008 // slow for many real-world inputs. This test shows that our matcher can match
6009 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
6010 // iterations and obviously effectively incomputable.
6011 // [ RUN ] UnorderedElementsAreTest.Performance
6012 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
6013 TEST_F(UnorderedElementsAreTest, Performance) {
6015 std::vector<Matcher<int> > mv;
6016 for (int i = 0; i < 100; ++i) {
6021 StringMatchResultListener listener;
6022 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
6023 s, &listener)) << listener.str();
6026 // Another variant of 'Performance' with similar expectations.
6027 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
6028 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
6029 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
6031 std::vector<Matcher<int> > mv;
6032 for (int i = 0; i < 100; ++i) {
6040 StringMatchResultListener listener;
6041 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
6042 s, &listener)) << listener.str();
6045 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
6048 StringMatchResultListener listener;
6049 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6050 v, &listener)) << listener.str();
6051 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
6054 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
6056 StringMatchResultListener listener;
6057 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6058 v, &listener)) << listener.str();
6059 EXPECT_THAT(listener.str(), Eq(""));
6062 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
6066 StringMatchResultListener listener;
6067 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6068 v, &listener)) << listener.str();
6071 Eq("where the following matchers don't match any elements:\n"
6072 "matcher #1: is equal to 2"));
6075 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
6079 StringMatchResultListener listener;
6080 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
6081 v, &listener)) << listener.str();
6084 Eq("where the following elements don't match any matchers:\n"
6088 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
6092 StringMatchResultListener listener;
6093 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6094 v, &listener)) << listener.str();
6098 " the following matchers don't match any elements:\n"
6099 "matcher #0: is equal to 1\n"
6102 " the following elements don't match any matchers:\n"
6106 // Test helper for formatting element, matcher index pairs in expectations.
6107 static std::string EMString(int element, int matcher) {
6109 ss << "(element #" << element << ", matcher #" << matcher << ")";
6113 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
6114 // A situation where all elements and matchers have a match
6115 // associated with them, but the max matching is not perfect.
6116 std::vector<std::string> v;
6120 StringMatchResultListener listener;
6121 EXPECT_FALSE(ExplainMatchResult(
6122 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
6125 std::string prefix =
6126 "where no permutation of the elements can satisfy all matchers, "
6127 "and the closest match is 2 of 3 matchers with the "
6130 // We have to be a bit loose here, because there are 4 valid max matches.
6133 AnyOf(prefix + "{\n " + EMString(0, 0) +
6134 ",\n " + EMString(1, 2) + "\n}",
6135 prefix + "{\n " + EMString(0, 1) +
6136 ",\n " + EMString(1, 2) + "\n}",
6137 prefix + "{\n " + EMString(0, 0) +
6138 ",\n " + EMString(2, 2) + "\n}",
6139 prefix + "{\n " + EMString(0, 1) +
6140 ",\n " + EMString(2, 2) + "\n}"));
6143 TEST_F(UnorderedElementsAreTest, Describe) {
6144 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
6147 Describe<IntVec>(UnorderedElementsAre(345)),
6148 Eq("has 1 element and that element is equal to 345"));
6150 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
6151 Eq("has 3 elements and there exists some permutation "
6152 "of elements such that:\n"
6153 " - element #0 is equal to 111, and\n"
6154 " - element #1 is equal to 222, and\n"
6155 " - element #2 is equal to 333"));
6158 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
6159 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
6162 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
6163 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
6165 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
6166 Eq("doesn't have 3 elements, or there exists no permutation "
6167 "of elements such that:\n"
6168 " - element #0 is equal to 123, and\n"
6169 " - element #1 is equal to 234, and\n"
6170 " - element #2 is equal to 345"));
6175 // Used as a check on the more complex max flow method used in the
6176 // real testing::internal::FindMaxBipartiteMatching. This method is
6177 // compatible but runs in worst-case factorial time, so we only
6178 // use it in testing for small problem sizes.
6179 template <typename Graph>
6180 class BacktrackingMaxBPMState {
6182 // Does not take ownership of 'g'.
6183 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
6185 ElementMatcherPairs Compute() {
6186 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
6187 return best_so_far_;
6189 lhs_used_.assign(graph_->LhsSize(), kUnused);
6190 rhs_used_.assign(graph_->RhsSize(), kUnused);
6191 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
6194 if (best_so_far_.size() == graph_->RhsSize())
6197 return best_so_far_;
6201 static const size_t kUnused = static_cast<size_t>(-1);
6203 void PushMatch(size_t lhs, size_t rhs) {
6204 matches_.push_back(ElementMatcherPair(lhs, rhs));
6205 lhs_used_[lhs] = rhs;
6206 rhs_used_[rhs] = lhs;
6207 if (matches_.size() > best_so_far_.size()) {
6208 best_so_far_ = matches_;
6213 const ElementMatcherPair& back = matches_.back();
6214 lhs_used_[back.first] = kUnused;
6215 rhs_used_[back.second] = kUnused;
6216 matches_.pop_back();
6219 bool RecurseInto(size_t irhs) {
6220 if (rhs_used_[irhs] != kUnused) {
6223 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
6224 if (lhs_used_[ilhs] != kUnused) {
6227 if (!graph_->HasEdge(ilhs, irhs)) {
6230 PushMatch(ilhs, irhs);
6231 if (best_so_far_.size() == graph_->RhsSize()) {
6234 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6235 if (!RecurseInto(mi)) return false;
6242 const Graph* graph_; // not owned
6243 std::vector<size_t> lhs_used_;
6244 std::vector<size_t> rhs_used_;
6245 ElementMatcherPairs matches_;
6246 ElementMatcherPairs best_so_far_;
6249 template <typename Graph>
6250 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6254 // Implement a simple backtracking algorithm to determine if it is possible
6255 // to find one element per matcher, without reusing elements.
6256 template <typename Graph>
6258 FindBacktrackingMaxBPM(const Graph& g) {
6259 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6262 class BacktrackingBPMTest : public ::testing::Test { };
6264 // Tests the MaxBipartiteMatching algorithm with square matrices.
6265 // The single int param is the # of nodes on each of the left and right sides.
6266 class BipartiteTest : public ::testing::TestWithParam<size_t> {};
6268 // Verify all match graphs up to some moderate number of edges.
6269 TEST_P(BipartiteTest, Exhaustive) {
6270 size_t nodes = GetParam();
6271 MatchMatrix graph(nodes, nodes);
6273 ElementMatcherPairs matches =
6274 internal::FindMaxBipartiteMatching(graph);
6275 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6276 << "graph: " << graph.DebugString();
6277 // Check that all elements of matches are in the graph.
6278 // Check that elements of first and second are unique.
6279 std::vector<bool> seen_element(graph.LhsSize());
6280 std::vector<bool> seen_matcher(graph.RhsSize());
6281 SCOPED_TRACE(PrintToString(matches));
6282 for (size_t i = 0; i < matches.size(); ++i) {
6283 size_t ilhs = matches[i].first;
6284 size_t irhs = matches[i].second;
6285 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
6286 EXPECT_FALSE(seen_element[ilhs]);
6287 EXPECT_FALSE(seen_matcher[irhs]);
6288 seen_element[ilhs] = true;
6289 seen_matcher[irhs] = true;
6291 } while (graph.NextGraph());
6294 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
6295 ::testing::Range(size_t{0}, size_t{5}));
6297 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
6298 class BipartiteNonSquareTest
6299 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6302 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6310 MatchMatrix g(4, 3);
6311 constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
6312 {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
6313 for (size_t i = 0; i < kEdges.size(); ++i) {
6314 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
6316 EXPECT_THAT(FindBacktrackingMaxBPM(g),
6317 ElementsAre(Pair(3, 0),
6318 Pair(AnyOf(1, 2), 1),
6319 Pair(0, 2))) << g.DebugString();
6322 // Verify a few nonsquare matrices.
6323 TEST_P(BipartiteNonSquareTest, Exhaustive) {
6324 size_t nlhs = GetParam().first;
6325 size_t nrhs = GetParam().second;
6326 MatchMatrix graph(nlhs, nrhs);
6328 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6329 internal::FindMaxBipartiteMatching(graph).size())
6330 << "graph: " << graph.DebugString()
6331 << "\nbacktracking: "
6332 << PrintToString(FindBacktrackingMaxBPM(graph))
6334 << PrintToString(internal::FindMaxBipartiteMatching(graph));
6335 } while (graph.NextGraph());
6338 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
6340 std::make_pair(1, 2),
6341 std::make_pair(2, 1),
6342 std::make_pair(3, 2),
6343 std::make_pair(2, 3),
6344 std::make_pair(4, 1),
6345 std::make_pair(1, 4),
6346 std::make_pair(4, 3),
6347 std::make_pair(3, 4)));
6349 class BipartiteRandomTest
6350 : public ::testing::TestWithParam<std::pair<int, int> > {
6353 // Verifies a large sample of larger graphs.
6354 TEST_P(BipartiteRandomTest, LargerNets) {
6355 int nodes = GetParam().first;
6356 int iters = GetParam().second;
6357 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
6359 auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));
6361 seed = static_cast<uint32_t>(time(nullptr));
6364 for (; iters > 0; --iters, ++seed) {
6365 srand(static_cast<unsigned int>(seed));
6367 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6368 internal::FindMaxBipartiteMatching(graph).size())
6369 << " graph: " << graph.DebugString()
6370 << "\nTo reproduce the failure, rerun the test with the flag"
6371 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6375 // Test argument is a std::pair<int, int> representing (nodes, iters).
6376 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
6378 std::make_pair(5, 10000),
6379 std::make_pair(6, 5000),
6380 std::make_pair(7, 2000),
6381 std::make_pair(8, 500),
6382 std::make_pair(9, 100)));
6384 // Tests IsReadableTypeName().
6386 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6387 EXPECT_TRUE(IsReadableTypeName("int"));
6388 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6389 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6390 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6393 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6394 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6395 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6396 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6399 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6401 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6402 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6405 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6406 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6409 // Tests FormatMatcherDescription().
6411 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6412 EXPECT_EQ("is even",
6413 FormatMatcherDescription(false, "IsEven", Strings()));
6414 EXPECT_EQ("not (is even)",
6415 FormatMatcherDescription(true, "IsEven", Strings()));
6417 const char* params[] = {"5"};
6418 EXPECT_EQ("equals 5",
6419 FormatMatcherDescription(false, "Equals",
6420 Strings(params, params + 1)));
6422 const char* params2[] = {"5", "8"};
6423 EXPECT_EQ("is in range (5, 8)",
6424 FormatMatcherDescription(false, "IsInRange",
6425 Strings(params2, params2 + 2)));
6428 // Tests PolymorphicMatcher::mutable_impl().
6429 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6430 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6431 DivisibleByImpl& impl = m.mutable_impl();
6432 EXPECT_EQ(42, impl.divider());
6434 impl.set_divider(0);
6435 EXPECT_EQ(0, m.mutable_impl().divider());
6438 // Tests PolymorphicMatcher::impl().
6439 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6440 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6441 const DivisibleByImpl& impl = m.impl();
6442 EXPECT_EQ(42, impl.divider());
6445 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6447 ExplainMatchFailureTupleTo(
6448 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6449 std::make_tuple('a', 10), &ss1);
6450 EXPECT_EQ("", ss1.str()); // Successful match.
6453 ExplainMatchFailureTupleTo(
6454 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6455 std::make_tuple(2, 'b'), &ss2);
6456 EXPECT_EQ(" Expected arg #0: is > 5\n"
6457 " Actual: 2, which is 3 less than 5\n"
6458 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6459 " Actual: 'b' (98, 0x62)\n",
6460 ss2.str()); // Failed match where both arguments need explanation.
6463 ExplainMatchFailureTupleTo(
6464 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6465 std::make_tuple(2, 'a'), &ss3);
6466 EXPECT_EQ(" Expected arg #0: is > 5\n"
6467 " Actual: 2, which is 3 less than 5\n",
6468 ss3.str()); // Failed match where only one argument needs
6474 TEST(EachTest, ExplainsMatchResultCorrectly) {
6475 set<int> a; // empty
6477 Matcher<set<int> > m = Each(2);
6478 EXPECT_EQ("", Explain(m, a));
6480 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6482 const int b[1] = {1};
6483 EXPECT_EQ("", Explain(n, b));
6486 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6491 m = Each(GreaterThan(0));
6492 EXPECT_EQ("", Explain(m, a));
6494 m = Each(GreaterThan(10));
6495 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6499 TEST(EachTest, DescribesItselfCorrectly) {
6500 Matcher<vector<int> > m = Each(1);
6501 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6503 Matcher<vector<int> > m2 = Not(m);
6504 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6507 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6508 vector<int> some_vector;
6509 EXPECT_THAT(some_vector, Each(1));
6510 some_vector.push_back(3);
6511 EXPECT_THAT(some_vector, Not(Each(1)));
6512 EXPECT_THAT(some_vector, Each(3));
6513 some_vector.push_back(1);
6514 some_vector.push_back(2);
6515 EXPECT_THAT(some_vector, Not(Each(3)));
6516 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6518 vector<std::string> another_vector;
6519 another_vector.push_back("fee");
6520 EXPECT_THAT(another_vector, Each(std::string("fee")));
6521 another_vector.push_back("fie");
6522 another_vector.push_back("foe");
6523 another_vector.push_back("fum");
6524 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6527 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6528 map<const char*, int> my_map;
6529 const char* bar = "a string";
6531 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6533 map<std::string, int> another_map;
6534 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6535 another_map["fee"] = 1;
6536 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6537 another_map["fie"] = 2;
6538 another_map["foe"] = 3;
6539 another_map["fum"] = 4;
6540 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6541 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6542 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6545 TEST(EachTest, AcceptsMatcher) {
6546 const int a[] = {1, 2, 3};
6547 EXPECT_THAT(a, Each(Gt(0)));
6548 EXPECT_THAT(a, Not(Each(Gt(1))));
6551 TEST(EachTest, WorksForNativeArrayAsTuple) {
6552 const int a[] = {1, 2};
6553 const int* const pointer = a;
6554 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6555 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6558 TEST(EachTest, WorksWithMoveOnly) {
6559 ContainerHelper helper;
6560 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6561 helper.Call(MakeUniquePtrs({1, 2}));
6564 // For testing Pointwise().
6565 class IsHalfOfMatcher {
6567 template <typename T1, typename T2>
6568 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
6569 MatchResultListener* listener) const {
6570 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6571 *listener << "where the second is " << std::get<1>(a_pair);
6574 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
6579 void DescribeTo(ostream* os) const {
6580 *os << "are a pair where the first is half of the second";
6583 void DescribeNegationTo(ostream* os) const {
6584 *os << "are a pair where the first isn't half of the second";
6588 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6589 return MakePolymorphicMatcher(IsHalfOfMatcher());
6592 TEST(PointwiseTest, DescribesSelf) {
6597 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6598 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6599 "in { 1, 2, 3 } are a pair where the first is half of the second",
6601 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6602 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6603 "where the first isn't half of the second",
6604 DescribeNegation(m));
6607 TEST(PointwiseTest, MakesCopyOfRhs) {
6608 list<signed char> rhs;
6613 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6614 EXPECT_THAT(lhs, m);
6616 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6618 EXPECT_THAT(lhs, m);
6621 TEST(PointwiseTest, WorksForLhsNativeArray) {
6622 const int lhs[] = {1, 2, 3};
6627 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6628 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6631 TEST(PointwiseTest, WorksForRhsNativeArray) {
6632 const int rhs[] = {1, 2, 3};
6637 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6638 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6641 // Test is effective only with sanitizers.
6642 TEST(PointwiseTest, WorksForVectorOfBool) {
6643 vector<bool> rhs(3, false);
6645 vector<bool> lhs = rhs;
6646 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6648 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6652 TEST(PointwiseTest, WorksForRhsInitializerList) {
6653 const vector<int> lhs{2, 4, 6};
6654 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6655 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6659 TEST(PointwiseTest, RejectsWrongSize) {
6660 const double lhs[2] = {1, 2};
6661 const int rhs[1] = {0};
6662 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6663 EXPECT_EQ("which contains 2 values",
6664 Explain(Pointwise(Gt(), rhs), lhs));
6666 const int rhs2[3] = {0, 1, 2};
6667 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6670 TEST(PointwiseTest, RejectsWrongContent) {
6671 const double lhs[3] = {1, 2, 3};
6672 const int rhs[3] = {2, 6, 4};
6673 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6674 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6675 "where the second/2 is 3",
6676 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6679 TEST(PointwiseTest, AcceptsCorrectContent) {
6680 const double lhs[3] = {1, 2, 3};
6681 const int rhs[3] = {2, 4, 6};
6682 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6683 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6686 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6687 const double lhs[3] = {1, 2, 3};
6688 const int rhs[3] = {2, 4, 6};
6689 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6690 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6691 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6693 // This type works as a std::tuple<const double&, const int&> can be
6694 // implicitly cast to std::tuple<double, int>.
6695 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6696 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6697 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6700 MATCHER(PointeeEquals, "Points to an equal value") {
6701 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6702 ::testing::get<0>(arg), result_listener);
6705 TEST(PointwiseTest, WorksWithMoveOnly) {
6706 ContainerHelper helper;
6707 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6708 helper.Call(MakeUniquePtrs({1, 2}));
6711 TEST(UnorderedPointwiseTest, DescribesSelf) {
6716 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6718 "has 3 elements and there exists some permutation of elements such "
6720 " - element #0 and 1 are a pair where the first is half of the second, "
6722 " - element #1 and 2 are a pair where the first is half of the second, "
6724 " - element #2 and 3 are a pair where the first is half of the second",
6727 "doesn't have 3 elements, or there exists no permutation of elements "
6729 " - element #0 and 1 are a pair where the first is half of the second, "
6731 " - element #1 and 2 are a pair where the first is half of the second, "
6733 " - element #2 and 3 are a pair where the first is half of the second",
6734 DescribeNegation(m));
6737 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6738 list<signed char> rhs;
6743 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6744 EXPECT_THAT(lhs, m);
6746 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6748 EXPECT_THAT(lhs, m);
6751 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6752 const int lhs[] = {1, 2, 3};
6757 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6758 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6761 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6762 const int rhs[] = {1, 2, 3};
6767 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6768 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6772 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6773 const vector<int> lhs{2, 4, 6};
6774 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6775 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6779 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6780 const double lhs[2] = {1, 2};
6781 const int rhs[1] = {0};
6782 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6783 EXPECT_EQ("which has 2 elements",
6784 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6786 const int rhs2[3] = {0, 1, 2};
6787 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6790 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6791 const double lhs[3] = {1, 2, 3};
6792 const int rhs[3] = {2, 6, 6};
6793 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6794 EXPECT_EQ("where the following elements don't match any matchers:\n"
6796 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6799 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6800 const double lhs[3] = {1, 2, 3};
6801 const int rhs[3] = {2, 4, 6};
6802 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6805 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6806 const double lhs[3] = {1, 2, 3};
6807 const int rhs[3] = {6, 4, 2};
6808 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6811 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6812 const double lhs[3] = {1, 2, 3};
6813 const int rhs[3] = {4, 6, 2};
6814 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6815 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6817 // This type works as a std::tuple<const double&, const int&> can be
6818 // implicitly cast to std::tuple<double, int>.
6819 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6820 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6823 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6824 ContainerHelper helper;
6825 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6826 std::vector<int>{1, 2})));
6827 helper.Call(MakeUniquePtrs({2, 1}));
6830 // Sample optional type implementation with minimal requirements for use with
6831 // Optional matcher.
6832 template <typename T>
6833 class SampleOptional {
6835 using value_type = T;
6836 explicit SampleOptional(T value)
6837 : value_(std::move(value)), has_value_(true) {}
6838 SampleOptional() : value_(), has_value_(false) {}
6839 operator bool() const { return has_value_; }
6840 const T& operator*() const { return value_; }
6847 TEST(OptionalTest, DescribesSelf) {
6848 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6849 EXPECT_EQ("value is equal to 1", Describe(m));
6852 TEST(OptionalTest, ExplainsSelf) {
6853 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6854 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6855 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6858 TEST(OptionalTest, MatchesNonEmptyOptional) {
6859 const Matcher<SampleOptional<int>> m1 = Optional(1);
6860 const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6861 const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6862 SampleOptional<int> opt(1);
6863 EXPECT_TRUE(m1.Matches(opt));
6864 EXPECT_FALSE(m2.Matches(opt));
6865 EXPECT_TRUE(m3.Matches(opt));
6868 TEST(OptionalTest, DoesNotMatchNullopt) {
6869 const Matcher<SampleOptional<int>> m = Optional(1);
6870 SampleOptional<int> empty;
6871 EXPECT_FALSE(m.Matches(empty));
6874 TEST(OptionalTest, WorksWithMoveOnly) {
6875 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6876 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6879 class SampleVariantIntString {
6881 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6882 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6884 template <typename T>
6885 friend bool holds_alternative(const SampleVariantIntString& value) {
6886 return value.has_int_ == std::is_same<T, int>::value;
6889 template <typename T>
6890 friend const T& get(const SampleVariantIntString& value) {
6891 return value.get_impl(static_cast<T*>(nullptr));
6895 const int& get_impl(int*) const { return i_; }
6896 const std::string& get_impl(std::string*) const { return s_; }
6903 TEST(VariantTest, DescribesSelf) {
6904 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6905 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6906 "'.*' and the value is equal to 1"));
6909 TEST(VariantTest, ExplainsSelf) {
6910 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6911 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6912 ContainsRegex("whose value 1"));
6913 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6914 HasSubstr("whose value is not of type '"));
6915 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6916 "whose value 2 doesn't match");
6919 TEST(VariantTest, FullMatch) {
6920 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6921 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6923 m = VariantWith<std::string>(Eq("1"));
6924 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6927 TEST(VariantTest, TypeDoesNotMatch) {
6928 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6929 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6931 m = VariantWith<std::string>(Eq("1"));
6932 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6935 TEST(VariantTest, InnerDoesNotMatch) {
6936 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6937 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6939 m = VariantWith<std::string>(Eq("1"));
6940 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6943 class SampleAnyType {
6945 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6946 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6948 template <typename T>
6949 friend const T* any_cast(const SampleAnyType* any) {
6950 return any->get_impl(static_cast<T*>(nullptr));
6958 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
6959 const std::string* get_impl(std::string*) const {
6960 return index_ == 1 ? &s_ : nullptr;
6964 TEST(AnyWithTest, FullMatch) {
6965 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6966 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6969 TEST(AnyWithTest, TestBadCastType) {
6970 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6971 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6974 TEST(AnyWithTest, TestUseInContainers) {
6975 std::vector<SampleAnyType> a;
6980 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6982 std::vector<SampleAnyType> b;
6983 b.emplace_back("hello");
6984 b.emplace_back("merhaba");
6985 b.emplace_back("salut");
6986 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6987 AnyWith<std::string>("merhaba"),
6988 AnyWith<std::string>("salut")}));
6990 TEST(AnyWithTest, TestCompare) {
6991 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6994 TEST(AnyWithTest, DescribesSelf) {
6995 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6996 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6997 "'.*' and the value is equal to 1"));
7000 TEST(AnyWithTest, ExplainsSelf) {
7001 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
7003 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
7004 EXPECT_THAT(Explain(m, SampleAnyType("A")),
7005 HasSubstr("whose value is not of type '"));
7006 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
7009 TEST(PointeeTest, WorksOnMoveOnlyType) {
7010 std::unique_ptr<int> p(new int(3));
7011 EXPECT_THAT(p, Pointee(Eq(3)));
7012 EXPECT_THAT(p, Not(Pointee(Eq(2))));
7015 TEST(NotTest, WorksOnMoveOnlyType) {
7016 std::unique_ptr<int> p(new int(3));
7017 EXPECT_THAT(p, Pointee(Eq(3)));
7018 EXPECT_THAT(p, Not(Pointee(Eq(2))));
7021 // Tests Args<k0, ..., kn>(m).
7023 TEST(ArgsTest, AcceptsZeroTemplateArg) {
7024 const std::tuple<int, bool> t(5, true);
7025 EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
7026 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
7029 TEST(ArgsTest, AcceptsOneTemplateArg) {
7030 const std::tuple<int, bool> t(5, true);
7031 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
7032 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
7033 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
7036 TEST(ArgsTest, AcceptsTwoTemplateArgs) {
7037 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7039 EXPECT_THAT(t, (Args<0, 1>(Lt())));
7040 EXPECT_THAT(t, (Args<1, 2>(Lt())));
7041 EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
7044 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
7045 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7046 EXPECT_THAT(t, (Args<0, 0>(Eq())));
7047 EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
7050 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
7051 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7052 EXPECT_THAT(t, (Args<2, 0>(Gt())));
7053 EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
7056 MATCHER(SumIsZero, "") {
7057 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
7060 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
7061 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
7062 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
7065 TEST(ArgsTest, CanBeNested) {
7066 const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
7067 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
7068 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
7071 TEST(ArgsTest, CanMatchTupleByValue) {
7072 typedef std::tuple<char, int, int> Tuple3;
7073 const Matcher<Tuple3> m = Args<1, 2>(Lt());
7074 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
7075 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
7078 TEST(ArgsTest, CanMatchTupleByReference) {
7079 typedef std::tuple<char, char, int> Tuple3;
7080 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
7081 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
7082 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
7085 // Validates that arg is printed as str.
7086 MATCHER_P(PrintsAs, str, "") {
7087 return testing::PrintToString(arg) == str;
7090 TEST(ArgsTest, AcceptsTenTemplateArgs) {
7091 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7092 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7093 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7094 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7095 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7096 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7099 TEST(ArgsTest, DescirbesSelfCorrectly) {
7100 const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
7101 EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
7102 "the first < the second",
7106 TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
7107 const Matcher<const std::tuple<int, bool, char, int>&> m =
7108 Args<0, 2, 3>(Args<2, 0>(Lt()));
7109 EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
7110 "whose fields (#2, #0) are a pair where the first < the second",
7114 TEST(ArgsTest, DescribesNegationCorrectly) {
7115 const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
7116 EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
7117 "where the first > the second",
7118 DescribeNegation(m));
7121 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
7122 const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
7123 EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
7124 Explain(m, std::make_tuple(false, 42, 42)));
7125 EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
7126 Explain(m, std::make_tuple(false, 42, 43)));
7129 // For testing Args<>'s explanation.
7130 class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
7132 void DescribeTo(::std::ostream* /*os*/) const override {}
7134 bool MatchAndExplain(std::tuple<char, int> value,
7135 MatchResultListener* listener) const override {
7136 const int diff = std::get<0>(value) - std::get<1>(value);
7138 *listener << "where the first value is " << diff
7139 << " more than the second";
7145 Matcher<std::tuple<char, int> > LessThan() {
7146 return MakeMatcher(new LessThanMatcher);
7149 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
7150 const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
7152 "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
7153 "where the first value is 55 more than the second",
7154 Explain(m, std::make_tuple('a', 42, 42)));
7155 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
7156 Explain(m, std::make_tuple('\0', 42, 43)));
7159 class PredicateFormatterFromMatcherTest : public ::testing::Test {
7161 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
7163 // A matcher that can return different results when used multiple times on the
7164 // same input. No real matcher should do this; but this lets us test that we
7165 // detect such behavior and fail appropriately.
7166 class MockMatcher : public MatcherInterface<Behavior> {
7168 bool MatchAndExplain(Behavior behavior,
7169 MatchResultListener* listener) const override {
7170 *listener << "[MatchAndExplain]";
7172 case kInitialSuccess:
7173 // The first call to MatchAndExplain should use a "not interested"
7174 // listener; so this is expected to return |true|. There should be no
7175 // subsequent calls.
7176 return !listener->IsInterested();
7182 // The first call to MatchAndExplain should use a "not interested"
7183 // listener; so this will return |false|. Subsequent calls should have
7184 // an "interested" listener; so this will return |true|, thus
7185 // simulating a flaky matcher.
7186 return listener->IsInterested();
7189 GTEST_LOG_(FATAL) << "This should never be reached";
7193 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
7195 void DescribeNegationTo(ostream* os) const override {
7196 *os << "[DescribeNegationTo]";
7200 AssertionResult RunPredicateFormatter(Behavior behavior) {
7201 auto matcher = MakeMatcher(new MockMatcher);
7202 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
7204 return predicate_formatter("dummy-name", behavior);
7208 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
7209 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
7210 EXPECT_TRUE(result); // Implicit cast to bool.
7212 EXPECT_EQ(expect, result.message());
7215 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
7216 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
7217 EXPECT_FALSE(result); // Implicit cast to bool.
7218 std::string expect =
7219 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7221 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7222 EXPECT_EQ(expect, result.message());
7225 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
7226 AssertionResult result = RunPredicateFormatter(kFlaky);
7227 EXPECT_FALSE(result); // Implicit cast to bool.
7228 std::string expect =
7229 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7230 " The matcher failed on the initial attempt; but passed when rerun to "
7231 "generate the explanation.\n"
7233 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7234 EXPECT_EQ(expect, result.message());
7237 // Tests for ElementsAre().
7239 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
7240 Matcher<const vector<int>&> m = ElementsAre();
7241 EXPECT_EQ("is empty", Describe(m));
7244 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
7245 Matcher<vector<int>> m = ElementsAre(Gt(5));
7246 EXPECT_EQ("has 1 element that is > 5", Describe(m));
7249 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
7250 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
7252 "has 2 elements where\n"
7253 "element #0 is equal to \"one\",\n"
7254 "element #1 is equal to \"two\"",
7258 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
7259 Matcher<vector<int>> m = ElementsAre();
7260 EXPECT_EQ("isn't empty", DescribeNegation(m));
7263 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
7264 Matcher<const list<int>&> m = ElementsAre(Gt(5));
7266 "doesn't have 1 element, or\n"
7267 "element #0 isn't > 5",
7268 DescribeNegation(m));
7271 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
7272 Matcher<const list<std::string>&> m = ElementsAre("one", "two");
7274 "doesn't have 2 elements, or\n"
7275 "element #0 isn't equal to \"one\", or\n"
7276 "element #1 isn't equal to \"two\"",
7277 DescribeNegation(m));
7280 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
7281 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
7283 list<int> test_list;
7284 test_list.push_back(1);
7285 test_list.push_back(3);
7286 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
7289 TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
7290 Matcher<const vector<int>&> m =
7291 ElementsAre(GreaterThan(1), 0, GreaterThan(2));
7293 const int a[] = {10, 0, 100};
7294 vector<int> test_vector(std::begin(a), std::end(a));
7296 "whose element #0 matches, which is 9 more than 1,\n"
7297 "and whose element #2 matches, which is 98 more than 2",
7298 Explain(m, test_vector));
7301 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
7302 Matcher<const list<int>&> m = ElementsAre(1, 3);
7304 list<int> test_list;
7305 // No need to explain when the container is empty.
7306 EXPECT_EQ("", Explain(m, test_list));
7308 test_list.push_back(1);
7309 EXPECT_EQ("which has 1 element", Explain(m, test_list));
7312 TEST(ElementsAreTest, CanExplainMismatchRightSize) {
7313 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
7318 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
7321 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
7325 TEST(ElementsAreTest, MatchesOneElementVector) {
7326 vector<std::string> test_vector;
7327 test_vector.push_back("test string");
7329 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
7332 TEST(ElementsAreTest, MatchesOneElementList) {
7333 list<std::string> test_list;
7334 test_list.push_back("test string");
7336 EXPECT_THAT(test_list, ElementsAre("test string"));
7339 TEST(ElementsAreTest, MatchesThreeElementVector) {
7340 vector<std::string> test_vector;
7341 test_vector.push_back("one");
7342 test_vector.push_back("two");
7343 test_vector.push_back("three");
7345 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
7348 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
7349 vector<int> test_vector;
7350 test_vector.push_back(4);
7352 EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
7355 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
7356 vector<int> test_vector;
7357 test_vector.push_back(4);
7359 EXPECT_THAT(test_vector, ElementsAre(_));
7362 TEST(ElementsAreTest, MatchesOneElementValue) {
7363 vector<int> test_vector;
7364 test_vector.push_back(4);
7366 EXPECT_THAT(test_vector, ElementsAre(4));
7369 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
7370 vector<int> test_vector;
7371 test_vector.push_back(1);
7372 test_vector.push_back(2);
7373 test_vector.push_back(3);
7375 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
7378 TEST(ElementsAreTest, MatchesTenElementVector) {
7379 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
7380 vector<int> test_vector(std::begin(a), std::end(a));
7382 EXPECT_THAT(test_vector,
7383 // The element list can contain values and/or matchers
7384 // of different types.
7385 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
7388 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
7389 vector<std::string> test_vector;
7390 test_vector.push_back("test string");
7391 test_vector.push_back("test string");
7393 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7394 EXPECT_FALSE(m.Matches(test_vector));
7397 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
7398 vector<std::string> test_vector;
7399 test_vector.push_back("other string");
7401 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7402 EXPECT_FALSE(m.Matches(test_vector));
7405 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
7406 vector<std::string> test_vector;
7407 test_vector.push_back("one");
7408 test_vector.push_back("three");
7409 test_vector.push_back("two");
7411 Matcher<vector<std::string>> m =
7412 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
7413 EXPECT_FALSE(m.Matches(test_vector));
7416 TEST(ElementsAreTest, WorksForNestedContainer) {
7417 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
7419 vector<list<char>> nested;
7420 for (const auto& s : strings) {
7421 nested.emplace_back(s, s + strlen(s));
7424 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
7425 ElementsAre('w', 'o', _, _, 'd')));
7426 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
7427 ElementsAre('w', 'o', _, _, 'd'))));
7430 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
7431 int a[] = {0, 1, 2};
7432 vector<int> v(std::begin(a), std::end(a));
7434 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
7435 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
7438 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
7439 int a[] = {0, 1, 2};
7440 vector<int> v(std::begin(a), std::end(a));
7442 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
7443 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
7446 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
7447 int array[] = {0, 1, 2};
7448 EXPECT_THAT(array, ElementsAre(0, 1, _));
7449 EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
7450 EXPECT_THAT(array, Not(ElementsAre(0, _)));
7453 class NativeArrayPassedAsPointerAndSize {
7455 NativeArrayPassedAsPointerAndSize() {}
7457 MOCK_METHOD(void, Helper, (int* array, int size));
7460 GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
7463 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
7464 int array[] = {0, 1};
7465 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
7466 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
7467 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
7469 NativeArrayPassedAsPointerAndSize helper;
7470 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
7471 helper.Helper(array, 2);
7474 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
7475 const char a2[][3] = {"hi", "lo"};
7476 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
7477 ElementsAre('l', 'o', '\0')));
7478 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
7479 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
7480 ElementsAre('l', 'o', '\0')));
7483 TEST(ElementsAreTest, AcceptsStringLiteral) {
7484 std::string array[] = {"hi", "one", "two"};
7485 EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
7486 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
7489 // Declared here with the size unknown. Defined AFTER the following test.
7490 extern const char kHi[];
7492 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
7493 // The size of kHi is not known in this test, but ElementsAre() should
7496 std::string array1[] = {"hi"};
7497 EXPECT_THAT(array1, ElementsAre(kHi));
7499 std::string array2[] = {"ho"};
7500 EXPECT_THAT(array2, Not(ElementsAre(kHi)));
7503 const char kHi[] = "hi";
7505 TEST(ElementsAreTest, MakesCopyOfArguments) {
7508 // This should make a copy of x and y.
7509 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
7510 polymorphic_matcher = ElementsAre(x, y);
7511 // Changing x and y now shouldn't affect the meaning of the above matcher.
7513 const int array1[] = {1, 2};
7514 EXPECT_THAT(array1, polymorphic_matcher);
7515 const int array2[] = {0, 0};
7516 EXPECT_THAT(array2, Not(polymorphic_matcher));
7519 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
7520 // of the implementation with ElementsAre(), we don't test it as
7523 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
7524 const int a[] = {1, 2, 3};
7526 vector<int> test_vector(std::begin(a), std::end(a));
7527 EXPECT_THAT(test_vector, ElementsAreArray(a));
7530 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7533 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
7534 std::array<const char*, 3> a = {{"one", "two", "three"}};
7536 vector<std::string> test_vector(std::begin(a), std::end(a));
7537 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
7539 const char** p = a.data();
7540 test_vector[0] = "1";
7541 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
7544 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
7545 const char* a[] = {"one", "two", "three"};
7547 vector<std::string> test_vector(std::begin(a), std::end(a));
7548 EXPECT_THAT(test_vector, ElementsAreArray(a));
7550 test_vector[0] = "1";
7551 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7554 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
7555 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
7558 vector<std::string> test_vector;
7559 test_vector.push_back("one");
7560 test_vector.push_back("two");
7561 test_vector.push_back("three");
7562 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
7564 test_vector.push_back("three");
7565 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
7568 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
7569 const int a[] = {1, 2, 3};
7570 vector<int> test_vector(std::begin(a), std::end(a));
7571 const vector<int> expected(std::begin(a), std::end(a));
7572 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7573 test_vector.push_back(4);
7574 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7577 TEST(ElementsAreArrayTest, TakesInitializerList) {
7578 const int a[5] = {1, 2, 3, 4, 5};
7579 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
7580 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
7581 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
7584 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
7585 const std::string a[5] = {"a", "b", "c", "d", "e"};
7586 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
7587 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
7588 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
7591 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
7592 const int a[5] = {1, 2, 3, 4, 5};
7593 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
7594 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
7597 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
7598 const int a[5] = {1, 2, 3, 4, 5};
7599 // The compiler cannot infer the type of the initializer list if its
7600 // elements have different types. We must explicitly specify the
7601 // unified element type in this case.
7603 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
7604 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
7605 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
7608 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
7609 const int a[] = {1, 2, 3};
7610 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
7611 vector<int> test_vector(std::begin(a), std::end(a));
7612 const vector<Matcher<int>> expected(std::begin(kMatchers),
7613 std::end(kMatchers));
7614 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7615 test_vector.push_back(4);
7616 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7619 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
7620 const int a[] = {1, 2, 3};
7621 const vector<int> test_vector(std::begin(a), std::end(a));
7622 const vector<int> expected(std::begin(a), std::end(a));
7623 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
7624 // Pointers are iterators, too.
7625 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
7626 // The empty range of NULL pointers should also be okay.
7627 int* const null_int = nullptr;
7628 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
7629 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
7632 // Since ElementsAre() and ElementsAreArray() share much of the
7633 // implementation, we only do a sanity test for native arrays here.
7634 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
7635 ::std::string a[] = {"hi", "ho"};
7636 ::std::string b[] = {"hi", "ho"};
7638 EXPECT_THAT(a, ElementsAreArray(b));
7639 EXPECT_THAT(a, ElementsAreArray(b, 2));
7640 EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
7643 TEST(ElementsAreArrayTest, SourceLifeSpan) {
7644 const int a[] = {1, 2, 3};
7645 vector<int> test_vector(std::begin(a), std::end(a));
7646 vector<int> expect(std::begin(a), std::end(a));
7647 ElementsAreArrayMatcher<int> matcher_maker =
7648 ElementsAreArray(expect.begin(), expect.end());
7649 EXPECT_THAT(test_vector, matcher_maker);
7650 // Changing in place the values that initialized matcher_maker should not
7651 // affect matcher_maker anymore. It should have made its own copy of them.
7652 for (int& i : expect) {
7655 EXPECT_THAT(test_vector, matcher_maker);
7656 test_vector.push_back(3);
7657 EXPECT_THAT(test_vector, Not(matcher_maker));
7660 // Tests for the MATCHER*() macro family.
7662 // Tests that a simple MATCHER() definition works.
7664 MATCHER(IsEven, "") { return (arg % 2) == 0; }
7666 TEST(MatcherMacroTest, Works) {
7667 const Matcher<int> m = IsEven();
7668 EXPECT_TRUE(m.Matches(6));
7669 EXPECT_FALSE(m.Matches(7));
7671 EXPECT_EQ("is even", Describe(m));
7672 EXPECT_EQ("not (is even)", DescribeNegation(m));
7673 EXPECT_EQ("", Explain(m, 6));
7674 EXPECT_EQ("", Explain(m, 7));
7677 // This also tests that the description string can reference 'negation'.
7678 MATCHER(IsEven2, negation ? "is odd" : "is even") {
7679 if ((arg % 2) == 0) {
7680 // Verifies that we can stream to result_listener, a listener
7681 // supplied by the MATCHER macro implicitly.
7682 *result_listener << "OK";
7685 *result_listener << "% 2 == " << (arg % 2);
7690 // This also tests that the description string can reference matcher
7692 MATCHER_P2(EqSumOf, x, y,
7693 std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
7694 PrintToString(x) + " and " + PrintToString(y)) {
7695 if (arg == (x + y)) {
7696 *result_listener << "OK";
7699 // Verifies that we can stream to the underlying stream of
7701 if (result_listener->stream() != nullptr) {
7702 *result_listener->stream() << "diff == " << (x + y - arg);
7708 // Tests that the matcher description can reference 'negation' and the
7709 // matcher parameters.
7710 TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
7711 const Matcher<int> m1 = IsEven2();
7712 EXPECT_EQ("is even", Describe(m1));
7713 EXPECT_EQ("is odd", DescribeNegation(m1));
7715 const Matcher<int> m2 = EqSumOf(5, 9);
7716 EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
7717 EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
7720 // Tests explaining match result in a MATCHER* macro.
7721 TEST(MatcherMacroTest, CanExplainMatchResult) {
7722 const Matcher<int> m1 = IsEven2();
7723 EXPECT_EQ("OK", Explain(m1, 4));
7724 EXPECT_EQ("% 2 == 1", Explain(m1, 5));
7726 const Matcher<int> m2 = EqSumOf(1, 2);
7727 EXPECT_EQ("OK", Explain(m2, 3));
7728 EXPECT_EQ("diff == -1", Explain(m2, 4));
7731 // Tests that the body of MATCHER() can reference the type of the
7732 // value being matched.
7734 MATCHER(IsEmptyString, "") {
7735 StaticAssertTypeEq<::std::string, arg_type>();
7739 MATCHER(IsEmptyStringByRef, "") {
7740 StaticAssertTypeEq<const ::std::string&, arg_type>();
7744 TEST(MatcherMacroTest, CanReferenceArgType) {
7745 const Matcher<::std::string> m1 = IsEmptyString();
7746 EXPECT_TRUE(m1.Matches(""));
7748 const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
7749 EXPECT_TRUE(m2.Matches(""));
7752 // Tests that MATCHER() can be used in a namespace.
7754 namespace matcher_test {
7755 MATCHER(IsOdd, "") { return (arg % 2) != 0; }
7756 } // namespace matcher_test
7758 TEST(MatcherMacroTest, WorksInNamespace) {
7759 Matcher<int> m = matcher_test::IsOdd();
7760 EXPECT_FALSE(m.Matches(4));
7761 EXPECT_TRUE(m.Matches(5));
7764 // Tests that Value() can be used to compose matchers.
7765 MATCHER(IsPositiveOdd, "") {
7766 return Value(arg, matcher_test::IsOdd()) && arg > 0;
7769 TEST(MatcherMacroTest, CanBeComposedUsingValue) {
7770 EXPECT_THAT(3, IsPositiveOdd());
7771 EXPECT_THAT(4, Not(IsPositiveOdd()));
7772 EXPECT_THAT(-1, Not(IsPositiveOdd()));
7775 // Tests that a simple MATCHER_P() definition works.
7777 MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
7779 TEST(MatcherPMacroTest, Works) {
7780 const Matcher<int> m = IsGreaterThan32And(5);
7781 EXPECT_TRUE(m.Matches(36));
7782 EXPECT_FALSE(m.Matches(5));
7784 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7785 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7786 EXPECT_EQ("", Explain(m, 36));
7787 EXPECT_EQ("", Explain(m, 5));
7790 // Tests that the description is calculated correctly from the matcher name.
7791 MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
7793 TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
7794 const Matcher<int> m = _is_Greater_Than32and_(5);
7796 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7797 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7798 EXPECT_EQ("", Explain(m, 36));
7799 EXPECT_EQ("", Explain(m, 5));
7802 // Tests that a MATCHER_P matcher can be explicitly instantiated with
7803 // a reference parameter type.
7805 class UncopyableFoo {
7807 explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
7809 UncopyableFoo(const UncopyableFoo&) = delete;
7810 void operator=(const UncopyableFoo&) = delete;
7816 MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
7818 TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
7819 UncopyableFoo foo1('1'), foo2('2');
7820 const Matcher<const UncopyableFoo&> m =
7821 ReferencesUncopyable<const UncopyableFoo&>(foo1);
7823 EXPECT_TRUE(m.Matches(foo1));
7824 EXPECT_FALSE(m.Matches(foo2));
7826 // We don't want the address of the parameter printed, as most
7827 // likely it will just annoy the user. If the address is
7828 // interesting, the user should consider passing the parameter by
7830 EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
7833 // Tests that the body of MATCHER_Pn() can reference the parameter
7836 MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
7837 StaticAssertTypeEq<int, foo_type>();
7838 StaticAssertTypeEq<long, bar_type>(); // NOLINT
7839 StaticAssertTypeEq<char, baz_type>();
7843 TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
7844 EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
7847 // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
7848 // reference parameter types.
7850 MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
7851 return &arg == &variable1 || &arg == &variable2;
7854 TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
7855 UncopyableFoo foo1('1'), foo2('2'), foo3('3');
7856 const Matcher<const UncopyableFoo&> const_m =
7857 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7859 EXPECT_TRUE(const_m.Matches(foo1));
7860 EXPECT_TRUE(const_m.Matches(foo2));
7861 EXPECT_FALSE(const_m.Matches(foo3));
7863 const Matcher<UncopyableFoo&> m =
7864 ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
7866 EXPECT_TRUE(m.Matches(foo1));
7867 EXPECT_TRUE(m.Matches(foo2));
7868 EXPECT_FALSE(m.Matches(foo3));
7871 TEST(MatcherPnMacroTest,
7872 GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
7873 UncopyableFoo foo1('1'), foo2('2');
7874 const Matcher<const UncopyableFoo&> m =
7875 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7877 // We don't want the addresses of the parameters printed, as most
7878 // likely they will just annoy the user. If the addresses are
7879 // interesting, the user should consider passing the parameters by
7880 // pointers instead.
7881 EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
7885 // Tests that a simple MATCHER_P2() definition works.
7887 MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
7889 TEST(MatcherPnMacroTest, Works) {
7890 const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
7891 EXPECT_TRUE(m.Matches(36L));
7892 EXPECT_FALSE(m.Matches(15L));
7894 EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
7895 EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
7896 EXPECT_EQ("", Explain(m, 36L));
7897 EXPECT_EQ("", Explain(m, 15L));
7900 // Tests that MATCHER*() definitions can be overloaded on the number
7901 // of parameters; also tests MATCHER_Pn() where n >= 3.
7903 MATCHER(EqualsSumOf, "") { return arg == 0; }
7904 MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
7905 MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
7906 MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
7907 MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
7908 MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
7909 MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
7910 return arg == a + b + c + d + e + f;
7912 MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
7913 return arg == a + b + c + d + e + f + g;
7915 MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
7916 return arg == a + b + c + d + e + f + g + h;
7918 MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
7919 return arg == a + b + c + d + e + f + g + h + i;
7921 MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
7922 return arg == a + b + c + d + e + f + g + h + i + j;
7925 TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
7926 EXPECT_THAT(0, EqualsSumOf());
7927 EXPECT_THAT(1, EqualsSumOf(1));
7928 EXPECT_THAT(12, EqualsSumOf(10, 2));
7929 EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
7930 EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
7931 EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
7932 EXPECT_THAT("abcdef",
7933 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
7934 EXPECT_THAT("abcdefg",
7935 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
7936 EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7938 EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7939 'f', 'g', "h", 'i'));
7940 EXPECT_THAT("abcdefghij",
7941 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
7942 'i', ::std::string("j")));
7944 EXPECT_THAT(1, Not(EqualsSumOf()));
7945 EXPECT_THAT(-1, Not(EqualsSumOf(1)));
7946 EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
7947 EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
7948 EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
7949 EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
7950 EXPECT_THAT("abcdef ",
7951 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
7952 EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7954 EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7955 "e", 'f', 'g', "h")));
7956 EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7957 "e", 'f', 'g', "h", 'i')));
7958 EXPECT_THAT("abcdefghij ",
7959 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
7960 "h", 'i', ::std::string("j"))));
7963 // Tests that a MATCHER_Pn() definition can be instantiated with any
7964 // compatible parameter types.
7965 TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
7966 EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
7967 EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
7969 EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
7970 EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
7973 // Tests that the matcher body can promote the parameter types.
7975 MATCHER_P2(EqConcat, prefix, suffix, "") {
7976 // The following lines promote the two parameters to desired types.
7977 std::string prefix_str(prefix);
7978 char suffix_char = static_cast<char>(suffix);
7979 return arg == prefix_str + suffix_char;
7982 TEST(MatcherPnMacroTest, SimpleTypePromotion) {
7983 Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
7984 Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
7985 EXPECT_FALSE(no_promo.Matches("fool"));
7986 EXPECT_FALSE(promo.Matches("fool"));
7987 EXPECT_TRUE(no_promo.Matches("foot"));
7988 EXPECT_TRUE(promo.Matches("foot"));
7991 // Verifies the type of a MATCHER*.
7993 TEST(MatcherPnMacroTest, TypesAreCorrect) {
7994 // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
7995 EqualsSumOfMatcher a0 = EqualsSumOf();
7997 // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
7998 EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
8000 // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
8001 // variable, and so on.
8002 EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
8003 EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
8004 EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
8005 EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
8006 EqualsSumOf(1, 2, 3, 4, '5');
8007 EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
8008 EqualsSumOf(1, 2, 3, 4, 5, '6');
8009 EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
8010 EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
8011 EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
8012 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
8013 EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
8014 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
8015 EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
8016 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
8018 // Avoid "unused variable" warnings.
8032 // Tests that matcher-typed parameters can be used in Value() inside a
8033 // MATCHER_Pn definition.
8035 // Succeeds if arg matches exactly 2 of the 3 matchers.
8036 MATCHER_P3(TwoOf, m1, m2, m3, "") {
8037 const int count = static_cast<int>(Value(arg, m1)) +
8038 static_cast<int>(Value(arg, m2)) +
8039 static_cast<int>(Value(arg, m3));
8043 TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
8044 EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
8045 EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
8048 // Tests Contains().
8050 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
8051 list<int> some_list;
8052 some_list.push_back(3);
8053 some_list.push_back(1);
8054 some_list.push_back(2);
8055 some_list.push_back(3);
8056 EXPECT_THAT(some_list, Contains(1));
8057 EXPECT_THAT(some_list, Contains(Gt(2.5)));
8058 EXPECT_THAT(some_list, Contains(Eq(2.0f)));
8060 list<std::string> another_list;
8061 another_list.push_back("fee");
8062 another_list.push_back("fie");
8063 another_list.push_back("foe");
8064 another_list.push_back("fum");
8065 EXPECT_THAT(another_list, Contains(std::string("fee")));
8068 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
8069 list<int> some_list;
8070 some_list.push_back(3);
8071 some_list.push_back(1);
8072 EXPECT_THAT(some_list, Not(Contains(4)));
8075 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
8080 EXPECT_THAT(some_set, Contains(Eq(1.0)));
8081 EXPECT_THAT(some_set, Contains(Eq(3.0f)));
8082 EXPECT_THAT(some_set, Contains(2));
8084 set<std::string> another_set;
8085 another_set.insert("fee");
8086 another_set.insert("fie");
8087 another_set.insert("foe");
8088 another_set.insert("fum");
8089 EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
8092 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
8096 EXPECT_THAT(some_set, Not(Contains(4)));
8098 set<std::string> c_string_set;
8099 c_string_set.insert("hello");
8100 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
8103 TEST(ContainsTest, ExplainsMatchResultCorrectly) {
8104 const int a[2] = {1, 2};
8105 Matcher<const int(&)[2]> m = Contains(2);
8106 EXPECT_EQ("whose element #1 matches", Explain(m, a));
8109 EXPECT_EQ("", Explain(m, a));
8111 m = Contains(GreaterThan(0));
8112 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
8114 m = Contains(GreaterThan(10));
8115 EXPECT_EQ("", Explain(m, a));
8118 TEST(ContainsTest, DescribesItselfCorrectly) {
8119 Matcher<vector<int>> m = Contains(1);
8120 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
8122 Matcher<vector<int>> m2 = Not(m);
8123 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
8126 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
8127 map<std::string, int> my_map;
8128 const char* bar = "a string";
8130 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
8132 map<std::string, int> another_map;
8133 another_map["fee"] = 1;
8134 another_map["fie"] = 2;
8135 another_map["foe"] = 3;
8136 another_map["fum"] = 4;
8137 EXPECT_THAT(another_map,
8138 Contains(pair<const std::string, int>(std::string("fee"), 1)));
8139 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
8142 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
8143 map<int, int> some_map;
8146 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
8149 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
8150 const char* string_array[] = {"fee", "fie", "foe", "fum"};
8151 EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
8154 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
8155 int int_array[] = {1, 2, 3, 4};
8156 EXPECT_THAT(int_array, Not(Contains(5)));
8159 TEST(ContainsTest, AcceptsMatcher) {
8160 const int a[] = {1, 2, 3};
8161 EXPECT_THAT(a, Contains(Gt(2)));
8162 EXPECT_THAT(a, Not(Contains(Gt(4))));
8165 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
8166 const int a[] = {1, 2};
8167 const int* const pointer = a;
8168 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
8169 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
8172 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
8173 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
8174 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
8175 EXPECT_THAT(a, Contains(Contains(5)));
8176 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
8177 EXPECT_THAT(a, Contains(Not(Contains(5))));
8180 // Tests Contains().Times().
8182 TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {
8183 list<int> some_list;
8184 some_list.push_back(3);
8185 some_list.push_back(1);
8186 some_list.push_back(2);
8187 some_list.push_back(3);
8188 EXPECT_THAT(some_list, Contains(3).Times(2));
8189 EXPECT_THAT(some_list, Contains(2).Times(1));
8190 EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));
8191 EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));
8192 EXPECT_THAT(some_list, Contains(4).Times(0));
8193 EXPECT_THAT(some_list, Contains(_).Times(4));
8194 EXPECT_THAT(some_list, Not(Contains(5).Times(1)));
8195 EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches
8196 EXPECT_THAT(some_list, Not(Contains(3).Times(1)));
8197 EXPECT_THAT(some_list, Contains(3).Times(Not(1)));
8198 EXPECT_THAT(list<int>{}, Not(Contains(_)));
8201 TEST(ContainsTimes, ExplainsMatchResultCorrectly) {
8202 const int a[2] = {1, 2};
8203 Matcher<const int(&)[2]> m = Contains(2).Times(3);
8205 "whose element #1 matches but whose match quantity of 1 does not match",
8208 m = Contains(3).Times(0);
8209 EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",
8212 m = Contains(3).Times(4);
8214 "has no element that matches and whose match quantity of 0 does not "
8218 m = Contains(2).Times(4);
8220 "whose element #1 matches but whose match quantity of 1 does not "
8224 m = Contains(GreaterThan(0)).Times(2);
8225 EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",
8228 m = Contains(GreaterThan(10)).Times(Gt(1));
8230 "has no element that matches and whose match quantity of 0 does not "
8234 m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));
8236 "whose elements (0, 1) match but whose match quantity of 2 does not "
8237 "match, which is 3 less than 5",
8241 TEST(ContainsTimes, DescribesItselfCorrectly) {
8242 Matcher<vector<int>> m = Contains(1).Times(2);
8243 EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",
8246 Matcher<vector<int>> m2 = Not(m);
8247 EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",
8251 // Tests AllOfArray()
8253 TEST(AllOfArrayTest, BasicForms) {
8255 std::vector<int> v0{};
8256 std::vector<int> v1{1};
8257 std::vector<int> v2{2, 3};
8258 std::vector<int> v3{4, 4, 4};
8259 EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
8260 EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
8261 EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
8262 EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
8263 EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
8265 int ar[6] = {1, 2, 3, 4, 4, 4};
8266 EXPECT_THAT(0, AllOfArray(ar, 0));
8267 EXPECT_THAT(1, AllOfArray(ar, 1));
8268 EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
8269 EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
8270 EXPECT_THAT(4, AllOfArray(ar + 3, 3));
8272 // int ar0[0]; Not usable
8274 int ar2[2] = {2, 3};
8275 int ar3[3] = {4, 4, 4};
8276 // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
8277 EXPECT_THAT(1, AllOfArray(ar1));
8278 EXPECT_THAT(2, Not(AllOfArray(ar1)));
8279 EXPECT_THAT(3, Not(AllOfArray(ar2)));
8280 EXPECT_THAT(4, AllOfArray(ar3));
8282 EXPECT_THAT(0, AllOfArray(v0));
8283 EXPECT_THAT(1, AllOfArray(v1));
8284 EXPECT_THAT(2, Not(AllOfArray(v1)));
8285 EXPECT_THAT(3, Not(AllOfArray(v2)));
8286 EXPECT_THAT(4, AllOfArray(v3));
8288 EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
8289 EXPECT_THAT(1, AllOfArray({1}));
8290 EXPECT_THAT(2, Not(AllOfArray({1})));
8291 EXPECT_THAT(3, Not(AllOfArray({2, 3})));
8292 EXPECT_THAT(4, AllOfArray({4, 4, 4}));
8295 TEST(AllOfArrayTest, Matchers) {
8297 std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
8298 EXPECT_THAT(0, Not(AllOfArray(matchers)));
8299 EXPECT_THAT(1, AllOfArray(matchers));
8300 EXPECT_THAT(2, Not(AllOfArray(matchers)));
8302 EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
8303 EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
8306 TEST(AnyOfArrayTest, BasicForms) {
8308 std::vector<int> v0{};
8309 std::vector<int> v1{1};
8310 std::vector<int> v2{2, 3};
8311 EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
8312 EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
8313 EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
8314 EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
8315 EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
8317 int ar[3] = {1, 2, 3};
8318 EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
8319 EXPECT_THAT(1, AnyOfArray(ar, 1));
8320 EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
8321 EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
8322 EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
8324 // int ar0[0]; Not usable
8326 int ar2[2] = {2, 3};
8327 // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
8328 EXPECT_THAT(1, AnyOfArray(ar1));
8329 EXPECT_THAT(2, Not(AnyOfArray(ar1)));
8330 EXPECT_THAT(3, AnyOfArray(ar2));
8331 EXPECT_THAT(4, Not(AnyOfArray(ar2)));
8333 EXPECT_THAT(0, Not(AnyOfArray(v0)));
8334 EXPECT_THAT(1, AnyOfArray(v1));
8335 EXPECT_THAT(2, Not(AnyOfArray(v1)));
8336 EXPECT_THAT(3, AnyOfArray(v2));
8337 EXPECT_THAT(4, Not(AnyOfArray(v2)));
8339 EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
8340 EXPECT_THAT(1, AnyOfArray({1}));
8341 EXPECT_THAT(2, Not(AnyOfArray({1})));
8342 EXPECT_THAT(3, AnyOfArray({2, 3}));
8343 EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
8346 TEST(AnyOfArrayTest, Matchers) {
8347 // We negate test AllOfArrayTest.Matchers.
8349 std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
8350 EXPECT_THAT(0, AnyOfArray(matchers));
8351 EXPECT_THAT(1, Not(AnyOfArray(matchers)));
8352 EXPECT_THAT(2, AnyOfArray(matchers));
8354 EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
8355 EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
8358 TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
8359 // AnyOfArray and AllOfArry use the same underlying template-template,
8360 // thus it is sufficient to test one here.
8361 const std::vector<int> v0{};
8362 const std::vector<int> v1{1};
8363 const std::vector<int> v2{2, 3};
8364 const Matcher<int> m0 = AnyOfArray(v0);
8365 const Matcher<int> m1 = AnyOfArray(v1);
8366 const Matcher<int> m2 = AnyOfArray(v2);
8367 EXPECT_EQ("", Explain(m0, 0));
8368 EXPECT_EQ("", Explain(m1, 1));
8369 EXPECT_EQ("", Explain(m1, 2));
8370 EXPECT_EQ("", Explain(m2, 3));
8371 EXPECT_EQ("", Explain(m2, 4));
8372 EXPECT_EQ("()", Describe(m0));
8373 EXPECT_EQ("(is equal to 1)", Describe(m1));
8374 EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
8375 EXPECT_EQ("()", DescribeNegation(m0));
8376 EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
8377 EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
8378 // Explain with matchers
8379 const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
8380 const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
8381 // Explains the first positiv match and all prior negative matches...
8382 EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
8383 EXPECT_EQ("which is the same as 1", Explain(g1, 1));
8384 EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
8385 EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
8387 EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
8389 EXPECT_EQ("which is 1 more than 1", // Only the first
8393 TEST(AllOfTest, HugeMatcher) {
8394 // Verify that using AllOf with many arguments doesn't cause
8395 // the compiler to exceed template instantiation depth limit.
8396 EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
8397 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
8400 TEST(AnyOfTest, HugeMatcher) {
8401 // Verify that using AnyOf with many arguments doesn't cause
8402 // the compiler to exceed template instantiation depth limit.
8403 EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
8404 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
8407 namespace adl_test {
8409 // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
8410 // don't issue unqualified recursive calls. If they do, the argument dependent
8411 // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
8412 // as a candidate and the compilation will break due to an ambiguous overload.
8414 // The matcher must be in the same namespace as AllOf/AnyOf to make argument
8415 // dependent lookup find those.
8421 template <typename T1, typename T2>
8422 bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
8426 TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
8428 testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8431 template <typename T1, typename T2>
8432 bool AnyOf(const T1&, const T2&) {
8436 TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
8438 testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8441 } // namespace adl_test
8443 TEST(AllOfTest, WorksOnMoveOnlyType) {
8444 std::unique_ptr<int> p(new int(3));
8445 EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
8446 EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
8449 TEST(AnyOfTest, WorksOnMoveOnlyType) {
8450 std::unique_ptr<int> p(new int(3));
8451 EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
8452 EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
8455 MATCHER(IsNotNull, "") { return arg != nullptr; }
8457 // Verifies that a matcher defined using MATCHER() can work on
8459 TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
8460 std::unique_ptr<int> p(new int(3));
8461 EXPECT_THAT(p, IsNotNull());
8462 EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
8465 MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
8467 // Verifies that a matcher defined using MATCHER_P*() can work on
8469 TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
8470 std::unique_ptr<int> p(new int(3));
8471 EXPECT_THAT(p, UniquePointee(3));
8472 EXPECT_THAT(p, Not(UniquePointee(2)));
8475 #if GTEST_HAS_EXCEPTIONS
8477 // std::function<void()> is used below for compatibility with older copies of
8478 // GCC. Normally, a raw lambda is all that is needed.
8480 // Test that examples from documentation compile
8481 TEST(ThrowsTest, Examples) {
8483 std::function<void()>([]() { throw std::runtime_error("message"); }),
8484 Throws<std::runtime_error>());
8487 std::function<void()>([]() { throw std::runtime_error("message"); }),
8488 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8491 TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
8492 EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
8493 Throws<std::exception>());
8496 TEST(ThrowsTest, CallableExecutedExactlyOnce) {
8499 EXPECT_THAT(std::function<void()>([&a]() {
8506 EXPECT_THAT(std::function<void()>([&a]() {
8508 throw std::runtime_error("message");
8510 Throws<std::runtime_error>());
8513 EXPECT_THAT(std::function<void()>([&a]() {
8515 throw std::runtime_error("message");
8517 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8520 EXPECT_THAT(std::function<void()>([&a]() {
8522 throw std::runtime_error("message");
8524 Throws<std::runtime_error>(
8525 Property(&std::runtime_error::what, HasSubstr("message"))));
8529 TEST(ThrowsTest, Describe) {
8530 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8531 std::stringstream ss;
8532 matcher.DescribeTo(&ss);
8533 auto explanation = ss.str();
8534 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8537 TEST(ThrowsTest, Success) {
8538 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8539 StringMatchResultListener listener;
8540 EXPECT_TRUE(matcher.MatchAndExplain(
8541 []() { throw std::runtime_error("error message"); }, &listener));
8542 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8545 TEST(ThrowsTest, FailWrongType) {
8546 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8547 StringMatchResultListener listener;
8548 EXPECT_FALSE(matcher.MatchAndExplain(
8549 []() { throw std::logic_error("error message"); }, &listener));
8550 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8551 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8554 TEST(ThrowsTest, FailWrongTypeNonStd) {
8555 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8556 StringMatchResultListener listener;
8557 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8558 EXPECT_THAT(listener.str(),
8559 HasSubstr("throws an exception of an unknown type"));
8562 TEST(ThrowsTest, FailNoThrow) {
8563 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8564 StringMatchResultListener listener;
8565 EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
8566 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8569 class ThrowsPredicateTest
8570 : public TestWithParam<Matcher<std::function<void()>>> {};
8572 TEST_P(ThrowsPredicateTest, Describe) {
8573 Matcher<std::function<void()>> matcher = GetParam();
8574 std::stringstream ss;
8575 matcher.DescribeTo(&ss);
8576 auto explanation = ss.str();
8577 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8578 EXPECT_THAT(explanation, HasSubstr("error message"));
8581 TEST_P(ThrowsPredicateTest, Success) {
8582 Matcher<std::function<void()>> matcher = GetParam();
8583 StringMatchResultListener listener;
8584 EXPECT_TRUE(matcher.MatchAndExplain(
8585 []() { throw std::runtime_error("error message"); }, &listener));
8586 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8589 TEST_P(ThrowsPredicateTest, FailWrongType) {
8590 Matcher<std::function<void()>> matcher = GetParam();
8591 StringMatchResultListener listener;
8592 EXPECT_FALSE(matcher.MatchAndExplain(
8593 []() { throw std::logic_error("error message"); }, &listener));
8594 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8595 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8598 TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
8599 Matcher<std::function<void()>> matcher = GetParam();
8600 StringMatchResultListener listener;
8601 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8602 EXPECT_THAT(listener.str(),
8603 HasSubstr("throws an exception of an unknown type"));
8606 TEST_P(ThrowsPredicateTest, FailWrongMessage) {
8607 Matcher<std::function<void()>> matcher = GetParam();
8608 StringMatchResultListener listener;
8609 EXPECT_FALSE(matcher.MatchAndExplain(
8610 []() { throw std::runtime_error("wrong message"); }, &listener));
8611 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8612 EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
8615 TEST_P(ThrowsPredicateTest, FailNoThrow) {
8616 Matcher<std::function<void()>> matcher = GetParam();
8617 StringMatchResultListener listener;
8618 EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
8619 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8622 INSTANTIATE_TEST_SUITE_P(
8623 AllMessagePredicates, ThrowsPredicateTest,
8624 Values(Matcher<std::function<void()>>(
8625 ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
8627 // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
8628 TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
8630 Matcher<std::function<void()>> matcher =
8631 ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
8633 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8635 matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
8639 Matcher<uint64_t> inner = Eq(10);
8640 Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
8641 EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
8642 EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
8646 // Tests that ThrowsMessage("message") is equivalent
8647 // to ThrowsMessage(Eq<std::string>("message")).
8648 TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
8649 Matcher<std::function<void()>> matcher =
8650 ThrowsMessage<std::runtime_error>("error message");
8652 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8653 EXPECT_FALSE(matcher.Matches(
8654 []() { throw std::runtime_error("wrong error message"); }));
8657 #endif // GTEST_HAS_EXCEPTIONS
8660 } // namespace gmock_matchers_test
8661 } // namespace testing
8664 # pragma warning(pop)