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 class GreaterThanMatcher : public MatcherInterface<int> {
119 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
121 void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
123 bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
124 const int diff = lhs - rhs_;
126 *listener << "which is " << diff << " more than " << rhs_;
127 } else if (diff == 0) {
128 *listener << "which is the same as " << rhs_;
130 *listener << "which is " << -diff << " less than " << rhs_;
140 Matcher<int> GreaterThan(int n) {
141 return MakeMatcher(new GreaterThanMatcher(n));
144 std::string OfType(const std::string& type_name) {
146 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
152 // Returns the description of the given matcher.
153 template <typename T>
154 std::string Describe(const Matcher<T>& m) {
155 return DescribeMatcher<T>(m);
158 // Returns the description of the negation of the given matcher.
159 template <typename T>
160 std::string DescribeNegation(const Matcher<T>& m) {
161 return DescribeMatcher<T>(m, true);
164 // Returns the reason why x matches, or doesn't match, m.
165 template <typename MatcherType, typename Value>
166 std::string Explain(const MatcherType& m, const Value& x) {
167 StringMatchResultListener listener;
168 ExplainMatchResult(m, x, &listener);
169 return listener.str();
172 TEST(MonotonicMatcherTest, IsPrintable) {
174 ss << GreaterThan(5);
175 EXPECT_EQ("is > 5", ss.str());
178 TEST(MatchResultListenerTest, StreamingWorks) {
179 StringMatchResultListener listener;
180 listener << "hi" << 5;
181 EXPECT_EQ("hi5", listener.str());
184 EXPECT_EQ("", listener.str());
187 EXPECT_EQ("42", listener.str());
189 // Streaming shouldn't crash when the underlying ostream is NULL.
190 DummyMatchResultListener dummy;
194 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
195 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
196 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
198 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
201 TEST(MatchResultListenerTest, IsInterestedWorks) {
202 EXPECT_TRUE(StringMatchResultListener().IsInterested());
203 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
205 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
206 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
209 // Makes sure that the MatcherInterface<T> interface doesn't
211 class EvenMatcherImpl : public MatcherInterface<int> {
213 bool MatchAndExplain(int x,
214 MatchResultListener* /* listener */) const override {
218 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
220 // We deliberately don't define DescribeNegationTo() and
221 // ExplainMatchResultTo() here, to make sure the definition of these
222 // two methods is optional.
225 // Makes sure that the MatcherInterface API doesn't change.
226 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
230 // Tests implementing a monomorphic matcher using MatchAndExplain().
232 class NewEvenMatcherImpl : public MatcherInterface<int> {
234 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
235 const bool match = x % 2 == 0;
236 // Verifies that we can stream to a listener directly.
237 *listener << "value % " << 2;
238 if (listener->stream() != nullptr) {
239 // Verifies that we can stream to a listener's underlying stream
241 *listener->stream() << " == " << (x % 2);
246 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
249 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
250 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
251 EXPECT_TRUE(m.Matches(2));
252 EXPECT_FALSE(m.Matches(3));
253 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
254 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
257 // Tests default-constructing a matcher.
258 TEST(MatcherTest, CanBeDefaultConstructed) {
262 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
263 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
264 const MatcherInterface<int>* impl = new EvenMatcherImpl;
265 Matcher<int> m(impl);
266 EXPECT_TRUE(m.Matches(4));
267 EXPECT_FALSE(m.Matches(5));
270 // Tests that value can be used in place of Eq(value).
271 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
273 EXPECT_TRUE(m1.Matches(5));
274 EXPECT_FALSE(m1.Matches(6));
277 // Tests that NULL can be used in place of Eq(NULL).
278 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
279 Matcher<int*> m1 = nullptr;
280 EXPECT_TRUE(m1.Matches(nullptr));
282 EXPECT_FALSE(m1.Matches(&n));
285 // Tests that matchers can be constructed from a variable that is not properly
286 // defined. This should be illegal, but many users rely on this accidentally.
288 virtual ~Undefined() = 0;
289 static const int kInt = 1;
292 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
293 Matcher<int> m1 = Undefined::kInt;
294 EXPECT_TRUE(m1.Matches(1));
295 EXPECT_FALSE(m1.Matches(2));
298 // Test that a matcher parameterized with an abstract class compiles.
299 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
301 // Tests that matchers are copyable.
302 TEST(MatcherTest, IsCopyable) {
303 // Tests the copy constructor.
304 Matcher<bool> m1 = Eq(false);
305 EXPECT_TRUE(m1.Matches(false));
306 EXPECT_FALSE(m1.Matches(true));
308 // Tests the assignment operator.
310 EXPECT_TRUE(m1.Matches(true));
311 EXPECT_FALSE(m1.Matches(false));
314 // Tests that Matcher<T>::DescribeTo() calls
315 // MatcherInterface<T>::DescribeTo().
316 TEST(MatcherTest, CanDescribeItself) {
317 EXPECT_EQ("is an even number",
318 Describe(Matcher<int>(new EvenMatcherImpl)));
321 // Tests Matcher<T>::MatchAndExplain().
322 TEST(MatcherTest, MatchAndExplain) {
323 Matcher<int> m = GreaterThan(0);
324 StringMatchResultListener listener1;
325 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
326 EXPECT_EQ("which is 42 more than 0", listener1.str());
328 StringMatchResultListener listener2;
329 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
330 EXPECT_EQ("which is 9 less than 0", listener2.str());
333 // Tests that a C-string literal can be implicitly converted to a
334 // Matcher<std::string> or Matcher<const std::string&>.
335 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
336 Matcher<std::string> m1 = "hi";
337 EXPECT_TRUE(m1.Matches("hi"));
338 EXPECT_FALSE(m1.Matches("hello"));
340 Matcher<const std::string&> m2 = "hi";
341 EXPECT_TRUE(m2.Matches("hi"));
342 EXPECT_FALSE(m2.Matches("hello"));
345 // Tests that a string object can be implicitly converted to a
346 // Matcher<std::string> or Matcher<const std::string&>.
347 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
348 Matcher<std::string> m1 = std::string("hi");
349 EXPECT_TRUE(m1.Matches("hi"));
350 EXPECT_FALSE(m1.Matches("hello"));
352 Matcher<const std::string&> m2 = std::string("hi");
353 EXPECT_TRUE(m2.Matches("hi"));
354 EXPECT_FALSE(m2.Matches("hello"));
357 #if GTEST_INTERNAL_HAS_STRING_VIEW
358 // Tests that a C-string literal can be implicitly converted to a
359 // Matcher<StringView> or Matcher<const StringView&>.
360 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
361 Matcher<internal::StringView> m1 = "cats";
362 EXPECT_TRUE(m1.Matches("cats"));
363 EXPECT_FALSE(m1.Matches("dogs"));
365 Matcher<const internal::StringView&> m2 = "cats";
366 EXPECT_TRUE(m2.Matches("cats"));
367 EXPECT_FALSE(m2.Matches("dogs"));
370 // Tests that a std::string object can be implicitly converted to a
371 // Matcher<StringView> or Matcher<const StringView&>.
372 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
373 Matcher<internal::StringView> m1 = std::string("cats");
374 EXPECT_TRUE(m1.Matches("cats"));
375 EXPECT_FALSE(m1.Matches("dogs"));
377 Matcher<const internal::StringView&> m2 = std::string("cats");
378 EXPECT_TRUE(m2.Matches("cats"));
379 EXPECT_FALSE(m2.Matches("dogs"));
382 // Tests that a StringView object can be implicitly converted to a
383 // Matcher<StringView> or Matcher<const StringView&>.
384 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
385 Matcher<internal::StringView> m1 = internal::StringView("cats");
386 EXPECT_TRUE(m1.Matches("cats"));
387 EXPECT_FALSE(m1.Matches("dogs"));
389 Matcher<const internal::StringView&> m2 = internal::StringView("cats");
390 EXPECT_TRUE(m2.Matches("cats"));
391 EXPECT_FALSE(m2.Matches("dogs"));
393 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
395 // Tests that a std::reference_wrapper<std::string> object can be implicitly
396 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
397 TEST(StringMatcherTest,
398 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
399 std::string value = "cats";
400 Matcher<std::string> m1 = Eq(std::ref(value));
401 EXPECT_TRUE(m1.Matches("cats"));
402 EXPECT_FALSE(m1.Matches("dogs"));
404 Matcher<const std::string&> m2 = Eq(std::ref(value));
405 EXPECT_TRUE(m2.Matches("cats"));
406 EXPECT_FALSE(m2.Matches("dogs"));
409 // Tests that MakeMatcher() constructs a Matcher<T> from a
410 // MatcherInterface* without requiring the user to explicitly
412 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
413 const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
414 Matcher<int> m = MakeMatcher(dummy_impl);
417 // Tests that MakePolymorphicMatcher() can construct a polymorphic
418 // matcher from its implementation using the old API.
420 class ReferencesBarOrIsZeroImpl {
422 template <typename T>
423 bool MatchAndExplain(const T& x,
424 MatchResultListener* /* listener */) const {
426 return p == &g_bar || x == 0;
429 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
431 void DescribeNegationTo(ostream* os) const {
432 *os << "doesn't reference g_bar and is not zero";
436 // This function verifies that MakePolymorphicMatcher() returns a
437 // PolymorphicMatcher<T> where T is the argument's type.
438 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
439 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
442 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
443 // Using a polymorphic matcher to match a reference type.
444 Matcher<const int&> m1 = ReferencesBarOrIsZero();
445 EXPECT_TRUE(m1.Matches(0));
446 // Verifies that the identity of a by-reference argument is preserved.
447 EXPECT_TRUE(m1.Matches(g_bar));
448 EXPECT_FALSE(m1.Matches(1));
449 EXPECT_EQ("g_bar or zero", Describe(m1));
451 // Using a polymorphic matcher to match a value type.
452 Matcher<double> m2 = ReferencesBarOrIsZero();
453 EXPECT_TRUE(m2.Matches(0.0));
454 EXPECT_FALSE(m2.Matches(0.1));
455 EXPECT_EQ("g_bar or zero", Describe(m2));
458 // Tests implementing a polymorphic matcher using MatchAndExplain().
460 class PolymorphicIsEvenImpl {
462 void DescribeTo(ostream* os) const { *os << "is even"; }
464 void DescribeNegationTo(ostream* os) const {
468 template <typename T>
469 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
470 // Verifies that we can stream to the listener directly.
471 *listener << "% " << 2;
472 if (listener->stream() != nullptr) {
473 // Verifies that we can stream to the listener's underlying stream
475 *listener->stream() << " == " << (x % 2);
481 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
482 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
485 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
486 // Using PolymorphicIsEven() as a Matcher<int>.
487 const Matcher<int> m1 = PolymorphicIsEven();
488 EXPECT_TRUE(m1.Matches(42));
489 EXPECT_FALSE(m1.Matches(43));
490 EXPECT_EQ("is even", Describe(m1));
492 const Matcher<int> not_m1 = Not(m1);
493 EXPECT_EQ("is odd", Describe(not_m1));
495 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
497 // Using PolymorphicIsEven() as a Matcher<char>.
498 const Matcher<char> m2 = PolymorphicIsEven();
499 EXPECT_TRUE(m2.Matches('\x42'));
500 EXPECT_FALSE(m2.Matches('\x43'));
501 EXPECT_EQ("is even", Describe(m2));
503 const Matcher<char> not_m2 = Not(m2);
504 EXPECT_EQ("is odd", Describe(not_m2));
506 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
509 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
510 TEST(MatcherCastTest, FromPolymorphicMatcher) {
511 Matcher<int> m = MatcherCast<int>(Eq(5));
512 EXPECT_TRUE(m.Matches(5));
513 EXPECT_FALSE(m.Matches(6));
516 // For testing casting matchers between compatible types.
519 // An int can be statically (although not implicitly) cast to a
521 explicit IntValue(int a_value) : value_(a_value) {}
523 int value() const { return value_; }
528 // For testing casting matchers between compatible types.
529 bool IsPositiveIntValue(const IntValue& foo) {
530 return foo.value() > 0;
533 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
534 // can be statically converted to U.
535 TEST(MatcherCastTest, FromCompatibleType) {
536 Matcher<double> m1 = Eq(2.0);
537 Matcher<int> m2 = MatcherCast<int>(m1);
538 EXPECT_TRUE(m2.Matches(2));
539 EXPECT_FALSE(m2.Matches(3));
541 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
542 Matcher<int> m4 = MatcherCast<int>(m3);
543 // In the following, the arguments 1 and 0 are statically converted
544 // to IntValue objects, and then tested by the IsPositiveIntValue()
546 EXPECT_TRUE(m4.Matches(1));
547 EXPECT_FALSE(m4.Matches(0));
550 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
551 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
552 Matcher<const int&> m1 = Eq(0);
553 Matcher<int> m2 = MatcherCast<int>(m1);
554 EXPECT_TRUE(m2.Matches(0));
555 EXPECT_FALSE(m2.Matches(1));
558 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
559 TEST(MatcherCastTest, FromReferenceToNonReference) {
560 Matcher<int&> m1 = Eq(0);
561 Matcher<int> m2 = MatcherCast<int>(m1);
562 EXPECT_TRUE(m2.Matches(0));
563 EXPECT_FALSE(m2.Matches(1));
566 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
567 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
568 Matcher<int> m1 = Eq(0);
569 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
570 EXPECT_TRUE(m2.Matches(0));
571 EXPECT_FALSE(m2.Matches(1));
574 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
575 TEST(MatcherCastTest, FromNonReferenceToReference) {
576 Matcher<int> m1 = Eq(0);
577 Matcher<int&> m2 = MatcherCast<int&>(m1);
579 EXPECT_TRUE(m2.Matches(n));
581 EXPECT_FALSE(m2.Matches(n));
584 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
585 TEST(MatcherCastTest, FromSameType) {
586 Matcher<int> m1 = Eq(0);
587 Matcher<int> m2 = MatcherCast<int>(m1);
588 EXPECT_TRUE(m2.Matches(0));
589 EXPECT_FALSE(m2.Matches(1));
592 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
593 // value type of the Matcher.
594 TEST(MatcherCastTest, FromAValue) {
595 Matcher<int> m = MatcherCast<int>(42);
596 EXPECT_TRUE(m.Matches(42));
597 EXPECT_FALSE(m.Matches(239));
600 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
601 // convertible to the value type of the Matcher.
602 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
603 const int kExpected = 'c';
604 Matcher<int> m = MatcherCast<int>('c');
605 EXPECT_TRUE(m.Matches(kExpected));
606 EXPECT_FALSE(m.Matches(kExpected + 1));
609 struct NonImplicitlyConstructibleTypeWithOperatorEq {
610 friend bool operator==(
611 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
615 friend bool operator==(
617 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
622 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
623 // implicitly convertible to the value type of the Matcher, but the value type
624 // of the matcher has operator==() overload accepting m.
625 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
626 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
627 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
628 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
630 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
631 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
632 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
634 // When updating the following lines please also change the comment to
635 // namespace convertible_from_any.
637 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
638 EXPECT_TRUE(m3.Matches(42));
639 EXPECT_FALSE(m3.Matches(239));
642 // ConvertibleFromAny does not work with MSVC. resulting in
643 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
644 // No constructor could take the source type, or constructor overload
645 // resolution was ambiguous
647 #if !defined _MSC_VER
649 // The below ConvertibleFromAny struct is implicitly constructible from anything
650 // and when in the same namespace can interact with other tests. In particular,
651 // if it is in the same namespace as other tests and one removes
652 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
653 // then the corresponding test still compiles (and it should not!) by implicitly
654 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
656 namespace convertible_from_any {
657 // Implicitly convertible from any type.
658 struct ConvertibleFromAny {
659 ConvertibleFromAny(int a_value) : value(a_value) {}
660 template <typename T>
661 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
662 ADD_FAILURE() << "Conversion constructor called";
667 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
668 return a.value == b.value;
671 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
672 return os << a.value;
675 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
676 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
677 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
678 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
681 TEST(MatcherCastTest, FromConvertibleFromAny) {
682 Matcher<ConvertibleFromAny> m =
683 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
684 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
685 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
687 } // namespace convertible_from_any
689 #endif // !defined _MSC_VER
691 struct IntReferenceWrapper {
692 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
696 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
697 return a.value == b.value;
700 TEST(MatcherCastTest, ValueIsNotCopied) {
702 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
703 // Verify that the matcher holds a reference to n, not to its temporary copy.
704 EXPECT_TRUE(m.Matches(n));
712 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
715 class Derived : public Base {
717 Derived() : Base() {}
721 class OtherDerived : public Base {};
723 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
724 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
725 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
726 EXPECT_TRUE(m2.Matches(' '));
727 EXPECT_FALSE(m2.Matches('\n'));
730 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
731 // T and U are arithmetic types and T can be losslessly converted to
733 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
734 Matcher<double> m1 = DoubleEq(1.0);
735 Matcher<float> m2 = SafeMatcherCast<float>(m1);
736 EXPECT_TRUE(m2.Matches(1.0f));
737 EXPECT_FALSE(m2.Matches(2.0f));
739 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
740 EXPECT_TRUE(m3.Matches('a'));
741 EXPECT_FALSE(m3.Matches('b'));
744 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
745 // are pointers or references to a derived and a base class, correspondingly.
746 TEST(SafeMatcherCastTest, FromBaseClass) {
748 Matcher<Base*> m1 = Eq(&d);
749 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
750 EXPECT_TRUE(m2.Matches(&d));
751 EXPECT_FALSE(m2.Matches(&d2));
753 Matcher<Base&> m3 = Ref(d);
754 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
755 EXPECT_TRUE(m4.Matches(d));
756 EXPECT_FALSE(m4.Matches(d2));
759 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
760 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
762 Matcher<const int&> m1 = Ref(n);
763 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
765 EXPECT_TRUE(m2.Matches(n));
766 EXPECT_FALSE(m2.Matches(n1));
769 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
770 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
771 Matcher<std::unique_ptr<int>> m1 = IsNull();
772 Matcher<const std::unique_ptr<int>&> m2 =
773 SafeMatcherCast<const std::unique_ptr<int>&>(m1);
774 EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
775 EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
778 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
779 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
780 Matcher<int> m1 = Eq(0);
781 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
783 EXPECT_TRUE(m2.Matches(n));
785 EXPECT_FALSE(m2.Matches(n));
788 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
789 TEST(SafeMatcherCastTest, FromSameType) {
790 Matcher<int> m1 = Eq(0);
791 Matcher<int> m2 = SafeMatcherCast<int>(m1);
792 EXPECT_TRUE(m2.Matches(0));
793 EXPECT_FALSE(m2.Matches(1));
796 #if !defined _MSC_VER
798 namespace convertible_from_any {
799 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
800 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
801 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
802 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
805 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
806 Matcher<ConvertibleFromAny> m =
807 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
808 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
809 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
811 } // namespace convertible_from_any
813 #endif // !defined _MSC_VER
815 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
817 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
818 // Verify that the matcher holds a reference to n, not to its temporary copy.
819 EXPECT_TRUE(m.Matches(n));
822 TEST(ExpectThat, TakesLiterals) {
824 EXPECT_THAT(1.0, 1.0);
825 EXPECT_THAT(std::string(), "");
828 TEST(ExpectThat, TakesFunctions) {
830 static void Func() {}
832 void (*func)() = Helper::Func;
833 EXPECT_THAT(func, Helper::Func);
834 EXPECT_THAT(func, &Helper::Func);
837 // Tests that A<T>() matches any value of type T.
838 TEST(ATest, MatchesAnyValue) {
839 // Tests a matcher for a value type.
840 Matcher<double> m1 = A<double>();
841 EXPECT_TRUE(m1.Matches(91.43));
842 EXPECT_TRUE(m1.Matches(-15.32));
844 // Tests a matcher for a reference type.
847 Matcher<int&> m2 = A<int&>();
848 EXPECT_TRUE(m2.Matches(a));
849 EXPECT_TRUE(m2.Matches(b));
852 TEST(ATest, WorksForDerivedClass) {
855 EXPECT_THAT(&base, A<Base*>());
856 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
857 EXPECT_THAT(&derived, A<Base*>());
858 EXPECT_THAT(&derived, A<Derived*>());
861 // Tests that A<T>() describes itself properly.
862 TEST(ATest, CanDescribeSelf) {
863 EXPECT_EQ("is anything", Describe(A<bool>()));
866 // Tests that An<T>() matches any value of type T.
867 TEST(AnTest, MatchesAnyValue) {
868 // Tests a matcher for a value type.
869 Matcher<int> m1 = An<int>();
870 EXPECT_TRUE(m1.Matches(9143));
871 EXPECT_TRUE(m1.Matches(-1532));
873 // Tests a matcher for a reference type.
876 Matcher<int&> m2 = An<int&>();
877 EXPECT_TRUE(m2.Matches(a));
878 EXPECT_TRUE(m2.Matches(b));
881 // Tests that An<T>() describes itself properly.
882 TEST(AnTest, CanDescribeSelf) {
883 EXPECT_EQ("is anything", Describe(An<int>()));
886 // Tests that _ can be used as a matcher for any type and matches any
887 // value of that type.
888 TEST(UnderscoreTest, MatchesAnyValue) {
889 // Uses _ as a matcher for a value type.
891 EXPECT_TRUE(m1.Matches(123));
892 EXPECT_TRUE(m1.Matches(-242));
894 // Uses _ as a matcher for a reference type.
897 Matcher<const bool&> m2 = _;
898 EXPECT_TRUE(m2.Matches(a));
899 EXPECT_TRUE(m2.Matches(b));
902 // Tests that _ describes itself properly.
903 TEST(UnderscoreTest, CanDescribeSelf) {
905 EXPECT_EQ("is anything", Describe(m));
908 // Tests that Eq(x) matches any value equal to x.
909 TEST(EqTest, MatchesEqualValue) {
910 // 2 C-strings with same content but different addresses.
911 const char a1[] = "hi";
912 const char a2[] = "hi";
914 Matcher<const char*> m1 = Eq(a1);
915 EXPECT_TRUE(m1.Matches(a1));
916 EXPECT_FALSE(m1.Matches(a2));
919 // Tests that Eq(v) describes itself properly.
923 Unprintable() : c_('a') {}
925 bool operator==(const Unprintable& /* rhs */) const { return true; }
926 // -Wunused-private-field: dummy accessor for `c_`.
927 char dummy_c() { return c_; }
932 TEST(EqTest, CanDescribeSelf) {
933 Matcher<Unprintable> m = Eq(Unprintable());
934 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
937 // Tests that Eq(v) can be used to match any type that supports
938 // comparing with type T, where T is v's type.
939 TEST(EqTest, IsPolymorphic) {
940 Matcher<int> m1 = Eq(1);
941 EXPECT_TRUE(m1.Matches(1));
942 EXPECT_FALSE(m1.Matches(2));
944 Matcher<char> m2 = Eq(1);
945 EXPECT_TRUE(m2.Matches('\1'));
946 EXPECT_FALSE(m2.Matches('a'));
949 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
950 TEST(TypedEqTest, ChecksEqualityForGivenType) {
951 Matcher<char> m1 = TypedEq<char>('a');
952 EXPECT_TRUE(m1.Matches('a'));
953 EXPECT_FALSE(m1.Matches('b'));
955 Matcher<int> m2 = TypedEq<int>(6);
956 EXPECT_TRUE(m2.Matches(6));
957 EXPECT_FALSE(m2.Matches(7));
960 // Tests that TypedEq(v) describes itself properly.
961 TEST(TypedEqTest, CanDescribeSelf) {
962 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
965 // Tests that TypedEq<T>(v) has type Matcher<T>.
967 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
968 // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
969 // not T, the compiler will generate a message about "undefined reference".
970 template <typename T>
972 static bool IsTypeOf(const T& /* v */) { return true; }
974 template <typename T2>
975 static void IsTypeOf(T2 v);
978 TEST(TypedEqTest, HasSpecifiedType) {
979 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
980 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
981 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
984 // Tests that Ge(v) matches anything >= v.
985 TEST(GeTest, ImplementsGreaterThanOrEqual) {
986 Matcher<int> m1 = Ge(0);
987 EXPECT_TRUE(m1.Matches(1));
988 EXPECT_TRUE(m1.Matches(0));
989 EXPECT_FALSE(m1.Matches(-1));
992 // Tests that Ge(v) describes itself properly.
993 TEST(GeTest, CanDescribeSelf) {
994 Matcher<int> m = Ge(5);
995 EXPECT_EQ("is >= 5", Describe(m));
998 // Tests that Gt(v) matches anything > v.
999 TEST(GtTest, ImplementsGreaterThan) {
1000 Matcher<double> m1 = Gt(0);
1001 EXPECT_TRUE(m1.Matches(1.0));
1002 EXPECT_FALSE(m1.Matches(0.0));
1003 EXPECT_FALSE(m1.Matches(-1.0));
1006 // Tests that Gt(v) describes itself properly.
1007 TEST(GtTest, CanDescribeSelf) {
1008 Matcher<int> m = Gt(5);
1009 EXPECT_EQ("is > 5", Describe(m));
1012 // Tests that Le(v) matches anything <= v.
1013 TEST(LeTest, ImplementsLessThanOrEqual) {
1014 Matcher<char> m1 = Le('b');
1015 EXPECT_TRUE(m1.Matches('a'));
1016 EXPECT_TRUE(m1.Matches('b'));
1017 EXPECT_FALSE(m1.Matches('c'));
1020 // Tests that Le(v) describes itself properly.
1021 TEST(LeTest, CanDescribeSelf) {
1022 Matcher<int> m = Le(5);
1023 EXPECT_EQ("is <= 5", Describe(m));
1026 // Tests that Lt(v) matches anything < v.
1027 TEST(LtTest, ImplementsLessThan) {
1028 Matcher<const std::string&> m1 = Lt("Hello");
1029 EXPECT_TRUE(m1.Matches("Abc"));
1030 EXPECT_FALSE(m1.Matches("Hello"));
1031 EXPECT_FALSE(m1.Matches("Hello, world!"));
1034 // Tests that Lt(v) describes itself properly.
1035 TEST(LtTest, CanDescribeSelf) {
1036 Matcher<int> m = Lt(5);
1037 EXPECT_EQ("is < 5", Describe(m));
1040 // Tests that Ne(v) matches anything != v.
1041 TEST(NeTest, ImplementsNotEqual) {
1042 Matcher<int> m1 = Ne(0);
1043 EXPECT_TRUE(m1.Matches(1));
1044 EXPECT_TRUE(m1.Matches(-1));
1045 EXPECT_FALSE(m1.Matches(0));
1048 // Tests that Ne(v) describes itself properly.
1049 TEST(NeTest, CanDescribeSelf) {
1050 Matcher<int> m = Ne(5);
1051 EXPECT_EQ("isn't equal to 5", Describe(m));
1056 explicit MoveOnly(int i) : i_(i) {}
1057 MoveOnly(const MoveOnly&) = delete;
1058 MoveOnly(MoveOnly&&) = default;
1059 MoveOnly& operator=(const MoveOnly&) = delete;
1060 MoveOnly& operator=(MoveOnly&&) = default;
1062 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
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_; }
1074 MOCK_METHOD1(Call, void(MoveOnly));
1077 // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
1078 #if defined(_MSC_VER) && (_MSC_VER < 1910)
1079 TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
1081 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1086 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1087 helper.Call(MoveOnly(0));
1088 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1089 helper.Call(MoveOnly(1));
1090 EXPECT_CALL(helper, Call(Le(ByRef(m))));
1091 helper.Call(MoveOnly(0));
1092 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1093 helper.Call(MoveOnly(-1));
1094 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1095 helper.Call(MoveOnly(0));
1096 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1097 helper.Call(MoveOnly(1));
1100 // Tests that IsNull() matches any NULL pointer of any type.
1101 TEST(IsNullTest, MatchesNullPointer) {
1102 Matcher<int*> m1 = IsNull();
1105 EXPECT_TRUE(m1.Matches(p1));
1106 EXPECT_FALSE(m1.Matches(&n));
1108 Matcher<const char*> m2 = IsNull();
1109 const char* p2 = nullptr;
1110 EXPECT_TRUE(m2.Matches(p2));
1111 EXPECT_FALSE(m2.Matches("hi"));
1113 Matcher<void*> m3 = IsNull();
1115 EXPECT_TRUE(m3.Matches(p3));
1116 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1119 TEST(IsNullTest, StdFunction) {
1120 const Matcher<std::function<void()>> m = IsNull();
1122 EXPECT_TRUE(m.Matches(std::function<void()>()));
1123 EXPECT_FALSE(m.Matches([]{}));
1126 // Tests that IsNull() describes itself properly.
1127 TEST(IsNullTest, CanDescribeSelf) {
1128 Matcher<int*> m = IsNull();
1129 EXPECT_EQ("is NULL", Describe(m));
1130 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1133 // Tests that NotNull() matches any non-NULL pointer of any type.
1134 TEST(NotNullTest, MatchesNonNullPointer) {
1135 Matcher<int*> m1 = NotNull();
1138 EXPECT_FALSE(m1.Matches(p1));
1139 EXPECT_TRUE(m1.Matches(&n));
1141 Matcher<const char*> m2 = NotNull();
1142 const char* p2 = nullptr;
1143 EXPECT_FALSE(m2.Matches(p2));
1144 EXPECT_TRUE(m2.Matches("hi"));
1147 TEST(NotNullTest, LinkedPtr) {
1148 const Matcher<std::shared_ptr<int>> m = NotNull();
1149 const std::shared_ptr<int> null_p;
1150 const std::shared_ptr<int> non_null_p(new int);
1152 EXPECT_FALSE(m.Matches(null_p));
1153 EXPECT_TRUE(m.Matches(non_null_p));
1156 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1157 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1158 const std::shared_ptr<double> null_p;
1159 const std::shared_ptr<double> non_null_p(new double);
1161 EXPECT_FALSE(m.Matches(null_p));
1162 EXPECT_TRUE(m.Matches(non_null_p));
1165 TEST(NotNullTest, StdFunction) {
1166 const Matcher<std::function<void()>> m = NotNull();
1168 EXPECT_TRUE(m.Matches([]{}));
1169 EXPECT_FALSE(m.Matches(std::function<void()>()));
1172 // Tests that NotNull() describes itself properly.
1173 TEST(NotNullTest, CanDescribeSelf) {
1174 Matcher<int*> m = NotNull();
1175 EXPECT_EQ("isn't NULL", Describe(m));
1178 // Tests that Ref(variable) matches an argument that references
1180 TEST(RefTest, MatchesSameVariable) {
1183 Matcher<int&> m = Ref(a);
1184 EXPECT_TRUE(m.Matches(a));
1185 EXPECT_FALSE(m.Matches(b));
1188 // Tests that Ref(variable) describes itself properly.
1189 TEST(RefTest, CanDescribeSelf) {
1191 Matcher<int&> m = Ref(n);
1193 ss << "references the variable @" << &n << " 5";
1194 EXPECT_EQ(ss.str(), Describe(m));
1197 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1199 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1202 Matcher<const int&> m = Ref(a);
1203 EXPECT_TRUE(m.Matches(a));
1204 EXPECT_FALSE(m.Matches(b));
1207 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1208 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1209 // of Ref(base), but not vice versa.
1211 TEST(RefTest, IsCovariant) {
1214 Matcher<const Base&> m1 = Ref(base);
1215 EXPECT_TRUE(m1.Matches(base));
1216 EXPECT_FALSE(m1.Matches(base2));
1217 EXPECT_FALSE(m1.Matches(derived));
1220 EXPECT_TRUE(m1.Matches(derived));
1221 EXPECT_FALSE(m1.Matches(base));
1222 EXPECT_FALSE(m1.Matches(base2));
1225 TEST(RefTest, ExplainsResult) {
1227 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1228 StartsWith("which is located @"));
1231 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1232 StartsWith("which is located @"));
1235 // Tests string comparison matchers.
1237 template <typename T = std::string>
1238 std::string FromStringLike(internal::StringLike<T> str) {
1239 return std::string(str);
1242 TEST(StringLike, TestConversions) {
1243 EXPECT_EQ("foo", FromStringLike("foo"));
1244 EXPECT_EQ("foo", FromStringLike(std::string("foo")));
1245 #if GTEST_INTERNAL_HAS_STRING_VIEW
1246 EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
1247 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1249 // Non deducible types.
1250 EXPECT_EQ("", FromStringLike({}));
1251 EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
1252 const char buf[] = "foo";
1253 EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
1256 TEST(StrEqTest, MatchesEqualString) {
1257 Matcher<const char*> m = StrEq(std::string("Hello"));
1258 EXPECT_TRUE(m.Matches("Hello"));
1259 EXPECT_FALSE(m.Matches("hello"));
1260 EXPECT_FALSE(m.Matches(nullptr));
1262 Matcher<const std::string&> m2 = StrEq("Hello");
1263 EXPECT_TRUE(m2.Matches("Hello"));
1264 EXPECT_FALSE(m2.Matches("Hi"));
1266 #if GTEST_INTERNAL_HAS_STRING_VIEW
1267 Matcher<const internal::StringView&> m3 =
1268 StrEq(internal::StringView("Hello"));
1269 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1270 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1271 EXPECT_FALSE(m3.Matches(internal::StringView()));
1273 Matcher<const internal::StringView&> m_empty = StrEq("");
1274 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1275 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1276 EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
1277 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1280 TEST(StrEqTest, CanDescribeSelf) {
1281 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1282 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1285 std::string str("01204500800");
1287 Matcher<std::string> m2 = StrEq(str);
1288 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1289 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1290 Matcher<std::string> m3 = StrEq(str);
1291 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1294 TEST(StrNeTest, MatchesUnequalString) {
1295 Matcher<const char*> m = StrNe("Hello");
1296 EXPECT_TRUE(m.Matches(""));
1297 EXPECT_TRUE(m.Matches(nullptr));
1298 EXPECT_FALSE(m.Matches("Hello"));
1300 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1301 EXPECT_TRUE(m2.Matches("hello"));
1302 EXPECT_FALSE(m2.Matches("Hello"));
1304 #if GTEST_INTERNAL_HAS_STRING_VIEW
1305 Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
1306 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1307 EXPECT_TRUE(m3.Matches(internal::StringView()));
1308 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1309 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1312 TEST(StrNeTest, CanDescribeSelf) {
1313 Matcher<const char*> m = StrNe("Hi");
1314 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1317 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1318 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1319 EXPECT_TRUE(m.Matches("Hello"));
1320 EXPECT_TRUE(m.Matches("hello"));
1321 EXPECT_FALSE(m.Matches("Hi"));
1322 EXPECT_FALSE(m.Matches(nullptr));
1324 Matcher<const std::string&> m2 = StrCaseEq("Hello");
1325 EXPECT_TRUE(m2.Matches("hello"));
1326 EXPECT_FALSE(m2.Matches("Hi"));
1328 #if GTEST_INTERNAL_HAS_STRING_VIEW
1329 Matcher<const internal::StringView&> m3 =
1330 StrCaseEq(internal::StringView("Hello"));
1331 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1332 EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
1333 EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
1334 EXPECT_FALSE(m3.Matches(internal::StringView()));
1335 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1338 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1339 std::string str1("oabocdooeoo");
1340 std::string str2("OABOCDOOEOO");
1341 Matcher<const std::string&> m0 = StrCaseEq(str1);
1342 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1344 str1[3] = str2[3] = '\0';
1345 Matcher<const std::string&> m1 = StrCaseEq(str1);
1346 EXPECT_TRUE(m1.Matches(str2));
1348 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1349 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1350 Matcher<const std::string&> m2 = StrCaseEq(str1);
1351 str1[9] = str2[9] = '\0';
1352 EXPECT_FALSE(m2.Matches(str2));
1354 Matcher<const std::string&> m3 = StrCaseEq(str1);
1355 EXPECT_TRUE(m3.Matches(str2));
1357 EXPECT_FALSE(m3.Matches(str2 + "x"));
1358 str2.append(1, '\0');
1359 EXPECT_FALSE(m3.Matches(str2));
1360 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1363 TEST(StrCaseEqTest, CanDescribeSelf) {
1364 Matcher<std::string> m = StrCaseEq("Hi");
1365 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1368 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1369 Matcher<const char*> m = StrCaseNe("Hello");
1370 EXPECT_TRUE(m.Matches("Hi"));
1371 EXPECT_TRUE(m.Matches(nullptr));
1372 EXPECT_FALSE(m.Matches("Hello"));
1373 EXPECT_FALSE(m.Matches("hello"));
1375 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1376 EXPECT_TRUE(m2.Matches(""));
1377 EXPECT_FALSE(m2.Matches("Hello"));
1379 #if GTEST_INTERNAL_HAS_STRING_VIEW
1380 Matcher<const internal::StringView> m3 =
1381 StrCaseNe(internal::StringView("Hello"));
1382 EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
1383 EXPECT_TRUE(m3.Matches(internal::StringView()));
1384 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1385 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1386 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1389 TEST(StrCaseNeTest, CanDescribeSelf) {
1390 Matcher<const char*> m = StrCaseNe("Hi");
1391 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1394 // Tests that HasSubstr() works for matching string-typed values.
1395 TEST(HasSubstrTest, WorksForStringClasses) {
1396 const Matcher<std::string> m1 = HasSubstr("foo");
1397 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1398 EXPECT_FALSE(m1.Matches(std::string("tofo")));
1400 const Matcher<const std::string&> m2 = HasSubstr("foo");
1401 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1402 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1404 const Matcher<std::string> m_empty = HasSubstr("");
1405 EXPECT_TRUE(m_empty.Matches(std::string()));
1406 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1409 // Tests that HasSubstr() works for matching C-string-typed values.
1410 TEST(HasSubstrTest, WorksForCStrings) {
1411 const Matcher<char*> m1 = HasSubstr("foo");
1412 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1413 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1414 EXPECT_FALSE(m1.Matches(nullptr));
1416 const Matcher<const char*> m2 = HasSubstr("foo");
1417 EXPECT_TRUE(m2.Matches("I love food."));
1418 EXPECT_FALSE(m2.Matches("tofo"));
1419 EXPECT_FALSE(m2.Matches(nullptr));
1421 const Matcher<const char*> m_empty = HasSubstr("");
1422 EXPECT_TRUE(m_empty.Matches("not empty"));
1423 EXPECT_TRUE(m_empty.Matches(""));
1424 EXPECT_FALSE(m_empty.Matches(nullptr));
1427 #if GTEST_INTERNAL_HAS_STRING_VIEW
1428 // Tests that HasSubstr() works for matching StringView-typed values.
1429 TEST(HasSubstrTest, WorksForStringViewClasses) {
1430 const Matcher<internal::StringView> m1 =
1431 HasSubstr(internal::StringView("foo"));
1432 EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
1433 EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
1434 EXPECT_FALSE(m1.Matches(internal::StringView()));
1436 const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
1437 EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
1438 EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
1439 EXPECT_FALSE(m2.Matches(internal::StringView()));
1441 const Matcher<const internal::StringView&> m3 = HasSubstr("");
1442 EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
1443 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1444 EXPECT_TRUE(m3.Matches(internal::StringView()));
1446 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1448 // Tests that HasSubstr(s) describes itself properly.
1449 TEST(HasSubstrTest, CanDescribeSelf) {
1450 Matcher<std::string> m = HasSubstr("foo\n\"");
1451 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1454 TEST(KeyTest, CanDescribeSelf) {
1455 Matcher<const pair<std::string, int>&> m = Key("foo");
1456 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1457 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1460 TEST(KeyTest, ExplainsResult) {
1461 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1462 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1463 Explain(m, make_pair(5, true)));
1464 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1465 Explain(m, make_pair(15, true)));
1468 TEST(KeyTest, MatchesCorrectly) {
1469 pair<int, std::string> p(25, "foo");
1470 EXPECT_THAT(p, Key(25));
1471 EXPECT_THAT(p, Not(Key(42)));
1472 EXPECT_THAT(p, Key(Ge(20)));
1473 EXPECT_THAT(p, Not(Key(Lt(25))));
1476 TEST(KeyTest, WorksWithMoveOnly) {
1477 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1478 EXPECT_THAT(p, Key(Eq(nullptr)));
1484 struct PairWithGet {
1486 std::string member_2;
1487 using first_type = int;
1488 using second_type = std::string;
1490 const int& GetImpl(Tag<0>) const { return member_1; }
1491 const std::string& GetImpl(Tag<1>) const { return member_2; }
1494 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1495 return value.GetImpl(Tag<I>());
1497 TEST(PairTest, MatchesPairWithGetCorrectly) {
1498 PairWithGet p{25, "foo"};
1499 EXPECT_THAT(p, Key(25));
1500 EXPECT_THAT(p, Not(Key(42)));
1501 EXPECT_THAT(p, Key(Ge(20)));
1502 EXPECT_THAT(p, Not(Key(Lt(25))));
1504 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1505 EXPECT_THAT(v, Contains(Key(29)));
1508 TEST(KeyTest, SafelyCastsInnerMatcher) {
1509 Matcher<int> is_positive = Gt(0);
1510 Matcher<int> is_negative = Lt(0);
1511 pair<char, bool> p('a', true);
1512 EXPECT_THAT(p, Key(is_positive));
1513 EXPECT_THAT(p, Not(Key(is_negative)));
1516 TEST(KeyTest, InsideContainsUsingMap) {
1517 map<int, char> container;
1518 container.insert(make_pair(1, 'a'));
1519 container.insert(make_pair(2, 'b'));
1520 container.insert(make_pair(4, 'c'));
1521 EXPECT_THAT(container, Contains(Key(1)));
1522 EXPECT_THAT(container, Not(Contains(Key(3))));
1525 TEST(KeyTest, InsideContainsUsingMultimap) {
1526 multimap<int, char> container;
1527 container.insert(make_pair(1, 'a'));
1528 container.insert(make_pair(2, 'b'));
1529 container.insert(make_pair(4, 'c'));
1531 EXPECT_THAT(container, Not(Contains(Key(25))));
1532 container.insert(make_pair(25, 'd'));
1533 EXPECT_THAT(container, Contains(Key(25)));
1534 container.insert(make_pair(25, 'e'));
1535 EXPECT_THAT(container, Contains(Key(25)));
1537 EXPECT_THAT(container, Contains(Key(1)));
1538 EXPECT_THAT(container, Not(Contains(Key(3))));
1541 TEST(PairTest, Typing) {
1542 // Test verifies the following type conversions can be compiled.
1543 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1544 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1545 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1547 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1548 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1551 TEST(PairTest, CanDescribeSelf) {
1552 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1553 EXPECT_EQ("has a first field that is equal to \"foo\""
1554 ", and has a second field that is equal to 42",
1556 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1557 ", or has a second field that isn't equal to 42",
1558 DescribeNegation(m1));
1559 // Double and triple negation (1 or 2 times not and description of negation).
1560 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1561 EXPECT_EQ("has a first field that isn't equal to 13"
1562 ", and has a second field that is equal to 42",
1563 DescribeNegation(m2));
1566 TEST(PairTest, CanExplainMatchResultTo) {
1567 // If neither field matches, Pair() should explain about the first
1569 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1570 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1571 Explain(m, make_pair(-1, -2)));
1573 // If the first field matches but the second doesn't, Pair() should
1574 // explain about the second field.
1575 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1576 Explain(m, make_pair(1, -2)));
1578 // If the first field doesn't match but the second does, Pair()
1579 // should explain about the first field.
1580 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1581 Explain(m, make_pair(-1, 2)));
1583 // If both fields match, Pair() should explain about them both.
1584 EXPECT_EQ("whose both fields match, where the first field is a value "
1585 "which is 1 more than 0, and the second field is a value "
1586 "which is 2 more than 0",
1587 Explain(m, make_pair(1, 2)));
1589 // If only the first match has an explanation, only this explanation should
1591 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1592 EXPECT_EQ("whose both fields match, where the first field is a value "
1593 "which is 1 more than 0",
1594 Explain(explain_first, make_pair(1, 0)));
1596 // If only the second match has an explanation, only this explanation should
1598 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1599 EXPECT_EQ("whose both fields match, where the second field is a value "
1600 "which is 1 more than 0",
1601 Explain(explain_second, make_pair(0, 1)));
1604 TEST(PairTest, MatchesCorrectly) {
1605 pair<int, std::string> p(25, "foo");
1607 // Both fields match.
1608 EXPECT_THAT(p, Pair(25, "foo"));
1609 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1611 // 'first' doesnt' match, but 'second' matches.
1612 EXPECT_THAT(p, Not(Pair(42, "foo")));
1613 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1615 // 'first' matches, but 'second' doesn't match.
1616 EXPECT_THAT(p, Not(Pair(25, "bar")));
1617 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1619 // Neither field matches.
1620 EXPECT_THAT(p, Not(Pair(13, "bar")));
1621 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1624 TEST(PairTest, WorksWithMoveOnly) {
1625 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1626 p.second.reset(new int(7));
1627 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1630 TEST(PairTest, SafelyCastsInnerMatchers) {
1631 Matcher<int> is_positive = Gt(0);
1632 Matcher<int> is_negative = Lt(0);
1633 pair<char, bool> p('a', true);
1634 EXPECT_THAT(p, Pair(is_positive, _));
1635 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1636 EXPECT_THAT(p, Pair(_, is_positive));
1637 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1640 TEST(PairTest, InsideContainsUsingMap) {
1641 map<int, char> container;
1642 container.insert(make_pair(1, 'a'));
1643 container.insert(make_pair(2, 'b'));
1644 container.insert(make_pair(4, 'c'));
1645 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1646 EXPECT_THAT(container, Contains(Pair(1, _)));
1647 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1648 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1651 TEST(FieldsAreTest, MatchesCorrectly) {
1652 std::tuple<int, std::string, double> p(25, "foo", .5);
1654 // All fields match.
1655 EXPECT_THAT(p, FieldsAre(25, "foo", .5));
1656 EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
1658 // Some don't match.
1659 EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
1660 EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
1661 EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
1664 TEST(FieldsAreTest, CanDescribeSelf) {
1665 Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
1667 "has field #0 that is equal to \"foo\""
1668 ", and has field #1 that is equal to 42",
1671 "has field #0 that isn't equal to \"foo\""
1672 ", or has field #1 that isn't equal to 42",
1673 DescribeNegation(m1));
1676 TEST(FieldsAreTest, CanExplainMatchResultTo) {
1677 // The first one that fails is the one that gives the error.
1678 Matcher<std::tuple<int, int, int>> m =
1679 FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
1681 EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
1682 Explain(m, std::make_tuple(-1, -2, -3)));
1683 EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
1684 Explain(m, std::make_tuple(1, -2, -3)));
1685 EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
1686 Explain(m, std::make_tuple(1, 2, -3)));
1688 // If they all match, we get a long explanation of success.
1690 "whose all elements match, "
1691 "where field #0 is a value which is 1 more than 0"
1692 ", and field #1 is a value which is 2 more than 0"
1693 ", and field #2 is a value which is 3 more than 0",
1694 Explain(m, std::make_tuple(1, 2, 3)));
1696 // Only print those that have an explanation.
1697 m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
1699 "whose all elements match, "
1700 "where field #0 is a value which is 1 more than 0"
1701 ", and field #2 is a value which is 3 more than 0",
1702 Explain(m, std::make_tuple(1, 0, 3)));
1704 // If only one has an explanation, then print that one.
1705 m = FieldsAre(0, GreaterThan(0), 0);
1707 "whose all elements match, "
1708 "where field #1 is a value which is 1 more than 0",
1709 Explain(m, std::make_tuple(0, 1, 0)));
1712 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
1713 TEST(FieldsAreTest, StructuredBindings) {
1714 // testing::FieldsAre can also match aggregates and such with C++17 and up.
1719 EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
1721 // Test all the supported arities.
1725 EXPECT_THAT(MyVarType1{}, FieldsAre(0));
1729 EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
1733 EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
1737 EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
1741 EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
1743 int a, b, c, d, e, f;
1745 EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
1747 int a, b, c, d, e, f, g;
1749 EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
1751 int a, b, c, d, e, f, g, h;
1753 EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
1755 int a, b, c, d, e, f, g, h, i;
1757 EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
1758 struct MyVarType10 {
1759 int a, b, c, d, e, f, g, h, i, j;
1761 EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1762 struct MyVarType11 {
1763 int a, b, c, d, e, f, g, h, i, j, k;
1765 EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1766 struct MyVarType12 {
1767 int a, b, c, d, e, f, g, h, i, j, k, l;
1769 EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1770 struct MyVarType13 {
1771 int a, b, c, d, e, f, g, h, i, j, k, l, m;
1773 EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1774 struct MyVarType14 {
1775 int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
1777 EXPECT_THAT(MyVarType14{},
1778 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1779 struct MyVarType15 {
1780 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
1782 EXPECT_THAT(MyVarType15{},
1783 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1784 struct MyVarType16 {
1785 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
1787 EXPECT_THAT(MyVarType16{},
1788 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1792 TEST(ContainsTest, WorksWithMoveOnly) {
1793 ContainerHelper helper;
1794 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1795 helper.Call(MakeUniquePtrs({1, 2}));
1798 TEST(PairTest, UseGetInsteadOfMembers) {
1799 PairWithGet pair{7, "ABC"};
1800 EXPECT_THAT(pair, Pair(7, "ABC"));
1801 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1802 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1804 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1806 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1809 // Tests StartsWith(s).
1811 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1812 const Matcher<const char*> m1 = StartsWith(std::string(""));
1813 EXPECT_TRUE(m1.Matches("Hi"));
1814 EXPECT_TRUE(m1.Matches(""));
1815 EXPECT_FALSE(m1.Matches(nullptr));
1817 const Matcher<const std::string&> m2 = StartsWith("Hi");
1818 EXPECT_TRUE(m2.Matches("Hi"));
1819 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1820 EXPECT_TRUE(m2.Matches("High"));
1821 EXPECT_FALSE(m2.Matches("H"));
1822 EXPECT_FALSE(m2.Matches(" Hi"));
1824 #if GTEST_INTERNAL_HAS_STRING_VIEW
1825 const Matcher<internal::StringView> m_empty =
1826 StartsWith(internal::StringView(""));
1827 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1828 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1829 EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
1830 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1833 TEST(StartsWithTest, CanDescribeSelf) {
1834 Matcher<const std::string> m = StartsWith("Hi");
1835 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1838 // Tests EndsWith(s).
1840 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1841 const Matcher<const char*> m1 = EndsWith("");
1842 EXPECT_TRUE(m1.Matches("Hi"));
1843 EXPECT_TRUE(m1.Matches(""));
1844 EXPECT_FALSE(m1.Matches(nullptr));
1846 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1847 EXPECT_TRUE(m2.Matches("Hi"));
1848 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1849 EXPECT_TRUE(m2.Matches("Super Hi"));
1850 EXPECT_FALSE(m2.Matches("i"));
1851 EXPECT_FALSE(m2.Matches("Hi "));
1853 #if GTEST_INTERNAL_HAS_STRING_VIEW
1854 const Matcher<const internal::StringView&> m4 =
1855 EndsWith(internal::StringView(""));
1856 EXPECT_TRUE(m4.Matches("Hi"));
1857 EXPECT_TRUE(m4.Matches(""));
1858 EXPECT_TRUE(m4.Matches(internal::StringView()));
1859 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1860 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1863 TEST(EndsWithTest, CanDescribeSelf) {
1864 Matcher<const std::string> m = EndsWith("Hi");
1865 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1868 // Tests MatchesRegex().
1870 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1871 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1872 EXPECT_TRUE(m1.Matches("az"));
1873 EXPECT_TRUE(m1.Matches("abcz"));
1874 EXPECT_FALSE(m1.Matches(nullptr));
1876 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1877 EXPECT_TRUE(m2.Matches("azbz"));
1878 EXPECT_FALSE(m2.Matches("az1"));
1879 EXPECT_FALSE(m2.Matches("1az"));
1881 #if GTEST_INTERNAL_HAS_STRING_VIEW
1882 const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
1883 EXPECT_TRUE(m3.Matches(internal::StringView("az")));
1884 EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
1885 EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
1886 EXPECT_FALSE(m3.Matches(internal::StringView()));
1887 const Matcher<const internal::StringView&> m4 =
1888 MatchesRegex(internal::StringView(""));
1889 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1890 EXPECT_TRUE(m4.Matches(internal::StringView()));
1891 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1894 TEST(MatchesRegexTest, CanDescribeSelf) {
1895 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1896 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1898 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1899 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1901 #if GTEST_INTERNAL_HAS_STRING_VIEW
1902 Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
1903 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1904 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1907 // Tests ContainsRegex().
1909 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1910 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1911 EXPECT_TRUE(m1.Matches("az"));
1912 EXPECT_TRUE(m1.Matches("0abcz1"));
1913 EXPECT_FALSE(m1.Matches(nullptr));
1915 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1916 EXPECT_TRUE(m2.Matches("azbz"));
1917 EXPECT_TRUE(m2.Matches("az1"));
1918 EXPECT_FALSE(m2.Matches("1a"));
1920 #if GTEST_INTERNAL_HAS_STRING_VIEW
1921 const Matcher<const internal::StringView&> m3 =
1922 ContainsRegex(new RE("a.*z"));
1923 EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
1924 EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
1925 EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
1926 EXPECT_FALSE(m3.Matches(internal::StringView()));
1927 const Matcher<const internal::StringView&> m4 =
1928 ContainsRegex(internal::StringView(""));
1929 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1930 EXPECT_TRUE(m4.Matches(internal::StringView()));
1931 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1934 TEST(ContainsRegexTest, CanDescribeSelf) {
1935 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1936 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1938 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1939 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1941 #if GTEST_INTERNAL_HAS_STRING_VIEW
1942 Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
1943 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1944 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1947 // Tests for wide strings.
1948 #if GTEST_HAS_STD_WSTRING
1949 TEST(StdWideStrEqTest, MatchesEqual) {
1950 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1951 EXPECT_TRUE(m.Matches(L"Hello"));
1952 EXPECT_FALSE(m.Matches(L"hello"));
1953 EXPECT_FALSE(m.Matches(nullptr));
1955 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1956 EXPECT_TRUE(m2.Matches(L"Hello"));
1957 EXPECT_FALSE(m2.Matches(L"Hi"));
1959 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1960 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1961 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1963 ::std::wstring str(L"01204500800");
1965 Matcher<const ::std::wstring&> m4 = StrEq(str);
1966 EXPECT_TRUE(m4.Matches(str));
1967 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1968 Matcher<const ::std::wstring&> m5 = StrEq(str);
1969 EXPECT_TRUE(m5.Matches(str));
1972 TEST(StdWideStrEqTest, CanDescribeSelf) {
1973 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1974 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1977 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1978 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1981 ::std::wstring str(L"01204500800");
1983 Matcher<const ::std::wstring&> m4 = StrEq(str);
1984 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1985 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1986 Matcher<const ::std::wstring&> m5 = StrEq(str);
1987 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1990 TEST(StdWideStrNeTest, MatchesUnequalString) {
1991 Matcher<const wchar_t*> m = StrNe(L"Hello");
1992 EXPECT_TRUE(m.Matches(L""));
1993 EXPECT_TRUE(m.Matches(nullptr));
1994 EXPECT_FALSE(m.Matches(L"Hello"));
1996 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1997 EXPECT_TRUE(m2.Matches(L"hello"));
1998 EXPECT_FALSE(m2.Matches(L"Hello"));
2001 TEST(StdWideStrNeTest, CanDescribeSelf) {
2002 Matcher<const wchar_t*> m = StrNe(L"Hi");
2003 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
2006 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2007 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
2008 EXPECT_TRUE(m.Matches(L"Hello"));
2009 EXPECT_TRUE(m.Matches(L"hello"));
2010 EXPECT_FALSE(m.Matches(L"Hi"));
2011 EXPECT_FALSE(m.Matches(nullptr));
2013 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
2014 EXPECT_TRUE(m2.Matches(L"hello"));
2015 EXPECT_FALSE(m2.Matches(L"Hi"));
2018 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
2019 ::std::wstring str1(L"oabocdooeoo");
2020 ::std::wstring str2(L"OABOCDOOEOO");
2021 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
2022 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
2024 str1[3] = str2[3] = L'\0';
2025 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
2026 EXPECT_TRUE(m1.Matches(str2));
2028 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
2029 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
2030 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
2031 str1[9] = str2[9] = L'\0';
2032 EXPECT_FALSE(m2.Matches(str2));
2034 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
2035 EXPECT_TRUE(m3.Matches(str2));
2037 EXPECT_FALSE(m3.Matches(str2 + L"x"));
2038 str2.append(1, L'\0');
2039 EXPECT_FALSE(m3.Matches(str2));
2040 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
2043 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2044 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
2045 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2048 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2049 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2050 EXPECT_TRUE(m.Matches(L"Hi"));
2051 EXPECT_TRUE(m.Matches(nullptr));
2052 EXPECT_FALSE(m.Matches(L"Hello"));
2053 EXPECT_FALSE(m.Matches(L"hello"));
2055 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
2056 EXPECT_TRUE(m2.Matches(L""));
2057 EXPECT_FALSE(m2.Matches(L"Hello"));
2060 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2061 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2062 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2065 // Tests that HasSubstr() works for matching wstring-typed values.
2066 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2067 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
2068 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
2069 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
2071 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
2072 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
2073 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
2076 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2077 TEST(StdWideHasSubstrTest, WorksForCStrings) {
2078 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2079 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2080 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
2081 EXPECT_FALSE(m1.Matches(nullptr));
2083 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2084 EXPECT_TRUE(m2.Matches(L"I love food."));
2085 EXPECT_FALSE(m2.Matches(L"tofo"));
2086 EXPECT_FALSE(m2.Matches(nullptr));
2089 // Tests that HasSubstr(s) describes itself properly.
2090 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2091 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
2092 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2095 // Tests StartsWith(s).
2097 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2098 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
2099 EXPECT_TRUE(m1.Matches(L"Hi"));
2100 EXPECT_TRUE(m1.Matches(L""));
2101 EXPECT_FALSE(m1.Matches(nullptr));
2103 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
2104 EXPECT_TRUE(m2.Matches(L"Hi"));
2105 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2106 EXPECT_TRUE(m2.Matches(L"High"));
2107 EXPECT_FALSE(m2.Matches(L"H"));
2108 EXPECT_FALSE(m2.Matches(L" Hi"));
2111 TEST(StdWideStartsWithTest, CanDescribeSelf) {
2112 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2113 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2116 // Tests EndsWith(s).
2118 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2119 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2120 EXPECT_TRUE(m1.Matches(L"Hi"));
2121 EXPECT_TRUE(m1.Matches(L""));
2122 EXPECT_FALSE(m1.Matches(nullptr));
2124 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2125 EXPECT_TRUE(m2.Matches(L"Hi"));
2126 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2127 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2128 EXPECT_FALSE(m2.Matches(L"i"));
2129 EXPECT_FALSE(m2.Matches(L"Hi "));
2132 TEST(StdWideEndsWithTest, CanDescribeSelf) {
2133 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2134 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2137 #endif // GTEST_HAS_STD_WSTRING
2139 typedef ::std::tuple<long, int> Tuple2; // NOLINT
2141 // Tests that Eq() matches a 2-tuple where the first field == the
2143 TEST(Eq2Test, MatchesEqualArguments) {
2144 Matcher<const Tuple2&> m = Eq();
2145 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2146 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2149 // Tests that Eq() describes itself properly.
2150 TEST(Eq2Test, CanDescribeSelf) {
2151 Matcher<const Tuple2&> m = Eq();
2152 EXPECT_EQ("are an equal pair", Describe(m));
2155 // Tests that Ge() matches a 2-tuple where the first field >= the
2157 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2158 Matcher<const Tuple2&> m = Ge();
2159 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2160 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2161 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2164 // Tests that Ge() describes itself properly.
2165 TEST(Ge2Test, CanDescribeSelf) {
2166 Matcher<const Tuple2&> m = Ge();
2167 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2170 // Tests that Gt() matches a 2-tuple where the first field > the
2172 TEST(Gt2Test, MatchesGreaterThanArguments) {
2173 Matcher<const Tuple2&> m = Gt();
2174 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2175 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2176 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2179 // Tests that Gt() describes itself properly.
2180 TEST(Gt2Test, CanDescribeSelf) {
2181 Matcher<const Tuple2&> m = Gt();
2182 EXPECT_EQ("are a pair where the first > the second", Describe(m));
2185 // Tests that Le() matches a 2-tuple where the first field <= the
2187 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2188 Matcher<const Tuple2&> m = Le();
2189 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2190 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2191 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2194 // Tests that Le() describes itself properly.
2195 TEST(Le2Test, CanDescribeSelf) {
2196 Matcher<const Tuple2&> m = Le();
2197 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2200 // Tests that Lt() matches a 2-tuple where the first field < the
2202 TEST(Lt2Test, MatchesLessThanArguments) {
2203 Matcher<const Tuple2&> m = Lt();
2204 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2205 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2206 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2209 // Tests that Lt() describes itself properly.
2210 TEST(Lt2Test, CanDescribeSelf) {
2211 Matcher<const Tuple2&> m = Lt();
2212 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2215 // Tests that Ne() matches a 2-tuple where the first field != the
2217 TEST(Ne2Test, MatchesUnequalArguments) {
2218 Matcher<const Tuple2&> m = Ne();
2219 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2220 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2221 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2224 // Tests that Ne() describes itself properly.
2225 TEST(Ne2Test, CanDescribeSelf) {
2226 Matcher<const Tuple2&> m = Ne();
2227 EXPECT_EQ("are an unequal pair", Describe(m));
2230 TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2231 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2232 Matcher<Pointers> matcher = Eq();
2234 // Tested values don't matter; the point is that matcher does not copy the
2236 EXPECT_TRUE(matcher.Matches(pointers));
2239 // Tests that IsNan() matches a NaN, with float.
2240 TEST(IsNan, FloatMatchesNan) {
2241 float quiet_nan = std::numeric_limits<float>::quiet_NaN();
2242 float other_nan = std::nanf("1");
2243 float real_value = 1.0f;
2245 Matcher<float> m = IsNan();
2246 EXPECT_TRUE(m.Matches(quiet_nan));
2247 EXPECT_TRUE(m.Matches(other_nan));
2248 EXPECT_FALSE(m.Matches(real_value));
2250 Matcher<float&> m_ref = IsNan();
2251 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2252 EXPECT_TRUE(m_ref.Matches(other_nan));
2253 EXPECT_FALSE(m_ref.Matches(real_value));
2255 Matcher<const float&> m_cref = IsNan();
2256 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2257 EXPECT_TRUE(m_cref.Matches(other_nan));
2258 EXPECT_FALSE(m_cref.Matches(real_value));
2261 // Tests that IsNan() matches a NaN, with double.
2262 TEST(IsNan, DoubleMatchesNan) {
2263 double quiet_nan = std::numeric_limits<double>::quiet_NaN();
2264 double other_nan = std::nan("1");
2265 double real_value = 1.0;
2267 Matcher<double> m = IsNan();
2268 EXPECT_TRUE(m.Matches(quiet_nan));
2269 EXPECT_TRUE(m.Matches(other_nan));
2270 EXPECT_FALSE(m.Matches(real_value));
2272 Matcher<double&> m_ref = IsNan();
2273 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2274 EXPECT_TRUE(m_ref.Matches(other_nan));
2275 EXPECT_FALSE(m_ref.Matches(real_value));
2277 Matcher<const double&> m_cref = IsNan();
2278 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2279 EXPECT_TRUE(m_cref.Matches(other_nan));
2280 EXPECT_FALSE(m_cref.Matches(real_value));
2283 // Tests that IsNan() matches a NaN, with long double.
2284 TEST(IsNan, LongDoubleMatchesNan) {
2285 long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
2286 long double other_nan = std::nan("1");
2287 long double real_value = 1.0;
2289 Matcher<long double> m = IsNan();
2290 EXPECT_TRUE(m.Matches(quiet_nan));
2291 EXPECT_TRUE(m.Matches(other_nan));
2292 EXPECT_FALSE(m.Matches(real_value));
2294 Matcher<long double&> m_ref = IsNan();
2295 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2296 EXPECT_TRUE(m_ref.Matches(other_nan));
2297 EXPECT_FALSE(m_ref.Matches(real_value));
2299 Matcher<const long double&> m_cref = IsNan();
2300 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2301 EXPECT_TRUE(m_cref.Matches(other_nan));
2302 EXPECT_FALSE(m_cref.Matches(real_value));
2305 // Tests that IsNan() works with Not.
2306 TEST(IsNan, NotMatchesNan) {
2307 Matcher<float> mf = Not(IsNan());
2308 EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2309 EXPECT_FALSE(mf.Matches(std::nanf("1")));
2310 EXPECT_TRUE(mf.Matches(1.0));
2312 Matcher<double> md = Not(IsNan());
2313 EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2314 EXPECT_FALSE(md.Matches(std::nan("1")));
2315 EXPECT_TRUE(md.Matches(1.0));
2317 Matcher<long double> mld = Not(IsNan());
2318 EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2319 EXPECT_FALSE(mld.Matches(std::nanl("1")));
2320 EXPECT_TRUE(mld.Matches(1.0));
2323 // Tests that IsNan() can describe itself.
2324 TEST(IsNan, CanDescribeSelf) {
2325 Matcher<float> mf = IsNan();
2326 EXPECT_EQ("is NaN", Describe(mf));
2328 Matcher<double> md = IsNan();
2329 EXPECT_EQ("is NaN", Describe(md));
2331 Matcher<long double> mld = IsNan();
2332 EXPECT_EQ("is NaN", Describe(mld));
2335 // Tests that IsNan() can describe itself with Not.
2336 TEST(IsNan, CanDescribeSelfWithNot) {
2337 Matcher<float> mf = Not(IsNan());
2338 EXPECT_EQ("isn't NaN", Describe(mf));
2340 Matcher<double> md = Not(IsNan());
2341 EXPECT_EQ("isn't NaN", Describe(md));
2343 Matcher<long double> mld = Not(IsNan());
2344 EXPECT_EQ("isn't NaN", Describe(mld));
2347 // Tests that FloatEq() matches a 2-tuple where
2348 // FloatEq(first field) matches the second field.
2349 TEST(FloatEq2Test, MatchesEqualArguments) {
2350 typedef ::std::tuple<float, float> Tpl;
2351 Matcher<const Tpl&> m = FloatEq();
2352 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2353 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2354 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2357 // Tests that FloatEq() describes itself properly.
2358 TEST(FloatEq2Test, CanDescribeSelf) {
2359 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2360 EXPECT_EQ("are an almost-equal pair", Describe(m));
2363 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2364 // NanSensitiveFloatEq(first field) matches the second field.
2365 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2366 typedef ::std::tuple<float, float> Tpl;
2367 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2368 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2369 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2370 std::numeric_limits<float>::quiet_NaN())));
2371 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2372 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2373 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2376 // Tests that NanSensitiveFloatEq() describes itself properly.
2377 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2378 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2379 EXPECT_EQ("are an almost-equal pair", Describe(m));
2382 // Tests that DoubleEq() matches a 2-tuple where
2383 // DoubleEq(first field) matches the second field.
2384 TEST(DoubleEq2Test, MatchesEqualArguments) {
2385 typedef ::std::tuple<double, double> Tpl;
2386 Matcher<const Tpl&> m = DoubleEq();
2387 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2388 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2389 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2392 // Tests that DoubleEq() describes itself properly.
2393 TEST(DoubleEq2Test, CanDescribeSelf) {
2394 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2395 EXPECT_EQ("are an almost-equal pair", Describe(m));
2398 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2399 // NanSensitiveDoubleEq(first field) matches the second field.
2400 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2401 typedef ::std::tuple<double, double> Tpl;
2402 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2403 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2404 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2405 std::numeric_limits<double>::quiet_NaN())));
2406 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2407 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2408 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2411 // Tests that DoubleEq() describes itself properly.
2412 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2413 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2414 EXPECT_EQ("are an almost-equal pair", Describe(m));
2417 // Tests that FloatEq() matches a 2-tuple where
2418 // FloatNear(first field, max_abs_error) matches the second field.
2419 TEST(FloatNear2Test, MatchesEqualArguments) {
2420 typedef ::std::tuple<float, float> Tpl;
2421 Matcher<const Tpl&> m = FloatNear(0.5f);
2422 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2423 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2424 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2427 // Tests that FloatNear() describes itself properly.
2428 TEST(FloatNear2Test, CanDescribeSelf) {
2429 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2430 EXPECT_EQ("are an almost-equal pair", Describe(m));
2433 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2434 // NanSensitiveFloatNear(first field) matches the second field.
2435 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2436 typedef ::std::tuple<float, float> Tpl;
2437 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2438 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2439 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2440 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2441 std::numeric_limits<float>::quiet_NaN())));
2442 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2443 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2444 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2447 // Tests that NanSensitiveFloatNear() describes itself properly.
2448 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2449 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2450 EXPECT_EQ("are an almost-equal pair", Describe(m));
2453 // Tests that FloatEq() matches a 2-tuple where
2454 // DoubleNear(first field, max_abs_error) matches the second field.
2455 TEST(DoubleNear2Test, MatchesEqualArguments) {
2456 typedef ::std::tuple<double, double> Tpl;
2457 Matcher<const Tpl&> m = DoubleNear(0.5);
2458 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2459 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2460 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2463 // Tests that DoubleNear() describes itself properly.
2464 TEST(DoubleNear2Test, CanDescribeSelf) {
2465 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2466 EXPECT_EQ("are an almost-equal pair", Describe(m));
2469 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2470 // NanSensitiveDoubleNear(first field) matches the second field.
2471 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2472 typedef ::std::tuple<double, double> Tpl;
2473 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2474 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2475 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2476 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2477 std::numeric_limits<double>::quiet_NaN())));
2478 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2479 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2480 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2483 // Tests that NanSensitiveDoubleNear() describes itself properly.
2484 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2485 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2486 EXPECT_EQ("are an almost-equal pair", Describe(m));
2489 // Tests that Not(m) matches any value that doesn't match m.
2490 TEST(NotTest, NegatesMatcher) {
2493 EXPECT_TRUE(m.Matches(3));
2494 EXPECT_FALSE(m.Matches(2));
2497 // Tests that Not(m) describes itself properly.
2498 TEST(NotTest, CanDescribeSelf) {
2499 Matcher<int> m = Not(Eq(5));
2500 EXPECT_EQ("isn't equal to 5", Describe(m));
2503 // Tests that monomorphic matchers are safely cast by the Not matcher.
2504 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2505 // greater_than_5 is a monomorphic matcher.
2506 Matcher<int> greater_than_5 = Gt(5);
2508 Matcher<const int&> m = Not(greater_than_5);
2509 Matcher<int&> m2 = Not(greater_than_5);
2510 Matcher<int&> m3 = Not(m);
2513 // Helper to allow easy testing of AllOf matchers with num parameters.
2514 void AllOfMatches(int num, const Matcher<int>& m) {
2515 SCOPED_TRACE(Describe(m));
2516 EXPECT_TRUE(m.Matches(0));
2517 for (int i = 1; i <= num; ++i) {
2518 EXPECT_FALSE(m.Matches(i));
2520 EXPECT_TRUE(m.Matches(num + 1));
2523 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2524 // the given matchers.
2525 TEST(AllOfTest, MatchesWhenAllMatch) {
2527 m = AllOf(Le(2), Ge(1));
2528 EXPECT_TRUE(m.Matches(1));
2529 EXPECT_TRUE(m.Matches(2));
2530 EXPECT_FALSE(m.Matches(0));
2531 EXPECT_FALSE(m.Matches(3));
2533 m = AllOf(Gt(0), Ne(1), Ne(2));
2534 EXPECT_TRUE(m.Matches(3));
2535 EXPECT_FALSE(m.Matches(2));
2536 EXPECT_FALSE(m.Matches(1));
2537 EXPECT_FALSE(m.Matches(0));
2539 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2540 EXPECT_TRUE(m.Matches(4));
2541 EXPECT_FALSE(m.Matches(3));
2542 EXPECT_FALSE(m.Matches(2));
2543 EXPECT_FALSE(m.Matches(1));
2544 EXPECT_FALSE(m.Matches(0));
2546 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2547 EXPECT_TRUE(m.Matches(0));
2548 EXPECT_TRUE(m.Matches(1));
2549 EXPECT_FALSE(m.Matches(3));
2551 // The following tests for varying number of sub-matchers. Due to the way
2552 // the sub-matchers are handled it is enough to test every sub-matcher once
2553 // with sub-matchers using the same matcher type. Varying matcher types are
2554 // checked for above.
2555 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2556 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2557 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2558 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2559 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2560 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2561 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2563 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2565 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2568 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2569 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2570 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2571 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2572 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2573 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2578 // Tests that AllOf(m1, ..., mn) describes itself properly.
2579 TEST(AllOfTest, CanDescribeSelf) {
2581 m = AllOf(Le(2), Ge(1));
2582 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2584 m = AllOf(Gt(0), Ne(1), Ne(2));
2585 std::string expected_descr1 =
2586 "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2587 EXPECT_EQ(expected_descr1, Describe(m));
2589 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2590 std::string expected_descr2 =
2591 "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2593 EXPECT_EQ(expected_descr2, Describe(m));
2595 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2596 std::string expected_descr3 =
2597 "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2598 "and (isn't equal to 7)";
2599 EXPECT_EQ(expected_descr3, Describe(m));
2602 // Tests that AllOf(m1, ..., mn) describes its negation properly.
2603 TEST(AllOfTest, CanDescribeNegation) {
2605 m = AllOf(Le(2), Ge(1));
2606 std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2607 EXPECT_EQ(expected_descr4, DescribeNegation(m));
2609 m = AllOf(Gt(0), Ne(1), Ne(2));
2610 std::string expected_descr5 =
2611 "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2612 EXPECT_EQ(expected_descr5, DescribeNegation(m));
2614 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2615 std::string expected_descr6 =
2616 "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2617 EXPECT_EQ(expected_descr6, DescribeNegation(m));
2619 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2620 std::string expected_desr7 =
2621 "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2623 EXPECT_EQ(expected_desr7, DescribeNegation(m));
2625 m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2627 AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2628 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2629 AllOfMatches(11, m);
2632 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
2633 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2634 // greater_than_5 and less_than_10 are monomorphic matchers.
2635 Matcher<int> greater_than_5 = Gt(5);
2636 Matcher<int> less_than_10 = Lt(10);
2638 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2639 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2640 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2642 // Tests that BothOf works when composing itself.
2643 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2644 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2647 TEST(AllOfTest, ExplainsResult) {
2650 // Successful match. Both matchers need to explain. The second
2651 // matcher doesn't give an explanation, so only the first matcher's
2652 // explanation is printed.
2653 m = AllOf(GreaterThan(10), Lt(30));
2654 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2656 // Successful match. Both matchers need to explain.
2657 m = AllOf(GreaterThan(10), GreaterThan(20));
2658 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2661 // Successful match. All matchers need to explain. The second
2662 // matcher doesn't given an explanation.
2663 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2664 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2667 // Successful match. All matchers need to explain.
2668 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2669 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2670 "and which is 10 more than 30",
2673 // Failed match. The first matcher, which failed, needs to
2675 m = AllOf(GreaterThan(10), GreaterThan(20));
2676 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2678 // Failed match. The second matcher, which failed, needs to
2679 // explain. Since it doesn't given an explanation, nothing is
2681 m = AllOf(GreaterThan(10), Lt(30));
2682 EXPECT_EQ("", Explain(m, 40));
2684 // Failed match. The second matcher, which failed, needs to
2686 m = AllOf(GreaterThan(10), GreaterThan(20));
2687 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2690 // Helper to allow easy testing of AnyOf matchers with num parameters.
2691 static void AnyOfMatches(int num, const Matcher<int>& m) {
2692 SCOPED_TRACE(Describe(m));
2693 EXPECT_FALSE(m.Matches(0));
2694 for (int i = 1; i <= num; ++i) {
2695 EXPECT_TRUE(m.Matches(i));
2697 EXPECT_FALSE(m.Matches(num + 1));
2700 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2701 SCOPED_TRACE(Describe(m));
2702 EXPECT_FALSE(m.Matches(std::to_string(0)));
2704 for (int i = 1; i <= num; ++i) {
2705 EXPECT_TRUE(m.Matches(std::to_string(i)));
2707 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2710 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2711 // least one of the given matchers.
2712 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2714 m = AnyOf(Le(1), Ge(3));
2715 EXPECT_TRUE(m.Matches(1));
2716 EXPECT_TRUE(m.Matches(4));
2717 EXPECT_FALSE(m.Matches(2));
2719 m = AnyOf(Lt(0), Eq(1), Eq(2));
2720 EXPECT_TRUE(m.Matches(-1));
2721 EXPECT_TRUE(m.Matches(1));
2722 EXPECT_TRUE(m.Matches(2));
2723 EXPECT_FALSE(m.Matches(0));
2725 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2726 EXPECT_TRUE(m.Matches(-1));
2727 EXPECT_TRUE(m.Matches(1));
2728 EXPECT_TRUE(m.Matches(2));
2729 EXPECT_TRUE(m.Matches(3));
2730 EXPECT_FALSE(m.Matches(0));
2732 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2733 EXPECT_TRUE(m.Matches(0));
2734 EXPECT_TRUE(m.Matches(11));
2735 EXPECT_TRUE(m.Matches(3));
2736 EXPECT_FALSE(m.Matches(2));
2738 // The following tests for varying number of sub-matchers. Due to the way
2739 // the sub-matchers are handled it is enough to test every sub-matcher once
2740 // with sub-matchers using the same matcher type. Varying matcher types are
2741 // checked for above.
2742 AnyOfMatches(2, AnyOf(1, 2));
2743 AnyOfMatches(3, AnyOf(1, 2, 3));
2744 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2745 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2746 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2747 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2748 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2749 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2750 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2753 // Tests the variadic version of the AnyOfMatcher.
2754 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2755 // Also make sure AnyOf is defined in the right namespace and does not depend
2757 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2759 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2760 AnyOfMatches(11, m);
2761 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2762 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2763 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2764 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2765 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2767 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2768 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2769 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2770 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2771 "43", "44", "45", "46", "47", "48", "49", "50"));
2774 // Tests the variadic version of the ElementsAreMatcher
2775 TEST(ElementsAreTest, HugeMatcher) {
2776 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2778 EXPECT_THAT(test_vector,
2779 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2780 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2783 // Tests the variadic version of the UnorderedElementsAreMatcher
2784 TEST(ElementsAreTest, HugeMatcherStr) {
2785 vector<std::string> test_vector{
2786 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2788 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2792 // Tests the variadic version of the UnorderedElementsAreMatcher
2793 TEST(ElementsAreTest, HugeMatcherUnordered) {
2794 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2796 EXPECT_THAT(test_vector, UnorderedElementsAre(
2797 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2798 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2802 // Tests that AnyOf(m1, ..., mn) describes itself properly.
2803 TEST(AnyOfTest, CanDescribeSelf) {
2805 m = AnyOf(Le(1), Ge(3));
2807 EXPECT_EQ("(is <= 1) or (is >= 3)",
2810 m = AnyOf(Lt(0), Eq(1), Eq(2));
2811 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
2813 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2814 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
2817 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2819 "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2824 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
2825 TEST(AnyOfTest, CanDescribeNegation) {
2827 m = AnyOf(Le(1), Ge(3));
2828 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2829 DescribeNegation(m));
2831 m = AnyOf(Lt(0), Eq(1), Eq(2));
2832 EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
2833 DescribeNegation(m));
2835 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2837 "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2839 DescribeNegation(m));
2841 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2843 "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2844 "to 5) and (isn't equal to 7)",
2845 DescribeNegation(m));
2848 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2849 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2850 // greater_than_5 and less_than_10 are monomorphic matchers.
2851 Matcher<int> greater_than_5 = Gt(5);
2852 Matcher<int> less_than_10 = Lt(10);
2854 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2855 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2856 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2858 // Tests that EitherOf works when composing itself.
2859 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2860 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2863 TEST(AnyOfTest, ExplainsResult) {
2866 // Failed match. Both matchers need to explain. The second
2867 // matcher doesn't give an explanation, so only the first matcher's
2868 // explanation is printed.
2869 m = AnyOf(GreaterThan(10), Lt(0));
2870 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2872 // Failed match. Both matchers need to explain.
2873 m = AnyOf(GreaterThan(10), GreaterThan(20));
2874 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2877 // Failed match. All matchers need to explain. The second
2878 // matcher doesn't given an explanation.
2879 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2880 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2883 // Failed match. All matchers need to explain.
2884 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2885 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2886 "and which is 25 less than 30",
2889 // Successful match. The first matcher, which succeeded, needs to
2891 m = AnyOf(GreaterThan(10), GreaterThan(20));
2892 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2894 // Successful match. The second matcher, which succeeded, needs to
2895 // explain. Since it doesn't given an explanation, nothing is
2897 m = AnyOf(GreaterThan(10), Lt(30));
2898 EXPECT_EQ("", Explain(m, 0));
2900 // Successful match. The second matcher, which succeeded, needs to
2902 m = AnyOf(GreaterThan(30), GreaterThan(20));
2903 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2906 // The following predicate function and predicate functor are for
2907 // testing the Truly(predicate) matcher.
2909 // Returns non-zero if the input is positive. Note that the return
2910 // type of this function is not bool. It's OK as Truly() accepts any
2911 // unary function or functor whose return type can be implicitly
2912 // converted to bool.
2913 int IsPositive(double x) {
2914 return x > 0 ? 1 : 0;
2917 // This functor returns true if the input is greater than the given
2919 class IsGreaterThan {
2921 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2923 bool operator()(int n) const { return n > threshold_; }
2929 // For testing Truly().
2932 // This predicate returns true if and only if the argument references foo and
2933 // has a zero value.
2934 bool ReferencesFooAndIsZero(const int& n) {
2935 return (&n == &foo) && (n == 0);
2938 // Tests that Truly(predicate) matches what satisfies the given
2940 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2941 Matcher<double> m = Truly(IsPositive);
2942 EXPECT_TRUE(m.Matches(2.0));
2943 EXPECT_FALSE(m.Matches(-1.5));
2946 // Tests that Truly(predicate_functor) works too.
2947 TEST(TrulyTest, CanBeUsedWithFunctor) {
2948 Matcher<int> m = Truly(IsGreaterThan(5));
2949 EXPECT_TRUE(m.Matches(6));
2950 EXPECT_FALSE(m.Matches(4));
2953 // A class that can be implicitly converted to bool.
2954 class ConvertibleToBool {
2956 explicit ConvertibleToBool(int number) : number_(number) {}
2957 operator bool() const { return number_ != 0; }
2963 ConvertibleToBool IsNotZero(int number) {
2964 return ConvertibleToBool(number);
2967 // Tests that the predicate used in Truly() may return a class that's
2968 // implicitly convertible to bool, even when the class has no
2970 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2971 Matcher<int> m = Truly(IsNotZero);
2972 EXPECT_TRUE(m.Matches(1));
2973 EXPECT_FALSE(m.Matches(0));
2976 // Tests that Truly(predicate) can describe itself properly.
2977 TEST(TrulyTest, CanDescribeSelf) {
2978 Matcher<double> m = Truly(IsPositive);
2979 EXPECT_EQ("satisfies the given predicate",
2983 // Tests that Truly(predicate) works when the matcher takes its
2984 // argument by reference.
2985 TEST(TrulyTest, WorksForByRefArguments) {
2986 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2987 EXPECT_TRUE(m.Matches(foo));
2989 EXPECT_FALSE(m.Matches(n));
2992 // Tests that Truly(predicate) provides a helpful reason when it fails.
2993 TEST(TrulyTest, ExplainsFailures) {
2994 StringMatchResultListener listener;
2995 EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
2996 EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
2999 // Tests that Matches(m) is a predicate satisfied by whatever that
3000 // matches matcher m.
3001 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
3002 EXPECT_TRUE(Matches(Ge(0))(1));
3003 EXPECT_FALSE(Matches(Eq('a'))('b'));
3006 // Tests that Matches(m) works when the matcher takes its argument by
3008 TEST(MatchesTest, WorksOnByRefArguments) {
3010 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
3011 EXPECT_FALSE(Matches(Ref(m))(n));
3014 // Tests that a Matcher on non-reference type can be used in
3016 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3017 Matcher<int> eq5 = Eq(5);
3018 EXPECT_TRUE(Matches(eq5)(5));
3019 EXPECT_FALSE(Matches(eq5)(2));
3022 // Tests Value(value, matcher). Since Value() is a simple wrapper for
3023 // Matches(), which has been tested already, we don't spend a lot of
3024 // effort on testing Value().
3025 TEST(ValueTest, WorksWithPolymorphicMatcher) {
3026 EXPECT_TRUE(Value("hi", StartsWith("h")));
3027 EXPECT_FALSE(Value(5, Gt(10)));
3030 TEST(ValueTest, WorksWithMonomorphicMatcher) {
3031 const Matcher<int> is_zero = Eq(0);
3032 EXPECT_TRUE(Value(0, is_zero));
3033 EXPECT_FALSE(Value('a', is_zero));
3036 const Matcher<const int&> ref_n = Ref(n);
3037 EXPECT_TRUE(Value(n, ref_n));
3038 EXPECT_FALSE(Value(1, ref_n));
3041 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3042 StringMatchResultListener listener1;
3043 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3044 EXPECT_EQ("% 2 == 0", listener1.str());
3046 StringMatchResultListener listener2;
3047 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3048 EXPECT_EQ("", listener2.str());
3051 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3052 const Matcher<int> is_even = PolymorphicIsEven();
3053 StringMatchResultListener listener1;
3054 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3055 EXPECT_EQ("% 2 == 0", listener1.str());
3057 const Matcher<const double&> is_zero = Eq(0);
3058 StringMatchResultListener listener2;
3059 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3060 EXPECT_EQ("", listener2.str());
3063 MATCHER(ConstructNoArg, "") { return true; }
3064 MATCHER_P(Construct1Arg, arg1, "") { return true; }
3065 MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
3067 TEST(MatcherConstruct, ExplicitVsImplicit) {
3069 // No arg constructor can be constructed with empty brace.
3070 ConstructNoArgMatcher m = {};
3073 ConstructNoArgMatcher m2;
3077 // The one arg constructor has an explicit constructor.
3078 // This is to prevent the implicit conversion.
3079 using M = Construct1ArgMatcherP<int>;
3080 EXPECT_TRUE((std::is_constructible<M, int>::value));
3081 EXPECT_FALSE((std::is_convertible<int, M>::value));
3084 // Multiple arg matchers can be constructed with an implicit construction.
3085 Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
3090 MATCHER_P(Really, inner_matcher, "") {
3091 return ExplainMatchResult(inner_matcher, arg, result_listener);
3094 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3095 EXPECT_THAT(0, Really(Eq(0)));
3098 TEST(DescribeMatcherTest, WorksWithValue) {
3099 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3100 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3103 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
3104 const Matcher<int> monomorphic = Le(0);
3105 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
3106 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
3109 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3110 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
3111 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
3114 TEST(AllArgsTest, WorksForTuple) {
3115 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
3116 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
3119 TEST(AllArgsTest, WorksForNonTuple) {
3120 EXPECT_THAT(42, AllArgs(Gt(0)));
3121 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3124 class AllArgsHelper {
3128 MOCK_METHOD2(Helper, int(char x, int y));
3131 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
3134 TEST(AllArgsTest, WorksInWithClause) {
3135 AllArgsHelper helper;
3136 ON_CALL(helper, Helper(_, _))
3137 .With(AllArgs(Lt()))
3138 .WillByDefault(Return(1));
3139 EXPECT_CALL(helper, Helper(_, _));
3140 EXPECT_CALL(helper, Helper(_, _))
3141 .With(AllArgs(Gt()))
3142 .WillOnce(Return(2));
3144 EXPECT_EQ(1, helper.Helper('\1', 2));
3145 EXPECT_EQ(2, helper.Helper('a', 1));
3148 class OptionalMatchersHelper {
3150 OptionalMatchersHelper() {}
3152 MOCK_METHOD0(NoArgs, int());
3154 MOCK_METHOD1(OneArg, int(int y));
3156 MOCK_METHOD2(TwoArgs, int(char x, int y));
3158 MOCK_METHOD1(Overloaded, int(char x));
3159 MOCK_METHOD2(Overloaded, int(char x, int y));
3162 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
3165 TEST(AllArgsTest, WorksWithoutMatchers) {
3166 OptionalMatchersHelper helper;
3168 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3169 ON_CALL(helper, OneArg).WillByDefault(Return(20));
3170 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3172 EXPECT_EQ(10, helper.NoArgs());
3173 EXPECT_EQ(20, helper.OneArg(1));
3174 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3176 EXPECT_CALL(helper, NoArgs).Times(1);
3177 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
3178 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
3179 EXPECT_CALL(helper, TwoArgs).Times(0);
3181 EXPECT_EQ(10, helper.NoArgs());
3182 EXPECT_EQ(100, helper.OneArg(1));
3183 EXPECT_EQ(200, helper.OneArg(17));
3186 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3187 // matches the matcher.
3188 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3189 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3190 ASSERT_THAT("Foo", EndsWith("oo"));
3191 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3192 EXPECT_THAT("Hello", StartsWith("Hell"));
3195 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3196 // doesn't match the matcher.
3197 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3198 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3199 // which cannot reference auto variables.
3200 static unsigned short n; // NOLINT
3203 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
3205 "Expected: is > 10\n"
3206 " Actual: 5" + OfType("unsigned short"));
3208 EXPECT_NONFATAL_FAILURE(
3209 EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
3211 "Expected: (is <= 7) and (is >= 5)\n"
3212 " Actual: 0" + OfType("unsigned short"));
3215 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3216 // has a reference type.
3217 TEST(MatcherAssertionTest, WorksForByRefArguments) {
3218 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3219 // reference auto variables.
3222 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3223 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3225 "Expected: does not reference the variable @");
3226 // Tests the "Actual" part.
3227 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3228 "Actual: 0" + OfType("int") + ", which is located @");
3231 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3233 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3234 Matcher<const char*> starts_with_he = StartsWith("he");
3235 ASSERT_THAT("hello", starts_with_he);
3237 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
3238 ASSERT_THAT("book", ends_with_ok);
3239 const std::string bad = "bad";
3240 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3242 "Expected: ends with \"ok\"\n"
3243 " Actual: \"bad\"");
3244 Matcher<int> is_greater_than_5 = Gt(5);
3245 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3247 "Expected: is > 5\n"
3248 " Actual: 5" + OfType("int"));
3251 // Tests floating-point matchers.
3252 template <typename RawType>
3253 class FloatingPointTest : public testing::Test {
3255 typedef testing::internal::FloatingPoint<RawType> Floating;
3256 typedef typename Floating::Bits Bits;
3259 : max_ulps_(Floating::kMaxUlps),
3260 zero_bits_(Floating(0).bits()),
3261 one_bits_(Floating(1).bits()),
3262 infinity_bits_(Floating(Floating::Infinity()).bits()),
3263 close_to_positive_zero_(
3264 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3265 close_to_negative_zero_(
3266 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3267 further_from_negative_zero_(-Floating::ReinterpretBits(
3268 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
3269 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3270 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
3271 infinity_(Floating::Infinity()),
3273 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3274 further_from_infinity_(
3275 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
3276 max_(Floating::Max()),
3277 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3278 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3282 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3285 // A battery of tests for FloatingEqMatcher::Matches.
3286 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3288 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3289 Matcher<RawType> m1 = matcher_maker(0.0);
3290 EXPECT_TRUE(m1.Matches(-0.0));
3291 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3292 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3293 EXPECT_FALSE(m1.Matches(1.0));
3295 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3296 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3298 Matcher<RawType> m3 = matcher_maker(1.0);
3299 EXPECT_TRUE(m3.Matches(close_to_one_));
3300 EXPECT_FALSE(m3.Matches(further_from_one_));
3302 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3303 EXPECT_FALSE(m3.Matches(0.0));
3305 Matcher<RawType> m4 = matcher_maker(-infinity_);
3306 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3308 Matcher<RawType> m5 = matcher_maker(infinity_);
3309 EXPECT_TRUE(m5.Matches(close_to_infinity_));
3311 // This is interesting as the representations of infinity_ and nan1_
3312 // are only 1 DLP apart.
3313 EXPECT_FALSE(m5.Matches(nan1_));
3315 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3317 Matcher<const RawType&> m6 = matcher_maker(0.0);
3318 EXPECT_TRUE(m6.Matches(-0.0));
3319 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3320 EXPECT_FALSE(m6.Matches(1.0));
3322 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3324 Matcher<RawType&> m7 = matcher_maker(0.0);
3326 EXPECT_TRUE(m7.Matches(x));
3328 EXPECT_FALSE(m7.Matches(x));
3331 // Pre-calculated numbers to be used by the tests.
3333 const Bits max_ulps_;
3335 const Bits zero_bits_; // The bits that represent 0.0.
3336 const Bits one_bits_; // The bits that represent 1.0.
3337 const Bits infinity_bits_; // The bits that represent +infinity.
3339 // Some numbers close to 0.0.
3340 const RawType close_to_positive_zero_;
3341 const RawType close_to_negative_zero_;
3342 const RawType further_from_negative_zero_;
3344 // Some numbers close to 1.0.
3345 const RawType close_to_one_;
3346 const RawType further_from_one_;
3348 // Some numbers close to +infinity.
3349 const RawType infinity_;
3350 const RawType close_to_infinity_;
3351 const RawType further_from_infinity_;
3353 // Maximum representable value that's not infinity.
3357 const RawType nan1_;
3358 const RawType nan2_;
3361 // Tests floating-point matchers with fixed epsilons.
3362 template <typename RawType>
3363 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3365 typedef FloatingPointTest<RawType> ParentType;
3367 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3368 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3369 void TestNearMatches(
3370 testing::internal::FloatingEqMatcher<RawType>
3371 (*matcher_maker)(RawType, RawType)) {
3372 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3373 EXPECT_TRUE(m1.Matches(0.0));
3374 EXPECT_TRUE(m1.Matches(-0.0));
3375 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3376 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3377 EXPECT_FALSE(m1.Matches(1.0));
3379 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3380 EXPECT_TRUE(m2.Matches(0.0));
3381 EXPECT_TRUE(m2.Matches(-0.0));
3382 EXPECT_TRUE(m2.Matches(1.0));
3383 EXPECT_TRUE(m2.Matches(-1.0));
3384 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3385 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3387 // Check that inf matches inf, regardless of the of the specified max
3389 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3390 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3391 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3392 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3394 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3395 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3396 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3397 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3399 // Test various overflow scenarios.
3400 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3401 EXPECT_TRUE(m5.Matches(ParentType::max_));
3402 EXPECT_FALSE(m5.Matches(-ParentType::max_));
3404 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3405 EXPECT_FALSE(m6.Matches(ParentType::max_));
3406 EXPECT_TRUE(m6.Matches(-ParentType::max_));
3408 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3409 EXPECT_TRUE(m7.Matches(ParentType::max_));
3410 EXPECT_FALSE(m7.Matches(-ParentType::max_));
3412 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3413 EXPECT_FALSE(m8.Matches(ParentType::max_));
3414 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3416 // The difference between max() and -max() normally overflows to infinity,
3417 // but it should still match if the max_abs_error is also infinity.
3418 Matcher<RawType> m9 = matcher_maker(
3419 ParentType::max_, ParentType::infinity_);
3420 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3422 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3424 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3425 EXPECT_TRUE(m10.Matches(-0.0));
3426 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3427 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3429 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3431 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3433 EXPECT_TRUE(m11.Matches(x));
3435 EXPECT_TRUE(m11.Matches(x));
3437 EXPECT_TRUE(m11.Matches(x));
3439 EXPECT_FALSE(m11.Matches(x));
3441 EXPECT_FALSE(m11.Matches(x));
3445 // Instantiate FloatingPointTest for testing floats.
3446 typedef FloatingPointTest<float> FloatTest;
3448 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3449 TestMatches(&FloatEq);
3452 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3453 TestMatches(&NanSensitiveFloatEq);
3456 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3457 // FloatEq never matches NaN.
3458 Matcher<float> m = FloatEq(nan1_);
3459 EXPECT_FALSE(m.Matches(nan1_));
3460 EXPECT_FALSE(m.Matches(nan2_));
3461 EXPECT_FALSE(m.Matches(1.0));
3464 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3465 // NanSensitiveFloatEq will match NaN.
3466 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3467 EXPECT_TRUE(m.Matches(nan1_));
3468 EXPECT_TRUE(m.Matches(nan2_));
3469 EXPECT_FALSE(m.Matches(1.0));
3472 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3473 Matcher<float> m1 = FloatEq(2.0f);
3474 EXPECT_EQ("is approximately 2", Describe(m1));
3475 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3477 Matcher<float> m2 = FloatEq(0.5f);
3478 EXPECT_EQ("is approximately 0.5", Describe(m2));
3479 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3481 Matcher<float> m3 = FloatEq(nan1_);
3482 EXPECT_EQ("never matches", Describe(m3));
3483 EXPECT_EQ("is anything", DescribeNegation(m3));
3486 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3487 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3488 EXPECT_EQ("is approximately 2", Describe(m1));
3489 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3491 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3492 EXPECT_EQ("is approximately 0.5", Describe(m2));
3493 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3495 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3496 EXPECT_EQ("is NaN", Describe(m3));
3497 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3500 // Instantiate FloatingPointTest for testing floats with a user-specified
3501 // max absolute error.
3502 typedef FloatingPointNearTest<float> FloatNearTest;
3504 TEST_F(FloatNearTest, FloatNearMatches) {
3505 TestNearMatches(&FloatNear);
3508 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3509 TestNearMatches(&NanSensitiveFloatNear);
3512 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3513 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3514 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3516 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3518 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3519 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3521 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3523 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3524 EXPECT_EQ("never matches", Describe(m3));
3525 EXPECT_EQ("is anything", DescribeNegation(m3));
3528 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3529 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3530 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3532 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3534 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3535 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3537 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3539 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3540 EXPECT_EQ("is NaN", Describe(m3));
3541 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3544 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3545 // FloatNear never matches NaN.
3546 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3547 EXPECT_FALSE(m.Matches(nan1_));
3548 EXPECT_FALSE(m.Matches(nan2_));
3549 EXPECT_FALSE(m.Matches(1.0));
3552 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3553 // NanSensitiveFloatNear will match NaN.
3554 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3555 EXPECT_TRUE(m.Matches(nan1_));
3556 EXPECT_TRUE(m.Matches(nan2_));
3557 EXPECT_FALSE(m.Matches(1.0));
3560 // Instantiate FloatingPointTest for testing doubles.
3561 typedef FloatingPointTest<double> DoubleTest;
3563 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3564 TestMatches(&DoubleEq);
3567 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3568 TestMatches(&NanSensitiveDoubleEq);
3571 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3572 // DoubleEq never matches NaN.
3573 Matcher<double> m = DoubleEq(nan1_);
3574 EXPECT_FALSE(m.Matches(nan1_));
3575 EXPECT_FALSE(m.Matches(nan2_));
3576 EXPECT_FALSE(m.Matches(1.0));
3579 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3580 // NanSensitiveDoubleEq will match NaN.
3581 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3582 EXPECT_TRUE(m.Matches(nan1_));
3583 EXPECT_TRUE(m.Matches(nan2_));
3584 EXPECT_FALSE(m.Matches(1.0));
3587 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3588 Matcher<double> m1 = DoubleEq(2.0);
3589 EXPECT_EQ("is approximately 2", Describe(m1));
3590 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3592 Matcher<double> m2 = DoubleEq(0.5);
3593 EXPECT_EQ("is approximately 0.5", Describe(m2));
3594 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3596 Matcher<double> m3 = DoubleEq(nan1_);
3597 EXPECT_EQ("never matches", Describe(m3));
3598 EXPECT_EQ("is anything", DescribeNegation(m3));
3601 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3602 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3603 EXPECT_EQ("is approximately 2", Describe(m1));
3604 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3606 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3607 EXPECT_EQ("is approximately 0.5", Describe(m2));
3608 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3610 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3611 EXPECT_EQ("is NaN", Describe(m3));
3612 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3615 // Instantiate FloatingPointTest for testing floats with a user-specified
3616 // max absolute error.
3617 typedef FloatingPointNearTest<double> DoubleNearTest;
3619 TEST_F(DoubleNearTest, DoubleNearMatches) {
3620 TestNearMatches(&DoubleNear);
3623 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3624 TestNearMatches(&NanSensitiveDoubleNear);
3627 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3628 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3629 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3631 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3633 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3634 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3636 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3638 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3639 EXPECT_EQ("never matches", Describe(m3));
3640 EXPECT_EQ("is anything", DescribeNegation(m3));
3643 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3644 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3645 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3646 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3648 const std::string explanation =
3649 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3650 // Different C++ implementations may print floating-point numbers
3651 // slightly differently.
3652 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3653 explanation == "which is 1.2e-010 from 2.1") // MSVC
3654 << " where explanation is \"" << explanation << "\".";
3657 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3658 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3659 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3661 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3663 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3664 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3666 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3668 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3669 EXPECT_EQ("is NaN", Describe(m3));
3670 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3673 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3674 // DoubleNear never matches NaN.
3675 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3676 EXPECT_FALSE(m.Matches(nan1_));
3677 EXPECT_FALSE(m.Matches(nan2_));
3678 EXPECT_FALSE(m.Matches(1.0));
3681 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3682 // NanSensitiveDoubleNear will match NaN.
3683 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3684 EXPECT_TRUE(m.Matches(nan1_));
3685 EXPECT_TRUE(m.Matches(nan2_));
3686 EXPECT_FALSE(m.Matches(1.0));
3689 TEST(PointeeTest, RawPointer) {
3690 const Matcher<int*> m = Pointee(Ge(0));
3693 EXPECT_TRUE(m.Matches(&n));
3695 EXPECT_FALSE(m.Matches(&n));
3696 EXPECT_FALSE(m.Matches(nullptr));
3699 TEST(PointeeTest, RawPointerToConst) {
3700 const Matcher<const double*> m = Pointee(Ge(0));
3703 EXPECT_TRUE(m.Matches(&x));
3705 EXPECT_FALSE(m.Matches(&x));
3706 EXPECT_FALSE(m.Matches(nullptr));
3709 TEST(PointeeTest, ReferenceToConstRawPointer) {
3710 const Matcher<int* const &> m = Pointee(Ge(0));
3713 EXPECT_TRUE(m.Matches(&n));
3715 EXPECT_FALSE(m.Matches(&n));
3716 EXPECT_FALSE(m.Matches(nullptr));
3719 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3720 const Matcher<double* &> m = Pointee(Ge(0));
3724 EXPECT_TRUE(m.Matches(p));
3726 EXPECT_FALSE(m.Matches(p));
3728 EXPECT_FALSE(m.Matches(p));
3731 TEST(PointeeTest, SmartPointer) {
3732 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
3734 std::unique_ptr<int> n(new int(1));
3735 EXPECT_TRUE(m.Matches(n));
3738 TEST(PointeeTest, SmartPointerToConst) {
3739 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
3741 // There's no implicit conversion from unique_ptr<int> to const
3742 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3744 std::unique_ptr<const int> n(new int(1));
3745 EXPECT_TRUE(m.Matches(n));
3748 TEST(PointerTest, RawPointer) {
3750 const Matcher<int*> m = Pointer(Eq(&n));
3752 EXPECT_TRUE(m.Matches(&n));
3755 EXPECT_FALSE(m.Matches(p));
3756 EXPECT_FALSE(m.Matches(nullptr));
3759 TEST(PointerTest, RawPointerToConst) {
3761 const Matcher<const int*> m = Pointer(Eq(&n));
3763 EXPECT_TRUE(m.Matches(&n));
3766 EXPECT_FALSE(m.Matches(p));
3767 EXPECT_FALSE(m.Matches(nullptr));
3770 TEST(PointerTest, SmartPointer) {
3771 std::unique_ptr<int> n(new int(10));
3772 int* raw_n = n.get();
3773 const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
3775 EXPECT_TRUE(m.Matches(n));
3778 TEST(PointerTest, SmartPointerToConst) {
3779 std::unique_ptr<const int> n(new int(10));
3780 const int* raw_n = n.get();
3781 const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
3783 // There's no implicit conversion from unique_ptr<int> to const
3784 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3786 std::unique_ptr<const int> p(new int(10));
3787 EXPECT_FALSE(m.Matches(p));
3790 TEST(AddressTest, NonConst) {
3792 const Matcher<int> m = Address(Eq(&n));
3794 EXPECT_TRUE(m.Matches(n));
3798 EXPECT_FALSE(m.Matches(other));
3802 EXPECT_TRUE(m.Matches(n_ref));
3805 TEST(AddressTest, Const) {
3807 const Matcher<int> m = Address(Eq(&n));
3809 EXPECT_TRUE(m.Matches(n));
3813 EXPECT_FALSE(m.Matches(other));
3816 TEST(AddressTest, MatcherDoesntCopy) {
3817 std::unique_ptr<int> n(new int(1));
3818 const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
3820 EXPECT_TRUE(m.Matches(n));
3823 TEST(AddressTest, Describe) {
3824 Matcher<int> matcher = Address(_);
3825 EXPECT_EQ("has address that is anything", Describe(matcher));
3826 EXPECT_EQ("does not have address that is anything",
3827 DescribeNegation(matcher));
3830 MATCHER_P(FieldIIs, inner_matcher, "") {
3831 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3835 TEST(WhenDynamicCastToTest, SameType) {
3839 // Right type. A pointer is passed down.
3840 Base* as_base_ptr = &derived;
3841 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3842 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3843 EXPECT_THAT(as_base_ptr,
3844 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3847 TEST(WhenDynamicCastToTest, WrongTypes) {
3850 OtherDerived other_derived;
3852 // Wrong types. NULL is passed.
3853 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3854 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3855 Base* as_base_ptr = &derived;
3856 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3857 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3858 as_base_ptr = &other_derived;
3859 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3860 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3863 TEST(WhenDynamicCastToTest, AlreadyNull) {
3865 Base* as_base_ptr = nullptr;
3866 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3869 struct AmbiguousCastTypes {
3870 class VirtualDerived : public virtual Base {};
3871 class DerivedSub1 : public VirtualDerived {};
3872 class DerivedSub2 : public VirtualDerived {};
3873 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3876 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3877 AmbiguousCastTypes::DerivedSub1 sub1;
3878 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3879 // Multiply derived from Base. dynamic_cast<> returns NULL.
3881 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3882 EXPECT_THAT(as_base_ptr,
3883 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3884 as_base_ptr = &sub1;
3887 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3890 TEST(WhenDynamicCastToTest, Describe) {
3891 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3892 const std::string prefix =
3893 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3894 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3895 EXPECT_EQ(prefix + "does not point to a value that is anything",
3896 DescribeNegation(matcher));
3899 TEST(WhenDynamicCastToTest, Explain) {
3900 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3901 Base* null = nullptr;
3902 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3904 EXPECT_TRUE(matcher.Matches(&derived));
3905 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3907 // With references, the matcher itself can fail. Test for that one.
3908 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3909 EXPECT_THAT(Explain(ref_matcher, derived),
3910 HasSubstr("which cannot be dynamic_cast"));
3913 TEST(WhenDynamicCastToTest, GoodReference) {
3916 Base& as_base_ref = derived;
3917 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3918 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3921 TEST(WhenDynamicCastToTest, BadReference) {
3923 Base& as_base_ref = derived;
3924 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3926 #endif // GTEST_HAS_RTTI
3928 // Minimal const-propagating pointer.
3929 template <typename T>
3930 class ConstPropagatingPtr {
3932 typedef T element_type;
3934 ConstPropagatingPtr() : val_() {}
3935 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3936 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3938 T* get() { return val_; }
3939 T& operator*() { return *val_; }
3940 // Most smart pointers return non-const T* and T& from the next methods.
3941 const T* get() const { return val_; }
3942 const T& operator*() const { return *val_; }
3948 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3949 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3951 const ConstPropagatingPtr<int> co(&three);
3952 ConstPropagatingPtr<int> o(&three);
3953 EXPECT_TRUE(m.Matches(o));
3954 EXPECT_TRUE(m.Matches(co));
3956 EXPECT_FALSE(m.Matches(o));
3957 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3960 TEST(PointeeTest, NeverMatchesNull) {
3961 const Matcher<const char*> m = Pointee(_);
3962 EXPECT_FALSE(m.Matches(nullptr));
3965 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3966 TEST(PointeeTest, MatchesAgainstAValue) {
3967 const Matcher<int*> m = Pointee(5);
3970 EXPECT_TRUE(m.Matches(&n));
3972 EXPECT_FALSE(m.Matches(&n));
3973 EXPECT_FALSE(m.Matches(nullptr));
3976 TEST(PointeeTest, CanDescribeSelf) {
3977 const Matcher<int*> m = Pointee(Gt(3));
3978 EXPECT_EQ("points to a value that is > 3", Describe(m));
3979 EXPECT_EQ("does not point to a value that is > 3",
3980 DescribeNegation(m));
3983 TEST(PointeeTest, CanExplainMatchResult) {
3984 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3986 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
3988 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3989 long n = 3; // NOLINT
3990 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3994 TEST(PointeeTest, AlwaysExplainsPointee) {
3995 const Matcher<int*> m = Pointee(0);
3997 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
4000 // An uncopyable class.
4003 Uncopyable() : value_(-1) {}
4004 explicit Uncopyable(int a_value) : value_(a_value) {}
4006 int value() const { return value_; }
4007 void set_value(int i) { value_ = i; }
4011 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
4014 // Returns true if and only if x.value() is positive.
4015 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
4017 MATCHER_P(UncopyableIs, inner_matcher, "") {
4018 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
4021 // A user-defined struct for testing Field().
4023 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
4024 AStruct(const AStruct& rhs)
4025 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
4027 int x; // A non-const field.
4028 const double y; // A const field.
4029 Uncopyable z; // An uncopyable field.
4030 const char* p; // A pointer field.
4033 // A derived struct for testing Field().
4034 struct DerivedStruct : public AStruct {
4038 // Tests that Field(&Foo::field, ...) works when field is non-const.
4039 TEST(FieldTest, WorksForNonConstField) {
4040 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
4041 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
4044 EXPECT_TRUE(m.Matches(a));
4045 EXPECT_TRUE(m_with_name.Matches(a));
4047 EXPECT_FALSE(m.Matches(a));
4048 EXPECT_FALSE(m_with_name.Matches(a));
4051 // Tests that Field(&Foo::field, ...) works when field is const.
4052 TEST(FieldTest, WorksForConstField) {
4055 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
4056 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
4057 EXPECT_TRUE(m.Matches(a));
4058 EXPECT_TRUE(m_with_name.Matches(a));
4059 m = Field(&AStruct::y, Le(0.0));
4060 m_with_name = Field("y", &AStruct::y, Le(0.0));
4061 EXPECT_FALSE(m.Matches(a));
4062 EXPECT_FALSE(m_with_name.Matches(a));
4065 // Tests that Field(&Foo::field, ...) works when field is not copyable.
4066 TEST(FieldTest, WorksForUncopyableField) {
4069 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
4070 EXPECT_TRUE(m.Matches(a));
4071 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
4072 EXPECT_FALSE(m.Matches(a));
4075 // Tests that Field(&Foo::field, ...) works when field is a pointer.
4076 TEST(FieldTest, WorksForPointerField) {
4077 // Matching against NULL.
4078 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
4080 EXPECT_TRUE(m.Matches(a));
4082 EXPECT_FALSE(m.Matches(a));
4084 // Matching a pointer that is not NULL.
4085 m = Field(&AStruct::p, StartsWith("hi"));
4087 EXPECT_TRUE(m.Matches(a));
4089 EXPECT_FALSE(m.Matches(a));
4092 // Tests that Field() works when the object is passed by reference.
4093 TEST(FieldTest, WorksForByRefArgument) {
4094 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4097 EXPECT_TRUE(m.Matches(a));
4099 EXPECT_FALSE(m.Matches(a));
4102 // Tests that Field(&Foo::field, ...) works when the argument's type
4103 // is a sub-type of Foo.
4104 TEST(FieldTest, WorksForArgumentOfSubType) {
4105 // Note that the matcher expects DerivedStruct but we say AStruct
4107 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
4110 EXPECT_TRUE(m.Matches(d));
4112 EXPECT_FALSE(m.Matches(d));
4115 // Tests that Field(&Foo::field, m) works when field's type and m's
4116 // argument type are compatible but not the same.
4117 TEST(FieldTest, WorksForCompatibleMatcherType) {
4118 // The field is an int, but the inner matcher expects a signed char.
4119 Matcher<const AStruct&> m = Field(&AStruct::x,
4120 Matcher<signed char>(Ge(0)));
4123 EXPECT_TRUE(m.Matches(a));
4125 EXPECT_FALSE(m.Matches(a));
4128 // Tests that Field() can describe itself.
4129 TEST(FieldTest, CanDescribeSelf) {
4130 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4132 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4133 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4136 TEST(FieldTest, CanDescribeSelfWithFieldName) {
4137 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4139 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4140 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4141 DescribeNegation(m));
4144 // Tests that Field() can explain the match result.
4145 TEST(FieldTest, CanExplainMatchResult) {
4146 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4150 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4152 m = Field(&AStruct::x, GreaterThan(0));
4154 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4158 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4159 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4163 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4165 m = Field("field_name", &AStruct::x, GreaterThan(0));
4166 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4167 ", which is 1 more than 0",
4171 // Tests that Field() works when the argument is a pointer to const.
4172 TEST(FieldForPointerTest, WorksForPointerToConst) {
4173 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4176 EXPECT_TRUE(m.Matches(&a));
4178 EXPECT_FALSE(m.Matches(&a));
4181 // Tests that Field() works when the argument is a pointer to non-const.
4182 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4183 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
4186 EXPECT_TRUE(m.Matches(&a));
4188 EXPECT_FALSE(m.Matches(&a));
4191 // Tests that Field() works when the argument is a reference to a const pointer.
4192 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4193 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
4196 EXPECT_TRUE(m.Matches(&a));
4198 EXPECT_FALSE(m.Matches(&a));
4201 // Tests that Field() does not match the NULL pointer.
4202 TEST(FieldForPointerTest, DoesNotMatchNull) {
4203 Matcher<const AStruct*> m = Field(&AStruct::x, _);
4204 EXPECT_FALSE(m.Matches(nullptr));
4207 // Tests that Field(&Foo::field, ...) works when the argument's type
4208 // is a sub-type of const Foo*.
4209 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4210 // Note that the matcher expects DerivedStruct but we say AStruct
4212 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
4215 EXPECT_TRUE(m.Matches(&d));
4217 EXPECT_FALSE(m.Matches(&d));
4220 // Tests that Field() can describe itself when used to match a pointer.
4221 TEST(FieldForPointerTest, CanDescribeSelf) {
4222 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4224 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4225 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4228 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4229 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4231 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4232 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4233 DescribeNegation(m));
4236 // Tests that Field() can explain the result of matching a pointer.
4237 TEST(FieldForPointerTest, CanExplainMatchResult) {
4238 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4242 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4243 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4246 m = Field(&AStruct::x, GreaterThan(0));
4247 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4248 ", which is 1 more than 0", Explain(m, &a));
4251 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4252 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4256 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4258 "which points to an object whose field `field_name` is 1" + OfType("int"),
4261 m = Field("field_name", &AStruct::x, GreaterThan(0));
4262 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4263 OfType("int") + ", which is 1 more than 0",
4267 // A user-defined class for testing Property().
4272 // A getter that returns a non-reference.
4273 int n() const { return n_; }
4275 void set_n(int new_n) { n_ = new_n; }
4277 // A getter that returns a reference to const.
4278 const std::string& s() const { return s_; }
4280 const std::string& s_ref() const & { return s_; }
4282 void set_s(const std::string& new_s) { s_ = new_s; }
4284 // A getter that returns a reference to non-const.
4285 double& x() const { return x_; }
4294 double AClass::x_ = 0.0;
4296 // A derived class for testing Property().
4297 class DerivedClass : public AClass {
4299 int k() const { return k_; }
4304 // Tests that Property(&Foo::property, ...) works when property()
4305 // returns a non-reference.
4306 TEST(PropertyTest, WorksForNonReferenceProperty) {
4307 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4308 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4312 EXPECT_TRUE(m.Matches(a));
4313 EXPECT_TRUE(m_with_name.Matches(a));
4316 EXPECT_FALSE(m.Matches(a));
4317 EXPECT_FALSE(m_with_name.Matches(a));
4320 // Tests that Property(&Foo::property, ...) works when property()
4321 // returns a reference to const.
4322 TEST(PropertyTest, WorksForReferenceToConstProperty) {
4323 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
4324 Matcher<const AClass&> m_with_name =
4325 Property("s", &AClass::s, StartsWith("hi"));
4329 EXPECT_TRUE(m.Matches(a));
4330 EXPECT_TRUE(m_with_name.Matches(a));
4333 EXPECT_FALSE(m.Matches(a));
4334 EXPECT_FALSE(m_with_name.Matches(a));
4337 // Tests that Property(&Foo::property, ...) works when property() is
4339 TEST(PropertyTest, WorksForRefQualifiedProperty) {
4340 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4341 Matcher<const AClass&> m_with_name =
4342 Property("s", &AClass::s_ref, StartsWith("hi"));
4346 EXPECT_TRUE(m.Matches(a));
4347 EXPECT_TRUE(m_with_name.Matches(a));
4350 EXPECT_FALSE(m.Matches(a));
4351 EXPECT_FALSE(m_with_name.Matches(a));
4354 // Tests that Property(&Foo::property, ...) works when property()
4355 // returns a reference to non-const.
4356 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4360 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4361 EXPECT_FALSE(m.Matches(a));
4363 m = Property(&AClass::x, Not(Ref(x)));
4364 EXPECT_TRUE(m.Matches(a));
4367 // Tests that Property(&Foo::property, ...) works when the argument is
4369 TEST(PropertyTest, WorksForByValueArgument) {
4370 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4374 EXPECT_TRUE(m.Matches(a));
4377 EXPECT_FALSE(m.Matches(a));
4380 // Tests that Property(&Foo::property, ...) works when the argument's
4381 // type is a sub-type of Foo.
4382 TEST(PropertyTest, WorksForArgumentOfSubType) {
4383 // The matcher expects a DerivedClass, but inside the Property() we
4385 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4389 EXPECT_TRUE(m.Matches(d));
4392 EXPECT_FALSE(m.Matches(d));
4395 // Tests that Property(&Foo::property, m) works when property()'s type
4396 // and m's argument type are compatible but different.
4397 TEST(PropertyTest, WorksForCompatibleMatcherType) {
4398 // n() returns an int but the inner matcher expects a signed char.
4399 Matcher<const AClass&> m = Property(&AClass::n,
4400 Matcher<signed char>(Ge(0)));
4402 Matcher<const AClass&> m_with_name =
4403 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4406 EXPECT_TRUE(m.Matches(a));
4407 EXPECT_TRUE(m_with_name.Matches(a));
4409 EXPECT_FALSE(m.Matches(a));
4410 EXPECT_FALSE(m_with_name.Matches(a));
4413 // Tests that Property() can describe itself.
4414 TEST(PropertyTest, CanDescribeSelf) {
4415 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4417 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4418 EXPECT_EQ("is an object whose given property isn't >= 0",
4419 DescribeNegation(m));
4422 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4423 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4425 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4426 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4427 DescribeNegation(m));
4430 // Tests that Property() can explain the match result.
4431 TEST(PropertyTest, CanExplainMatchResult) {
4432 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4436 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4438 m = Property(&AClass::n, GreaterThan(0));
4440 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4444 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4445 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4449 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4451 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4452 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4453 ", which is 1 more than 0",
4457 // Tests that Property() works when the argument is a pointer to const.
4458 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4459 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4463 EXPECT_TRUE(m.Matches(&a));
4466 EXPECT_FALSE(m.Matches(&a));
4469 // Tests that Property() works when the argument is a pointer to non-const.
4470 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4471 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4475 EXPECT_TRUE(m.Matches(&a));
4478 EXPECT_FALSE(m.Matches(&a));
4481 // Tests that Property() works when the argument is a reference to a
4483 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4484 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4488 EXPECT_TRUE(m.Matches(&a));
4491 EXPECT_FALSE(m.Matches(&a));
4494 // Tests that Property() does not match the NULL pointer.
4495 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4496 Matcher<const AClass*> m = Property(&AClass::x, _);
4497 EXPECT_FALSE(m.Matches(nullptr));
4500 // Tests that Property(&Foo::property, ...) works when the argument's
4501 // type is a sub-type of const Foo*.
4502 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4503 // The matcher expects a DerivedClass, but inside the Property() we
4505 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4509 EXPECT_TRUE(m.Matches(&d));
4512 EXPECT_FALSE(m.Matches(&d));
4515 // Tests that Property() can describe itself when used to match a pointer.
4516 TEST(PropertyForPointerTest, CanDescribeSelf) {
4517 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4519 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4520 EXPECT_EQ("is an object whose given property isn't >= 0",
4521 DescribeNegation(m));
4524 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4525 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4527 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4528 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4529 DescribeNegation(m));
4532 // Tests that Property() can explain the result of matching a pointer.
4533 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4534 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4538 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4540 "which points to an object whose given property is 1" + OfType("int"),
4543 m = Property(&AClass::n, GreaterThan(0));
4544 EXPECT_EQ("which points to an object whose given property is 1" +
4545 OfType("int") + ", which is 1 more than 0",
4549 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4550 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4554 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4555 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4559 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4560 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4561 OfType("int") + ", which is 1 more than 0",
4567 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4568 // function pointer.
4569 std::string IntToStringFunction(int input) {
4570 return input == 1 ? "foo" : "bar";
4573 TEST(ResultOfTest, WorksForFunctionPointers) {
4574 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4576 EXPECT_TRUE(matcher.Matches(1));
4577 EXPECT_FALSE(matcher.Matches(2));
4580 // Tests that ResultOf() can describe itself.
4581 TEST(ResultOfTest, CanDescribeItself) {
4582 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4584 EXPECT_EQ("is mapped by the given callable to a value that "
4585 "is equal to \"foo\"", Describe(matcher));
4586 EXPECT_EQ("is mapped by the given callable to a value that "
4587 "isn't equal to \"foo\"", DescribeNegation(matcher));
4590 // Tests that ResultOf() can explain the match result.
4591 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4593 TEST(ResultOfTest, CanExplainMatchResult) {
4594 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4595 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4596 Explain(matcher, 36));
4598 matcher = ResultOf(&IntFunction, GreaterThan(85));
4599 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4600 ", which is 5 more than 85", Explain(matcher, 36));
4603 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4604 // returns a non-reference.
4605 TEST(ResultOfTest, WorksForNonReferenceResults) {
4606 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4608 EXPECT_TRUE(matcher.Matches(42));
4609 EXPECT_FALSE(matcher.Matches(36));
4612 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4613 // returns a reference to non-const.
4614 double& DoubleFunction(double& input) { return input; } // NOLINT
4616 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
4620 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4623 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4625 EXPECT_TRUE(matcher.Matches(x));
4626 EXPECT_FALSE(matcher.Matches(x2));
4628 // Test that ResultOf works with uncopyable objects
4631 Matcher<Uncopyable&> matcher2 =
4632 ResultOf(&RefUncopyableFunction, Ref(obj));
4634 EXPECT_TRUE(matcher2.Matches(obj));
4635 EXPECT_FALSE(matcher2.Matches(obj2));
4638 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4639 // returns a reference to const.
4640 const std::string& StringFunction(const std::string& input) { return input; }
4642 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4643 std::string s = "foo";
4645 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4647 EXPECT_TRUE(matcher.Matches(s));
4648 EXPECT_FALSE(matcher.Matches(s2));
4651 // Tests that ResultOf(f, m) works when f(x) and m's
4652 // argument types are compatible but different.
4653 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4654 // IntFunction() returns int but the inner matcher expects a signed char.
4655 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4657 EXPECT_TRUE(matcher.Matches(36));
4658 EXPECT_FALSE(matcher.Matches(42));
4661 // Tests that the program aborts when ResultOf is passed
4662 // a NULL function pointer.
4663 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4664 EXPECT_DEATH_IF_SUPPORTED(
4665 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4666 Eq(std::string("foo"))),
4667 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4670 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4671 // function reference.
4672 TEST(ResultOfTest, WorksForFunctionReferences) {
4673 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4674 EXPECT_TRUE(matcher.Matches(1));
4675 EXPECT_FALSE(matcher.Matches(2));
4678 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4681 std::string operator()(int input) const {
4682 return IntToStringFunction(input);
4686 TEST(ResultOfTest, WorksForFunctors) {
4687 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4689 EXPECT_TRUE(matcher.Matches(1));
4690 EXPECT_FALSE(matcher.Matches(2));
4693 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4694 // functor with more than one operator() defined. ResultOf() must work
4695 // for each defined operator().
4696 struct PolymorphicFunctor {
4697 typedef int result_type;
4698 int operator()(int n) { return n; }
4699 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
4700 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4703 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4704 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4706 EXPECT_TRUE(matcher_int.Matches(10));
4707 EXPECT_FALSE(matcher_int.Matches(2));
4709 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4711 EXPECT_TRUE(matcher_string.Matches("long string"));
4712 EXPECT_FALSE(matcher_string.Matches("shrt"));
4715 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4716 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4719 EXPECT_TRUE(matcher.Matches(&n));
4720 EXPECT_FALSE(matcher.Matches(nullptr));
4723 TEST(ResultOfTest, WorksForLambdas) {
4724 Matcher<int> matcher = ResultOf(
4726 return std::string(static_cast<size_t>(str_len), 'x');
4729 EXPECT_TRUE(matcher.Matches(3));
4730 EXPECT_FALSE(matcher.Matches(1));
4733 TEST(ResultOfTest, WorksForNonCopyableArguments) {
4734 Matcher<std::unique_ptr<int>> matcher = ResultOf(
4735 [](const std::unique_ptr<int>& str_len) {
4736 return std::string(static_cast<size_t>(*str_len), 'x');
4739 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4740 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4743 const int* ReferencingFunction(const int& n) { return &n; }
4745 struct ReferencingFunctor {
4746 typedef const int* result_type;
4747 result_type operator()(const int& n) { return &n; }
4750 TEST(ResultOfTest, WorksForReferencingCallables) {
4753 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4754 EXPECT_TRUE(matcher2.Matches(n));
4755 EXPECT_FALSE(matcher2.Matches(n2));
4757 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4758 EXPECT_TRUE(matcher3.Matches(n));
4759 EXPECT_FALSE(matcher3.Matches(n2));
4762 class DivisibleByImpl {
4764 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4766 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4767 template <typename T>
4768 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4769 *listener << "which is " << (n % divider_) << " modulo "
4771 return (n % divider_) == 0;
4774 void DescribeTo(ostream* os) const {
4775 *os << "is divisible by " << divider_;
4778 void DescribeNegationTo(ostream* os) const {
4779 *os << "is not divisible by " << divider_;
4782 void set_divider(int a_divider) { divider_ = a_divider; }
4783 int divider() const { return divider_; }
4789 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4790 return MakePolymorphicMatcher(DivisibleByImpl(n));
4793 // Tests that when AllOf() fails, only the first failing matcher is
4794 // asked to explain why.
4795 TEST(ExplainMatchResultTest, AllOf_False_False) {
4796 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4797 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4800 // Tests that when AllOf() fails, only the first failing matcher is
4801 // asked to explain why.
4802 TEST(ExplainMatchResultTest, AllOf_False_True) {
4803 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4804 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4807 // Tests that when AllOf() fails, only the first failing matcher is
4808 // asked to explain why.
4809 TEST(ExplainMatchResultTest, AllOf_True_False) {
4810 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4811 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4814 // Tests that when AllOf() succeeds, all matchers are asked to explain
4816 TEST(ExplainMatchResultTest, AllOf_True_True) {
4817 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4818 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4821 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4822 const Matcher<int> m = AllOf(Ge(2), Le(3));
4823 EXPECT_EQ("", Explain(m, 2));
4826 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4827 const Matcher<int> m = GreaterThan(5);
4828 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4831 // The following two tests verify that values without a public copy
4832 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4833 // with the help of ByRef().
4837 explicit NotCopyable(int a_value) : value_(a_value) {}
4839 int value() const { return value_; }
4841 bool operator==(const NotCopyable& rhs) const {
4842 return value() == rhs.value();
4845 bool operator>=(const NotCopyable& rhs) const {
4846 return value() >= rhs.value();
4851 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4854 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4855 const NotCopyable const_value1(1);
4856 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4858 const NotCopyable n1(1), n2(2);
4859 EXPECT_TRUE(m.Matches(n1));
4860 EXPECT_FALSE(m.Matches(n2));
4863 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4864 NotCopyable value2(2);
4865 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4867 NotCopyable n1(1), n2(2);
4868 EXPECT_FALSE(m.Matches(n1));
4869 EXPECT_TRUE(m.Matches(n2));
4872 TEST(IsEmptyTest, ImplementsIsEmpty) {
4873 vector<int> container;
4874 EXPECT_THAT(container, IsEmpty());
4875 container.push_back(0);
4876 EXPECT_THAT(container, Not(IsEmpty()));
4877 container.push_back(1);
4878 EXPECT_THAT(container, Not(IsEmpty()));
4881 TEST(IsEmptyTest, WorksWithString) {
4883 EXPECT_THAT(text, IsEmpty());
4885 EXPECT_THAT(text, Not(IsEmpty()));
4886 text = std::string("\0", 1);
4887 EXPECT_THAT(text, Not(IsEmpty()));
4890 TEST(IsEmptyTest, CanDescribeSelf) {
4891 Matcher<vector<int> > m = IsEmpty();
4892 EXPECT_EQ("is empty", Describe(m));
4893 EXPECT_EQ("isn't empty", DescribeNegation(m));
4896 TEST(IsEmptyTest, ExplainsResult) {
4897 Matcher<vector<int> > m = IsEmpty();
4898 vector<int> container;
4899 EXPECT_EQ("", Explain(m, container));
4900 container.push_back(0);
4901 EXPECT_EQ("whose size is 1", Explain(m, container));
4904 TEST(IsEmptyTest, WorksWithMoveOnly) {
4905 ContainerHelper helper;
4906 EXPECT_CALL(helper, Call(IsEmpty()));
4910 TEST(IsTrueTest, IsTrueIsFalse) {
4911 EXPECT_THAT(true, IsTrue());
4912 EXPECT_THAT(false, IsFalse());
4913 EXPECT_THAT(true, Not(IsFalse()));
4914 EXPECT_THAT(false, Not(IsTrue()));
4915 EXPECT_THAT(0, Not(IsTrue()));
4916 EXPECT_THAT(0, IsFalse());
4917 EXPECT_THAT(nullptr, Not(IsTrue()));
4918 EXPECT_THAT(nullptr, IsFalse());
4919 EXPECT_THAT(-1, IsTrue());
4920 EXPECT_THAT(-1, Not(IsFalse()));
4921 EXPECT_THAT(1, IsTrue());
4922 EXPECT_THAT(1, Not(IsFalse()));
4923 EXPECT_THAT(2, IsTrue());
4924 EXPECT_THAT(2, Not(IsFalse()));
4926 EXPECT_THAT(a, IsTrue());
4927 EXPECT_THAT(a, Not(IsFalse()));
4928 EXPECT_THAT(&a, IsTrue());
4929 EXPECT_THAT(&a, Not(IsFalse()));
4930 EXPECT_THAT(false, Not(IsTrue()));
4931 EXPECT_THAT(true, Not(IsFalse()));
4932 EXPECT_THAT(std::true_type(), IsTrue());
4933 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4934 EXPECT_THAT(std::false_type(), IsFalse());
4935 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4936 EXPECT_THAT(nullptr, Not(IsTrue()));
4937 EXPECT_THAT(nullptr, IsFalse());
4938 std::unique_ptr<int> null_unique;
4939 std::unique_ptr<int> nonnull_unique(new int(0));
4940 EXPECT_THAT(null_unique, Not(IsTrue()));
4941 EXPECT_THAT(null_unique, IsFalse());
4942 EXPECT_THAT(nonnull_unique, IsTrue());
4943 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4946 TEST(SizeIsTest, ImplementsSizeIs) {
4947 vector<int> container;
4948 EXPECT_THAT(container, SizeIs(0));
4949 EXPECT_THAT(container, Not(SizeIs(1)));
4950 container.push_back(0);
4951 EXPECT_THAT(container, Not(SizeIs(0)));
4952 EXPECT_THAT(container, SizeIs(1));
4953 container.push_back(0);
4954 EXPECT_THAT(container, Not(SizeIs(0)));
4955 EXPECT_THAT(container, SizeIs(2));
4958 TEST(SizeIsTest, WorksWithMap) {
4959 map<std::string, int> container;
4960 EXPECT_THAT(container, SizeIs(0));
4961 EXPECT_THAT(container, Not(SizeIs(1)));
4962 container.insert(make_pair("foo", 1));
4963 EXPECT_THAT(container, Not(SizeIs(0)));
4964 EXPECT_THAT(container, SizeIs(1));
4965 container.insert(make_pair("bar", 2));
4966 EXPECT_THAT(container, Not(SizeIs(0)));
4967 EXPECT_THAT(container, SizeIs(2));
4970 TEST(SizeIsTest, WorksWithReferences) {
4971 vector<int> container;
4972 Matcher<const vector<int>&> m = SizeIs(1);
4973 EXPECT_THAT(container, Not(m));
4974 container.push_back(0);
4975 EXPECT_THAT(container, m);
4978 TEST(SizeIsTest, WorksWithMoveOnly) {
4979 ContainerHelper helper;
4980 EXPECT_CALL(helper, Call(SizeIs(3)));
4981 helper.Call(MakeUniquePtrs({1, 2, 3}));
4984 // SizeIs should work for any type that provides a size() member function.
4985 // For example, a size_type member type should not need to be provided.
4986 struct MinimalistCustomType {
4987 int size() const { return 1; }
4989 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4990 MinimalistCustomType container;
4991 EXPECT_THAT(container, SizeIs(1));
4992 EXPECT_THAT(container, Not(SizeIs(0)));
4995 TEST(SizeIsTest, CanDescribeSelf) {
4996 Matcher<vector<int> > m = SizeIs(2);
4997 EXPECT_EQ("size is equal to 2", Describe(m));
4998 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
5001 TEST(SizeIsTest, ExplainsResult) {
5002 Matcher<vector<int> > m1 = SizeIs(2);
5003 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
5004 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
5005 Matcher<vector<int> > m4 = SizeIs(Gt(1u));
5006 vector<int> container;
5007 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
5008 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
5009 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
5010 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
5011 container.push_back(0);
5012 container.push_back(0);
5013 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
5014 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
5015 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
5016 EXPECT_EQ("whose size 2 matches", Explain(m4, container));
5019 #if GTEST_HAS_TYPED_TEST
5020 // Tests ContainerEq with different container types, and
5021 // different element types.
5023 template <typename T>
5024 class ContainerEqTest : public testing::Test {};
5026 typedef testing::Types<
5031 ContainerEqTestTypes;
5033 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
5035 // Tests that the filled container is equal to itself.
5036 TYPED_TEST(ContainerEqTest, EqualsSelf) {
5037 static const int vals[] = {1, 1, 2, 3, 5, 8};
5038 TypeParam my_set(vals, vals + 6);
5039 const Matcher<TypeParam> m = ContainerEq(my_set);
5040 EXPECT_TRUE(m.Matches(my_set));
5041 EXPECT_EQ("", Explain(m, my_set));
5044 // Tests that missing values are reported.
5045 TYPED_TEST(ContainerEqTest, ValueMissing) {
5046 static const int vals[] = {1, 1, 2, 3, 5, 8};
5047 static const int test_vals[] = {2, 1, 8, 5};
5048 TypeParam my_set(vals, vals + 6);
5049 TypeParam test_set(test_vals, test_vals + 4);
5050 const Matcher<TypeParam> m = ContainerEq(my_set);
5051 EXPECT_FALSE(m.Matches(test_set));
5052 EXPECT_EQ("which doesn't have these expected elements: 3",
5053 Explain(m, test_set));
5056 // Tests that added values are reported.
5057 TYPED_TEST(ContainerEqTest, ValueAdded) {
5058 static const int vals[] = {1, 1, 2, 3, 5, 8};
5059 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
5060 TypeParam my_set(vals, vals + 6);
5061 TypeParam test_set(test_vals, test_vals + 6);
5062 const Matcher<const TypeParam&> m = ContainerEq(my_set);
5063 EXPECT_FALSE(m.Matches(test_set));
5064 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
5067 // Tests that added and missing values are reported together.
5068 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
5069 static const int vals[] = {1, 1, 2, 3, 5, 8};
5070 static const int test_vals[] = {1, 2, 3, 8, 46};
5071 TypeParam my_set(vals, vals + 6);
5072 TypeParam test_set(test_vals, test_vals + 5);
5073 const Matcher<TypeParam> m = ContainerEq(my_set);
5074 EXPECT_FALSE(m.Matches(test_set));
5075 EXPECT_EQ("which has these unexpected elements: 46,\n"
5076 "and doesn't have these expected elements: 5",
5077 Explain(m, test_set));
5080 // Tests duplicated value -- expect no explanation.
5081 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
5082 static const int vals[] = {1, 1, 2, 3, 5, 8};
5083 static const int test_vals[] = {1, 2, 3, 5, 8};
5084 TypeParam my_set(vals, vals + 6);
5085 TypeParam test_set(test_vals, test_vals + 5);
5086 const Matcher<const TypeParam&> m = ContainerEq(my_set);
5087 // Depending on the container, match may be true or false
5088 // But in any case there should be no explanation.
5089 EXPECT_EQ("", Explain(m, test_set));
5091 #endif // GTEST_HAS_TYPED_TEST
5093 // Tests that multiple missing values are reported.
5094 // Using just vector here, so order is predictable.
5095 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
5096 static const int vals[] = {1, 1, 2, 3, 5, 8};
5097 static const int test_vals[] = {2, 1, 5};
5098 vector<int> my_set(vals, vals + 6);
5099 vector<int> test_set(test_vals, test_vals + 3);
5100 const Matcher<vector<int> > m = ContainerEq(my_set);
5101 EXPECT_FALSE(m.Matches(test_set));
5102 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
5103 Explain(m, test_set));
5106 // Tests that added values are reported.
5107 // Using just vector here, so order is predictable.
5108 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
5109 static const int vals[] = {1, 1, 2, 3, 5, 8};
5110 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
5111 list<size_t> my_set(vals, vals + 6);
5112 list<size_t> test_set(test_vals, test_vals + 7);
5113 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
5114 EXPECT_FALSE(m.Matches(test_set));
5115 EXPECT_EQ("which has these unexpected elements: 92, 46",
5116 Explain(m, test_set));
5119 // Tests that added and missing values are reported together.
5120 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
5121 static const int vals[] = {1, 1, 2, 3, 5, 8};
5122 static const int test_vals[] = {1, 2, 3, 92, 46};
5123 list<size_t> my_set(vals, vals + 6);
5124 list<size_t> test_set(test_vals, test_vals + 5);
5125 const Matcher<const list<size_t> > m = ContainerEq(my_set);
5126 EXPECT_FALSE(m.Matches(test_set));
5127 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
5128 "and doesn't have these expected elements: 5, 8",
5129 Explain(m, test_set));
5132 // Tests to see that duplicate elements are detected,
5133 // but (as above) not reported in the explanation.
5134 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
5135 static const int vals[] = {1, 1, 2, 3, 5, 8};
5136 static const int test_vals[] = {1, 2, 3, 5, 8};
5137 vector<int> my_set(vals, vals + 6);
5138 vector<int> test_set(test_vals, test_vals + 5);
5139 const Matcher<vector<int> > m = ContainerEq(my_set);
5140 EXPECT_TRUE(m.Matches(my_set));
5141 EXPECT_FALSE(m.Matches(test_set));
5142 // There is nothing to report when both sets contain all the same values.
5143 EXPECT_EQ("", Explain(m, test_set));
5146 // Tests that ContainerEq works for non-trivial associative containers,
5148 TEST(ContainerEqExtraTest, WorksForMaps) {
5149 map<int, std::string> my_map;
5153 map<int, std::string> test_map;
5157 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
5158 EXPECT_TRUE(m.Matches(my_map));
5159 EXPECT_FALSE(m.Matches(test_map));
5161 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
5162 "and doesn't have these expected elements: (0, \"a\")",
5163 Explain(m, test_map));
5166 TEST(ContainerEqExtraTest, WorksForNativeArray) {
5167 int a1[] = {1, 2, 3};
5168 int a2[] = {1, 2, 3};
5169 int b[] = {1, 2, 4};
5171 EXPECT_THAT(a1, ContainerEq(a2));
5172 EXPECT_THAT(a1, Not(ContainerEq(b)));
5175 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5176 const char a1[][3] = {"hi", "lo"};
5177 const char a2[][3] = {"hi", "lo"};
5178 const char b[][3] = {"lo", "hi"};
5180 // Tests using ContainerEq() in the first dimension.
5181 EXPECT_THAT(a1, ContainerEq(a2));
5182 EXPECT_THAT(a1, Not(ContainerEq(b)));
5184 // Tests using ContainerEq() in the second dimension.
5185 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5186 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5189 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5190 const int a1[] = {1, 2, 3};
5191 const int a2[] = {1, 2, 3};
5192 const int b[] = {1, 2, 3, 4};
5194 const int* const p1 = a1;
5195 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
5196 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
5198 const int c[] = {1, 3, 2};
5199 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
5202 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5203 std::string a1[][3] = {
5204 {"hi", "hello", "ciao"},
5205 {"bye", "see you", "ciao"}
5208 std::string a2[][3] = {
5209 {"hi", "hello", "ciao"},
5210 {"bye", "see you", "ciao"}
5213 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5220 TEST(WhenSortedByTest, WorksForEmptyContainer) {
5221 const vector<int> numbers;
5222 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
5223 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
5226 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
5227 vector<unsigned> numbers;
5228 numbers.push_back(3);
5229 numbers.push_back(1);
5230 numbers.push_back(2);
5231 numbers.push_back(2);
5232 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
5233 ElementsAre(3, 2, 2, 1)));
5234 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
5235 ElementsAre(1, 2, 2, 3))));
5238 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
5239 list<std::string> words;
5240 words.push_back("say");
5241 words.push_back("hello");
5242 words.push_back("world");
5243 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
5244 ElementsAre("hello", "say", "world")));
5245 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
5246 ElementsAre("say", "hello", "world"))));
5249 TEST(WhenSortedByTest, WorksForNativeArray) {
5250 const int numbers[] = {1, 3, 2, 4};
5251 const int sorted_numbers[] = {1, 2, 3, 4};
5252 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
5253 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
5254 ElementsAreArray(sorted_numbers)));
5255 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5258 TEST(WhenSortedByTest, CanDescribeSelf) {
5259 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
5260 EXPECT_EQ("(when sorted) has 2 elements where\n"
5261 "element #0 is equal to 1,\n"
5262 "element #1 is equal to 2",
5264 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5265 "element #0 isn't equal to 1, or\n"
5266 "element #1 isn't equal to 2",
5267 DescribeNegation(m));
5270 TEST(WhenSortedByTest, ExplainsMatchResult) {
5271 const int a[] = {2, 1};
5272 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5273 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
5274 EXPECT_EQ("which is { 1, 2 } when sorted",
5275 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
5278 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5279 // need to test it as exhaustively as we test the latter.
5281 TEST(WhenSortedTest, WorksForEmptyContainer) {
5282 const vector<int> numbers;
5283 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5284 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5287 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
5288 list<std::string> words;
5289 words.push_back("3");
5290 words.push_back("1");
5291 words.push_back("2");
5292 words.push_back("2");
5293 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
5294 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5297 TEST(WhenSortedTest, WorksForMapTypes) {
5298 map<std::string, int> word_counts;
5299 word_counts["and"] = 1;
5300 word_counts["the"] = 1;
5301 word_counts["buffalo"] = 2;
5302 EXPECT_THAT(word_counts,
5303 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5305 EXPECT_THAT(word_counts,
5306 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5307 Pair("buffalo", 2)))));
5310 TEST(WhenSortedTest, WorksForMultiMapTypes) {
5311 multimap<int, int> ifib;
5312 ifib.insert(make_pair(8, 6));
5313 ifib.insert(make_pair(2, 3));
5314 ifib.insert(make_pair(1, 1));
5315 ifib.insert(make_pair(3, 4));
5316 ifib.insert(make_pair(1, 2));
5317 ifib.insert(make_pair(5, 5));
5318 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5324 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5332 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5336 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5337 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5340 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5344 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5345 EXPECT_THAT(d, WhenSorted(vector_match));
5346 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5347 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5350 // Deliberately bare pseudo-container.
5351 // Offers only begin() and end() accessors, yielding InputIterator.
5352 template <typename T>
5357 typedef ConstIter const_iterator;
5358 typedef T value_type;
5360 template <typename InIter>
5361 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5363 const_iterator begin() const {
5364 return const_iterator(this, remainder_.begin());
5366 const_iterator end() const {
5367 return const_iterator(this, remainder_.end());
5371 class ConstIter : public std::iterator<std::input_iterator_tag,
5375 const value_type&> {
5377 ConstIter(const Streamlike* s,
5378 typename std::list<value_type>::iterator pos)
5379 : s_(s), pos_(pos) {}
5381 const value_type& operator*() const { return *pos_; }
5382 const value_type* operator->() const { return &*pos_; }
5383 ConstIter& operator++() {
5384 s_->remainder_.erase(pos_++);
5388 // *iter++ is required to work (see std::istreambuf_iterator).
5389 // (void)iter++ is also required to work.
5390 class PostIncrProxy {
5392 explicit PostIncrProxy(const value_type& value) : value_(value) {}
5393 value_type operator*() const { return value_; }
5397 PostIncrProxy operator++(int) {
5398 PostIncrProxy proxy(**this);
5403 friend bool operator==(const ConstIter& a, const ConstIter& b) {
5404 return a.s_ == b.s_ && a.pos_ == b.pos_;
5406 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5411 const Streamlike* s_;
5412 typename std::list<value_type>::iterator pos_;
5415 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5417 typedef typename std::list<value_type>::const_iterator Iter;
5418 const char* sep = "";
5419 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5427 mutable std::list<value_type> remainder_; // modified by iteration
5430 TEST(StreamlikeTest, Iteration) {
5431 const int a[5] = {2, 1, 4, 5, 3};
5432 Streamlike<int> s(a, a + 5);
5433 Streamlike<int>::const_iterator it = s.begin();
5435 while (it != s.end()) {
5436 SCOPED_TRACE(ip - a);
5437 EXPECT_EQ(*ip++, *it++);
5441 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5442 std::forward_list<int> container;
5443 EXPECT_THAT(container, BeginEndDistanceIs(0));
5444 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5445 container.push_front(0);
5446 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5447 EXPECT_THAT(container, BeginEndDistanceIs(1));
5448 container.push_front(0);
5449 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5450 EXPECT_THAT(container, BeginEndDistanceIs(2));
5453 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5454 const int a[5] = {1, 2, 3, 4, 5};
5455 Streamlike<int> s(a, a + 5);
5456 EXPECT_THAT(s, BeginEndDistanceIs(5));
5459 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5460 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5461 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5462 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5463 DescribeNegation(m));
5466 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5467 ContainerHelper helper;
5468 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5469 helper.Call(MakeUniquePtrs({1, 2}));
5472 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5473 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5474 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5475 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5476 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5477 vector<int> container;
5478 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5479 Explain(m1, container));
5480 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5481 Explain(m2, container));
5482 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5483 Explain(m3, container));
5485 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5487 Explain(m4, container));
5488 container.push_back(0);
5489 container.push_back(0);
5490 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5491 Explain(m1, container));
5492 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5493 Explain(m2, container));
5494 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5495 Explain(m3, container));
5497 "whose distance between begin() and end() 2 matches, which is 1 more "
5499 Explain(m4, container));
5502 TEST(WhenSortedTest, WorksForStreamlike) {
5503 // Streamlike 'container' provides only minimal iterator support.
5504 // Its iterators are tagged with input_iterator_tag.
5505 const int a[5] = {2, 1, 4, 5, 3};
5506 Streamlike<int> s(std::begin(a), std::end(a));
5507 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5508 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5511 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5512 const int a[] = {2, 1, 4, 5, 3};
5513 Streamlike<int> s(std::begin(a), std::end(a));
5514 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5515 EXPECT_THAT(s, WhenSorted(vector_match));
5516 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5519 TEST(IsSupersetOfTest, WorksForNativeArray) {
5520 const int subset[] = {1, 4};
5521 const int superset[] = {1, 2, 4};
5522 const int disjoint[] = {1, 0, 3};
5523 EXPECT_THAT(subset, IsSupersetOf(subset));
5524 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5525 EXPECT_THAT(superset, IsSupersetOf(subset));
5526 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5527 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5530 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5531 const int not_enough[] = {1, 2};
5532 const int enough[] = {1, 1, 2};
5533 const int expected[] = {1, 1};
5534 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5535 EXPECT_THAT(enough, IsSupersetOf(expected));
5538 TEST(IsSupersetOfTest, WorksForEmpty) {
5539 vector<int> numbers;
5540 vector<int> expected;
5541 EXPECT_THAT(numbers, IsSupersetOf(expected));
5542 expected.push_back(1);
5543 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5545 numbers.push_back(1);
5546 numbers.push_back(2);
5547 EXPECT_THAT(numbers, IsSupersetOf(expected));
5548 expected.push_back(1);
5549 EXPECT_THAT(numbers, IsSupersetOf(expected));
5550 expected.push_back(2);
5551 EXPECT_THAT(numbers, IsSupersetOf(expected));
5552 expected.push_back(3);
5553 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5556 TEST(IsSupersetOfTest, WorksForStreamlike) {
5557 const int a[5] = {1, 2, 3, 4, 5};
5558 Streamlike<int> s(std::begin(a), std::end(a));
5560 vector<int> expected;
5561 expected.push_back(1);
5562 expected.push_back(2);
5563 expected.push_back(5);
5564 EXPECT_THAT(s, IsSupersetOf(expected));
5566 expected.push_back(0);
5567 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5570 TEST(IsSupersetOfTest, TakesStlContainer) {
5571 const int actual[] = {3, 1, 2};
5573 ::std::list<int> expected;
5574 expected.push_back(1);
5575 expected.push_back(3);
5576 EXPECT_THAT(actual, IsSupersetOf(expected));
5578 expected.push_back(4);
5579 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5582 TEST(IsSupersetOfTest, Describe) {
5583 typedef std::vector<int> IntVec;
5585 expected.push_back(111);
5586 expected.push_back(222);
5587 expected.push_back(333);
5589 Describe<IntVec>(IsSupersetOf(expected)),
5590 Eq("a surjection from elements to requirements exists such that:\n"
5591 " - an element is equal to 111\n"
5592 " - an element is equal to 222\n"
5593 " - an element is equal to 333"));
5596 TEST(IsSupersetOfTest, DescribeNegation) {
5597 typedef std::vector<int> IntVec;
5599 expected.push_back(111);
5600 expected.push_back(222);
5601 expected.push_back(333);
5603 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5604 Eq("no surjection from elements to requirements exists such that:\n"
5605 " - an element is equal to 111\n"
5606 " - an element is equal to 222\n"
5607 " - an element is equal to 333"));
5610 TEST(IsSupersetOfTest, MatchAndExplain) {
5614 std::vector<int> expected;
5615 expected.push_back(1);
5616 expected.push_back(2);
5617 StringMatchResultListener listener;
5618 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5620 EXPECT_THAT(listener.str(),
5621 Eq("where the following matchers don't match any elements:\n"
5622 "matcher #0: is equal to 1"));
5626 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5628 EXPECT_THAT(listener.str(), Eq("where:\n"
5629 " - element #0 is matched by matcher #1,\n"
5630 " - element #2 is matched by matcher #0"));
5633 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5634 const int numbers[] = {1, 3, 6, 2, 4, 5};
5635 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5636 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5639 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5640 ContainerHelper helper;
5641 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5642 helper.Call(MakeUniquePtrs({1, 2}));
5643 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5644 helper.Call(MakeUniquePtrs({2}));
5647 TEST(IsSubsetOfTest, WorksForNativeArray) {
5648 const int subset[] = {1, 4};
5649 const int superset[] = {1, 2, 4};
5650 const int disjoint[] = {1, 0, 3};
5651 EXPECT_THAT(subset, IsSubsetOf(subset));
5652 EXPECT_THAT(subset, IsSubsetOf(superset));
5653 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5654 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5655 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5658 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5659 const int not_enough[] = {1, 2};
5660 const int enough[] = {1, 1, 2};
5661 const int actual[] = {1, 1};
5662 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5663 EXPECT_THAT(actual, IsSubsetOf(enough));
5666 TEST(IsSubsetOfTest, WorksForEmpty) {
5667 vector<int> numbers;
5668 vector<int> expected;
5669 EXPECT_THAT(numbers, IsSubsetOf(expected));
5670 expected.push_back(1);
5671 EXPECT_THAT(numbers, IsSubsetOf(expected));
5673 numbers.push_back(1);
5674 numbers.push_back(2);
5675 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5676 expected.push_back(1);
5677 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5678 expected.push_back(2);
5679 EXPECT_THAT(numbers, IsSubsetOf(expected));
5680 expected.push_back(3);
5681 EXPECT_THAT(numbers, IsSubsetOf(expected));
5684 TEST(IsSubsetOfTest, WorksForStreamlike) {
5685 const int a[5] = {1, 2};
5686 Streamlike<int> s(std::begin(a), std::end(a));
5688 vector<int> expected;
5689 expected.push_back(1);
5690 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5691 expected.push_back(2);
5692 expected.push_back(5);
5693 EXPECT_THAT(s, IsSubsetOf(expected));
5696 TEST(IsSubsetOfTest, TakesStlContainer) {
5697 const int actual[] = {3, 1, 2};
5699 ::std::list<int> expected;
5700 expected.push_back(1);
5701 expected.push_back(3);
5702 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5704 expected.push_back(2);
5705 expected.push_back(4);
5706 EXPECT_THAT(actual, IsSubsetOf(expected));
5709 TEST(IsSubsetOfTest, Describe) {
5710 typedef std::vector<int> IntVec;
5712 expected.push_back(111);
5713 expected.push_back(222);
5714 expected.push_back(333);
5717 Describe<IntVec>(IsSubsetOf(expected)),
5718 Eq("an injection from elements to requirements exists such that:\n"
5719 " - an element is equal to 111\n"
5720 " - an element is equal to 222\n"
5721 " - an element is equal to 333"));
5724 TEST(IsSubsetOfTest, DescribeNegation) {
5725 typedef std::vector<int> IntVec;
5727 expected.push_back(111);
5728 expected.push_back(222);
5729 expected.push_back(333);
5731 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5732 Eq("no injection from elements to requirements exists such that:\n"
5733 " - an element is equal to 111\n"
5734 " - an element is equal to 222\n"
5735 " - an element is equal to 333"));
5738 TEST(IsSubsetOfTest, MatchAndExplain) {
5742 std::vector<int> expected;
5743 expected.push_back(1);
5744 expected.push_back(2);
5745 StringMatchResultListener listener;
5746 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5748 EXPECT_THAT(listener.str(),
5749 Eq("where the following elements don't match any matchers:\n"
5752 expected.push_back(3);
5754 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5756 EXPECT_THAT(listener.str(), Eq("where:\n"
5757 " - element #0 is matched by matcher #1,\n"
5758 " - element #1 is matched by matcher #2"));
5761 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5762 const int numbers[] = {1, 2, 3};
5763 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5764 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5767 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5768 ContainerHelper helper;
5769 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5770 helper.Call(MakeUniquePtrs({1}));
5771 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5772 helper.Call(MakeUniquePtrs({2}));
5775 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5778 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5779 const int a[5] = {1, 2, 3, 4, 5};
5780 Streamlike<int> s(std::begin(a), std::end(a));
5781 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5782 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5785 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5786 const int a[5] = {1, 2, 3, 4, 5};
5787 Streamlike<int> s(std::begin(a), std::end(a));
5789 vector<int> expected;
5790 expected.push_back(1);
5791 expected.push_back(2);
5792 expected.push_back(3);
5793 expected.push_back(4);
5794 expected.push_back(5);
5795 EXPECT_THAT(s, ElementsAreArray(expected));
5798 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5801 TEST(ElementsAreTest, WorksWithUncopyable) {
5803 objs[0].set_value(-3);
5804 objs[1].set_value(1);
5805 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5808 TEST(ElementsAreTest, WorksWithMoveOnly) {
5809 ContainerHelper helper;
5810 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5811 helper.Call(MakeUniquePtrs({1, 2}));
5813 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5814 helper.Call(MakeUniquePtrs({3, 4}));
5817 TEST(ElementsAreTest, TakesStlContainer) {
5818 const int actual[] = {3, 1, 2};
5820 ::std::list<int> expected;
5821 expected.push_back(3);
5822 expected.push_back(1);
5823 expected.push_back(2);
5824 EXPECT_THAT(actual, ElementsAreArray(expected));
5826 expected.push_back(4);
5827 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5830 // Tests for UnorderedElementsAreArray()
5832 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5833 const int a[] = {0, 1, 2, 3, 4};
5834 std::vector<int> s(std::begin(a), std::end(a));
5836 StringMatchResultListener listener;
5837 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5838 s, &listener)) << listener.str();
5839 } while (std::next_permutation(s.begin(), s.end()));
5842 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5843 const bool a[] = {0, 1, 0, 1, 1};
5844 const bool b[] = {1, 0, 1, 1, 0};
5845 std::vector<bool> expected(std::begin(a), std::end(a));
5846 std::vector<bool> actual(std::begin(b), std::end(b));
5847 StringMatchResultListener listener;
5848 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5849 actual, &listener)) << listener.str();
5852 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5853 // Streamlike 'container' provides only minimal iterator support.
5854 // Its iterators are tagged with input_iterator_tag, and it has no
5855 // size() or empty() methods.
5856 const int a[5] = {2, 1, 4, 5, 3};
5857 Streamlike<int> s(std::begin(a), std::end(a));
5859 ::std::vector<int> expected;
5860 expected.push_back(1);
5861 expected.push_back(2);
5862 expected.push_back(3);
5863 expected.push_back(4);
5864 expected.push_back(5);
5865 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5867 expected.push_back(6);
5868 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5871 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5872 const int actual[] = {3, 1, 2};
5874 ::std::list<int> expected;
5875 expected.push_back(1);
5876 expected.push_back(2);
5877 expected.push_back(3);
5878 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5880 expected.push_back(4);
5881 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5885 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5886 const int a[5] = {2, 1, 4, 5, 3};
5887 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5888 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5891 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5892 const std::string a[5] = {"a", "b", "c", "d", "e"};
5893 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5894 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5897 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5898 const int a[5] = {2, 1, 4, 5, 3};
5899 EXPECT_THAT(a, UnorderedElementsAreArray(
5900 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5901 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5902 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5905 TEST(UnorderedElementsAreArrayTest,
5906 TakesInitializerListOfDifferentTypedMatchers) {
5907 const int a[5] = {2, 1, 4, 5, 3};
5908 // The compiler cannot infer the type of the initializer list if its
5909 // elements have different types. We must explicitly specify the
5910 // unified element type in this case.
5911 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5912 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5913 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5914 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5918 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5919 ContainerHelper helper;
5921 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5922 helper.Call(MakeUniquePtrs({2, 1}));
5925 class UnorderedElementsAreTest : public testing::Test {
5927 typedef std::vector<int> IntVec;
5930 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5932 objs[0].set_value(-3);
5933 objs[1].set_value(1);
5935 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5938 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5939 const int a[] = {1, 2, 3};
5940 std::vector<int> s(std::begin(a), std::end(a));
5942 StringMatchResultListener listener;
5943 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5944 s, &listener)) << listener.str();
5945 } while (std::next_permutation(s.begin(), s.end()));
5948 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5949 const int a[] = {1, 2, 3};
5950 std::vector<int> s(std::begin(a), std::end(a));
5951 std::vector<Matcher<int> > mv;
5955 // The element with value '3' matches nothing: fail fast.
5956 StringMatchResultListener listener;
5957 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5958 s, &listener)) << listener.str();
5961 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5962 // Streamlike 'container' provides only minimal iterator support.
5963 // Its iterators are tagged with input_iterator_tag, and it has no
5964 // size() or empty() methods.
5965 const int a[5] = {2, 1, 4, 5, 3};
5966 Streamlike<int> s(std::begin(a), std::end(a));
5968 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5969 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5972 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5973 ContainerHelper helper;
5974 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5975 helper.Call(MakeUniquePtrs({2, 1}));
5978 // One naive implementation of the matcher runs in O(N!) time, which is too
5979 // slow for many real-world inputs. This test shows that our matcher can match
5980 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5981 // iterations and obviously effectively incomputable.
5982 // [ RUN ] UnorderedElementsAreTest.Performance
5983 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
5984 TEST_F(UnorderedElementsAreTest, Performance) {
5986 std::vector<Matcher<int> > mv;
5987 for (int i = 0; i < 100; ++i) {
5992 StringMatchResultListener listener;
5993 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5994 s, &listener)) << listener.str();
5997 // Another variant of 'Performance' with similar expectations.
5998 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5999 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
6000 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
6002 std::vector<Matcher<int> > mv;
6003 for (int i = 0; i < 100; ++i) {
6011 StringMatchResultListener listener;
6012 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
6013 s, &listener)) << listener.str();
6016 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
6019 StringMatchResultListener listener;
6020 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6021 v, &listener)) << listener.str();
6022 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
6025 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
6027 StringMatchResultListener listener;
6028 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6029 v, &listener)) << listener.str();
6030 EXPECT_THAT(listener.str(), Eq(""));
6033 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
6037 StringMatchResultListener listener;
6038 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6039 v, &listener)) << listener.str();
6042 Eq("where the following matchers don't match any elements:\n"
6043 "matcher #1: is equal to 2"));
6046 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
6050 StringMatchResultListener listener;
6051 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
6052 v, &listener)) << listener.str();
6055 Eq("where the following elements don't match any matchers:\n"
6059 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
6063 StringMatchResultListener listener;
6064 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6065 v, &listener)) << listener.str();
6069 " the following matchers don't match any elements:\n"
6070 "matcher #0: is equal to 1\n"
6073 " the following elements don't match any matchers:\n"
6077 // Test helper for formatting element, matcher index pairs in expectations.
6078 static std::string EMString(int element, int matcher) {
6080 ss << "(element #" << element << ", matcher #" << matcher << ")";
6084 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
6085 // A situation where all elements and matchers have a match
6086 // associated with them, but the max matching is not perfect.
6087 std::vector<std::string> v;
6091 StringMatchResultListener listener;
6092 EXPECT_FALSE(ExplainMatchResult(
6093 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
6096 std::string prefix =
6097 "where no permutation of the elements can satisfy all matchers, "
6098 "and the closest match is 2 of 3 matchers with the "
6101 // We have to be a bit loose here, because there are 4 valid max matches.
6104 AnyOf(prefix + "{\n " + EMString(0, 0) +
6105 ",\n " + EMString(1, 2) + "\n}",
6106 prefix + "{\n " + EMString(0, 1) +
6107 ",\n " + EMString(1, 2) + "\n}",
6108 prefix + "{\n " + EMString(0, 0) +
6109 ",\n " + EMString(2, 2) + "\n}",
6110 prefix + "{\n " + EMString(0, 1) +
6111 ",\n " + EMString(2, 2) + "\n}"));
6114 TEST_F(UnorderedElementsAreTest, Describe) {
6115 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
6118 Describe<IntVec>(UnorderedElementsAre(345)),
6119 Eq("has 1 element and that element is equal to 345"));
6121 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
6122 Eq("has 3 elements and there exists some permutation "
6123 "of elements such that:\n"
6124 " - element #0 is equal to 111, and\n"
6125 " - element #1 is equal to 222, and\n"
6126 " - element #2 is equal to 333"));
6129 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
6130 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
6133 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
6134 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
6136 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
6137 Eq("doesn't have 3 elements, or there exists no permutation "
6138 "of elements such that:\n"
6139 " - element #0 is equal to 123, and\n"
6140 " - element #1 is equal to 234, and\n"
6141 " - element #2 is equal to 345"));
6146 // Used as a check on the more complex max flow method used in the
6147 // real testing::internal::FindMaxBipartiteMatching. This method is
6148 // compatible but runs in worst-case factorial time, so we only
6149 // use it in testing for small problem sizes.
6150 template <typename Graph>
6151 class BacktrackingMaxBPMState {
6153 // Does not take ownership of 'g'.
6154 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
6156 ElementMatcherPairs Compute() {
6157 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
6158 return best_so_far_;
6160 lhs_used_.assign(graph_->LhsSize(), kUnused);
6161 rhs_used_.assign(graph_->RhsSize(), kUnused);
6162 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
6165 if (best_so_far_.size() == graph_->RhsSize())
6168 return best_so_far_;
6172 static const size_t kUnused = static_cast<size_t>(-1);
6174 void PushMatch(size_t lhs, size_t rhs) {
6175 matches_.push_back(ElementMatcherPair(lhs, rhs));
6176 lhs_used_[lhs] = rhs;
6177 rhs_used_[rhs] = lhs;
6178 if (matches_.size() > best_so_far_.size()) {
6179 best_so_far_ = matches_;
6184 const ElementMatcherPair& back = matches_.back();
6185 lhs_used_[back.first] = kUnused;
6186 rhs_used_[back.second] = kUnused;
6187 matches_.pop_back();
6190 bool RecurseInto(size_t irhs) {
6191 if (rhs_used_[irhs] != kUnused) {
6194 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
6195 if (lhs_used_[ilhs] != kUnused) {
6198 if (!graph_->HasEdge(ilhs, irhs)) {
6201 PushMatch(ilhs, irhs);
6202 if (best_so_far_.size() == graph_->RhsSize()) {
6205 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6206 if (!RecurseInto(mi)) return false;
6213 const Graph* graph_; // not owned
6214 std::vector<size_t> lhs_used_;
6215 std::vector<size_t> rhs_used_;
6216 ElementMatcherPairs matches_;
6217 ElementMatcherPairs best_so_far_;
6220 template <typename Graph>
6221 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6225 // Implement a simple backtracking algorithm to determine if it is possible
6226 // to find one element per matcher, without reusing elements.
6227 template <typename Graph>
6229 FindBacktrackingMaxBPM(const Graph& g) {
6230 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6233 class BacktrackingBPMTest : public ::testing::Test { };
6235 // Tests the MaxBipartiteMatching algorithm with square matrices.
6236 // The single int param is the # of nodes on each of the left and right sides.
6237 class BipartiteTest : public ::testing::TestWithParam<size_t> {};
6239 // Verify all match graphs up to some moderate number of edges.
6240 TEST_P(BipartiteTest, Exhaustive) {
6241 size_t nodes = GetParam();
6242 MatchMatrix graph(nodes, nodes);
6244 ElementMatcherPairs matches =
6245 internal::FindMaxBipartiteMatching(graph);
6246 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6247 << "graph: " << graph.DebugString();
6248 // Check that all elements of matches are in the graph.
6249 // Check that elements of first and second are unique.
6250 std::vector<bool> seen_element(graph.LhsSize());
6251 std::vector<bool> seen_matcher(graph.RhsSize());
6252 SCOPED_TRACE(PrintToString(matches));
6253 for (size_t i = 0; i < matches.size(); ++i) {
6254 size_t ilhs = matches[i].first;
6255 size_t irhs = matches[i].second;
6256 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
6257 EXPECT_FALSE(seen_element[ilhs]);
6258 EXPECT_FALSE(seen_matcher[irhs]);
6259 seen_element[ilhs] = true;
6260 seen_matcher[irhs] = true;
6262 } while (graph.NextGraph());
6265 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
6266 ::testing::Range(size_t{0}, size_t{5}));
6268 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
6269 class BipartiteNonSquareTest
6270 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6273 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6281 MatchMatrix g(4, 3);
6282 constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
6283 {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
6284 for (size_t i = 0; i < kEdges.size(); ++i) {
6285 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
6287 EXPECT_THAT(FindBacktrackingMaxBPM(g),
6288 ElementsAre(Pair(3, 0),
6289 Pair(AnyOf(1, 2), 1),
6290 Pair(0, 2))) << g.DebugString();
6293 // Verify a few nonsquare matrices.
6294 TEST_P(BipartiteNonSquareTest, Exhaustive) {
6295 size_t nlhs = GetParam().first;
6296 size_t nrhs = GetParam().second;
6297 MatchMatrix graph(nlhs, nrhs);
6299 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6300 internal::FindMaxBipartiteMatching(graph).size())
6301 << "graph: " << graph.DebugString()
6302 << "\nbacktracking: "
6303 << PrintToString(FindBacktrackingMaxBPM(graph))
6305 << PrintToString(internal::FindMaxBipartiteMatching(graph));
6306 } while (graph.NextGraph());
6309 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
6311 std::make_pair(1, 2),
6312 std::make_pair(2, 1),
6313 std::make_pair(3, 2),
6314 std::make_pair(2, 3),
6315 std::make_pair(4, 1),
6316 std::make_pair(1, 4),
6317 std::make_pair(4, 3),
6318 std::make_pair(3, 4)));
6320 class BipartiteRandomTest
6321 : public ::testing::TestWithParam<std::pair<int, int> > {
6324 // Verifies a large sample of larger graphs.
6325 TEST_P(BipartiteRandomTest, LargerNets) {
6326 int nodes = GetParam().first;
6327 int iters = GetParam().second;
6328 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
6330 auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
6332 seed = static_cast<uint32_t>(time(nullptr));
6335 for (; iters > 0; --iters, ++seed) {
6336 srand(static_cast<unsigned int>(seed));
6338 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6339 internal::FindMaxBipartiteMatching(graph).size())
6340 << " graph: " << graph.DebugString()
6341 << "\nTo reproduce the failure, rerun the test with the flag"
6342 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6346 // Test argument is a std::pair<int, int> representing (nodes, iters).
6347 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
6349 std::make_pair(5, 10000),
6350 std::make_pair(6, 5000),
6351 std::make_pair(7, 2000),
6352 std::make_pair(8, 500),
6353 std::make_pair(9, 100)));
6355 // Tests IsReadableTypeName().
6357 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6358 EXPECT_TRUE(IsReadableTypeName("int"));
6359 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6360 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6361 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6364 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6365 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6366 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6367 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6370 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6372 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6373 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6376 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6377 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6380 // Tests FormatMatcherDescription().
6382 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6383 EXPECT_EQ("is even",
6384 FormatMatcherDescription(false, "IsEven", Strings()));
6385 EXPECT_EQ("not (is even)",
6386 FormatMatcherDescription(true, "IsEven", Strings()));
6388 const char* params[] = {"5"};
6389 EXPECT_EQ("equals 5",
6390 FormatMatcherDescription(false, "Equals",
6391 Strings(params, params + 1)));
6393 const char* params2[] = {"5", "8"};
6394 EXPECT_EQ("is in range (5, 8)",
6395 FormatMatcherDescription(false, "IsInRange",
6396 Strings(params2, params2 + 2)));
6399 // Tests PolymorphicMatcher::mutable_impl().
6400 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6401 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6402 DivisibleByImpl& impl = m.mutable_impl();
6403 EXPECT_EQ(42, impl.divider());
6405 impl.set_divider(0);
6406 EXPECT_EQ(0, m.mutable_impl().divider());
6409 // Tests PolymorphicMatcher::impl().
6410 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6411 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6412 const DivisibleByImpl& impl = m.impl();
6413 EXPECT_EQ(42, impl.divider());
6416 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6418 ExplainMatchFailureTupleTo(
6419 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6420 std::make_tuple('a', 10), &ss1);
6421 EXPECT_EQ("", ss1.str()); // Successful match.
6424 ExplainMatchFailureTupleTo(
6425 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6426 std::make_tuple(2, 'b'), &ss2);
6427 EXPECT_EQ(" Expected arg #0: is > 5\n"
6428 " Actual: 2, which is 3 less than 5\n"
6429 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6430 " Actual: 'b' (98, 0x62)\n",
6431 ss2.str()); // Failed match where both arguments need explanation.
6434 ExplainMatchFailureTupleTo(
6435 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6436 std::make_tuple(2, 'a'), &ss3);
6437 EXPECT_EQ(" Expected arg #0: is > 5\n"
6438 " Actual: 2, which is 3 less than 5\n",
6439 ss3.str()); // Failed match where only one argument needs
6445 TEST(EachTest, ExplainsMatchResultCorrectly) {
6446 set<int> a; // empty
6448 Matcher<set<int> > m = Each(2);
6449 EXPECT_EQ("", Explain(m, a));
6451 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6453 const int b[1] = {1};
6454 EXPECT_EQ("", Explain(n, b));
6457 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6462 m = Each(GreaterThan(0));
6463 EXPECT_EQ("", Explain(m, a));
6465 m = Each(GreaterThan(10));
6466 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6470 TEST(EachTest, DescribesItselfCorrectly) {
6471 Matcher<vector<int> > m = Each(1);
6472 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6474 Matcher<vector<int> > m2 = Not(m);
6475 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6478 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6479 vector<int> some_vector;
6480 EXPECT_THAT(some_vector, Each(1));
6481 some_vector.push_back(3);
6482 EXPECT_THAT(some_vector, Not(Each(1)));
6483 EXPECT_THAT(some_vector, Each(3));
6484 some_vector.push_back(1);
6485 some_vector.push_back(2);
6486 EXPECT_THAT(some_vector, Not(Each(3)));
6487 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6489 vector<std::string> another_vector;
6490 another_vector.push_back("fee");
6491 EXPECT_THAT(another_vector, Each(std::string("fee")));
6492 another_vector.push_back("fie");
6493 another_vector.push_back("foe");
6494 another_vector.push_back("fum");
6495 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6498 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6499 map<const char*, int> my_map;
6500 const char* bar = "a string";
6502 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6504 map<std::string, int> another_map;
6505 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6506 another_map["fee"] = 1;
6507 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6508 another_map["fie"] = 2;
6509 another_map["foe"] = 3;
6510 another_map["fum"] = 4;
6511 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6512 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6513 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6516 TEST(EachTest, AcceptsMatcher) {
6517 const int a[] = {1, 2, 3};
6518 EXPECT_THAT(a, Each(Gt(0)));
6519 EXPECT_THAT(a, Not(Each(Gt(1))));
6522 TEST(EachTest, WorksForNativeArrayAsTuple) {
6523 const int a[] = {1, 2};
6524 const int* const pointer = a;
6525 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6526 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6529 TEST(EachTest, WorksWithMoveOnly) {
6530 ContainerHelper helper;
6531 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6532 helper.Call(MakeUniquePtrs({1, 2}));
6535 // For testing Pointwise().
6536 class IsHalfOfMatcher {
6538 template <typename T1, typename T2>
6539 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
6540 MatchResultListener* listener) const {
6541 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6542 *listener << "where the second is " << std::get<1>(a_pair);
6545 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
6550 void DescribeTo(ostream* os) const {
6551 *os << "are a pair where the first is half of the second";
6554 void DescribeNegationTo(ostream* os) const {
6555 *os << "are a pair where the first isn't half of the second";
6559 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6560 return MakePolymorphicMatcher(IsHalfOfMatcher());
6563 TEST(PointwiseTest, DescribesSelf) {
6568 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6569 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6570 "in { 1, 2, 3 } are a pair where the first is half of the second",
6572 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6573 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6574 "where the first isn't half of the second",
6575 DescribeNegation(m));
6578 TEST(PointwiseTest, MakesCopyOfRhs) {
6579 list<signed char> rhs;
6584 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6585 EXPECT_THAT(lhs, m);
6587 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6589 EXPECT_THAT(lhs, m);
6592 TEST(PointwiseTest, WorksForLhsNativeArray) {
6593 const int lhs[] = {1, 2, 3};
6598 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6599 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6602 TEST(PointwiseTest, WorksForRhsNativeArray) {
6603 const int rhs[] = {1, 2, 3};
6608 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6609 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6612 // Test is effective only with sanitizers.
6613 TEST(PointwiseTest, WorksForVectorOfBool) {
6614 vector<bool> rhs(3, false);
6616 vector<bool> lhs = rhs;
6617 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6619 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6623 TEST(PointwiseTest, WorksForRhsInitializerList) {
6624 const vector<int> lhs{2, 4, 6};
6625 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6626 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6630 TEST(PointwiseTest, RejectsWrongSize) {
6631 const double lhs[2] = {1, 2};
6632 const int rhs[1] = {0};
6633 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6634 EXPECT_EQ("which contains 2 values",
6635 Explain(Pointwise(Gt(), rhs), lhs));
6637 const int rhs2[3] = {0, 1, 2};
6638 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6641 TEST(PointwiseTest, RejectsWrongContent) {
6642 const double lhs[3] = {1, 2, 3};
6643 const int rhs[3] = {2, 6, 4};
6644 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6645 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6646 "where the second/2 is 3",
6647 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6650 TEST(PointwiseTest, AcceptsCorrectContent) {
6651 const double lhs[3] = {1, 2, 3};
6652 const int rhs[3] = {2, 4, 6};
6653 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6654 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6657 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6658 const double lhs[3] = {1, 2, 3};
6659 const int rhs[3] = {2, 4, 6};
6660 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6661 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6662 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6664 // This type works as a std::tuple<const double&, const int&> can be
6665 // implicitly cast to std::tuple<double, int>.
6666 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6667 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6668 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6671 MATCHER(PointeeEquals, "Points to an equal value") {
6672 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6673 ::testing::get<0>(arg), result_listener);
6676 TEST(PointwiseTest, WorksWithMoveOnly) {
6677 ContainerHelper helper;
6678 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6679 helper.Call(MakeUniquePtrs({1, 2}));
6682 TEST(UnorderedPointwiseTest, DescribesSelf) {
6687 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6689 "has 3 elements and there exists some permutation of elements such "
6691 " - element #0 and 1 are a pair where the first is half of the second, "
6693 " - element #1 and 2 are a pair where the first is half of the second, "
6695 " - element #2 and 3 are a pair where the first is half of the second",
6698 "doesn't have 3 elements, or there exists no permutation of elements "
6700 " - element #0 and 1 are a pair where the first is half of the second, "
6702 " - element #1 and 2 are a pair where the first is half of the second, "
6704 " - element #2 and 3 are a pair where the first is half of the second",
6705 DescribeNegation(m));
6708 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6709 list<signed char> rhs;
6714 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6715 EXPECT_THAT(lhs, m);
6717 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6719 EXPECT_THAT(lhs, m);
6722 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6723 const int lhs[] = {1, 2, 3};
6728 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6729 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6732 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6733 const int rhs[] = {1, 2, 3};
6738 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6739 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6743 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6744 const vector<int> lhs{2, 4, 6};
6745 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6746 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6750 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6751 const double lhs[2] = {1, 2};
6752 const int rhs[1] = {0};
6753 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6754 EXPECT_EQ("which has 2 elements",
6755 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6757 const int rhs2[3] = {0, 1, 2};
6758 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6761 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6762 const double lhs[3] = {1, 2, 3};
6763 const int rhs[3] = {2, 6, 6};
6764 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6765 EXPECT_EQ("where the following elements don't match any matchers:\n"
6767 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6770 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6771 const double lhs[3] = {1, 2, 3};
6772 const int rhs[3] = {2, 4, 6};
6773 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6776 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6777 const double lhs[3] = {1, 2, 3};
6778 const int rhs[3] = {6, 4, 2};
6779 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6782 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6783 const double lhs[3] = {1, 2, 3};
6784 const int rhs[3] = {4, 6, 2};
6785 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6786 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6788 // This type works as a std::tuple<const double&, const int&> can be
6789 // implicitly cast to std::tuple<double, int>.
6790 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6791 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6794 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6795 ContainerHelper helper;
6796 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6797 std::vector<int>{1, 2})));
6798 helper.Call(MakeUniquePtrs({2, 1}));
6801 // Sample optional type implementation with minimal requirements for use with
6802 // Optional matcher.
6803 template <typename T>
6804 class SampleOptional {
6806 using value_type = T;
6807 explicit SampleOptional(T value)
6808 : value_(std::move(value)), has_value_(true) {}
6809 SampleOptional() : value_(), has_value_(false) {}
6810 operator bool() const { return has_value_; }
6811 const T& operator*() const { return value_; }
6818 TEST(OptionalTest, DescribesSelf) {
6819 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6820 EXPECT_EQ("value is equal to 1", Describe(m));
6823 TEST(OptionalTest, ExplainsSelf) {
6824 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6825 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6826 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6829 TEST(OptionalTest, MatchesNonEmptyOptional) {
6830 const Matcher<SampleOptional<int>> m1 = Optional(1);
6831 const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6832 const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6833 SampleOptional<int> opt(1);
6834 EXPECT_TRUE(m1.Matches(opt));
6835 EXPECT_FALSE(m2.Matches(opt));
6836 EXPECT_TRUE(m3.Matches(opt));
6839 TEST(OptionalTest, DoesNotMatchNullopt) {
6840 const Matcher<SampleOptional<int>> m = Optional(1);
6841 SampleOptional<int> empty;
6842 EXPECT_FALSE(m.Matches(empty));
6845 TEST(OptionalTest, WorksWithMoveOnly) {
6846 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6847 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6850 class SampleVariantIntString {
6852 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6853 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6855 template <typename T>
6856 friend bool holds_alternative(const SampleVariantIntString& value) {
6857 return value.has_int_ == std::is_same<T, int>::value;
6860 template <typename T>
6861 friend const T& get(const SampleVariantIntString& value) {
6862 return value.get_impl(static_cast<T*>(nullptr));
6866 const int& get_impl(int*) const { return i_; }
6867 const std::string& get_impl(std::string*) const { return s_; }
6874 TEST(VariantTest, DescribesSelf) {
6875 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6876 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6877 "'.*' and the value is equal to 1"));
6880 TEST(VariantTest, ExplainsSelf) {
6881 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6882 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6883 ContainsRegex("whose value 1"));
6884 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6885 HasSubstr("whose value is not of type '"));
6886 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6887 "whose value 2 doesn't match");
6890 TEST(VariantTest, FullMatch) {
6891 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6892 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6894 m = VariantWith<std::string>(Eq("1"));
6895 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6898 TEST(VariantTest, TypeDoesNotMatch) {
6899 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6900 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6902 m = VariantWith<std::string>(Eq("1"));
6903 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6906 TEST(VariantTest, InnerDoesNotMatch) {
6907 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6908 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6910 m = VariantWith<std::string>(Eq("1"));
6911 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6914 class SampleAnyType {
6916 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6917 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6919 template <typename T>
6920 friend const T* any_cast(const SampleAnyType* any) {
6921 return any->get_impl(static_cast<T*>(nullptr));
6929 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
6930 const std::string* get_impl(std::string*) const {
6931 return index_ == 1 ? &s_ : nullptr;
6935 TEST(AnyWithTest, FullMatch) {
6936 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6937 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6940 TEST(AnyWithTest, TestBadCastType) {
6941 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6942 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6945 TEST(AnyWithTest, TestUseInContainers) {
6946 std::vector<SampleAnyType> a;
6951 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6953 std::vector<SampleAnyType> b;
6954 b.emplace_back("hello");
6955 b.emplace_back("merhaba");
6956 b.emplace_back("salut");
6957 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6958 AnyWith<std::string>("merhaba"),
6959 AnyWith<std::string>("salut")}));
6961 TEST(AnyWithTest, TestCompare) {
6962 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6965 TEST(AnyWithTest, DescribesSelf) {
6966 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6967 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6968 "'.*' and the value is equal to 1"));
6971 TEST(AnyWithTest, ExplainsSelf) {
6972 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6974 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6975 EXPECT_THAT(Explain(m, SampleAnyType("A")),
6976 HasSubstr("whose value is not of type '"));
6977 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6980 TEST(PointeeTest, WorksOnMoveOnlyType) {
6981 std::unique_ptr<int> p(new int(3));
6982 EXPECT_THAT(p, Pointee(Eq(3)));
6983 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6986 TEST(NotTest, WorksOnMoveOnlyType) {
6987 std::unique_ptr<int> p(new int(3));
6988 EXPECT_THAT(p, Pointee(Eq(3)));
6989 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6992 // Tests Args<k0, ..., kn>(m).
6994 TEST(ArgsTest, AcceptsZeroTemplateArg) {
6995 const std::tuple<int, bool> t(5, true);
6996 EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
6997 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
7000 TEST(ArgsTest, AcceptsOneTemplateArg) {
7001 const std::tuple<int, bool> t(5, true);
7002 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
7003 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
7004 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
7007 TEST(ArgsTest, AcceptsTwoTemplateArgs) {
7008 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7010 EXPECT_THAT(t, (Args<0, 1>(Lt())));
7011 EXPECT_THAT(t, (Args<1, 2>(Lt())));
7012 EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
7015 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
7016 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7017 EXPECT_THAT(t, (Args<0, 0>(Eq())));
7018 EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
7021 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
7022 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
7023 EXPECT_THAT(t, (Args<2, 0>(Gt())));
7024 EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
7027 MATCHER(SumIsZero, "") {
7028 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
7031 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
7032 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
7033 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
7036 TEST(ArgsTest, CanBeNested) {
7037 const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
7038 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
7039 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
7042 TEST(ArgsTest, CanMatchTupleByValue) {
7043 typedef std::tuple<char, int, int> Tuple3;
7044 const Matcher<Tuple3> m = Args<1, 2>(Lt());
7045 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
7046 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
7049 TEST(ArgsTest, CanMatchTupleByReference) {
7050 typedef std::tuple<char, char, int> Tuple3;
7051 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
7052 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
7053 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
7056 // Validates that arg is printed as str.
7057 MATCHER_P(PrintsAs, str, "") {
7058 return testing::PrintToString(arg) == str;
7061 TEST(ArgsTest, AcceptsTenTemplateArgs) {
7062 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7063 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7064 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7065 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7066 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7067 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7070 TEST(ArgsTest, DescirbesSelfCorrectly) {
7071 const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
7072 EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
7073 "the first < the second",
7077 TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
7078 const Matcher<const std::tuple<int, bool, char, int>&> m =
7079 Args<0, 2, 3>(Args<2, 0>(Lt()));
7080 EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
7081 "whose fields (#2, #0) are a pair where the first < the second",
7085 TEST(ArgsTest, DescribesNegationCorrectly) {
7086 const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
7087 EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
7088 "where the first > the second",
7089 DescribeNegation(m));
7092 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
7093 const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
7094 EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
7095 Explain(m, std::make_tuple(false, 42, 42)));
7096 EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
7097 Explain(m, std::make_tuple(false, 42, 43)));
7100 // For testing Args<>'s explanation.
7101 class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
7103 void DescribeTo(::std::ostream* /*os*/) const override {}
7105 bool MatchAndExplain(std::tuple<char, int> value,
7106 MatchResultListener* listener) const override {
7107 const int diff = std::get<0>(value) - std::get<1>(value);
7109 *listener << "where the first value is " << diff
7110 << " more than the second";
7116 Matcher<std::tuple<char, int> > LessThan() {
7117 return MakeMatcher(new LessThanMatcher);
7120 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
7121 const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
7123 "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
7124 "where the first value is 55 more than the second",
7125 Explain(m, std::make_tuple('a', 42, 42)));
7126 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
7127 Explain(m, std::make_tuple('\0', 42, 43)));
7130 class PredicateFormatterFromMatcherTest : public ::testing::Test {
7132 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
7134 // A matcher that can return different results when used multiple times on the
7135 // same input. No real matcher should do this; but this lets us test that we
7136 // detect such behavior and fail appropriately.
7137 class MockMatcher : public MatcherInterface<Behavior> {
7139 bool MatchAndExplain(Behavior behavior,
7140 MatchResultListener* listener) const override {
7141 *listener << "[MatchAndExplain]";
7143 case kInitialSuccess:
7144 // The first call to MatchAndExplain should use a "not interested"
7145 // listener; so this is expected to return |true|. There should be no
7146 // subsequent calls.
7147 return !listener->IsInterested();
7153 // The first call to MatchAndExplain should use a "not interested"
7154 // listener; so this will return |false|. Subsequent calls should have
7155 // an "interested" listener; so this will return |true|, thus
7156 // simulating a flaky matcher.
7157 return listener->IsInterested();
7160 GTEST_LOG_(FATAL) << "This should never be reached";
7164 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
7166 void DescribeNegationTo(ostream* os) const override {
7167 *os << "[DescribeNegationTo]";
7171 AssertionResult RunPredicateFormatter(Behavior behavior) {
7172 auto matcher = MakeMatcher(new MockMatcher);
7173 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
7175 return predicate_formatter("dummy-name", behavior);
7179 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
7180 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
7181 EXPECT_TRUE(result); // Implicit cast to bool.
7183 EXPECT_EQ(expect, result.message());
7186 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
7187 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
7188 EXPECT_FALSE(result); // Implicit cast to bool.
7189 std::string expect =
7190 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7192 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7193 EXPECT_EQ(expect, result.message());
7196 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
7197 AssertionResult result = RunPredicateFormatter(kFlaky);
7198 EXPECT_FALSE(result); // Implicit cast to bool.
7199 std::string expect =
7200 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7201 " The matcher failed on the initial attempt; but passed when rerun to "
7202 "generate the explanation.\n"
7204 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7205 EXPECT_EQ(expect, result.message());
7208 // Tests for ElementsAre().
7210 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
7211 Matcher<const vector<int>&> m = ElementsAre();
7212 EXPECT_EQ("is empty", Describe(m));
7215 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
7216 Matcher<vector<int>> m = ElementsAre(Gt(5));
7217 EXPECT_EQ("has 1 element that is > 5", Describe(m));
7220 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
7221 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
7223 "has 2 elements where\n"
7224 "element #0 is equal to \"one\",\n"
7225 "element #1 is equal to \"two\"",
7229 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
7230 Matcher<vector<int>> m = ElementsAre();
7231 EXPECT_EQ("isn't empty", DescribeNegation(m));
7234 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
7235 Matcher<const list<int>&> m = ElementsAre(Gt(5));
7237 "doesn't have 1 element, or\n"
7238 "element #0 isn't > 5",
7239 DescribeNegation(m));
7242 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
7243 Matcher<const list<std::string>&> m = ElementsAre("one", "two");
7245 "doesn't have 2 elements, or\n"
7246 "element #0 isn't equal to \"one\", or\n"
7247 "element #1 isn't equal to \"two\"",
7248 DescribeNegation(m));
7251 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
7252 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
7254 list<int> test_list;
7255 test_list.push_back(1);
7256 test_list.push_back(3);
7257 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
7260 TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
7261 Matcher<const vector<int>&> m =
7262 ElementsAre(GreaterThan(1), 0, GreaterThan(2));
7264 const int a[] = {10, 0, 100};
7265 vector<int> test_vector(std::begin(a), std::end(a));
7267 "whose element #0 matches, which is 9 more than 1,\n"
7268 "and whose element #2 matches, which is 98 more than 2",
7269 Explain(m, test_vector));
7272 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
7273 Matcher<const list<int>&> m = ElementsAre(1, 3);
7275 list<int> test_list;
7276 // No need to explain when the container is empty.
7277 EXPECT_EQ("", Explain(m, test_list));
7279 test_list.push_back(1);
7280 EXPECT_EQ("which has 1 element", Explain(m, test_list));
7283 TEST(ElementsAreTest, CanExplainMismatchRightSize) {
7284 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
7289 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
7292 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
7296 TEST(ElementsAreTest, MatchesOneElementVector) {
7297 vector<std::string> test_vector;
7298 test_vector.push_back("test string");
7300 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
7303 TEST(ElementsAreTest, MatchesOneElementList) {
7304 list<std::string> test_list;
7305 test_list.push_back("test string");
7307 EXPECT_THAT(test_list, ElementsAre("test string"));
7310 TEST(ElementsAreTest, MatchesThreeElementVector) {
7311 vector<std::string> test_vector;
7312 test_vector.push_back("one");
7313 test_vector.push_back("two");
7314 test_vector.push_back("three");
7316 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
7319 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
7320 vector<int> test_vector;
7321 test_vector.push_back(4);
7323 EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
7326 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
7327 vector<int> test_vector;
7328 test_vector.push_back(4);
7330 EXPECT_THAT(test_vector, ElementsAre(_));
7333 TEST(ElementsAreTest, MatchesOneElementValue) {
7334 vector<int> test_vector;
7335 test_vector.push_back(4);
7337 EXPECT_THAT(test_vector, ElementsAre(4));
7340 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
7341 vector<int> test_vector;
7342 test_vector.push_back(1);
7343 test_vector.push_back(2);
7344 test_vector.push_back(3);
7346 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
7349 TEST(ElementsAreTest, MatchesTenElementVector) {
7350 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
7351 vector<int> test_vector(std::begin(a), std::end(a));
7353 EXPECT_THAT(test_vector,
7354 // The element list can contain values and/or matchers
7355 // of different types.
7356 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
7359 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
7360 vector<std::string> test_vector;
7361 test_vector.push_back("test string");
7362 test_vector.push_back("test string");
7364 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7365 EXPECT_FALSE(m.Matches(test_vector));
7368 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
7369 vector<std::string> test_vector;
7370 test_vector.push_back("other string");
7372 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7373 EXPECT_FALSE(m.Matches(test_vector));
7376 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
7377 vector<std::string> test_vector;
7378 test_vector.push_back("one");
7379 test_vector.push_back("three");
7380 test_vector.push_back("two");
7382 Matcher<vector<std::string>> m =
7383 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
7384 EXPECT_FALSE(m.Matches(test_vector));
7387 TEST(ElementsAreTest, WorksForNestedContainer) {
7388 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
7390 vector<list<char>> nested;
7391 for (const auto& s : strings) {
7392 nested.emplace_back(s, s + strlen(s));
7395 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
7396 ElementsAre('w', 'o', _, _, 'd')));
7397 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
7398 ElementsAre('w', 'o', _, _, 'd'))));
7401 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
7402 int a[] = {0, 1, 2};
7403 vector<int> v(std::begin(a), std::end(a));
7405 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
7406 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
7409 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
7410 int a[] = {0, 1, 2};
7411 vector<int> v(std::begin(a), std::end(a));
7413 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
7414 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
7417 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
7418 int array[] = {0, 1, 2};
7419 EXPECT_THAT(array, ElementsAre(0, 1, _));
7420 EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
7421 EXPECT_THAT(array, Not(ElementsAre(0, _)));
7424 class NativeArrayPassedAsPointerAndSize {
7426 NativeArrayPassedAsPointerAndSize() {}
7428 MOCK_METHOD(void, Helper, (int* array, int size));
7431 GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
7434 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
7435 int array[] = {0, 1};
7436 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
7437 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
7438 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
7440 NativeArrayPassedAsPointerAndSize helper;
7441 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
7442 helper.Helper(array, 2);
7445 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
7446 const char a2[][3] = {"hi", "lo"};
7447 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
7448 ElementsAre('l', 'o', '\0')));
7449 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
7450 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
7451 ElementsAre('l', 'o', '\0')));
7454 TEST(ElementsAreTest, AcceptsStringLiteral) {
7455 std::string array[] = {"hi", "one", "two"};
7456 EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
7457 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
7460 // Declared here with the size unknown. Defined AFTER the following test.
7461 extern const char kHi[];
7463 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
7464 // The size of kHi is not known in this test, but ElementsAre() should
7467 std::string array1[] = {"hi"};
7468 EXPECT_THAT(array1, ElementsAre(kHi));
7470 std::string array2[] = {"ho"};
7471 EXPECT_THAT(array2, Not(ElementsAre(kHi)));
7474 const char kHi[] = "hi";
7476 TEST(ElementsAreTest, MakesCopyOfArguments) {
7479 // This should make a copy of x and y.
7480 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
7481 polymorphic_matcher = ElementsAre(x, y);
7482 // Changing x and y now shouldn't affect the meaning of the above matcher.
7484 const int array1[] = {1, 2};
7485 EXPECT_THAT(array1, polymorphic_matcher);
7486 const int array2[] = {0, 0};
7487 EXPECT_THAT(array2, Not(polymorphic_matcher));
7490 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
7491 // of the implementation with ElementsAre(), we don't test it as
7494 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
7495 const int a[] = {1, 2, 3};
7497 vector<int> test_vector(std::begin(a), std::end(a));
7498 EXPECT_THAT(test_vector, ElementsAreArray(a));
7501 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7504 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
7505 std::array<const char*, 3> a = {{"one", "two", "three"}};
7507 vector<std::string> test_vector(std::begin(a), std::end(a));
7508 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
7510 const char** p = a.data();
7511 test_vector[0] = "1";
7512 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
7515 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
7516 const char* a[] = {"one", "two", "three"};
7518 vector<std::string> test_vector(std::begin(a), std::end(a));
7519 EXPECT_THAT(test_vector, ElementsAreArray(a));
7521 test_vector[0] = "1";
7522 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7525 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
7526 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
7529 vector<std::string> test_vector;
7530 test_vector.push_back("one");
7531 test_vector.push_back("two");
7532 test_vector.push_back("three");
7533 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
7535 test_vector.push_back("three");
7536 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
7539 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
7540 const int a[] = {1, 2, 3};
7541 vector<int> test_vector(std::begin(a), std::end(a));
7542 const vector<int> expected(std::begin(a), std::end(a));
7543 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7544 test_vector.push_back(4);
7545 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7548 TEST(ElementsAreArrayTest, TakesInitializerList) {
7549 const int a[5] = {1, 2, 3, 4, 5};
7550 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
7551 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
7552 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
7555 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
7556 const std::string a[5] = {"a", "b", "c", "d", "e"};
7557 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
7558 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
7559 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
7562 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
7563 const int a[5] = {1, 2, 3, 4, 5};
7564 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
7565 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
7568 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
7569 const int a[5] = {1, 2, 3, 4, 5};
7570 // The compiler cannot infer the type of the initializer list if its
7571 // elements have different types. We must explicitly specify the
7572 // unified element type in this case.
7574 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
7575 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
7576 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
7579 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
7580 const int a[] = {1, 2, 3};
7581 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
7582 vector<int> test_vector(std::begin(a), std::end(a));
7583 const vector<Matcher<int>> expected(std::begin(kMatchers),
7584 std::end(kMatchers));
7585 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7586 test_vector.push_back(4);
7587 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7590 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
7591 const int a[] = {1, 2, 3};
7592 const vector<int> test_vector(std::begin(a), std::end(a));
7593 const vector<int> expected(std::begin(a), std::end(a));
7594 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
7595 // Pointers are iterators, too.
7596 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
7597 // The empty range of NULL pointers should also be okay.
7598 int* const null_int = nullptr;
7599 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
7600 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
7603 // Since ElementsAre() and ElementsAreArray() share much of the
7604 // implementation, we only do a sanity test for native arrays here.
7605 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
7606 ::std::string a[] = {"hi", "ho"};
7607 ::std::string b[] = {"hi", "ho"};
7609 EXPECT_THAT(a, ElementsAreArray(b));
7610 EXPECT_THAT(a, ElementsAreArray(b, 2));
7611 EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
7614 TEST(ElementsAreArrayTest, SourceLifeSpan) {
7615 const int a[] = {1, 2, 3};
7616 vector<int> test_vector(std::begin(a), std::end(a));
7617 vector<int> expect(std::begin(a), std::end(a));
7618 ElementsAreArrayMatcher<int> matcher_maker =
7619 ElementsAreArray(expect.begin(), expect.end());
7620 EXPECT_THAT(test_vector, matcher_maker);
7621 // Changing in place the values that initialized matcher_maker should not
7622 // affect matcher_maker anymore. It should have made its own copy of them.
7623 for (int& i : expect) {
7626 EXPECT_THAT(test_vector, matcher_maker);
7627 test_vector.push_back(3);
7628 EXPECT_THAT(test_vector, Not(matcher_maker));
7631 // Tests for the MATCHER*() macro family.
7633 // Tests that a simple MATCHER() definition works.
7635 MATCHER(IsEven, "") { return (arg % 2) == 0; }
7637 TEST(MatcherMacroTest, Works) {
7638 const Matcher<int> m = IsEven();
7639 EXPECT_TRUE(m.Matches(6));
7640 EXPECT_FALSE(m.Matches(7));
7642 EXPECT_EQ("is even", Describe(m));
7643 EXPECT_EQ("not (is even)", DescribeNegation(m));
7644 EXPECT_EQ("", Explain(m, 6));
7645 EXPECT_EQ("", Explain(m, 7));
7648 // This also tests that the description string can reference 'negation'.
7649 MATCHER(IsEven2, negation ? "is odd" : "is even") {
7650 if ((arg % 2) == 0) {
7651 // Verifies that we can stream to result_listener, a listener
7652 // supplied by the MATCHER macro implicitly.
7653 *result_listener << "OK";
7656 *result_listener << "% 2 == " << (arg % 2);
7661 // This also tests that the description string can reference matcher
7663 MATCHER_P2(EqSumOf, x, y,
7664 std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
7665 PrintToString(x) + " and " + PrintToString(y)) {
7666 if (arg == (x + y)) {
7667 *result_listener << "OK";
7670 // Verifies that we can stream to the underlying stream of
7672 if (result_listener->stream() != nullptr) {
7673 *result_listener->stream() << "diff == " << (x + y - arg);
7679 // Tests that the matcher description can reference 'negation' and the
7680 // matcher parameters.
7681 TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
7682 const Matcher<int> m1 = IsEven2();
7683 EXPECT_EQ("is even", Describe(m1));
7684 EXPECT_EQ("is odd", DescribeNegation(m1));
7686 const Matcher<int> m2 = EqSumOf(5, 9);
7687 EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
7688 EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
7691 // Tests explaining match result in a MATCHER* macro.
7692 TEST(MatcherMacroTest, CanExplainMatchResult) {
7693 const Matcher<int> m1 = IsEven2();
7694 EXPECT_EQ("OK", Explain(m1, 4));
7695 EXPECT_EQ("% 2 == 1", Explain(m1, 5));
7697 const Matcher<int> m2 = EqSumOf(1, 2);
7698 EXPECT_EQ("OK", Explain(m2, 3));
7699 EXPECT_EQ("diff == -1", Explain(m2, 4));
7702 // Tests that the body of MATCHER() can reference the type of the
7703 // value being matched.
7705 MATCHER(IsEmptyString, "") {
7706 StaticAssertTypeEq<::std::string, arg_type>();
7710 MATCHER(IsEmptyStringByRef, "") {
7711 StaticAssertTypeEq<const ::std::string&, arg_type>();
7715 TEST(MatcherMacroTest, CanReferenceArgType) {
7716 const Matcher<::std::string> m1 = IsEmptyString();
7717 EXPECT_TRUE(m1.Matches(""));
7719 const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
7720 EXPECT_TRUE(m2.Matches(""));
7723 // Tests that MATCHER() can be used in a namespace.
7725 namespace matcher_test {
7726 MATCHER(IsOdd, "") { return (arg % 2) != 0; }
7727 } // namespace matcher_test
7729 TEST(MatcherMacroTest, WorksInNamespace) {
7730 Matcher<int> m = matcher_test::IsOdd();
7731 EXPECT_FALSE(m.Matches(4));
7732 EXPECT_TRUE(m.Matches(5));
7735 // Tests that Value() can be used to compose matchers.
7736 MATCHER(IsPositiveOdd, "") {
7737 return Value(arg, matcher_test::IsOdd()) && arg > 0;
7740 TEST(MatcherMacroTest, CanBeComposedUsingValue) {
7741 EXPECT_THAT(3, IsPositiveOdd());
7742 EXPECT_THAT(4, Not(IsPositiveOdd()));
7743 EXPECT_THAT(-1, Not(IsPositiveOdd()));
7746 // Tests that a simple MATCHER_P() definition works.
7748 MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
7750 TEST(MatcherPMacroTest, Works) {
7751 const Matcher<int> m = IsGreaterThan32And(5);
7752 EXPECT_TRUE(m.Matches(36));
7753 EXPECT_FALSE(m.Matches(5));
7755 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7756 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7757 EXPECT_EQ("", Explain(m, 36));
7758 EXPECT_EQ("", Explain(m, 5));
7761 // Tests that the description is calculated correctly from the matcher name.
7762 MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
7764 TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
7765 const Matcher<int> m = _is_Greater_Than32and_(5);
7767 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7768 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7769 EXPECT_EQ("", Explain(m, 36));
7770 EXPECT_EQ("", Explain(m, 5));
7773 // Tests that a MATCHER_P matcher can be explicitly instantiated with
7774 // a reference parameter type.
7776 class UncopyableFoo {
7778 explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
7780 UncopyableFoo(const UncopyableFoo&) = delete;
7781 void operator=(const UncopyableFoo&) = delete;
7787 MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
7789 TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
7790 UncopyableFoo foo1('1'), foo2('2');
7791 const Matcher<const UncopyableFoo&> m =
7792 ReferencesUncopyable<const UncopyableFoo&>(foo1);
7794 EXPECT_TRUE(m.Matches(foo1));
7795 EXPECT_FALSE(m.Matches(foo2));
7797 // We don't want the address of the parameter printed, as most
7798 // likely it will just annoy the user. If the address is
7799 // interesting, the user should consider passing the parameter by
7801 EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
7804 // Tests that the body of MATCHER_Pn() can reference the parameter
7807 MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
7808 StaticAssertTypeEq<int, foo_type>();
7809 StaticAssertTypeEq<long, bar_type>(); // NOLINT
7810 StaticAssertTypeEq<char, baz_type>();
7814 TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
7815 EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
7818 // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
7819 // reference parameter types.
7821 MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
7822 return &arg == &variable1 || &arg == &variable2;
7825 TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
7826 UncopyableFoo foo1('1'), foo2('2'), foo3('3');
7827 const Matcher<const UncopyableFoo&> const_m =
7828 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7830 EXPECT_TRUE(const_m.Matches(foo1));
7831 EXPECT_TRUE(const_m.Matches(foo2));
7832 EXPECT_FALSE(const_m.Matches(foo3));
7834 const Matcher<UncopyableFoo&> m =
7835 ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
7837 EXPECT_TRUE(m.Matches(foo1));
7838 EXPECT_TRUE(m.Matches(foo2));
7839 EXPECT_FALSE(m.Matches(foo3));
7842 TEST(MatcherPnMacroTest,
7843 GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
7844 UncopyableFoo foo1('1'), foo2('2');
7845 const Matcher<const UncopyableFoo&> m =
7846 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7848 // We don't want the addresses of the parameters printed, as most
7849 // likely they will just annoy the user. If the addresses are
7850 // interesting, the user should consider passing the parameters by
7851 // pointers instead.
7852 EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
7856 // Tests that a simple MATCHER_P2() definition works.
7858 MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
7860 TEST(MatcherPnMacroTest, Works) {
7861 const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
7862 EXPECT_TRUE(m.Matches(36L));
7863 EXPECT_FALSE(m.Matches(15L));
7865 EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
7866 EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
7867 EXPECT_EQ("", Explain(m, 36L));
7868 EXPECT_EQ("", Explain(m, 15L));
7871 // Tests that MATCHER*() definitions can be overloaded on the number
7872 // of parameters; also tests MATCHER_Pn() where n >= 3.
7874 MATCHER(EqualsSumOf, "") { return arg == 0; }
7875 MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
7876 MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
7877 MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
7878 MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
7879 MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
7880 MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
7881 return arg == a + b + c + d + e + f;
7883 MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
7884 return arg == a + b + c + d + e + f + g;
7886 MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
7887 return arg == a + b + c + d + e + f + g + h;
7889 MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
7890 return arg == a + b + c + d + e + f + g + h + i;
7892 MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
7893 return arg == a + b + c + d + e + f + g + h + i + j;
7896 TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
7897 EXPECT_THAT(0, EqualsSumOf());
7898 EXPECT_THAT(1, EqualsSumOf(1));
7899 EXPECT_THAT(12, EqualsSumOf(10, 2));
7900 EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
7901 EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
7902 EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
7903 EXPECT_THAT("abcdef",
7904 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
7905 EXPECT_THAT("abcdefg",
7906 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
7907 EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7909 EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7910 'f', 'g', "h", 'i'));
7911 EXPECT_THAT("abcdefghij",
7912 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
7913 'i', ::std::string("j")));
7915 EXPECT_THAT(1, Not(EqualsSumOf()));
7916 EXPECT_THAT(-1, Not(EqualsSumOf(1)));
7917 EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
7918 EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
7919 EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
7920 EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
7921 EXPECT_THAT("abcdef ",
7922 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
7923 EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7925 EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7926 "e", 'f', 'g', "h")));
7927 EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7928 "e", 'f', 'g', "h", 'i')));
7929 EXPECT_THAT("abcdefghij ",
7930 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
7931 "h", 'i', ::std::string("j"))));
7934 // Tests that a MATCHER_Pn() definition can be instantiated with any
7935 // compatible parameter types.
7936 TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
7937 EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
7938 EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
7940 EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
7941 EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
7944 // Tests that the matcher body can promote the parameter types.
7946 MATCHER_P2(EqConcat, prefix, suffix, "") {
7947 // The following lines promote the two parameters to desired types.
7948 std::string prefix_str(prefix);
7949 char suffix_char = static_cast<char>(suffix);
7950 return arg == prefix_str + suffix_char;
7953 TEST(MatcherPnMacroTest, SimpleTypePromotion) {
7954 Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
7955 Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
7956 EXPECT_FALSE(no_promo.Matches("fool"));
7957 EXPECT_FALSE(promo.Matches("fool"));
7958 EXPECT_TRUE(no_promo.Matches("foot"));
7959 EXPECT_TRUE(promo.Matches("foot"));
7962 // Verifies the type of a MATCHER*.
7964 TEST(MatcherPnMacroTest, TypesAreCorrect) {
7965 // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
7966 EqualsSumOfMatcher a0 = EqualsSumOf();
7968 // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
7969 EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
7971 // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
7972 // variable, and so on.
7973 EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
7974 EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
7975 EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
7976 EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
7977 EqualsSumOf(1, 2, 3, 4, '5');
7978 EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
7979 EqualsSumOf(1, 2, 3, 4, 5, '6');
7980 EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
7981 EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
7982 EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
7983 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
7984 EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
7985 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
7986 EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
7987 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
7989 // Avoid "unused variable" warnings.
8003 // Tests that matcher-typed parameters can be used in Value() inside a
8004 // MATCHER_Pn definition.
8006 // Succeeds if arg matches exactly 2 of the 3 matchers.
8007 MATCHER_P3(TwoOf, m1, m2, m3, "") {
8008 const int count = static_cast<int>(Value(arg, m1)) +
8009 static_cast<int>(Value(arg, m2)) +
8010 static_cast<int>(Value(arg, m3));
8014 TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
8015 EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
8016 EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
8019 // Tests Contains().
8021 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
8022 list<int> some_list;
8023 some_list.push_back(3);
8024 some_list.push_back(1);
8025 some_list.push_back(2);
8026 EXPECT_THAT(some_list, Contains(1));
8027 EXPECT_THAT(some_list, Contains(Gt(2.5)));
8028 EXPECT_THAT(some_list, Contains(Eq(2.0f)));
8030 list<std::string> another_list;
8031 another_list.push_back("fee");
8032 another_list.push_back("fie");
8033 another_list.push_back("foe");
8034 another_list.push_back("fum");
8035 EXPECT_THAT(another_list, Contains(std::string("fee")));
8038 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
8039 list<int> some_list;
8040 some_list.push_back(3);
8041 some_list.push_back(1);
8042 EXPECT_THAT(some_list, Not(Contains(4)));
8045 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
8050 EXPECT_THAT(some_set, Contains(Eq(1.0)));
8051 EXPECT_THAT(some_set, Contains(Eq(3.0f)));
8052 EXPECT_THAT(some_set, Contains(2));
8054 set<std::string> another_set;
8055 another_set.insert("fee");
8056 another_set.insert("fie");
8057 another_set.insert("foe");
8058 another_set.insert("fum");
8059 EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
8062 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
8066 EXPECT_THAT(some_set, Not(Contains(4)));
8068 set<std::string> c_string_set;
8069 c_string_set.insert("hello");
8070 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
8073 TEST(ContainsTest, ExplainsMatchResultCorrectly) {
8074 const int a[2] = {1, 2};
8075 Matcher<const int(&)[2]> m = Contains(2);
8076 EXPECT_EQ("whose element #1 matches", Explain(m, a));
8079 EXPECT_EQ("", Explain(m, a));
8081 m = Contains(GreaterThan(0));
8082 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
8084 m = Contains(GreaterThan(10));
8085 EXPECT_EQ("", Explain(m, a));
8088 TEST(ContainsTest, DescribesItselfCorrectly) {
8089 Matcher<vector<int>> m = Contains(1);
8090 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
8092 Matcher<vector<int>> m2 = Not(m);
8093 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
8096 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
8097 map<std::string, int> my_map;
8098 const char* bar = "a string";
8100 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
8102 map<std::string, int> another_map;
8103 another_map["fee"] = 1;
8104 another_map["fie"] = 2;
8105 another_map["foe"] = 3;
8106 another_map["fum"] = 4;
8107 EXPECT_THAT(another_map,
8108 Contains(pair<const std::string, int>(std::string("fee"), 1)));
8109 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
8112 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
8113 map<int, int> some_map;
8116 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
8119 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
8120 const char* string_array[] = {"fee", "fie", "foe", "fum"};
8121 EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
8124 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
8125 int int_array[] = {1, 2, 3, 4};
8126 EXPECT_THAT(int_array, Not(Contains(5)));
8129 TEST(ContainsTest, AcceptsMatcher) {
8130 const int a[] = {1, 2, 3};
8131 EXPECT_THAT(a, Contains(Gt(2)));
8132 EXPECT_THAT(a, Not(Contains(Gt(4))));
8135 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
8136 const int a[] = {1, 2};
8137 const int* const pointer = a;
8138 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
8139 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
8142 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
8143 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
8144 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
8145 EXPECT_THAT(a, Contains(Contains(5)));
8146 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
8147 EXPECT_THAT(a, Contains(Not(Contains(5))));
8150 TEST(AllOfArrayTest, BasicForms) {
8152 std::vector<int> v0{};
8153 std::vector<int> v1{1};
8154 std::vector<int> v2{2, 3};
8155 std::vector<int> v3{4, 4, 4};
8156 EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
8157 EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
8158 EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
8159 EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
8160 EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
8162 int ar[6] = {1, 2, 3, 4, 4, 4};
8163 EXPECT_THAT(0, AllOfArray(ar, 0));
8164 EXPECT_THAT(1, AllOfArray(ar, 1));
8165 EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
8166 EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
8167 EXPECT_THAT(4, AllOfArray(ar + 3, 3));
8169 // int ar0[0]; Not usable
8171 int ar2[2] = {2, 3};
8172 int ar3[3] = {4, 4, 4};
8173 // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
8174 EXPECT_THAT(1, AllOfArray(ar1));
8175 EXPECT_THAT(2, Not(AllOfArray(ar1)));
8176 EXPECT_THAT(3, Not(AllOfArray(ar2)));
8177 EXPECT_THAT(4, AllOfArray(ar3));
8179 EXPECT_THAT(0, AllOfArray(v0));
8180 EXPECT_THAT(1, AllOfArray(v1));
8181 EXPECT_THAT(2, Not(AllOfArray(v1)));
8182 EXPECT_THAT(3, Not(AllOfArray(v2)));
8183 EXPECT_THAT(4, AllOfArray(v3));
8185 EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
8186 EXPECT_THAT(1, AllOfArray({1}));
8187 EXPECT_THAT(2, Not(AllOfArray({1})));
8188 EXPECT_THAT(3, Not(AllOfArray({2, 3})));
8189 EXPECT_THAT(4, AllOfArray({4, 4, 4}));
8192 TEST(AllOfArrayTest, Matchers) {
8194 std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
8195 EXPECT_THAT(0, Not(AllOfArray(matchers)));
8196 EXPECT_THAT(1, AllOfArray(matchers));
8197 EXPECT_THAT(2, Not(AllOfArray(matchers)));
8199 EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
8200 EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
8203 TEST(AnyOfArrayTest, BasicForms) {
8205 std::vector<int> v0{};
8206 std::vector<int> v1{1};
8207 std::vector<int> v2{2, 3};
8208 EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
8209 EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
8210 EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
8211 EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
8212 EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
8214 int ar[3] = {1, 2, 3};
8215 EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
8216 EXPECT_THAT(1, AnyOfArray(ar, 1));
8217 EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
8218 EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
8219 EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
8221 // int ar0[0]; Not usable
8223 int ar2[2] = {2, 3};
8224 // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
8225 EXPECT_THAT(1, AnyOfArray(ar1));
8226 EXPECT_THAT(2, Not(AnyOfArray(ar1)));
8227 EXPECT_THAT(3, AnyOfArray(ar2));
8228 EXPECT_THAT(4, Not(AnyOfArray(ar2)));
8230 EXPECT_THAT(0, Not(AnyOfArray(v0)));
8231 EXPECT_THAT(1, AnyOfArray(v1));
8232 EXPECT_THAT(2, Not(AnyOfArray(v1)));
8233 EXPECT_THAT(3, AnyOfArray(v2));
8234 EXPECT_THAT(4, Not(AnyOfArray(v2)));
8236 EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
8237 EXPECT_THAT(1, AnyOfArray({1}));
8238 EXPECT_THAT(2, Not(AnyOfArray({1})));
8239 EXPECT_THAT(3, AnyOfArray({2, 3}));
8240 EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
8243 TEST(AnyOfArrayTest, Matchers) {
8244 // We negate test AllOfArrayTest.Matchers.
8246 std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
8247 EXPECT_THAT(0, AnyOfArray(matchers));
8248 EXPECT_THAT(1, Not(AnyOfArray(matchers)));
8249 EXPECT_THAT(2, AnyOfArray(matchers));
8251 EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
8252 EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
8255 TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
8256 // AnyOfArray and AllOfArry use the same underlying template-template,
8257 // thus it is sufficient to test one here.
8258 const std::vector<int> v0{};
8259 const std::vector<int> v1{1};
8260 const std::vector<int> v2{2, 3};
8261 const Matcher<int> m0 = AnyOfArray(v0);
8262 const Matcher<int> m1 = AnyOfArray(v1);
8263 const Matcher<int> m2 = AnyOfArray(v2);
8264 EXPECT_EQ("", Explain(m0, 0));
8265 EXPECT_EQ("", Explain(m1, 1));
8266 EXPECT_EQ("", Explain(m1, 2));
8267 EXPECT_EQ("", Explain(m2, 3));
8268 EXPECT_EQ("", Explain(m2, 4));
8269 EXPECT_EQ("()", Describe(m0));
8270 EXPECT_EQ("(is equal to 1)", Describe(m1));
8271 EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
8272 EXPECT_EQ("()", DescribeNegation(m0));
8273 EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
8274 EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
8275 // Explain with matchers
8276 const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
8277 const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
8278 // Explains the first positiv match and all prior negative matches...
8279 EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
8280 EXPECT_EQ("which is the same as 1", Explain(g1, 1));
8281 EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
8282 EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
8284 EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
8286 EXPECT_EQ("which is 1 more than 1", // Only the first
8290 TEST(AllOfTest, HugeMatcher) {
8291 // Verify that using AllOf with many arguments doesn't cause
8292 // the compiler to exceed template instantiation depth limit.
8293 EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
8294 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
8297 TEST(AnyOfTest, HugeMatcher) {
8298 // Verify that using AnyOf with many arguments doesn't cause
8299 // the compiler to exceed template instantiation depth limit.
8300 EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
8301 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
8304 namespace adl_test {
8306 // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
8307 // don't issue unqualified recursive calls. If they do, the argument dependent
8308 // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
8309 // as a candidate and the compilation will break due to an ambiguous overload.
8311 // The matcher must be in the same namespace as AllOf/AnyOf to make argument
8312 // dependent lookup find those.
8318 template <typename T1, typename T2>
8319 bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
8323 TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
8325 testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8328 template <typename T1, typename T2>
8329 bool AnyOf(const T1&, const T2&) {
8333 TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
8335 testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8338 } // namespace adl_test
8340 TEST(AllOfTest, WorksOnMoveOnlyType) {
8341 std::unique_ptr<int> p(new int(3));
8342 EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
8343 EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
8346 TEST(AnyOfTest, WorksOnMoveOnlyType) {
8347 std::unique_ptr<int> p(new int(3));
8348 EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
8349 EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
8352 MATCHER(IsNotNull, "") { return arg != nullptr; }
8354 // Verifies that a matcher defined using MATCHER() can work on
8356 TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
8357 std::unique_ptr<int> p(new int(3));
8358 EXPECT_THAT(p, IsNotNull());
8359 EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
8362 MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
8364 // Verifies that a matcher defined using MATCHER_P*() can work on
8366 TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
8367 std::unique_ptr<int> p(new int(3));
8368 EXPECT_THAT(p, UniquePointee(3));
8369 EXPECT_THAT(p, Not(UniquePointee(2)));
8372 #if GTEST_HAS_EXCEPTIONS
8374 // std::function<void()> is used below for compatibility with older copies of
8375 // GCC. Normally, a raw lambda is all that is needed.
8377 // Test that examples from documentation compile
8378 TEST(ThrowsTest, Examples) {
8380 std::function<void()>([]() { throw std::runtime_error("message"); }),
8381 Throws<std::runtime_error>());
8384 std::function<void()>([]() { throw std::runtime_error("message"); }),
8385 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8388 TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
8389 EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
8390 Throws<std::exception>());
8393 TEST(ThrowsTest, CallableExecutedExactlyOnce) {
8396 EXPECT_THAT(std::function<void()>([&a]() {
8403 EXPECT_THAT(std::function<void()>([&a]() {
8405 throw std::runtime_error("message");
8407 Throws<std::runtime_error>());
8410 EXPECT_THAT(std::function<void()>([&a]() {
8412 throw std::runtime_error("message");
8414 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8417 EXPECT_THAT(std::function<void()>([&a]() {
8419 throw std::runtime_error("message");
8421 Throws<std::runtime_error>(
8422 Property(&std::runtime_error::what, HasSubstr("message"))));
8426 TEST(ThrowsTest, Describe) {
8427 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8428 std::stringstream ss;
8429 matcher.DescribeTo(&ss);
8430 auto explanation = ss.str();
8431 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8434 TEST(ThrowsTest, Success) {
8435 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8436 StringMatchResultListener listener;
8437 EXPECT_TRUE(matcher.MatchAndExplain(
8438 []() { throw std::runtime_error("error message"); }, &listener));
8439 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8442 TEST(ThrowsTest, FailWrongType) {
8443 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8444 StringMatchResultListener listener;
8445 EXPECT_FALSE(matcher.MatchAndExplain(
8446 []() { throw std::logic_error("error message"); }, &listener));
8447 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8448 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8451 TEST(ThrowsTest, FailWrongTypeNonStd) {
8452 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8453 StringMatchResultListener listener;
8454 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8455 EXPECT_THAT(listener.str(),
8456 HasSubstr("throws an exception of an unknown type"));
8459 TEST(ThrowsTest, FailNoThrow) {
8460 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8461 StringMatchResultListener listener;
8462 EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
8463 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8466 class ThrowsPredicateTest
8467 : public TestWithParam<Matcher<std::function<void()>>> {};
8469 TEST_P(ThrowsPredicateTest, Describe) {
8470 Matcher<std::function<void()>> matcher = GetParam();
8471 std::stringstream ss;
8472 matcher.DescribeTo(&ss);
8473 auto explanation = ss.str();
8474 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8475 EXPECT_THAT(explanation, HasSubstr("error message"));
8478 TEST_P(ThrowsPredicateTest, Success) {
8479 Matcher<std::function<void()>> matcher = GetParam();
8480 StringMatchResultListener listener;
8481 EXPECT_TRUE(matcher.MatchAndExplain(
8482 []() { throw std::runtime_error("error message"); }, &listener));
8483 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8486 TEST_P(ThrowsPredicateTest, FailWrongType) {
8487 Matcher<std::function<void()>> matcher = GetParam();
8488 StringMatchResultListener listener;
8489 EXPECT_FALSE(matcher.MatchAndExplain(
8490 []() { throw std::logic_error("error message"); }, &listener));
8491 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8492 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8495 TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
8496 Matcher<std::function<void()>> matcher = GetParam();
8497 StringMatchResultListener listener;
8498 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8499 EXPECT_THAT(listener.str(),
8500 HasSubstr("throws an exception of an unknown type"));
8503 TEST_P(ThrowsPredicateTest, FailWrongMessage) {
8504 Matcher<std::function<void()>> matcher = GetParam();
8505 StringMatchResultListener listener;
8506 EXPECT_FALSE(matcher.MatchAndExplain(
8507 []() { throw std::runtime_error("wrong message"); }, &listener));
8508 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8509 EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
8512 TEST_P(ThrowsPredicateTest, FailNoThrow) {
8513 Matcher<std::function<void()>> matcher = GetParam();
8514 StringMatchResultListener listener;
8515 EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
8516 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8519 INSTANTIATE_TEST_SUITE_P(
8520 AllMessagePredicates, ThrowsPredicateTest,
8521 Values(Matcher<std::function<void()>>(
8522 ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
8524 // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
8525 TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
8527 Matcher<std::function<void()>> matcher =
8528 ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
8530 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8532 matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
8536 Matcher<uint64_t> inner = Eq(10);
8537 Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
8538 EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
8539 EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
8543 // Tests that ThrowsMessage("message") is equivalent
8544 // to ThrowsMessage(Eq<std::string>("message")).
8545 TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
8546 Matcher<std::function<void()>> matcher =
8547 ThrowsMessage<std::runtime_error>("error message");
8549 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8550 EXPECT_FALSE(matcher.Matches(
8551 []() { throw std::runtime_error("wrong error message"); }));
8554 #endif // GTEST_HAS_EXCEPTIONS
8557 } // namespace gmock_matchers_test
8558 } // namespace testing
8561 # pragma warning(pop)