39# pragma warning(disable:4244)
40# pragma warning(disable:4100)
51#include <forward_list>
63#include <unordered_map>
64#include <unordered_set>
74namespace gmock_matchers_test {
87using std::stringstream;
89using testing::internal::DummyMatchResultListener;
90using testing::internal::ElementMatcherPair;
91using testing::internal::ElementMatcherPairs;
92using testing::internal::ElementsAreArrayMatcher;
93using testing::internal::ExplainMatchFailureTupleTo;
94using testing::internal::FloatingEqMatcher;
96using testing::internal::IsReadableTypeName;
97using testing::internal::MatchMatrix;
98using testing::internal::PredicateFormatterFromMatcher;
100using testing::internal::StreamMatchResultListener;
106struct ContainerHelper {
107 MOCK_METHOD1(Call,
void(std::vector<std::unique_ptr<int>>));
110std::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));
117class 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_;
141 return MakeMatcher(
new GreaterThanMatcher(n));
144std::string OfType(
const std::string& type_name) {
146 return IsReadableTypeName(type_name) ?
" (of type " + type_name +
")" :
"";
155 return DescribeMatcher<T>(m);
160std::string DescribeNegation(
const Matcher<T>& m) {
161 return DescribeMatcher<T>(m,
true);
165template <
typename MatcherType,
typename Value>
166std::string Explain(
const MatcherType& m,
const Value&
x) {
167 StringMatchResultListener listener;
168 ExplainMatchResult(m,
x, &listener);
169 return listener.str();
172TEST(MonotonicMatcherTest, IsPrintable) {
174 ss << GreaterThan(5);
178TEST(MatchResultListenerTest, StreamingWorks) {
179 StringMatchResultListener listener;
180 listener <<
"hi" << 5;
190 DummyMatchResultListener dummy;
194TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
195 EXPECT_TRUE(DummyMatchResultListener().stream() ==
nullptr);
196 EXPECT_TRUE(StreamMatchResultListener(
nullptr).stream() ==
nullptr);
198 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
201TEST(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());
211class EvenMatcherImpl :
public MatcherInterface<int> {
213 bool MatchAndExplain(
int x,
214 MatchResultListener* )
const override {
218 void DescribeTo(ostream* os)
const override { *os <<
"is an even number"; }
226TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
232class NewEvenMatcherImpl :
public MatcherInterface<int> {
234 bool MatchAndExplain(
int x, MatchResultListener* listener)
const override {
235 const bool match =
x % 2 == 0;
237 *listener <<
"value % " << 2;
238 if (listener->stream() !=
nullptr) {
241 *listener->stream() <<
" == " << (
x % 2);
246 void DescribeTo(ostream* os)
const override { *os <<
"is an even number"; }
249TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
253 EXPECT_EQ(
"value % 2 == 0", Explain(m, 2));
254 EXPECT_EQ(
"value % 2 == 1", Explain(m, 3));
258TEST(MatcherTest, CanBeDefaultConstructed) {
263TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
264 const MatcherInterface<int>* impl =
new EvenMatcherImpl;
271TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
278TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
288 virtual ~Undefined() = 0;
289 static const int kInt = 1;
292TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
302TEST(MatcherTest, IsCopyable) {
316TEST(MatcherTest, CanDescribeItself) {
322TEST(MatcherTest, MatchAndExplain) {
324 StringMatchResultListener listener1;
326 EXPECT_EQ(
"which is 42 more than 0", listener1.str());
328 StringMatchResultListener listener2;
330 EXPECT_EQ(
"which is 9 less than 0", listener2.str());
335TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
347TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
357#if GTEST_INTERNAL_HAS_STRING_VIEW
360TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
372TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
384TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
397TEST(StringMatcherTest,
398 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
399 std::string
value =
"cats";
412TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
413 const MatcherInterface<int>* dummy_impl =
new EvenMatcherImpl;
420class ReferencesBarOrIsZeroImpl {
422 template <
typename T>
423 bool MatchAndExplain(
const T&
x,
424 MatchResultListener* )
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";
438PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
439 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
442TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
449 EXPECT_EQ(
"g_bar or zero", Describe(m1));
455 EXPECT_EQ(
"g_bar or zero", Describe(m2));
460class 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 {
471 *listener <<
"% " << 2;
472 if (listener->stream() !=
nullptr) {
475 *listener->stream() <<
" == " << (
x % 2);
481PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
482 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
485TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
506 EXPECT_EQ(
"% 2 == 0", Explain(m2,
'\x42'));
510TEST(MatcherCastTest, FromPolymorphicMatcher) {
521 explicit IntValue(
int a_value) : value_(a_value) {}
523 int value()
const {
return value_; }
529bool IsPositiveIntValue(
const IntValue&
foo) {
530 return foo.value() > 0;
535TEST(MatcherCastTest, FromCompatibleType) {
551TEST(MatcherCastTest, FromConstReferenceToNonReference) {
559TEST(MatcherCastTest, FromReferenceToNonReference) {
567TEST(MatcherCastTest, FromNonReferenceToConstReference) {
575TEST(MatcherCastTest, FromNonReferenceToReference) {
585TEST(MatcherCastTest, FromSameType) {
594TEST(MatcherCastTest, FromAValue) {
602TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
603 const int kExpected =
'c';
609struct NonImplicitlyConstructibleTypeWithOperatorEq {
611 const NonImplicitlyConstructibleTypeWithOperatorEq& ,
617 const NonImplicitlyConstructibleTypeWithOperatorEq& ) {
625TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
627 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
628 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
631 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
632 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
637 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
656namespace convertible_from_any {
658struct ConvertibleFromAny {
659 ConvertibleFromAny(
int a_value) :
value(a_value) {}
660 template <
typename T>
661 ConvertibleFromAny(
const T& ) :
value(-1) {
667bool operator==(
const ConvertibleFromAny& a,
const ConvertibleFromAny& b) {
668 return a.value == b.value;
671ostream&
operator<<(ostream& os,
const ConvertibleFromAny& a) {
672 return os << a.value;
675TEST(MatcherCastTest, ConversionConstructorIsUsed) {
676 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
681TEST(MatcherCastTest, FromConvertibleFromAny) {
682 Matcher<ConvertibleFromAny> m =
683 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
691struct IntReferenceWrapper {
692 IntReferenceWrapper(
const int& a_value) :
value(&a_value) {}
696bool operator==(
const IntReferenceWrapper& a,
const IntReferenceWrapper& b) {
697 return a.value == b.value;
700TEST(MatcherCastTest, ValueIsNotCopied) {
702 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
715class Derived :
public Base {
717 Derived() : Base() {}
721class OtherDerived :
public Base {};
724TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
725 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
733TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
734 Matcher<double> m1 = DoubleEq(1.0);
735 Matcher<float> m2 = SafeMatcherCast<float>(m1);
739 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>(
'a'));
746TEST(SafeMatcherCastTest, FromBaseClass) {
748 Matcher<Base*> m1 = Eq(&d);
749 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
753 Matcher<Base&> m3 = Ref(d);
754 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
760TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
762 Matcher<const int&> m1 = Ref(n);
763 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
770TEST(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);
775 EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(
new int)));
779TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
780 Matcher<int> m1 = Eq(0);
781 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
789TEST(SafeMatcherCastTest, FromSameType) {
790 Matcher<int> m1 = Eq(0);
791 Matcher<int> m2 = SafeMatcherCast<int>(m1);
798namespace convertible_from_any {
799TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
800 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
805TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
806 Matcher<ConvertibleFromAny> m =
807 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
815TEST(SafeMatcherCastTest, ValueIsNotCopied) {
817 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
822TEST(ExpectThat, TakesLiterals) {
828TEST(ExpectThat, TakesFunctions) {
830 static void Func() {}
832 void (*func)() = Helper::Func;
838TEST(ATest, MatchesAnyValue) {
840 Matcher<double> m1 = A<double>();
847 Matcher<int&> m2 = A<int&>();
852TEST(ATest, WorksForDerivedClass) {
862TEST(ATest, CanDescribeSelf) {
863 EXPECT_EQ(
"is anything", Describe(A<bool>()));
867TEST(AnTest, MatchesAnyValue) {
869 Matcher<int> m1 = An<int>();
876 Matcher<int&> m2 = An<int&>();
882TEST(AnTest, CanDescribeSelf) {
883 EXPECT_EQ(
"is anything", Describe(An<int>()));
888TEST(UnderscoreTest, MatchesAnyValue) {
897 Matcher<const bool&> m2 = _;
903TEST(UnderscoreTest, CanDescribeSelf) {
909TEST(EqTest, MatchesEqualValue) {
911 const char a1[] =
"hi";
912 const char a2[] =
"hi";
914 Matcher<const char*> m1 = Eq(a1);
923 Unprintable() : c_(
'a') {}
925 bool operator==(
const Unprintable& )
const {
return true; }
927 char dummy_c() {
return c_; }
932TEST(EqTest, CanDescribeSelf) {
933 Matcher<Unprintable> m = Eq(Unprintable());
934 EXPECT_EQ(
"is equal to 1-byte object <61>", Describe(m));
939TEST(EqTest, IsPolymorphic) {
940 Matcher<int> m1 = Eq(1);
944 Matcher<char> m2 = Eq(1);
950TEST(TypedEqTest, ChecksEqualityForGivenType) {
951 Matcher<char> m1 = TypedEq<char>(
'a');
955 Matcher<int> m2 = TypedEq<int>(6);
961TEST(TypedEqTest, CanDescribeSelf) {
962 EXPECT_EQ(
"is equal to 2", Describe(TypedEq<int>(2)));
972 static bool IsTypeOf(
const T& ) {
return true; }
974 template <
typename T2>
975 static void IsTypeOf(
T2 v);
978TEST(TypedEqTest, HasSpecifiedType) {
980 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
981 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
985TEST(GeTest, ImplementsGreaterThanOrEqual) {
986 Matcher<int> m1 = Ge(0);
993TEST(GeTest, CanDescribeSelf) {
994 Matcher<int> m = Ge(5);
999TEST(GtTest, ImplementsGreaterThan) {
1000 Matcher<double> m1 = Gt(0);
1007TEST(GtTest, CanDescribeSelf) {
1008 Matcher<int> m = Gt(5);
1013TEST(LeTest, ImplementsLessThanOrEqual) {
1014 Matcher<char> m1 = Le(
'b');
1021TEST(LeTest, CanDescribeSelf) {
1022 Matcher<int> m = Le(5);
1027TEST(LtTest, ImplementsLessThan) {
1028 Matcher<const std::string&> m1 = Lt(
"Hello");
1035TEST(LtTest, CanDescribeSelf) {
1036 Matcher<int> m = Lt(5);
1041TEST(NeTest, ImplementsNotEqual) {
1042 Matcher<int> m1 = Ne(0);
1049TEST(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_; }
1078#if defined(_MSC_VER) && (_MSC_VER < 1910)
1079TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
1081TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1087 helper.Call(MoveOnly(0));
1089 helper.Call(MoveOnly(1));
1091 helper.Call(MoveOnly(0));
1093 helper.Call(MoveOnly(-1));
1095 helper.Call(MoveOnly(0));
1097 helper.Call(MoveOnly(1));
1101TEST(IsNullTest, MatchesNullPointer) {
1102 Matcher<int*> m1 =
IsNull();
1108 Matcher<const char*> m2 =
IsNull();
1109 const char* p2 =
nullptr;
1113 Matcher<void*> m3 =
IsNull();
1116 EXPECT_FALSE(m3.Matches(
reinterpret_cast<void*
>(0xbeef)));
1119TEST(IsNullTest, StdFunction) {
1120 const Matcher<std::function<void()>> m =
IsNull();
1127TEST(IsNullTest, CanDescribeSelf) {
1128 Matcher<int*> m =
IsNull();
1130 EXPECT_EQ(
"isn't NULL", DescribeNegation(m));
1134TEST(NotNullTest, MatchesNonNullPointer) {
1135 Matcher<int*> m1 = NotNull();
1141 Matcher<const char*> m2 = NotNull();
1142 const char* p2 =
nullptr;
1147TEST(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);
1156TEST(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);
1165TEST(NotNullTest, StdFunction) {
1166 const Matcher<std::function<void()>> m = NotNull();
1173TEST(NotNullTest, CanDescribeSelf) {
1174 Matcher<int*> m = NotNull();
1180TEST(RefTest, MatchesSameVariable) {
1183 Matcher<int&> m = Ref(a);
1189TEST(RefTest, CanDescribeSelf) {
1191 Matcher<int&> m = Ref(n);
1193 ss <<
"references the variable @" << &n <<
" 5";
1199TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1202 Matcher<const int&> m = Ref(a);
1211TEST(RefTest, IsCovariant) {
1214 Matcher<const Base&> m1 = Ref(base);
1225TEST(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 @"));
1237template <
typename T = std::
string>
1238std::string FromStringLike(internal::StringLike<T> str) {
1239 return std::string(str);
1242TEST(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")));
1251 EXPECT_EQ(
"foo", FromStringLike({
'f',
'o',
'o'}));
1252 const char buf[] =
"foo";
1253 EXPECT_EQ(
"foo", FromStringLike({buf, buf + 3}));
1256TEST(StrEqTest, MatchesEqualString) {
1257 Matcher<const char*> m = StrEq(std::string(
"Hello"));
1262 Matcher<const std::string&> m2 = StrEq(
"Hello");
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")));
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")));
1280TEST(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));
1294TEST(StrNeTest, MatchesUnequalString) {
1295 Matcher<const char*> m = StrNe(
"Hello");
1300 Matcher<std::string> m2 = StrNe(std::string(
"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(
"")));
1308 EXPECT_FALSE(m3.Matches(internal::StringView(
"Hello")));
1312TEST(StrNeTest, CanDescribeSelf) {
1313 Matcher<const char*> m = StrNe(
"Hi");
1314 EXPECT_EQ(
"isn't equal to \"Hi\"", Describe(m));
1317TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1318 Matcher<const char*> m = StrCaseEq(std::string(
"Hello"));
1324 Matcher<const std::string&> m2 = StrCaseEq(
"Hello");
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")));
1338TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1339 std::string str1(
"oabocdooeoo");
1340 std::string str2(
"OABOCDOOEOO");
1341 Matcher<const std::string&> m0 = StrCaseEq(str1);
1344 str1[3] = str2[3] =
'\0';
1345 Matcher<const std::string&> m1 = StrCaseEq(str1);
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';
1354 Matcher<const std::string&> m3 = StrCaseEq(str1);
1358 str2.append(1,
'\0');
1363TEST(StrCaseEqTest, CanDescribeSelf) {
1364 Matcher<std::string> m = StrCaseEq(
"Hi");
1365 EXPECT_EQ(
"is equal to (ignoring case) \"Hi\"", Describe(m));
1368TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1369 Matcher<const char*> m = StrCaseNe(
"Hello");
1375 Matcher<std::string> m2 = StrCaseNe(std::string(
"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")));
1384 EXPECT_FALSE(m3.Matches(internal::StringView(
"Hello")));
1385 EXPECT_FALSE(m3.Matches(internal::StringView(
"hello")));
1389TEST(StrCaseNeTest, CanDescribeSelf) {
1390 Matcher<const char*> m = StrCaseNe(
"Hi");
1391 EXPECT_EQ(
"isn't equal to (ignoring case) \"Hi\"", Describe(m));
1395TEST(HasSubstrTest, WorksForStringClasses) {
1396 const Matcher<std::string> m1 = HasSubstr(
"foo");
1397 EXPECT_TRUE(m1.Matches(std::string(
"I love food.")));
1400 const Matcher<const std::string&> m2 = HasSubstr(
"foo");
1401 EXPECT_TRUE(m2.Matches(std::string(
"I love food.")));
1404 const Matcher<std::string> m_empty = HasSubstr(
"");
1406 EXPECT_TRUE(m_empty.Matches(std::string(
"not empty")));
1410TEST(HasSubstrTest, WorksForCStrings) {
1411 const Matcher<char*> m1 = HasSubstr(
"foo");
1412 EXPECT_TRUE(m1.Matches(
const_cast<char*
>(
"I love food.")));
1416 const Matcher<const char*> m2 = HasSubstr(
"foo");
1421 const Matcher<const char*> m_empty = HasSubstr(
"");
1427#if GTEST_INTERNAL_HAS_STRING_VIEW
1429TEST(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")));
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")));
1441 const Matcher<const internal::StringView&> m3 = HasSubstr(
"");
1442 EXPECT_TRUE(m3.Matches(internal::StringView(
"foo")));
1443 EXPECT_TRUE(m3.Matches(internal::StringView(
"")));
1449TEST(HasSubstrTest, CanDescribeSelf) {
1450 Matcher<std::string> m = HasSubstr(
"foo\n\"");
1451 EXPECT_EQ(
"has substring \"foo\\n\\\"\"", Describe(m));
1454TEST(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));
1460TEST(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)));
1468TEST(KeyTest, MatchesCorrectly) {
1469 pair<int, std::string>
p(25,
"foo");
1476TEST(KeyTest, WorksWithMoveOnly) {
1477 pair<std::unique_ptr<int>, std::unique_ptr<int>>
p;
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; }
1494auto get(
const PairWithGet&
value) ->
decltype(
value.GetImpl(Tag<I>())) {
1495 return value.GetImpl(Tag<I>());
1497TEST(PairTest, MatchesPairWithGetCorrectly) {
1498 PairWithGet
p{25,
"foo"};
1504 std::vector<PairWithGet> v = {{11,
"Foo"}, {29,
"gMockIsBestMock"}};
1508TEST(KeyTest, SafelyCastsInnerMatcher) {
1509 Matcher<int> is_positive = Gt(0);
1510 Matcher<int> is_negative = Lt(0);
1511 pair<char, bool>
p(
'a',
true);
1516TEST(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'));
1525TEST(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'));
1532 container.insert(make_pair(25,
'd'));
1534 container.insert(make_pair(25,
'e'));
1541TEST(PairTest, Typing) {
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);
1551TEST(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));
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));
1566TEST(PairTest, CanExplainMatchResultTo) {
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)));
1575 EXPECT_EQ(
"whose second field does not match, which is 2 less than 0",
1576 Explain(m, make_pair(1, -2)));
1580 EXPECT_EQ(
"whose first field does not match, which is 1 less than 0",
1581 Explain(m, make_pair(-1, 2)));
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)));
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)));
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)));
1604TEST(PairTest, MatchesCorrectly) {
1605 pair<int, std::string>
p(25,
"foo");
1624TEST(PairTest, WorksWithMoveOnly) {
1625 pair<std::unique_ptr<int>, std::unique_ptr<int>>
p;
1626 p.second.reset(
new int(7));
1630TEST(PairTest, SafelyCastsInnerMatchers) {
1631 Matcher<int> is_positive = Gt(0);
1632 Matcher<int> is_negative = Lt(0);
1633 pair<char, bool>
p(
'a',
true);
1640TEST(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'));
1648 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1651TEST(FieldsAreTest, MatchesCorrectly) {
1652 std::tuple<int, std::string, double>
p(25,
"foo", .5);
1656 EXPECT_THAT(
p, FieldsAre(Ge(20), HasSubstr(
"o"), DoubleEq(.5)));
1664TEST(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));
1676TEST(FieldsAreTest, CanExplainMatchResultTo) {
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)));
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)));
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)));
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
1713TEST(FieldsAreTest, StructuredBindings) {
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;
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;
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;
1788 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1792TEST(ContainsTest, WorksWithMoveOnly) {
1793 ContainerHelper helper;
1795 helper.Call(MakeUniquePtrs({1, 2}));
1798TEST(PairTest, UseGetInsteadOfMembers) {
1799 PairWithGet pair{7,
"ABC"};
1804 std::vector<PairWithGet> v = {{11,
"Foo"}, {29,
"gMockIsBestMock"}};
1806 ElementsAre(Pair(11, std::string(
"Foo")), Pair(Ge(10), Not(
""))));
1811TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1812 const Matcher<const char*> m1 = StartsWith(std::string(
""));
1817 const Matcher<const std::string&> m2 = StartsWith(
"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")));
1833TEST(StartsWithTest, CanDescribeSelf) {
1834 Matcher<const std::string> m = StartsWith(
"Hi");
1835 EXPECT_EQ(
"starts with \"Hi\"", Describe(m));
1840TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1841 const Matcher<const char*> m1 = EndsWith(
"");
1846 const Matcher<const std::string&> m2 = EndsWith(std::string(
"Hi"));
1853#if GTEST_INTERNAL_HAS_STRING_VIEW
1854 const Matcher<const internal::StringView&> m4 =
1855 EndsWith(internal::StringView(
""));
1859 EXPECT_TRUE(m4.Matches(internal::StringView(
"")));
1863TEST(EndsWithTest, CanDescribeSelf) {
1864 Matcher<const std::string> m = EndsWith(
"Hi");
1865 EXPECT_EQ(
"ends with \"Hi\"", Describe(m));
1870TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1871 const Matcher<const char*> m1 = MatchesRegex(
"a.*z");
1876 const Matcher<const std::string&> m2 = MatchesRegex(
new RE(
"a.*z"));
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")));
1887 const Matcher<const internal::StringView&> m4 =
1888 MatchesRegex(internal::StringView(
""));
1889 EXPECT_TRUE(m4.Matches(internal::StringView(
"")));
1894TEST(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));
1909TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1910 const Matcher<const char*> m1 = ContainsRegex(std::string(
"a.*z"));
1915 const Matcher<const std::string&> m2 = ContainsRegex(
new RE(
"a.*z"));
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")));
1927 const Matcher<const internal::StringView&> m4 =
1928 ContainsRegex(internal::StringView(
""));
1929 EXPECT_TRUE(m4.Matches(internal::StringView(
"")));
1934TEST(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));
1948#if GTEST_HAS_STD_WSTRING
1949TEST(StdWideStrEqTest, MatchesEqual) {
1950 Matcher<const wchar_t*> m = StrEq(::std::wstring(L
"Hello"));
1955 Matcher<const ::std::wstring&> m2 = StrEq(L
"Hello");
1959 Matcher<const ::std::wstring&> m3 = StrEq(L
"\xD3\x576\x8D3\xC74D");
1963 ::std::wstring str(L
"01204500800");
1965 Matcher<const ::std::wstring&> m4 = StrEq(str);
1967 str[0] = str[6] = str[7] = str[9] = str[10] = L
'\0';
1968 Matcher<const ::std::wstring&> m5 = StrEq(str);
1972TEST(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));
1990TEST(StdWideStrNeTest, MatchesUnequalString) {
1991 Matcher<const wchar_t*> m = StrNe(L
"Hello");
1996 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L
"Hello"));
2001TEST(StdWideStrNeTest, CanDescribeSelf) {
2002 Matcher<const wchar_t*> m = StrNe(L
"Hi");
2003 EXPECT_EQ(
"isn't equal to L\"Hi\"", Describe(m));
2006TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2007 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L
"Hello"));
2013 Matcher<const ::std::wstring&> m2 = StrCaseEq(L
"Hello");
2018TEST(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);
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';
2034 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
2038 str2.append(1, L
'\0');
2043TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2044 Matcher< ::std::wstring> m = StrCaseEq(L
"Hi");
2045 EXPECT_EQ(
"is equal to (ignoring case) L\"Hi\"", Describe(m));
2048TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2049 Matcher<const wchar_t*> m = StrCaseNe(L
"Hello");
2055 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L
"Hello"));
2060TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2061 Matcher<const wchar_t*> m = StrCaseNe(L
"Hi");
2062 EXPECT_EQ(
"isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2066TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2067 const Matcher< ::std::wstring> m1 = HasSubstr(L
"foo");
2068 EXPECT_TRUE(m1.Matches(::std::wstring(L
"I love food.")));
2071 const Matcher<const ::std::wstring&> m2 = HasSubstr(L
"foo");
2072 EXPECT_TRUE(m2.Matches(::std::wstring(L
"I love food.")));
2077TEST(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")));
2083 const Matcher<const wchar_t*> m2 = HasSubstr(L
"foo");
2090TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2091 Matcher< ::std::wstring> m = HasSubstr(L
"foo\n\"");
2092 EXPECT_EQ(
"has substring L\"foo\\n\\\"\"", Describe(m));
2097TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2098 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L
""));
2103 const Matcher<const ::std::wstring&> m2 = StartsWith(L
"Hi");
2111TEST(StdWideStartsWithTest, CanDescribeSelf) {
2112 Matcher<const ::std::wstring> m = StartsWith(L
"Hi");
2113 EXPECT_EQ(
"starts with L\"Hi\"", Describe(m));
2118TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2119 const Matcher<const wchar_t*> m1 = EndsWith(L
"");
2124 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L
"Hi"));
2132TEST(StdWideEndsWithTest, CanDescribeSelf) {
2133 Matcher<const ::std::wstring> m = EndsWith(L
"Hi");
2134 EXPECT_EQ(
"ends with L\"Hi\"", Describe(m));
2139typedef ::std::tuple<long, int> Tuple2;
2143TEST(Eq2Test, MatchesEqualArguments) {
2144 Matcher<const Tuple2&> m = Eq();
2150TEST(Eq2Test, CanDescribeSelf) {
2151 Matcher<const Tuple2&> m = Eq();
2152 EXPECT_EQ(
"are an equal pair", Describe(m));
2157TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2158 Matcher<const Tuple2&> m = Ge();
2165TEST(Ge2Test, CanDescribeSelf) {
2166 Matcher<const Tuple2&> m = Ge();
2167 EXPECT_EQ(
"are a pair where the first >= the second", Describe(m));
2172TEST(Gt2Test, MatchesGreaterThanArguments) {
2173 Matcher<const Tuple2&> m = Gt();
2180TEST(Gt2Test, CanDescribeSelf) {
2181 Matcher<const Tuple2&> m = Gt();
2182 EXPECT_EQ(
"are a pair where the first > the second", Describe(m));
2187TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2188 Matcher<const Tuple2&> m = Le();
2195TEST(Le2Test, CanDescribeSelf) {
2196 Matcher<const Tuple2&> m = Le();
2197 EXPECT_EQ(
"are a pair where the first <= the second", Describe(m));
2202TEST(Lt2Test, MatchesLessThanArguments) {
2203 Matcher<const Tuple2&> m = Lt();
2210TEST(Lt2Test, CanDescribeSelf) {
2211 Matcher<const Tuple2&> m = Lt();
2212 EXPECT_EQ(
"are a pair where the first < the second", Describe(m));
2217TEST(Ne2Test, MatchesUnequalArguments) {
2218 Matcher<const Tuple2&> m = Ne();
2225TEST(Ne2Test, CanDescribeSelf) {
2226 Matcher<const Tuple2&> m = Ne();
2227 EXPECT_EQ(
"are an unequal pair", Describe(m));
2230TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2231 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2232 Matcher<Pointers> matcher = Eq();
2240TEST(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();
2250 Matcher<float&> m_ref = IsNan();
2255 Matcher<const float&> m_cref = IsNan();
2262TEST(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();
2272 Matcher<double&> m_ref = IsNan();
2277 Matcher<const double&> m_cref = IsNan();
2284TEST(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();
2294 Matcher<long double&> m_ref = IsNan();
2299 Matcher<const long double&> m_cref = IsNan();
2306TEST(IsNan, NotMatchesNan) {
2307 Matcher<float> mf = Not(IsNan());
2308 EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2312 Matcher<double> md = Not(IsNan());
2313 EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2317 Matcher<long double> mld = Not(IsNan());
2318 EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2324TEST(IsNan, CanDescribeSelf) {
2325 Matcher<float> mf = IsNan();
2328 Matcher<double> md = IsNan();
2331 Matcher<long double> mld = IsNan();
2336TEST(IsNan, CanDescribeSelfWithNot) {
2337 Matcher<float> mf = Not(IsNan());
2340 Matcher<double> md = Not(IsNan());
2343 Matcher<long double> mld = Not(IsNan());
2349TEST(FloatEq2Test, MatchesEqualArguments) {
2350 typedef ::std::tuple<float, float> Tpl;
2351 Matcher<const Tpl&> m = FloatEq();
2353 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2358TEST(FloatEq2Test, CanDescribeSelf) {
2359 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2360 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2365TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2366 typedef ::std::tuple<float, float> Tpl;
2367 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2369 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2370 std::numeric_limits<float>::quiet_NaN())));
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)));
2377TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2378 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2379 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2384TEST(DoubleEq2Test, MatchesEqualArguments) {
2385 typedef ::std::tuple<double, double> Tpl;
2386 Matcher<const Tpl&> m = DoubleEq();
2388 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2393TEST(DoubleEq2Test, CanDescribeSelf) {
2394 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2395 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2400TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2401 typedef ::std::tuple<double, double> Tpl;
2402 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2404 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2405 std::numeric_limits<double>::quiet_NaN())));
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)));
2412TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2413 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2414 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2419TEST(FloatNear2Test, MatchesEqualArguments) {
2420 typedef ::std::tuple<float, float> Tpl;
2421 Matcher<const Tpl&> m = FloatNear(0.5f);
2428TEST(FloatNear2Test, CanDescribeSelf) {
2429 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2430 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2435TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2436 typedef ::std::tuple<float, float> Tpl;
2437 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2440 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2441 std::numeric_limits<float>::quiet_NaN())));
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)));
2448TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2449 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2450 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2455TEST(DoubleNear2Test, MatchesEqualArguments) {
2456 typedef ::std::tuple<double, double> Tpl;
2457 Matcher<const Tpl&> m = DoubleNear(0.5);
2464TEST(DoubleNear2Test, CanDescribeSelf) {
2465 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2466 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2471TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2472 typedef ::std::tuple<double, double> Tpl;
2473 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2476 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2477 std::numeric_limits<double>::quiet_NaN())));
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)));
2484TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2485 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2486 EXPECT_EQ(
"are an almost-equal pair", Describe(m));
2490TEST(NotTest, NegatesMatcher) {
2498TEST(NotTest, CanDescribeSelf) {
2499 Matcher<int> m = Not(Eq(5));
2500 EXPECT_EQ(
"isn't equal to 5", Describe(m));
2504TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
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);
2514void AllOfMatches(
int num,
const Matcher<int>& m) {
2517 for (
int i = 1;
i <= num; ++
i) {
2525TEST(AllOfTest, MatchesWhenAllMatch) {
2527 m = AllOf(Le(2), Ge(1));
2533 m = AllOf(Gt(0), Ne(1), Ne(2));
2539 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2546 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
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),
2579TEST(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));
2603TEST(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);
2633TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
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);
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);
2647TEST(AllOfTest, ExplainsResult) {
2653 m = AllOf(GreaterThan(10), Lt(30));
2654 EXPECT_EQ(
"which is 15 more than 10", Explain(m, 25));
2657 m = AllOf(GreaterThan(10), GreaterThan(20));
2658 EXPECT_EQ(
"which is 20 more than 10, and which is 10 more than 20",
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",
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",
2675 m = AllOf(GreaterThan(10), GreaterThan(20));
2676 EXPECT_EQ(
"which is 5 less than 10", Explain(m, 5));
2681 m = AllOf(GreaterThan(10), Lt(30));
2686 m = AllOf(GreaterThan(10), GreaterThan(20));
2687 EXPECT_EQ(
"which is 5 less than 20", Explain(m, 15));
2691static void AnyOfMatches(
int num,
const Matcher<int>& m) {
2694 for (
int i = 1;
i <= num; ++
i) {
2700static void AnyOfStringMatches(
int num,
const Matcher<std::string>& m) {
2704 for (
int i = 1;
i <= num; ++
i) {
2712TEST(AnyOfTest, MatchesWhenAnyMatches) {
2714 m = AnyOf(Le(1), Ge(3));
2719 m = AnyOf(Lt(0), Eq(1), Eq(2));
2725 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2732 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
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));
2754TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
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"));
2775TEST(ElementsAreTest, HugeMatcher) {
2776 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
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)));
2784TEST(ElementsAreTest, HugeMatcherStr) {
2785 vector<std::string> test_vector{
2786 "literal_string",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""};
2788 EXPECT_THAT(test_vector, UnorderedElementsAre(
"literal_string", _, _, _, _, _,
2793TEST(ElementsAreTest, HugeMatcherUnordered) {
2794 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
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)));
2803TEST(AnyOfTest, CanDescribeSelf) {
2805 m = AnyOf(Le(1), Ge(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 "
2825TEST(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));
2849TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
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);
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);
2863TEST(AnyOfTest, ExplainsResult) {
2869 m = AnyOf(GreaterThan(10), Lt(0));
2870 EXPECT_EQ(
"which is 5 less than 10", Explain(m, 5));
2873 m = AnyOf(GreaterThan(10), GreaterThan(20));
2874 EXPECT_EQ(
"which is 5 less than 10, and which is 15 less than 20",
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",
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",
2891 m = AnyOf(GreaterThan(10), GreaterThan(20));
2892 EXPECT_EQ(
"which is 5 more than 10", Explain(m, 15));
2897 m = AnyOf(GreaterThan(10), Lt(30));
2902 m = AnyOf(GreaterThan(30), GreaterThan(20));
2903 EXPECT_EQ(
"which is 5 more than 20", Explain(m, 25));
2913int IsPositive(
double x) {
2914 return x > 0 ? 1 : 0;
2919class IsGreaterThan {
2921 explicit IsGreaterThan(
int threshold) : threshold_(threshold) {}
2923 bool operator()(
int n)
const {
return n > threshold_; }
2934bool ReferencesFooAndIsZero(
const int& n) {
2935 return (&n == &
foo) && (n == 0);
2940TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2941 Matcher<double> m = Truly(IsPositive);
2947TEST(TrulyTest, CanBeUsedWithFunctor) {
2948 Matcher<int> m = Truly(IsGreaterThan(5));
2954class ConvertibleToBool {
2956 explicit ConvertibleToBool(
int number) : number_(number) {}
2957 operator bool()
const {
return number_ != 0; }
2963ConvertibleToBool IsNotZero(
int number) {
2964 return ConvertibleToBool(number);
2970TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2971 Matcher<int> m = Truly(IsNotZero);
2977TEST(TrulyTest, CanDescribeSelf) {
2978 Matcher<double> m = Truly(IsPositive);
2979 EXPECT_EQ(
"satisfies the given predicate",
2985TEST(TrulyTest, WorksForByRefArguments) {
2986 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2993TEST(TrulyTest, ExplainsFailures) {
2994 StringMatchResultListener listener;
2995 EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
2996 EXPECT_EQ(listener.str(),
"didn't satisfy the given predicate");
3001TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
3008TEST(MatchesTest, WorksOnByRefArguments) {
3016TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3017 Matcher<int> eq5 = Eq(5);
3025TEST(ValueTest, WorksWithPolymorphicMatcher) {
3030TEST(ValueTest, WorksWithMonomorphicMatcher) {
3031 const Matcher<int> is_zero = Eq(0);
3036 const Matcher<const int&> ref_n = Ref(n);
3041TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3042 StringMatchResultListener listener1;
3043 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3046 StringMatchResultListener listener2;
3047 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3051TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3052 const Matcher<int> is_even = PolymorphicIsEven();
3053 StringMatchResultListener listener1;
3054 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3057 const Matcher<const double&> is_zero = Eq(0);
3058 StringMatchResultListener listener2;
3059 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3063MATCHER(ConstructNoArg,
"") {
return true; }
3064MATCHER_P(Construct1Arg, arg1,
"") {
return true; }
3065MATCHER_P2(Construct2Args, arg1, arg2,
"") {
return true; }
3067TEST(MatcherConstruct, ExplicitVsImplicit) {
3070 ConstructNoArgMatcher m = {};
3073 ConstructNoArgMatcher m2;
3079 using M = Construct1ArgMatcherP<int>;
3085 Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
3091 return ExplainMatchResult(inner_matcher, arg, result_listener);
3094TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3098TEST(DescribeMatcherTest, WorksWithValue) {
3099 EXPECT_EQ(
"is equal to 42", DescribeMatcher<int>(42));
3100 EXPECT_EQ(
"isn't equal to 42", DescribeMatcher<int>(42,
true));
3103TEST(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));
3109TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3110 EXPECT_EQ(
"is even", DescribeMatcher<int>(PolymorphicIsEven()));
3111 EXPECT_EQ(
"is odd", DescribeMatcher<int>(PolymorphicIsEven(),
true));
3114TEST(AllArgsTest, WorksForTuple) {
3115 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
3116 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
3119TEST(AllArgsTest, WorksForNonTuple) {
3124class AllArgsHelper {
3134TEST(AllArgsTest, WorksInWithClause) {
3135 AllArgsHelper helper;
3137 .With(AllArgs(Lt()))
3138 .WillByDefault(
Return(1));
3141 .With(AllArgs(Gt()))
3148class OptionalMatchersHelper {
3150 OptionalMatchersHelper() {}
3165TEST(AllArgsTest, WorksWithoutMatchers) {
3166 OptionalMatchersHelper helper;
3188TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3191 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) <<
"This should succeed too.";
3197TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3200 static unsigned short n;
3205 "Expected: is > 10\n"
3206 " Actual: 5" + OfType(
"unsigned short"));
3211 "Expected: (is <= 7) and (is >= 5)\n"
3212 " Actual: 0" + OfType(
"unsigned short"));
3217TEST(MatcherAssertionTest, WorksForByRefArguments) {
3225 "Expected: does not reference the variable @");
3228 "Actual: 0" + OfType(
"int") +
", which is located @");
3233TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3234 Matcher<const char*> starts_with_he = StartsWith(
"he");
3237 Matcher<const std::string&> ends_with_ok = EndsWith(
"ok");
3239 const std::string bad =
"bad";
3242 "Expected: ends with \"ok\"\n"
3243 " Actual: \"bad\"");
3244 Matcher<int> is_greater_than_5 = Gt(5);
3247 "Expected: is > 5\n"
3248 " Actual: 5" + OfType(
"int"));
3252template <
typename RawType>
3277 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3278 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3282 EXPECT_EQ(
sizeof(RawType),
sizeof(Bits));
3288 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3289 Matcher<RawType> m1 = matcher_maker(0.0);
3298 Matcher<RawType> m3 = matcher_maker(1.0);
3305 Matcher<RawType> m4 = matcher_maker(-
infinity_);
3308 Matcher<RawType> m5 = matcher_maker(
infinity_);
3317 Matcher<const RawType&> m6 = matcher_maker(0.0);
3324 Matcher<RawType&> m7 = matcher_maker(0.0);
3362template <
typename RawType>
3363class FloatingPointNearTest :
public FloatingPointTest<RawType> {
3365 typedef FloatingPointTest<RawType> ParentType;
3369 void TestNearMatches(
3370 testing::internal::FloatingEqMatcher<RawType>
3371 (*matcher_maker)(RawType, RawType)) {
3372 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3379 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3418 Matcher<RawType> m9 = matcher_maker(
3424 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3431 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3446typedef FloatingPointTest<float> FloatTest;
3448TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3449 TestMatches(&FloatEq);
3452TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3453 TestMatches(&NanSensitiveFloatEq);
3456TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3458 Matcher<float> m = FloatEq(
nan1_);
3464TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3466 Matcher<float> m = NanSensitiveFloatEq(
nan1_);
3472TEST_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));
3486TEST_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_);
3497 EXPECT_EQ(
"isn't NaN", DescribeNegation(m3));
3502typedef FloatingPointNearTest<float> FloatNearTest;
3504TEST_F(FloatNearTest, FloatNearMatches) {
3505 TestNearMatches(&FloatNear);
3508TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3509 TestNearMatches(&NanSensitiveFloatNear);
3512TEST_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));
3528TEST_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);
3541 EXPECT_EQ(
"isn't NaN", DescribeNegation(m3));
3544TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3552TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3554 Matcher<float> m = NanSensitiveFloatNear(
nan1_, 0.1f);
3561typedef FloatingPointTest<double> DoubleTest;
3563TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3564 TestMatches(&DoubleEq);
3567TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3568 TestMatches(&NanSensitiveDoubleEq);
3571TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3573 Matcher<double> m = DoubleEq(
nan1_);
3579TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3581 Matcher<double> m = NanSensitiveDoubleEq(
nan1_);
3587TEST_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));
3601TEST_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_);
3612 EXPECT_EQ(
"isn't NaN", DescribeNegation(m3));
3617typedef FloatingPointNearTest<double> DoubleNearTest;
3619TEST_F(DoubleNearTest, DoubleNearMatches) {
3620 TestNearMatches(&DoubleNear);
3623TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3624 TestNearMatches(&NanSensitiveDoubleNear);
3627TEST_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));
3643TEST_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);
3652 EXPECT_TRUE(explanation ==
"which is 1.2e-10 from 2.1" ||
3653 explanation ==
"which is 1.2e-010 from 2.1")
3654 <<
" where explanation is \"" << explanation <<
"\".";
3657TEST_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);
3670 EXPECT_EQ(
"isn't NaN", DescribeNegation(m3));
3673TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3681TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3683 Matcher<double> m = NanSensitiveDoubleNear(
nan1_, 0.1);
3689TEST(PointeeTest, RawPointer) {
3690 const Matcher<int*> m = Pointee(Ge(0));
3699TEST(PointeeTest, RawPointerToConst) {
3700 const Matcher<const double*> m = Pointee(Ge(0));
3709TEST(PointeeTest, ReferenceToConstRawPointer) {
3710 const Matcher<int* const &> m = Pointee(Ge(0));
3719TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3720 const Matcher<double* &> m = Pointee(Ge(0));
3731TEST(PointeeTest, SmartPointer) {
3732 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
3734 std::unique_ptr<int> n(
new int(1));
3738TEST(PointeeTest, SmartPointerToConst) {
3739 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
3744 std::unique_ptr<const int> n(
new int(1));
3748TEST(PointerTest, RawPointer) {
3750 const Matcher<int*> m = Pointer(Eq(&n));
3759TEST(PointerTest, RawPointerToConst) {
3761 const Matcher<const int*> m = Pointer(Eq(&n));
3770TEST(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));
3778TEST(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));
3786 std::unique_ptr<const int>
p(
new int(10));
3790TEST(AddressTest, NonConst) {
3792 const Matcher<int> m = Address(Eq(&n));
3805TEST(AddressTest, Const) {
3807 const Matcher<int> m = Address(Eq(&n));
3816TEST(AddressTest, MatcherDoesntCopy) {
3817 std::unique_ptr<int> n(
new int(1));
3818 const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
3823TEST(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));
3831 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3835TEST(WhenDynamicCastToTest, SameType) {
3840 Base* as_base_ptr = &derived;
3842 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3844 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3847TEST(WhenDynamicCastToTest, WrongTypes) {
3850 OtherDerived other_derived;
3853 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3855 Base* as_base_ptr = &derived;
3856 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3858 as_base_ptr = &other_derived;
3859 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3863TEST(WhenDynamicCastToTest, AlreadyNull) {
3865 Base* as_base_ptr =
nullptr;
3869struct AmbiguousCastTypes {
3870 class VirtualDerived :
public virtual Base {};
3871 class DerivedSub1 :
public VirtualDerived {};
3872 class DerivedSub2 :
public VirtualDerived {};
3873 class ManyDerivedInHierarchy :
public DerivedSub1,
public DerivedSub2 {};
3876TEST(WhenDynamicCastToTest, AmbiguousCast) {
3877 AmbiguousCastTypes::DerivedSub1 sub1;
3878 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3881 static_cast<AmbiguousCastTypes::DerivedSub1*
>(&many_derived);
3883 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(
IsNull()));
3884 as_base_ptr = &sub1;
3887 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(
IsNull())));
3890TEST(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));
3899TEST(WhenDynamicCastToTest, Explain) {
3900 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3901 Base* null =
nullptr;
3902 EXPECT_THAT(Explain(matcher, null), HasSubstr(
"NULL"));
3905 EXPECT_THAT(Explain(matcher, &derived), HasSubstr(
"which points to "));
3908 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3910 HasSubstr(
"which cannot be dynamic_cast"));
3913TEST(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))));
3921TEST(WhenDynamicCastToTest, BadReference) {
3923 Base& as_base_ref = derived;
3924 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3929template <
typename T>
3930class 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_; }
3941 const T* get()
const {
return val_; }
3942 const T&
operator*()
const {
return *val_; }
3948TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3949 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3951 const ConstPropagatingPtr<int> co(&three);
3952 ConstPropagatingPtr<int> o(&three);
3960TEST(PointeeTest, NeverMatchesNull) {
3961 const Matcher<const char*> m = Pointee(_);
3966TEST(PointeeTest, MatchesAgainstAValue) {
3967 const Matcher<int*> m = Pointee(5);
3976TEST(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));
3983TEST(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));
3990 EXPECT_EQ(
"which points to 3" + OfType(
"long") +
", which is 2 more than 1",
3994TEST(PointeeTest, AlwaysExplainsPointee) {
3995 const Matcher<int*> m = Pointee(0);
3997 EXPECT_EQ(
"which points to 42" + OfType(
"int"), Explain(m, &n));
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; }
4015bool ValueIsPositive(
const Uncopyable&
x) {
return x.value() > 0; }
4017MATCHER_P(UncopyableIs, inner_matcher,
"") {
4018 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
4023 AStruct() :
x(0),
y(1.0),
z(5),
p(nullptr) {}
4024 AStruct(
const AStruct& rhs)
4034struct DerivedStruct :
public AStruct {
4039TEST(FieldTest, WorksForNonConstField) {
4040 Matcher<AStruct> m = Field(&
AStruct::x, Ge(0));
4041 Matcher<AStruct> m_with_name = Field(
"x", &
AStruct::x, Ge(0));
4052TEST(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));
4060 m_with_name = Field(
"y", &
AStruct::y, Le(0.0));
4066TEST(FieldTest, WorksForUncopyableField) {
4069 Matcher<AStruct> m = Field(&
AStruct::z, Truly(ValueIsPositive));
4071 m = Field(&
AStruct::z, Not(Truly(ValueIsPositive)));
4076TEST(FieldTest, WorksForPointerField) {
4078 Matcher<AStruct> m = Field(&
AStruct::p,
static_cast<const char*
>(
nullptr));
4093TEST(FieldTest, WorksForByRefArgument) {
4094 Matcher<const AStruct&> m = Field(&
AStruct::x, Ge(0));
4104TEST(FieldTest, WorksForArgumentOfSubType) {
4107 Matcher<const DerivedStruct&> m = Field(&
AStruct::x, Ge(0));
4117TEST(FieldTest, WorksForCompatibleMatcherType) {
4119 Matcher<const AStruct&> m = Field(&
AStruct::x,
4120 Matcher<signed char>(Ge(0)));
4129TEST(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));
4136TEST(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));
4145TEST(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));
4154 "whose given field is 1" + OfType(
"int") +
", which is 1 more than 0",
4158TEST(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",
4172TEST(FieldForPointerTest, WorksForPointerToConst) {
4173 Matcher<const AStruct*> m = Field(&
AStruct::x, Ge(0));
4182TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4183 Matcher<AStruct*> m = Field(&
AStruct::x, Ge(0));
4192TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4193 Matcher<AStruct* const&> m = Field(&
AStruct::x, Ge(0));
4202TEST(FieldForPointerTest, DoesNotMatchNull) {
4203 Matcher<const AStruct*> m = Field(&
AStruct::x, _);
4209TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4212 Matcher<DerivedStruct*> m = Field(&
AStruct::x, Ge(0));
4221TEST(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));
4228TEST(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));
4237TEST(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"),
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));
4251TEST(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",
4273 int n()
const {
return n_; }
4275 void set_n(
int new_n) { n_ = new_n; }
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; }
4285 double&
x()
const {
return x_; }
4294double AClass::x_ = 0.0;
4297class DerivedClass :
public AClass {
4299 int k()
const {
return k_; }
4306TEST(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));
4322TEST(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"));
4339TEST(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"));
4356TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4360 Matcher<const AClass&> m = Property(&
AClass::x, Ref(
x));
4369TEST(PropertyTest, WorksForByValueArgument) {
4370 Matcher<AClass> m = Property(&AClass::s, StartsWith(
"hi"));
4382TEST(PropertyTest, WorksForArgumentOfSubType) {
4385 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4397TEST(PropertyTest, WorksForCompatibleMatcherType) {
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)));
4414TEST(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));
4422TEST(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));
4431TEST(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",
4444TEST(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",
4458TEST(PropertyForPointerTest, WorksForPointerToConst) {
4459 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4470TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4471 Matcher<AClass*> m = Property(&AClass::s, StartsWith(
"hi"));
4483TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4484 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith(
"hi"));
4495TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4496 Matcher<const AClass*> m = Property(&
AClass::x, _);
4502TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4505 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4516TEST(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));
4524TEST(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));
4533TEST(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",
4549TEST(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",
4569std::string IntToStringFunction(
int input) {
4570 return input == 1 ?
"foo" :
"bar";
4573TEST(ResultOfTest, WorksForFunctionPointers) {
4574 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string(
"foo")));
4581TEST(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));
4591int IntFunction(
int input) {
return input == 42 ? 80 : 90; }
4593TEST(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));
4605TEST(ResultOfTest, WorksForNonReferenceResults) {
4606 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4614double& DoubleFunction(
double& input) {
return input; }
4616Uncopyable& RefUncopyableFunction(Uncopyable& obj) {
4620TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4623 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(
x));
4631 Matcher<Uncopyable&> matcher2 =
4632 ResultOf(&RefUncopyableFunction, Ref(obj));
4640const std::string& StringFunction(
const std::string& input) {
return input; }
4642TEST(ResultOfTest, WorksForReferenceToConstResults) {
4643 std::string s =
"foo";
4645 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4653TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4655 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4663TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4665 ResultOf(
static_cast<std::string (*)(
int dummy)
>(
nullptr),
4666 Eq(std::string(
"foo"))),
4667 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4672TEST(ResultOfTest, WorksForFunctionReferences) {
4673 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq(
"foo"));
4681 std::string operator()(
int input)
const {
4682 return IntToStringFunction(input);
4686TEST(ResultOfTest, WorksForFunctors) {
4687 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string(
"foo")));
4696struct 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"; }
4703TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4704 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4709 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4711 EXPECT_TRUE(matcher_string.Matches(
"long string"));
4715TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4716 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(),
"good ptr");
4723TEST(ResultOfTest, WorksForLambdas) {
4724 Matcher<int> matcher = ResultOf(
4726 return std::string(
static_cast<size_t>(str_len),
'x');
4733TEST(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))));
4743const int* ReferencingFunction(
const int& n) {
return &n; }
4745struct ReferencingFunctor {
4746 typedef const int* result_type;
4747 result_type operator()(
const int& n) {
return &n; }
4750TEST(ResultOfTest, WorksForReferencingCallables) {
4753 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4757 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4762class DivisibleByImpl {
4764 explicit DivisibleByImpl(
int a_divider) : divider_(a_divider) {}
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_; }
4789PolymorphicMatcher<DivisibleByImpl> DivisibleBy(
int n) {
4790 return MakePolymorphicMatcher(DivisibleByImpl(n));
4795TEST(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));
4802TEST(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));
4809TEST(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));
4816TEST(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));
4821TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4822 const Matcher<int> m = AllOf(Ge(2), Le(3));
4826TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4827 const Matcher<int> m = GreaterThan(5);
4828 EXPECT_EQ(
"which is 1 more than 5", Explain(m, 6));
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();
4854TEST(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);
4863TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4864 NotCopyable value2(2);
4865 const Matcher<NotCopyable&> m = Ge(
ByRef(value2));
4867 NotCopyable n1(1), n2(2);
4872TEST(IsEmptyTest, ImplementsIsEmpty) {
4873 vector<int> container;
4875 container.push_back(0);
4877 container.push_back(1);
4881TEST(IsEmptyTest, WorksWithString) {
4886 text = std::string(
"\0", 1);
4890TEST(IsEmptyTest, CanDescribeSelf) {
4891 Matcher<vector<int> > m = IsEmpty();
4893 EXPECT_EQ(
"isn't empty", DescribeNegation(m));
4896TEST(IsEmptyTest, ExplainsResult) {
4897 Matcher<vector<int> > m = IsEmpty();
4898 vector<int> container;
4900 container.push_back(0);
4901 EXPECT_EQ(
"whose size is 1", Explain(m, container));
4904TEST(IsEmptyTest, WorksWithMoveOnly) {
4905 ContainerHelper helper;
4910TEST(IsTrueTest, IsTrueIsFalse) {
4938 std::unique_ptr<int> null_unique;
4939 std::unique_ptr<int> nonnull_unique(
new int(0));
4946TEST(SizeIsTest, ImplementsSizeIs) {
4947 vector<int> container;
4950 container.push_back(0);
4953 container.push_back(0);
4958TEST(SizeIsTest, WorksWithMap) {
4959 map<std::string, int> container;
4962 container.insert(make_pair(
"foo", 1));
4965 container.insert(make_pair(
"bar", 2));
4970TEST(SizeIsTest, WorksWithReferences) {
4971 vector<int> container;
4972 Matcher<const vector<int>&> m = SizeIs(1);
4974 container.push_back(0);
4978TEST(SizeIsTest, WorksWithMoveOnly) {
4979 ContainerHelper helper;
4981 helper.Call(MakeUniquePtrs({1, 2, 3}));
4986struct MinimalistCustomType {
4987 int size()
const {
return 1; }
4989TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4990 MinimalistCustomType container;
4995TEST(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));
5001TEST(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
5023template <
typename T>
5031 ContainerEqTestTypes;
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);
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);
5052 EXPECT_EQ(
"which doesn't have these expected elements: 3",
5053 Explain(m, test_set));
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);
5064 EXPECT_EQ(
"which has these unexpected elements: 46", Explain(m, test_set));
5068TYPED_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);
5075 EXPECT_EQ(
"which has these unexpected elements: 46,\n"
5076 "and doesn't have these expected elements: 5",
5077 Explain(m, test_set));
5081TYPED_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);
5095TEST(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);
5102 EXPECT_EQ(
"which doesn't have these expected elements: 3, 8",
5103 Explain(m, test_set));
5108TEST(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);
5115 EXPECT_EQ(
"which has these unexpected elements: 92, 46",
5116 Explain(m, test_set));
5120TEST(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);
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));
5134TEST(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);
5148TEST(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);
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));
5166TEST(ContainerEqExtraTest, WorksForNativeArray) {
5167 int a1[] = {1, 2, 3};
5168 int a2[] = {1, 2, 3};
5169 int b[] = {1, 2, 4};
5175TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5176 const char a1[][3] = {
"hi",
"lo"};
5177 const char a2[][3] = {
"hi",
"lo"};
5178 const char b[][3] = {
"lo",
"hi"};
5185 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5186 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5189TEST(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)));
5202TEST(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);
5220TEST(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))));
5226TEST(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))));
5238TEST(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"))));
5249TEST(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)));
5254 ElementsAreArray(sorted_numbers)));
5255 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5258TEST(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));
5270TEST(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));
5281TEST(WhenSortedTest, WorksForEmptyContainer) {
5282 const vector<int> numbers;
5284 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5287TEST(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"))));
5297TEST(WhenSortedTest, WorksForMapTypes) {
5298 map<std::string, int> word_counts;
5299 word_counts[
"and"] = 1;
5300 word_counts[
"the"] = 1;
5301 word_counts[
"buffalo"] = 2;
5303 WhenSorted(ElementsAre(Pair(
"and", 1), Pair(
"buffalo", 2),
5306 Not(WhenSorted(ElementsAre(Pair(
"and", 1), Pair(
"the", 1),
5307 Pair(
"buffalo", 2)))));
5310TEST(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),
5332TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5337 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5340TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5344 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5346 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5347 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5352template <
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_++);
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_;
5430TEST(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()) {
5441TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5442 std::forward_list<int> container;
5444 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5445 container.push_front(0);
5446 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5448 container.push_front(0);
5449 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5453TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5454 const int a[5] = {1, 2, 3, 4, 5};
5455 Streamlike<int> s(a, a + 5);
5459TEST(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));
5466TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5467 ContainerHelper helper;
5469 helper.Call(MakeUniquePtrs({1, 2}));
5472TEST(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));
5502TEST(WhenSortedTest, WorksForStreamlike) {
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))));
5511TEST(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);
5516 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5519TEST(IsSupersetOfTest, WorksForNativeArray) {
5520 const int subset[] = {1, 4};
5521 const int superset[] = {1, 2, 4};
5522 const int disjoint[] = {1, 0, 3};
5530TEST(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)));
5538TEST(IsSupersetOfTest, WorksForEmpty) {
5539 vector<int> numbers;
5540 vector<int> expected;
5542 expected.push_back(1);
5543 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5545 numbers.push_back(1);
5546 numbers.push_back(2);
5548 expected.push_back(1);
5550 expected.push_back(2);
5552 expected.push_back(3);
5553 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5556TEST(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);
5566 expected.push_back(0);
5570TEST(IsSupersetOfTest, TakesStlContainer) {
5571 const int actual[] = {3, 1, 2};
5573 ::std::list<int> expected;
5574 expected.push_back(1);
5575 expected.push_back(3);
5578 expected.push_back(4);
5582TEST(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"));
5596TEST(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"));
5610TEST(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))
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))
5629 " - element #0 is matched by matcher #1,\n"
5630 " - element #2 is matched by matcher #0"));
5633TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5634 const int numbers[] = {1, 3, 6, 2, 4, 5};
5639TEST(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}));
5647TEST(IsSubsetOfTest, WorksForNativeArray) {
5648 const int subset[] = {1, 4};
5649 const int superset[] = {1, 2, 4};
5650 const int disjoint[] = {1, 0, 3};
5658TEST(IsSubsetOfTest, WorksWithDuplicates) {
5659 const int not_enough[] = {1, 2};
5660 const int enough[] = {1, 1, 2};
5661 const int actual[] = {1, 1};
5666TEST(IsSubsetOfTest, WorksForEmpty) {
5667 vector<int> numbers;
5668 vector<int> expected;
5670 expected.push_back(1);
5673 numbers.push_back(1);
5674 numbers.push_back(2);
5676 expected.push_back(1);
5678 expected.push_back(2);
5680 expected.push_back(3);
5684TEST(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);
5691 expected.push_back(2);
5692 expected.push_back(5);
5696TEST(IsSubsetOfTest, TakesStlContainer) {
5697 const int actual[] = {3, 1, 2};
5699 ::std::list<int> expected;
5700 expected.push_back(1);
5701 expected.push_back(3);
5704 expected.push_back(2);
5705 expected.push_back(4);
5709TEST(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"));
5724TEST(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"));
5738TEST(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))
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))
5757 " - element #0 is matched by matcher #1,\n"
5758 " - element #1 is matched by matcher #2"));
5761TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5762 const int numbers[] = {1, 2, 3};
5767TEST(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}));
5778TEST(ElemensAreStreamTest, WorksForStreamlike) {
5779 const int a[5] = {1, 2, 3, 4, 5};
5780 Streamlike<int> s(std::begin(a), std::end(a));
5785TEST(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);
5801TEST(ElementsAreTest, WorksWithUncopyable) {
5803 objs[0].set_value(-3);
5804 objs[1].set_value(1);
5805 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5808TEST(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}));
5817TEST(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);
5826 expected.push_back(4);
5827 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5832TEST(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()));
5842TEST(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();
5852TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
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)));
5871TEST(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)));
5885TEST(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})));
5891TEST(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"})));
5897TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5898 const int a[5] = {2, 1, 4, 5, 3};
5900 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5902 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5905TEST(UnorderedElementsAreArrayTest,
5906 TakesInitializerListOfDifferentTypedMatchers) {
5907 const int a[5] = {2, 1, 4, 5, 3};
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)})));
5918TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5919 ContainerHelper helper;
5921 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5922 helper.Call(MakeUniquePtrs({2, 1}));
5927 typedef std::vector<int> IntVec;
5930TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5932 objs[0].set_value(-3);
5933 objs[1].set_value(1);
5935 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5938TEST_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()));
5948TEST_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;
5956 StringMatchResultListener listener;
5957 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5958 s, &listener)) << listener.str();
5961TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
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)));
5972TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5973 ContainerHelper helper;
5974 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5975 helper.Call(MakeUniquePtrs({2, 1}));
5984TEST_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();
6000TEST_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();
6016TEST_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"));
6025TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
6027 StringMatchResultListener listener;
6028 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6029 v, &listener)) << listener.str();
6033TEST_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"));
6046TEST_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"
6059TEST_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"
6078static std::string EMString(
int element,
int matcher) {
6080 ss <<
"(element #" << element <<
", matcher #" << matcher <<
")";
6084TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
6087 std::vector<std::string> v;
6091 StringMatchResultListener listener;
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 "
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}"));
6114TEST_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"));
6129TEST_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"));
6150template <
typename Graph>
6151class BacktrackingMaxBPMState {
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_;
6214 std::vector<size_t> lhs_used_;
6215 std::vector<size_t> rhs_used_;
6216 ElementMatcherPairs matches_;
6217 ElementMatcherPairs best_so_far_;
6220template <
typename Graph>
6221const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6227template <
typename Graph>
6229FindBacktrackingMaxBPM(
const Graph& g) {
6230 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6240TEST_P(BipartiteTest, Exhaustive) {
6241 size_t nodes = GetParam();
6242 MatchMatrix graph(nodes, nodes);
6244 ElementMatcherPairs matches =
6246 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6247 <<
"graph: " << graph.DebugString();
6250 std::vector<bool> seen_element(graph.LhsSize());
6251 std::vector<bool> seen_matcher(graph.RhsSize());
6253 for (
size_t i = 0;
i < matches.size(); ++
i) {
6254 size_t ilhs = matches[
i].first;
6255 size_t irhs = matches[
i].second;
6259 seen_element[ilhs] =
true;
6260 seen_matcher[irhs] =
true;
6262 }
while (graph.NextGraph());
6269class BipartiteNonSquareTest
6273TEST_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);
6288 ElementsAre(Pair(3, 0),
6289 Pair(AnyOf(1, 2), 1),
6290 Pair(0, 2))) << g.DebugString();
6294TEST_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(),
6301 <<
"graph: " << graph.DebugString()
6302 <<
"\nbacktracking: "
6306 }
while (graph.NextGraph());
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)));
6320class BipartiteRandomTest
6325TEST_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(),
6340 <<
" graph: " << graph.DebugString()
6341 <<
"\nTo reproduce the failure, rerun the test with the flag"
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)));
6357TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6359 EXPECT_TRUE(IsReadableTypeName(
"const unsigned char*"));
6360 EXPECT_TRUE(IsReadableTypeName(
"MyMap<int, void*>"));
6361 EXPECT_TRUE(IsReadableTypeName(
"void (*)(int, bool)"));
6364TEST(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"));
6370TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6372 IsReadableTypeName(
"basic_string<char, std::char_traits<char> >"));
6373 EXPECT_FALSE(IsReadableTypeName(
"std::vector<int, std::alloc_traits<int> >"));
6376TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6377 EXPECT_FALSE(IsReadableTypeName(
"void (&)(int, bool, char, float)"));
6382TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6388 const char* params[] = {
"5"};
6391 Strings(params, params + 1)));
6393 const char* params2[] = {
"5",
"8"};
6396 Strings(params2, params2 + 2)));
6400TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6401 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6402 DivisibleByImpl& impl = m.mutable_impl();
6405 impl.set_divider(0);
6406 EXPECT_EQ(0, m.mutable_impl().divider());
6410TEST(PolymorphicMatcherTest, CanAccessImpl) {
6411 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6412 const DivisibleByImpl& impl = m.impl();
6416TEST(MatcherTupleTest, ExplainsMatchFailure) {
6418 ExplainMatchFailureTupleTo(
6419 std::make_tuple(Matcher<char>(Eq(
'a')), GreaterThan(5)),
6420 std::make_tuple(
'a', 10), &ss1);
6424 ExplainMatchFailureTupleTo(
6425 std::make_tuple(GreaterThan(5), Matcher<char>(Eq(
'a'))),
6426 std::make_tuple(2,
'b'), &ss2);
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",
6434 ExplainMatchFailureTupleTo(
6435 std::make_tuple(GreaterThan(5), Matcher<char>(Eq(
'a'))),
6436 std::make_tuple(2,
'a'), &ss3);
6438 " Actual: 2, which is 3 less than 5\n",
6445TEST(EachTest, ExplainsMatchResultCorrectly) {
6448 Matcher<set<int> > m = Each(2);
6451 Matcher<
const int(&)[1]> n = Each(1);
6453 const int b[1] = {1};
6457 EXPECT_EQ(
"whose element #0 doesn't match", Explain(n, b));
6462 m = Each(GreaterThan(0));
6465 m = Each(GreaterThan(10));
6466 EXPECT_EQ(
"whose element #0 doesn't match, which is 9 less than 10",
6470TEST(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));
6478TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6479 vector<int> some_vector;
6481 some_vector.push_back(3);
6484 some_vector.push_back(1);
6485 some_vector.push_back(2);
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"))));
6498TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6499 map<const char*, int> my_map;
6500 const char*
bar =
"a string";
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))));
6516TEST(EachTest, AcceptsMatcher) {
6517 const int a[] = {1, 2, 3};
6522TEST(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))));
6529TEST(EachTest, WorksWithMoveOnly) {
6530 ContainerHelper helper;
6532 helper.Call(MakeUniquePtrs({1, 2}));
6536class 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";
6559PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6560 return MakePolymorphicMatcher(IsHalfOfMatcher());
6563TEST(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));
6578TEST(PointwiseTest, MakesCopyOfRhs) {
6579 list<signed char> rhs;
6584 const Matcher<
const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6592TEST(PointwiseTest, WorksForLhsNativeArray) {
6593 const int lhs[] = {1, 2, 3};
6602TEST(PointwiseTest, WorksForRhsNativeArray) {
6603 const int rhs[] = {1, 2, 3};
6613TEST(PointwiseTest, WorksForVectorOfBool) {
6614 vector<bool> rhs(3,
false);
6616 vector<bool> lhs = rhs;
6623TEST(PointwiseTest, WorksForRhsInitializerList) {
6624 const vector<int> lhs{2, 4, 6};
6626 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6630TEST(PointwiseTest, RejectsWrongSize) {
6631 const double lhs[2] = {1, 2};
6632 const int rhs[1] = {0};
6635 Explain(Pointwise(Gt(), rhs), lhs));
6637 const int rhs2[3] = {0, 1, 2};
6641TEST(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));
6650TEST(PointwiseTest, AcceptsCorrectContent) {
6651 const double lhs[3] = {1, 2, 3};
6652 const int rhs[3] = {2, 4, 6};
6654 EXPECT_EQ(
"", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6657TEST(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();
6662 EXPECT_EQ(
"", Explain(Pointwise(m1, rhs), lhs));
6666 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6668 EXPECT_EQ(
"", Explain(Pointwise(m2, rhs), lhs));
6671MATCHER(PointeeEquals,
"Points to an equal value") {
6672 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6673 ::testing::get<0>(arg), result_listener);
6676TEST(PointwiseTest, WorksWithMoveOnly) {
6677 ContainerHelper helper;
6678 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6679 helper.Call(MakeUniquePtrs({1, 2}));
6682TEST(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));
6708TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6709 list<signed char> rhs;
6714 const Matcher<
const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6722TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6723 const int lhs[] = {1, 2, 3};
6729 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6732TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6733 const int rhs[] = {1, 2, 3};
6739 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6743TEST(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})));
6750TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6751 const double lhs[2] = {1, 2};
6752 const int rhs[1] = {0};
6753 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6755 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6757 const int rhs2[3] = {0, 1, 2};
6758 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6761TEST(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));
6770TEST(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));
6776TEST(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));
6782TEST(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();
6790 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6794TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6795 ContainerHelper helper;
6796 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6797 std::vector<int>{1, 2})));
6798 helper.Call(MakeUniquePtrs({2, 1}));
6803template <
typename T>
6804class 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_; }
6818TEST(OptionalTest, DescribesSelf) {
6819 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6820 EXPECT_EQ(
"value is equal to 1", Describe(m));
6823TEST(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)));
6829TEST(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);
6839TEST(OptionalTest, DoesNotMatchNullopt) {
6840 const Matcher<SampleOptional<int>> m = Optional(1);
6841 SampleOptional<int> empty;
6845TEST(OptionalTest, WorksWithMoveOnly) {
6846 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(
nullptr));
6847 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(
nullptr)));
6850class 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) {
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_; }
6874TEST(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"));
6880TEST(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");
6890TEST(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")));
6898TEST(VariantTest, TypeDoesNotMatch) {
6899 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6902 m = VariantWith<std::string>(Eq(
"1"));
6906TEST(VariantTest, InnerDoesNotMatch) {
6907 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6910 m = VariantWith<std::string>(Eq(
"1"));
6914class 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;
6935TEST(AnyWithTest, FullMatch) {
6936 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6940TEST(AnyWithTest, TestBadCastType) {
6941 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq(
"fail"));
6945TEST(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")}));
6961TEST(AnyWithTest, TestCompare) {
6962 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6965TEST(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"));
6971TEST(AnyWithTest, ExplainsSelf) {
6972 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6974 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex(
"whose value 1"));
6976 HasSubstr(
"whose value is not of type '"));
6977 EXPECT_THAT(Explain(m, SampleAnyType(2)),
"whose value 2 doesn't match");
6980TEST(PointeeTest, WorksOnMoveOnlyType) {
6981 std::unique_ptr<int>
p(
new int(3));
6986TEST(NotTest, WorksOnMoveOnlyType) {
6987 std::unique_ptr<int>
p(
new int(3));
6994TEST(ArgsTest, AcceptsZeroTemplateArg) {
6995 const std::tuple<int, bool> t(5,
true);
7000TEST(ArgsTest, AcceptsOneTemplateArg) {
7001 const std::tuple<int, bool> t(5,
true);
7003 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(
true))));
7004 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(
false)))));
7007TEST(ArgsTest, AcceptsTwoTemplateArgs) {
7008 const std::tuple<short, int, long> t(4, 5, 6L);
7015TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
7016 const std::tuple<short, int, long> t(4, 5, 6L);
7021TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
7022 const std::tuple<short, int, long> t(4, 5, 6L);
7028 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
7031TEST(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())));
7036TEST(ArgsTest, CanBeNested) {
7037 const std::tuple<short, int, long, int> t(4, 5, 6L, 6);
7038 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
7039 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
7042TEST(ArgsTest, CanMatchTupleByValue) {
7043 typedef std::tuple<char, int, int> Tuple3;
7044 const Matcher<Tuple3> m = Args<1, 2>(Lt());
7049TEST(ArgsTest, CanMatchTupleByReference) {
7050 typedef std::tuple<char, char, int> Tuple3;
7051 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
7061TEST(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)"))));
7070TEST(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",
7077TEST(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",
7085TEST(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));
7092TEST(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)));
7101class LessThanMatcher :
public MatcherInterface<std::tuple<char, int> > {
7103 void DescribeTo(::std::ostream* )
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";
7116Matcher<std::tuple<char, int> > LessThan() {
7117 return MakeMatcher(
new LessThanMatcher);
7120TEST(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)));
7132 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
7137 class MockMatcher :
public MatcherInterface<Behavior> {
7139 bool MatchAndExplain(Behavior behavior,
7140 MatchResultListener* listener)
const override {
7141 *listener <<
"[MatchAndExplain]";
7143 case kInitialSuccess:
7147 return !listener->IsInterested();
7157 return listener->IsInterested();
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);
7179TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
7180 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
7186TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
7187 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
7189 std::string expect =
7190 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7192 OfType(internal::GetTypeName<Behavior>()) +
", [MatchAndExplain]";
7196TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
7197 AssertionResult result = RunPredicateFormatter(kFlaky);
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]";
7210TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
7211 Matcher<const vector<int>&> m = ElementsAre();
7215TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
7216 Matcher<vector<int>> m = ElementsAre(Gt(5));
7217 EXPECT_EQ(
"has 1 element that is > 5", Describe(m));
7220TEST(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\"",
7229TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
7230 Matcher<vector<int>> m = ElementsAre();
7231 EXPECT_EQ(
"isn't empty", DescribeNegation(m));
7234TEST(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));
7242TEST(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));
7251TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
7252 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
7260TEST(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));
7272TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
7273 Matcher<const list<int>&> m = ElementsAre(1, 3);
7283TEST(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",
7296TEST(ElementsAreTest, MatchesOneElementVector) {
7297 vector<std::string> test_vector;
7298 test_vector.push_back(
"test string");
7300 EXPECT_THAT(test_vector, ElementsAre(StrEq(
"test string")));
7303TEST(ElementsAreTest, MatchesOneElementList) {
7310TEST(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"), _));
7319TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
7320 vector<int> test_vector;
7321 test_vector.push_back(4);
7326TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
7327 vector<int> test_vector;
7328 test_vector.push_back(4);
7333TEST(ElementsAreTest, MatchesOneElementValue) {
7334 vector<int> test_vector;
7335 test_vector.push_back(4);
7340TEST(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), _));
7349TEST(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));
7356 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
7359TEST(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"));
7368TEST(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"));
7376TEST(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"));
7387TEST(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'))));
7401TEST(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]))));
7409TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
7410 int a[] = {0, 1, 2};
7411 vector<int> v(std::begin(a), std::end(a));
7414 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
7417TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
7418 int array[] = {0, 1, 2};
7424class NativeArrayPassedAsPointerAndSize {
7426 NativeArrayPassedAsPointerAndSize() {}
7428 MOCK_METHOD(
void, Helper, (
int* array,
int size));
7434TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
7435 int array[] = {0, 1};
7436 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
7440 NativeArrayPassedAsPointerAndSize helper;
7441 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
7442 helper.Helper(array, 2);
7445TEST(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')));
7454TEST(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")));
7461extern const char kHi[];
7463TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
7467 std::string array1[] = {
"hi"};
7470 std::string array2[] = {
"ho"};
7474const char kHi[] =
"hi";
7476TEST(ElementsAreTest, MakesCopyOfArguments) {
7480 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
7481 polymorphic_matcher = ElementsAre(
x,
y);
7484 const int array1[] = {1, 2};
7486 const int array2[] = {0, 0};
7494TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
7495 const int a[] = {1, 2, 3};
7497 vector<int> test_vector(std::begin(a), std::end(a));
7501 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7504TEST(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())));
7515TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
7516 const char* a[] = {
"one",
"two",
"three"};
7518 vector<std::string> test_vector(std::begin(a), std::end(a));
7521 test_vector[0] =
"1";
7522 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7525TEST(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)));
7539TEST(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)));
7548TEST(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})));
7555TEST(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"})));
7562TEST(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)})));
7568TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
7569 const int a[5] = {1, 2, 3, 4, 5};
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)})));
7579TEST(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)));
7590TEST(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()));
7596 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
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));
7605TEST(ElementsAreArrayTest, WorksWithNativeArray) {
7606 ::std::string a[] = {
"hi",
"ho"};
7607 ::std::string b[] = {
"hi",
"ho"};
7614TEST(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());
7623 for (
int&
i : expect) {
7627 test_vector.push_back(3);
7635MATCHER(IsEven,
"") {
return (arg % 2) == 0; }
7637TEST(MatcherMacroTest, Works) {
7638 const Matcher<int> m = IsEven();
7643 EXPECT_EQ(
"not (is even)", DescribeNegation(m));
7649MATCHER(IsEven2, negation ?
"is odd" :
"is even") {
7650 if ((arg % 2) == 0) {
7653 *result_listener <<
"OK";
7656 *result_listener <<
"% 2 == " << (arg % 2);
7664 std::string(negation ?
"doesn't equal" :
"equals") +
" the sum of " +
7666 if (arg == (
x +
y)) {
7667 *result_listener <<
"OK";
7672 if (result_listener->stream() !=
nullptr) {
7673 *result_listener->stream() <<
"diff == " << (
x +
y - arg);
7681TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
7682 const Matcher<int> m1 = IsEven2();
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));
7692TEST(MatcherMacroTest, CanExplainMatchResult) {
7693 const Matcher<int> m1 = IsEven2();
7697 const Matcher<int> m2 = EqSumOf(1, 2);
7699 EXPECT_EQ(
"diff == -1", Explain(m2, 4));
7706 StaticAssertTypeEq<::std::string, arg_type>();
7710MATCHER(IsEmptyStringByRef,
"") {
7711 StaticAssertTypeEq<const ::std::string&, arg_type>();
7715TEST(MatcherMacroTest, CanReferenceArgType) {
7716 const Matcher<::std::string> m1 = IsEmptyString();
7719 const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
7725namespace matcher_test {
7726MATCHER(IsOdd,
"") {
return (arg % 2) != 0; }
7729TEST(MatcherMacroTest, WorksInNamespace) {
7737 return Value(arg, matcher_test::IsOdd()) && arg > 0;
7740TEST(MatcherMacroTest, CanBeComposedUsingValue) {
7748MATCHER_P(IsGreaterThan32And, n,
"") {
return arg > 32 && arg > n; }
7750TEST(MatcherPMacroTest, Works) {
7751 const Matcher<int> m = IsGreaterThan32And(5);
7755 EXPECT_EQ(
"is greater than 32 and 5", Describe(m));
7756 EXPECT_EQ(
"not (is greater than 32 and 5)", DescribeNegation(m));
7762MATCHER_P(_is_Greater_Than32and_, n,
"") {
return arg > 32 && arg > n; }
7764TEST(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));
7776class UncopyableFoo {
7778 explicit UncopyableFoo(
char value) : value_(
value) { (void)value_; }
7780 UncopyableFoo(
const UncopyableFoo&) =
delete;
7781 void operator=(
const UncopyableFoo&) =
delete;
7787MATCHER_P(ReferencesUncopyable, variable,
"") {
return &arg == &variable; }
7789TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
7790 UncopyableFoo foo1(
'1'), foo2(
'2');
7791 const Matcher<const UncopyableFoo&> m =
7792 ReferencesUncopyable<const UncopyableFoo&>(foo1);
7801 EXPECT_EQ(
"references uncopyable 1-byte object <31>", Describe(m));
7808 StaticAssertTypeEq<int, foo_type>();
7809 StaticAssertTypeEq<long, bar_type>();
7810 StaticAssertTypeEq<char, baz_type>();
7814TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
7815 EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L,
'a'));
7821MATCHER_P2(ReferencesAnyOf, variable1, variable2,
"") {
7822 return &arg == &variable1 || &arg == &variable2;
7825TEST(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);
7834 const Matcher<UncopyableFoo&> m =
7835 ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
7842TEST(MatcherPnMacroTest,
7843 GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
7844 UncopyableFoo foo1(
'1'), foo2(
'2');
7845 const Matcher<const UncopyableFoo&> m =
7846 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7852 EXPECT_EQ(
"references any of (1-byte object <31>, 1-byte object <32>)",
7858MATCHER_P2(IsNotInClosedRange, low, hi,
"") {
return arg < low || arg > hi; }
7860TEST(MatcherPnMacroTest, Works) {
7861 const Matcher<const long&> m = IsNotInClosedRange(10, 20);
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));
7874MATCHER(EqualsSumOf,
"") {
return arg == 0; }
7875MATCHER_P(EqualsSumOf, a,
"") {
return arg == a; }
7876MATCHER_P2(EqualsSumOf, a, b,
"") {
return arg == a + b; }
7877MATCHER_P3(EqualsSumOf, a, b, c,
"") {
return arg == a + b + c; }
7878MATCHER_P4(EqualsSumOf, a, b, c, d,
"") {
return arg == a + b + c + d; }
7879MATCHER_P5(EqualsSumOf, a, b, c, d, e,
"") {
return arg == a + b + c + d + e; }
7880MATCHER_P6(EqualsSumOf, a, b, c, d, e, f,
"") {
7881 return arg == a + b + c + d + e + f;
7883MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g,
"") {
7884 return arg == a + b + c + d + e + f + g;
7886MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h,
"") {
7887 return arg == a + b + c + d + e + f + g + h;
7889MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h,
i,
"") {
7890 return arg == a + b + c + d + e + f + g + h +
i;
7892MATCHER_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;
7896TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
7902 EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
7904 EqualsSumOf(::std::string(
"a"),
'b',
'c',
"d",
"e",
'f'));
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'));
7912 EqualsSumOf(::std::string(
"a"),
'b',
'c',
"d",
"e",
'f',
'g',
"h",
7913 'i', ::std::string(
"j")));
7919 EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
7920 EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
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')));
7930 Not(EqualsSumOf(::std::string(
"a"),
'b',
'c',
"d",
"e",
'f',
'g',
7931 "h",
'i', ::std::string(
"j"))));
7936TEST(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")));
7948 std::string prefix_str(prefix);
7949 char suffix_char =
static_cast<char>(suffix);
7950 return arg == prefix_str + suffix_char;
7953TEST(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'));
7964TEST(MatcherPnMacroTest, TypesAreCorrect) {
7966 EqualsSumOfMatcher a0 = EqualsSumOf();
7969 EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
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');
8008 const int count =
static_cast<int>(Value(arg, m1)) +
8009 static_cast<int>(Value(arg, m2)) +
8010 static_cast<int>(Value(arg, m3));
8014TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
8021TEST(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);
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")));
8038TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
8039 list<int> some_list;
8040 some_list.push_back(3);
8041 some_list.push_back(1);
8045TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
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"))));
8062TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
8068 set<std::string> c_string_set;
8069 c_string_set.insert(
"hello");
8070 EXPECT_THAT(c_string_set, Not(Contains(std::string(
"goodbye"))));
8073TEST(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));
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));
8088TEST(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));
8096TEST(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;
8108 Contains(pair<const std::string, int>(std::string(
"fee"), 1)));
8109 EXPECT_THAT(another_map, Contains(pair<const std::string, int>(
"fie", 2)));
8112TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
8113 map<int, int> some_map;
8116 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
8119TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
8120 const char* string_array[] = {
"fee",
"fie",
"foe",
"fum"};
8121 EXPECT_THAT(string_array, Contains(Eq(std::string(
"fum"))));
8124TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
8125 int int_array[] = {1, 2, 3, 4};
8129TEST(ContainsTest, AcceptsMatcher) {
8130 const int a[] = {1, 2, 3};
8135TEST(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))));
8142TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
8143 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
8146 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
8150TEST(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};
8158 EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
8159 EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
8162 int ar[6] = {1, 2, 3, 4, 4, 4};
8171 int ar2[2] = {2, 3};
8172 int ar3[3] = {4, 4, 4};
8192TEST(AllOfArrayTest, Matchers) {
8194 std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
8203TEST(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())));
8210 EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
8212 EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
8214 int ar[3] = {1, 2, 3};
8223 int ar2[2] = {2, 3};
8243TEST(AnyOfArrayTest, Matchers) {
8246 std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
8255TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
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);
8270 EXPECT_EQ(
"(is equal to 1)", Describe(m1));
8271 EXPECT_EQ(
"(is equal to 2) or (is equal to 3)", Describe(m2));
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));
8276 const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
8277 const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
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",
8290TEST(AllOfTest, HugeMatcher) {
8293 EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
8294 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
8297TEST(AnyOfTest, HugeMatcher) {
8300 EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
8301 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
8318template <
typename T1,
typename T2>
8319bool AllOf(
const T1& ,
const T2& ) {
8323TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
8325 testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8328template <
typename T1,
typename T2>
8329bool AnyOf(
const T1&,
const T2&) {
8333TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
8335 testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8340TEST(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)))));
8346TEST(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)))));
8352MATCHER(IsNotNull,
"") {
return arg !=
nullptr; }
8356TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
8357 std::unique_ptr<int>
p(
new int(3));
8359 EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
8362MATCHER_P(UniquePointee, pointee,
"") {
return *arg == pointee; }
8366TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
8367 std::unique_ptr<int>
p(
new int(3));
8372#if GTEST_HAS_EXCEPTIONS
8378TEST(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")));
8388TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
8389 EXPECT_THAT(std::function<
void()>([]() {
throw std::exception(); }),
8390 Throws<std::exception>());
8393TEST(ThrowsTest, CallableExecutedExactlyOnce) {
8405 throw std::runtime_error(
"message");
8407 Throws<std::runtime_error>());
8412 throw std::runtime_error(
"message");
8414 ThrowsMessage<std::runtime_error>(HasSubstr(
"message")));
8419 throw std::runtime_error(
"message");
8421 Throws<std::runtime_error>(
8422 Property(&std::runtime_error::what, HasSubstr(
"message"))));
8426TEST(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"));
8434TEST(ThrowsTest, Success) {
8435 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8436 StringMatchResultListener listener;
8438 []() { throw std::runtime_error(
"error message"); }, &listener));
8439 EXPECT_THAT(listener.str(), HasSubstr(
"std::runtime_error"));
8442TEST(ThrowsTest, FailWrongType) {
8443 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8444 StringMatchResultListener listener;
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\""));
8451TEST(ThrowsTest, FailWrongTypeNonStd) {
8452 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8453 StringMatchResultListener listener;
8454 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8456 HasSubstr(
"throws an exception of an unknown type"));
8459TEST(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"));
8466class ThrowsPredicateTest
8467 :
public TestWithParam<Matcher<std::function<void()>>> {};
8469TEST_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"));
8478TEST_P(ThrowsPredicateTest, Success) {
8479 Matcher<std::function<void()>> matcher = GetParam();
8480 StringMatchResultListener listener;
8482 []() { throw std::runtime_error(
"error message"); }, &listener));
8483 EXPECT_THAT(listener.str(), HasSubstr(
"std::runtime_error"));
8486TEST_P(ThrowsPredicateTest, FailWrongType) {
8487 Matcher<std::function<void()>> matcher = GetParam();
8488 StringMatchResultListener listener;
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\""));
8495TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
8496 Matcher<std::function<void()>> matcher = GetParam();
8497 StringMatchResultListener listener;
8498 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8500 HasSubstr(
"throws an exception of an unknown type"));
8503TEST_P(ThrowsPredicateTest, FailWrongMessage) {
8504 Matcher<std::function<void()>> matcher = GetParam();
8505 StringMatchResultListener listener;
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")));
8512TEST_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"));
8520 AllMessagePredicates, ThrowsPredicateTest,
8521 Values(Matcher<std::function<
void()>>(
8522 ThrowsMessage<std::runtime_error>(HasSubstr(
"error message")))));
8525TEST(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; }));
8545TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
8546 Matcher<std::function<void()>> matcher =
8547 ThrowsMessage<std::runtime_error>(
"error message");
8549 matcher.Matches([]() { throw std::runtime_error(
"error message"); }));
8551 []() { throw std::runtime_error(
"wrong error message"); }));
8561# pragma warning(pop)
bool operator<(const UnicodeText::const_iterator &lhs, const UnicodeText::const_iterator &rhs)
bool operator!=(const UnicodeText &lhs, const UnicodeText &rhs)
#define EXPECT_CALL(obj, call)
#define ON_CALL(obj, call)
#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)
#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)
#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)
#define ASSERT_THAT(value, matcher)
#define MATCHER_P3(name, p0, p1, p2, description)
#define MATCHER_P4(name, p0, p1, p2, p3, description)
#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)
#define EXPECT_THAT(value, matcher)
#define MATCHER_P(name, p0, description)
#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)
#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)
#define MOCK_METHOD0(m,...)
#define MOCK_METHOD2(m,...)
#define MOCK_METHOD1(m,...)
const RawType close_to_negative_zero_
const RawType further_from_one_
const Bits infinity_bits_
const RawType close_to_positive_zero_
const RawType further_from_negative_zero_
const RawType close_to_one_
const RawType further_from_infinity_
const RawType close_to_infinity_
MATCHER_P2(IsPair, first, second, "")
#define EXPECT_EQ(val1, val2)
#define SCOPED_TRACE(message)
#define ASSERT_FALSE(condition)
#define EXPECT_TRUE(condition)
#define ASSERT_TRUE(condition)
#define EXPECT_FALSE(condition)
#define EXPECT_FATAL_FAILURE(statement, substr)
#define EXPECT_NONFATAL_FAILURE(statement, substr)
#define GTEST_FLAG_PREFIX_
#define GTEST_LOG_(severity)
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
int32_t operator*(const ICOORD &op1, const ICOORD &op2)
std::ostream & operator<<(std::ostream &os, const Message &sb)
inline ::std::reference_wrapper< T > ByRef(T &l_value)
TYPED_TEST(CodeLocationForTYPEDTEST, Verify)
TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int)
internal::ParamGenerator< T > Range(T start, T end, IncrementT step)
MATCHER(IsEmpty, negation ? "isn't empty" :"is empty")
INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0))
::std::string PrintToString(const T &value)
internal::ValueArray< T... > Values(T... v)
TEST_F(TestInfoTest, Names)
internal::ReturnAction< R > Return(R value)
TEST_P(CodeLocationForTESTP, Verify)
TEST(GTestEnvVarTest, Dummy)
::std::vector< ::std::string > Strings
GTEST_API_ bool IsTrue(bool condition)
bool operator==(faketype, faketype)
GTEST_API_ std::string FormatMatcherDescription(bool negation, const char *matcher_name, const Strings ¶m_values)
AssertionResult IsNull(const char *str)
GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix &g)
def Iter(n, format, sep='')
TypeWithSize< sizeof(RawType)>::UInt Bits