Index: ext/googletest/googlemock/test/gmock-matchers_test.cc =================================================================== diff -u -N -r4a481bbe77043e0bda2435c6d62a02700b3e46c5 -r3d5880c6661c3ed500e0c1c739a923ae9ede0364 --- ext/googletest/googlemock/test/gmock-matchers_test.cc (.../gmock-matchers_test.cc) (revision 4a481bbe77043e0bda2435c6d62a02700b3e46c5) +++ ext/googletest/googlemock/test/gmock-matchers_test.cc (.../gmock-matchers_test.cc) (revision 3d5880c6661c3ed500e0c1c739a923ae9ede0364) @@ -26,9 +26,8 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file tests some commonly used argument matchers. @@ -45,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -58,12 +58,11 @@ # include // NOLINT #endif -namespace testing { +#if GTEST_LANG_CXX11 +# include +#endif -namespace internal { -GTEST_API_ string JoinAsTuple(const Strings& fields); -} // namespace internal - +namespace testing { namespace gmock_matchers_test { using std::greater; @@ -145,7 +144,6 @@ using testing::internal::FloatingEqMatcher; using testing::internal::FormatMatcherDescription; using testing::internal::IsReadableTypeName; -using testing::internal::JoinAsTuple; using testing::internal::linked_ptr; using testing::internal::MatchMatrix; using testing::internal::RE; @@ -189,7 +187,7 @@ return MakeMatcher(new GreaterThanMatcher(n)); } -string OfType(const string& type_name) { +std::string OfType(const std::string& type_name) { #if GTEST_HAS_RTTI return " (of type " + type_name + ")"; #else @@ -199,28 +197,30 @@ // Returns the description of the given matcher. template -string Describe(const Matcher& m) { - stringstream ss; - m.DescribeTo(&ss); - return ss.str(); +std::string Describe(const Matcher& m) { + return DescribeMatcher(m); } // Returns the description of the negation of the given matcher. template -string DescribeNegation(const Matcher& m) { - stringstream ss; - m.DescribeNegationTo(&ss); - return ss.str(); +std::string DescribeNegation(const Matcher& m) { + return DescribeMatcher(m, true); } // Returns the reason why x matches, or doesn't match, m. template -string Explain(const MatcherType& m, const Value& x) { +std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } +TEST(MonotonicMatcherTest, IsPrintable) { + stringstream ss; + ss << GreaterThan(5); + EXPECT_EQ("is > 5", ss.str()); +} + TEST(MatchResultListenerTest, StreamingWorks) { StringMatchResultListener listener; listener << "hi" << 5; @@ -332,6 +332,22 @@ EXPECT_FALSE(m1.Matches(&n)); } +// Tests that matchers can be constructed from a variable that is not properly +// defined. This should be illegal, but many users rely on this accidentally. +struct Undefined { + virtual ~Undefined() = 0; + static const int kInt = 1; +}; + +TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { + Matcher m1 = Undefined::kInt; + EXPECT_TRUE(m1.Matches(1)); + EXPECT_FALSE(m1.Matches(2)); +} + +// Test that a matcher parameterized with an abstract class compiles. +TEST(MatcherTest, CanAcceptAbstractClass) { Matcher m = _; } + // Tests that matchers are copyable. TEST(MatcherTest, IsCopyable) { // Tests the copy constructor. @@ -365,67 +381,133 @@ } // Tests that a C-string literal can be implicitly converted to a -// Matcher or Matcher. +// Matcher or Matcher. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "hi"; + Matcher m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher m2 = "hi"; + Matcher m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a string object can be implicitly converted to a -// Matcher or Matcher. +// Matcher or Matcher. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = string("hi"); + Matcher m1 = std::string("hi"); EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher m2 = string("hi"); + Matcher m2 = std::string("hi"); EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } -#if GTEST_HAS_STRING_PIECE_ +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher or Matcher. +TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_STRING // Tests that a C-string literal can be implicitly converted to a -// Matcher or Matcher. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "cats"; +// Matcher<::string> or Matcher. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher< ::string> m1 = "hi"; + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher m2 = "hi"; + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +// Tests that a std::string object can be implicitly converted to a +// Matcher<::string> or Matcher. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher< ::string> m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher m2 = std::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +// Tests that a ::string object can be implicitly converted to a +// Matcher<::string> or Matcher. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher< ::string> m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL +// Tests that a C-string literal can be implicitly converted to a +// Matcher or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher m1 = "cats"; EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher m2 = "cats"; + Matcher m2 = "cats"; EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -// Tests that a string object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = string("cats"); +// Tests that a std::string object can be implicitly converted to a +// Matcher or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher m1 = std::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher m2 = string("cats"); + Matcher m2 = std::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -// Tests that a StringPiece object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) { - Matcher m1 = StringPiece("cats"); +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher m1 = ::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher m2 = StringPiece("cats"); + Matcher m2 = ::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -#endif // GTEST_HAS_STRING_PIECE_ +#endif // GTEST_HAS_GLOBAL_STRING +// Tests that a absl::string_view object can be implicitly converted to a +// Matcher or Matcher. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { + Matcher m1 = absl::string_view("cats"); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher m2 = absl::string_view("cats"); + EXPECT_TRUE(m2.Matches("cats")); + EXPECT_FALSE(m2.Matches("dogs")); +} +#endif // GTEST_HAS_ABSL + // Tests that MakeMatcher() constructs a Matcher from a // MatcherInterface* without requiring the user to explicitly // write the type. @@ -609,11 +691,76 @@ EXPECT_FALSE(m2.Matches(1)); } +// Tests that MatcherCast(m) works when m is a value of the same type as the +// value type of the Matcher. +TEST(MatcherCastTest, FromAValue) { + Matcher m = MatcherCast(42); + EXPECT_TRUE(m.Matches(42)); + EXPECT_FALSE(m.Matches(239)); +} + +// Tests that MatcherCast(m) works when m is a value of the type implicitly +// convertible to the value type of the Matcher. +TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { + const int kExpected = 'c'; + Matcher m = MatcherCast('c'); + EXPECT_TRUE(m.Matches(kExpected)); + EXPECT_FALSE(m.Matches(kExpected + 1)); +} + +struct NonImplicitlyConstructibleTypeWithOperatorEq { + friend bool operator==( + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, + int rhs) { + return 42 == rhs; + } + friend bool operator==( + int lhs, + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { + return lhs == 42; + } +}; + +// Tests that MatcherCast(m) works when m is a neither a matcher nor +// implicitly convertible to the value type of the Matcher, but the value type +// of the matcher has operator==() overload accepting m. +TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { + Matcher m1 = + MatcherCast(42); + EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + Matcher m2 = + MatcherCast(239); + EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + // When updating the following lines please also change the comment to + // namespace convertible_from_any. + Matcher m3 = + MatcherCast(NonImplicitlyConstructibleTypeWithOperatorEq()); + EXPECT_TRUE(m3.Matches(42)); + EXPECT_FALSE(m3.Matches(239)); +} + +// ConvertibleFromAny does not work with MSVC. resulting in +// error C2440: 'initializing': cannot convert from 'Eq' to 'M' +// No constructor could take the source type, or constructor overload +// resolution was ambiguous + +#if !defined _MSC_VER + +// The below ConvertibleFromAny struct is implicitly constructible from anything +// and when in the same namespace can interact with other tests. In particular, +// if it is in the same namespace as other tests and one removes +// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); +// then the corresponding test still compiles (and it should not!) by implicitly +// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny +// in m3.Matcher(). +namespace convertible_from_any { // Implicitly convertible from any type. struct ConvertibleFromAny { ConvertibleFromAny(int a_value) : value(a_value) {} template - explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) { + ConvertibleFromAny(const T& /*a_value*/) : value(-1) { ADD_FAILURE() << "Conversion constructor called"; } int value; @@ -639,7 +786,10 @@ EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any +#endif // !defined _MSC_VER + struct IntReferenceWrapper { IntReferenceWrapper(const int& a_value) : value(&a_value) {} const int* value; @@ -744,6 +894,9 @@ EXPECT_FALSE(m2.Matches(1)); } +#if !defined _MSC_VER + +namespace convertible_from_any { TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { Matcher m = SafeMatcherCast(1); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); @@ -756,7 +909,10 @@ EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any +#endif // !defined _MSC_VER + TEST(SafeMatcherCastTest, ValueIsNotCopied) { int n = 42; Matcher m = SafeMatcherCast(n); @@ -767,7 +923,7 @@ TEST(ExpectThat, TakesLiterals) { EXPECT_THAT(1, 1); EXPECT_THAT(1.0, 1.0); - EXPECT_THAT(string(), ""); + EXPECT_THAT(std::string(), ""); } TEST(ExpectThat, TakesFunctions) { @@ -867,15 +1023,11 @@ public: Unprintable() : c_('a') {} + bool operator==(const Unprintable& /* rhs */) const { return true; } private: char c_; }; -inline bool operator==(const Unprintable& /* lhs */, - const Unprintable& /* rhs */) { - return true; -} - TEST(EqTest, CanDescribeSelf) { Matcher m = Eq(Unprintable()); EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); @@ -914,7 +1066,7 @@ // Type::IsTypeOf(v) compiles iff the type of value v is T, where T // is a "bare" type (i.e. not in the form of const U or U&). If v's // type is not T, the compiler will generate a message about -// "undefined referece". +// "undefined reference". template struct Type { static bool IsTypeOf(const T& /* v */) { return true; } @@ -973,7 +1125,7 @@ // Tests that Lt(v) matches anything < v. TEST(LtTest, ImplementsLessThan) { - Matcher m1 = Lt("Hello"); + Matcher m1 = Lt("Hello"); EXPECT_TRUE(m1.Matches("Abc")); EXPECT_FALSE(m1.Matches("Hello")); EXPECT_FALSE(m1.Matches("Hello, world!")); @@ -1046,14 +1198,14 @@ EXPECT_FALSE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(IsNullTest, StdFunction) { const Matcher> m = IsNull(); EXPECT_TRUE(m.Matches(std::function())); EXPECT_FALSE(m.Matches([]{})); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that IsNull() describes itself properly. TEST(IsNullTest, CanDescribeSelf) { @@ -1094,14 +1246,14 @@ EXPECT_TRUE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(NotNullTest, StdFunction) { const Matcher> m = NotNull(); EXPECT_TRUE(m.Matches([]{})); EXPECT_FALSE(m.Matches(std::function())); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that NotNull() describes itself properly. TEST(NotNullTest, CanDescribeSelf) { @@ -1125,7 +1277,7 @@ Matcher m = Ref(n); stringstream ss; ss << "references the variable @" << &n << " 5"; - EXPECT_EQ(string(ss.str()), Describe(m)); + EXPECT_EQ(ss.str(), Describe(m)); } // Test that Ref(non_const_varialbe) can be used as a matcher for a @@ -1169,27 +1321,34 @@ // Tests string comparison matchers. TEST(StrEqTest, MatchesEqualString) { - Matcher m = StrEq(string("Hello")); + Matcher m = StrEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); EXPECT_FALSE(m.Matches(NULL)); - Matcher m2 = StrEq("Hello"); + Matcher m2 = StrEq("Hello"); EXPECT_TRUE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher m3 = StrEq("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(StrEqTest, CanDescribeSelf) { - Matcher m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); + Matcher m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", Describe(m)); - string str("01204500800"); + std::string str("01204500800"); str[3] = '\0'; - Matcher m2 = StrEq(str); + Matcher m2 = StrEq(str); EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; - Matcher m3 = StrEq(str); + Matcher m3 = StrEq(str); EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); } @@ -1199,9 +1358,16 @@ EXPECT_TRUE(m.Matches(NULL)); EXPECT_FALSE(m.Matches("Hello")); - Matcher m2 = StrNe(string("Hello")); + Matcher m2 = StrNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher m3 = StrNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view(""))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrNeTest, CanDescribeSelf) { @@ -1210,44 +1376,52 @@ } TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher m = StrCaseEq(string("Hello")); + Matcher m = StrCaseEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_TRUE(m.Matches("hello")); EXPECT_FALSE(m.Matches("Hi")); EXPECT_FALSE(m.Matches(NULL)); - Matcher m2 = StrCaseEq("Hello"); + Matcher m2 = StrCaseEq("Hello"); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher m3 = StrCaseEq(std::string("Hello")); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { - string str1("oabocdooeoo"); - string str2("OABOCDOOEOO"); - Matcher m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + string(1, '\0'))); + std::string str1("oabocdooeoo"); + std::string str2("OABOCDOOEOO"); + Matcher m0 = StrCaseEq(str1); + EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); str1[3] = str2[3] = '\0'; - Matcher m1 = StrCaseEq(str1); + Matcher m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = '\0'; str2[0] = str2[6] = str2[7] = str2[10] = '\0'; - Matcher m2 = StrCaseEq(str1); + Matcher m2 = StrCaseEq(str1); str1[9] = str2[9] = '\0'; EXPECT_FALSE(m2.Matches(str2)); - Matcher m3 = StrCaseEq(str1); + Matcher m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + "x")); str2.append(1, '\0'); EXPECT_FALSE(m3.Matches(str2)); - EXPECT_FALSE(m3.Matches(string(str2, 0, 9))); + EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); } TEST(StrCaseEqTest, CanDescribeSelf) { - Matcher m = StrCaseEq("Hi"); + Matcher m = StrCaseEq("Hi"); EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); } @@ -1258,9 +1432,17 @@ EXPECT_FALSE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); - Matcher m2 = StrCaseNe(string("Hello")); + Matcher m2 = StrCaseNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher m3 = StrCaseNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrCaseNeTest, CanDescribeSelf) { @@ -1270,9 +1452,9 @@ // Tests that HasSubstr() works for matching string-typed values. TEST(HasSubstrTest, WorksForStringClasses) { - const Matcher m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(string("I love food."))); - EXPECT_FALSE(m1.Matches(string("tofo"))); + const Matcher m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(std::string("I love food."))); + EXPECT_FALSE(m1.Matches(std::string("tofo"))); const Matcher m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches(std::string("I love food."))); @@ -1292,9 +1474,28 @@ EXPECT_FALSE(m2.Matches(NULL)); } +#if GTEST_HAS_ABSL +// Tests that HasSubstr() works for matching absl::string_view-typed values. +TEST(HasSubstrTest, WorksForStringViewClasses) { + const Matcher m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m1.Matches(absl::string_view())); + + const Matcher m2 = HasSubstr("foo"); + EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m2.Matches(absl::string_view())); + + const Matcher m3 = HasSubstr(""); + EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); +} +#endif // GTEST_HAS_ABSL + // Tests that HasSubstr(s) describes itself properly. TEST(HasSubstrTest, CanDescribeSelf) { - Matcher m = HasSubstr("foo\n\""); + Matcher m = HasSubstr("foo\n\""); EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); } @@ -1320,6 +1521,35 @@ EXPECT_THAT(p, Not(Key(Lt(25)))); } +#if GTEST_LANG_CXX11 +template +struct Tag {}; + +struct PairWithGet { + int member_1; + string member_2; + using first_type = int; + using second_type = string; + + const int& GetImpl(Tag<0>) const { return member_1; } + const string& GetImpl(Tag<1>) const { return member_2; } +}; +template +auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag())) { + return value.GetImpl(Tag()); +} +TEST(PairTest, MatchesPairWithGetCorrectly) { + PairWithGet p{25, "foo"}; + EXPECT_THAT(p, Key(25)); + EXPECT_THAT(p, Not(Key(42))); + EXPECT_THAT(p, Key(Ge(20))); + EXPECT_THAT(p, Not(Key(Lt(25)))); + + std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, Contains(Key(29))); +} +#endif // GTEST_LANG_CXX11 + TEST(KeyTest, SafelyCastsInnerMatcher) { Matcher is_positive = Gt(0); Matcher is_negative = Lt(0); @@ -1457,15 +1687,27 @@ EXPECT_THAT(container, Not(Contains(Pair(3, _)))); } +#if GTEST_LANG_CXX11 +TEST(PairTest, UseGetInsteadOfMembers) { + PairWithGet pair{7, "ABC"}; + EXPECT_THAT(pair, Pair(7, "ABC")); + EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); + EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); + + std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); +} +#endif // GTEST_LANG_CXX11 + // Tests StartsWith(s). TEST(StartsWithTest, MatchesStringWithGivenPrefix) { - const Matcher m1 = StartsWith(string("")); + const Matcher m1 = StartsWith(std::string("")); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); EXPECT_FALSE(m1.Matches(NULL)); - const Matcher m2 = StartsWith("Hi"); + const Matcher m2 = StartsWith("Hi"); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Hi Hi!")); EXPECT_TRUE(m2.Matches("High")); @@ -1486,12 +1728,30 @@ EXPECT_TRUE(m1.Matches("")); EXPECT_FALSE(m1.Matches(NULL)); - const Matcher m2 = EndsWith(string("Hi")); + const Matcher m2 = EndsWith(std::string("Hi")); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Wow Hi Hi")); EXPECT_TRUE(m2.Matches("Super Hi")); EXPECT_FALSE(m2.Matches("i")); EXPECT_FALSE(m2.Matches("Hi ")); + +#if GTEST_HAS_GLOBAL_STRING + const Matcher m3 = EndsWith(::string("Hi")); + EXPECT_TRUE(m3.Matches("Hi")); + EXPECT_TRUE(m3.Matches("Wow Hi Hi")); + EXPECT_TRUE(m3.Matches("Super Hi")); + EXPECT_FALSE(m3.Matches("i")); + EXPECT_FALSE(m3.Matches("Hi ")); +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL + const Matcher m4 = EndsWith(""); + EXPECT_TRUE(m4.Matches("Hi")); + EXPECT_TRUE(m4.Matches("")); + // Default-constructed absl::string_view should not match anything, in order + // to distinguish it from an empty string. + EXPECT_FALSE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(EndsWithTest, CanDescribeSelf) { @@ -1507,32 +1767,61 @@ EXPECT_TRUE(m1.Matches("abcz")); EXPECT_FALSE(m1.Matches(NULL)); - const Matcher m2 = MatchesRegex(new RE("a.*z")); + const Matcher m2 = MatchesRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_FALSE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1az")); + +#if GTEST_HAS_ABSL + const Matcher m3 = MatchesRegex("a.*z"); + EXPECT_TRUE(m3.Matches(absl::string_view("az"))); + EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); + // Default-constructed absl::string_view should not match anything, in order + // to distinguish it from an empty string. + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher m4 = MatchesRegex(""); + EXPECT_FALSE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(MatchesRegexTest, CanDescribeSelf) { - Matcher m1 = MatchesRegex(string("Hi.*")); + Matcher m1 = MatchesRegex(std::string("Hi.*")); EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); Matcher m2 = MatchesRegex(new RE("a.*")); EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher m3 = MatchesRegex(new RE("0.*")); + EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests ContainsRegex(). TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { - const Matcher m1 = ContainsRegex(string("a.*z")); + const Matcher m1 = ContainsRegex(std::string("a.*z")); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("0abcz1")); EXPECT_FALSE(m1.Matches(NULL)); - const Matcher m2 = ContainsRegex(new RE("a.*z")); + const Matcher m2 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_TRUE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1a")); + +#if GTEST_HAS_ABSL + const Matcher m3 = ContainsRegex(new RE("a.*z")); + EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); + EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); + // Default-constructed absl::string_view should not match anything, in order + // to distinguish it from an empty string. + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher m4 = ContainsRegex(""); + EXPECT_FALSE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(ContainsRegexTest, CanDescribeSelf) { @@ -1541,6 +1830,11 @@ Matcher m2 = ContainsRegex(new RE("a.*")); EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher m3 = ContainsRegex(new RE("0.*")); + EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests for wide strings. @@ -2018,6 +2312,150 @@ EXPECT_EQ("are an unequal pair", Describe(m)); } +// Tests that FloatEq() matches a 2-tuple where +// FloatEq(first field) matches the second field. +TEST(FloatEq2Test, MatchesEqualArguments) { + typedef ::testing::tuple Tpl; + Matcher m = FloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); +} + +// Tests that FloatEq() describes itself properly. +TEST(FloatEq2Test, CanDescribeSelf) { + Matcher&> m = FloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatEq() matches a 2-tuple where +// NanSensitiveFloatEq(first field) matches the second field. +TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::testing::tuple Tpl; + Matcher m = NanSensitiveFloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatEq() describes itself properly. +TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { + Matcher&> m = NanSensitiveFloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that DoubleEq() matches a 2-tuple where +// DoubleEq(first field) matches the second field. +TEST(DoubleEq2Test, MatchesEqualArguments) { + typedef ::testing::tuple Tpl; + Matcher m = DoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); + EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(DoubleEq2Test, CanDescribeSelf) { + Matcher&> m = DoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleEq() matches a 2-tuple where +// NanSensitiveDoubleEq(first field) matches the second field. +TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::testing::tuple Tpl; + Matcher m = NanSensitiveDoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { + Matcher&> m = NanSensitiveDoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field. +TEST(FloatNear2Test, MatchesEqualArguments) { + typedef ::testing::tuple Tpl; + Matcher m = FloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); +} + +// Tests that FloatNear() describes itself properly. +TEST(FloatNear2Test, CanDescribeSelf) { + Matcher&> m = FloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatNear() matches a 2-tuple where +// NanSensitiveFloatNear(first field) matches the second field. +TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::testing::tuple Tpl; + Matcher m = NanSensitiveFloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatNear() describes itself properly. +TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { + Matcher&> m = + NanSensitiveFloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field. +TEST(DoubleNear2Test, MatchesEqualArguments) { + typedef ::testing::tuple Tpl; + Matcher m = DoubleNear(0.5); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); + EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); +} + +// Tests that DoubleNear() describes itself properly. +TEST(DoubleNear2Test, CanDescribeSelf) { + Matcher&> m = DoubleNear(0.5); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleNear() matches a 2-tuple where +// NanSensitiveDoubleNear(first field) matches the second field. +TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::testing::tuple Tpl; + Matcher m = NanSensitiveDoubleNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveDoubleNear() describes itself properly. +TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { + Matcher&> m = + NanSensitiveDoubleNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + // Tests that Not(m) matches any value that doesn't match m. TEST(NotTest, NegatesMatcher) { Matcher m; @@ -2106,7 +2544,7 @@ ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); Matcher m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10), Ne(11)); - EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))")); + EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); AllOfMatches(11, m); AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), @@ -2241,7 +2679,7 @@ } // Helper to allow easy testing of AnyOf matchers with num parameters. -void AnyOfMatches(int num, const Matcher& m) { +static void AnyOfMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { @@ -2250,6 +2688,18 @@ EXPECT_FALSE(m.Matches(num + 1)); } +#if GTEST_LANG_CXX11 +static void AnyOfStringMatches(int num, const Matcher& m) { + SCOPED_TRACE(Describe(m)); + EXPECT_FALSE(m.Matches(std::to_string(0))); + + for (int i = 1; i <= num; ++i) { + EXPECT_TRUE(m.Matches(std::to_string(i))); + } + EXPECT_FALSE(m.Matches(std::to_string(num + 1))); +} +#endif + // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { @@ -2300,15 +2750,48 @@ // on ADL. Matcher m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))")); + EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); AnyOfMatches(11, m); AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfStringMatches( + 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", + "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", + "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", + "43", "44", "45", "46", "47", "48", "49", "50")); } +// Tests the variadic version of the ElementsAreMatcher +TEST(ElementsAreTest, HugeMatcher) { + vector test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + + EXPECT_THAT(test_vector, + ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), + Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherStr) { + vector test_vector{ + "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; + + EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, + _, _, _, _, _, _)); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherUnordered) { + vector test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; + + EXPECT_THAT(test_vector, UnorderedElementsAre( + Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), + Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); +} + #endif // GTEST_LANG_CXX11 // Tests that AnyOf(m1, ..., mn) describes itself properly. @@ -2583,6 +3066,22 @@ EXPECT_THAT(0, Really(Eq(0))); } +TEST(DescribeMatcherTest, WorksWithValue) { + EXPECT_EQ("is equal to 42", DescribeMatcher(42)); + EXPECT_EQ("isn't equal to 42", DescribeMatcher(42, true)); +} + +TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { + const Matcher monomorphic = Le(0); + EXPECT_EQ("is <= 0", DescribeMatcher(monomorphic)); + EXPECT_EQ("isn't <= 0", DescribeMatcher(monomorphic, true)); +} + +TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { + EXPECT_EQ("is even", DescribeMatcher(PolymorphicIsEven())); + EXPECT_EQ("is odd", DescribeMatcher(PolymorphicIsEven(), true)); +} + TEST(AllArgsTest, WorksForTuple) { EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt())); EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt()))); @@ -2617,6 +3116,44 @@ EXPECT_EQ(2, helper.Helper('a', 1)); } +class OptionalMatchersHelper { + public: + OptionalMatchersHelper() {} + + MOCK_METHOD0(NoArgs, int()); + + MOCK_METHOD1(OneArg, int(int y)); + + MOCK_METHOD2(TwoArgs, int(char x, int y)); + + MOCK_METHOD1(Overloaded, int(char x)); + MOCK_METHOD2(Overloaded, int(char x, int y)); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); +}; + +TEST(AllArgsTest, WorksWithoutMatchers) { + OptionalMatchersHelper helper; + + ON_CALL(helper, NoArgs).WillByDefault(Return(10)); + ON_CALL(helper, OneArg).WillByDefault(Return(20)); + ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(20, helper.OneArg(1)); + EXPECT_EQ(30, helper.TwoArgs('\1', 2)); + + EXPECT_CALL(helper, NoArgs).Times(1); + EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); + EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); + EXPECT_CALL(helper, TwoArgs).Times(0); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(100, helper.OneArg(1)); + EXPECT_EQ(200, helper.OneArg(17)); +} + // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value // matches the matcher. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { @@ -2685,9 +3222,9 @@ Matcher starts_with_he = StartsWith("he"); ASSERT_THAT("hello", starts_with_he); - Matcher ends_with_ok = EndsWith("ok"); + Matcher ends_with_ok = EndsWith("ok"); ASSERT_THAT("book", ends_with_ok); - const string bad = "bad"; + const std::string bad = "bad"; EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), "Value of: bad\n" "Expected: ends with \"ok\"\n" @@ -2712,18 +3249,22 @@ zero_bits_(Floating(0).bits()), one_bits_(Floating(1).bits()), infinity_bits_(Floating(Floating::Infinity()).bits()), - close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)), - close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)), - further_from_negative_zero_(-AsBits( + close_to_positive_zero_( + Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), + close_to_negative_zero_( + -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), + further_from_negative_zero_(-Floating::ReinterpretBits( zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), - close_to_one_(AsBits(one_bits_ + max_ulps_)), - further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)), + close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), + further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), infinity_(Floating::Infinity()), - close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)), - further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)), + close_to_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), + further_from_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), max_(Floating::Max()), - nan1_(AsBits(Floating::kExponentBitMask | 1)), - nan2_(AsBits(Floating::kExponentBitMask | 200)) { + nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), + nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { } void TestSize() { @@ -2778,7 +3319,7 @@ // Pre-calculated numbers to be used by the tests. - const size_t max_ulps_; + const Bits max_ulps_; const Bits zero_bits_; // The bits that represent 0.0. const Bits one_bits_; // The bits that represent 1.0. @@ -2804,12 +3345,6 @@ // Some NaNs. const RawType nan1_; const RawType nan2_; - - private: - template - static RawType AsBits(T value) { - return Floating::ReinterpretBits(static_cast(value)); - } }; // Tests floating-point matchers with fixed epsilons. @@ -3099,7 +3634,8 @@ EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); - const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); + const std::string explanation = + Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); // Different C++ implementations may print floating-point numbers // slightly differently. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC @@ -3186,7 +3722,6 @@ } #if GTEST_HAS_RTTI - TEST(WhenDynamicCastToTest, SameType) { Derived derived; derived.i = 4; @@ -3244,7 +3779,7 @@ TEST(WhenDynamicCastToTest, Describe) { Matcher matcher = WhenDynamicCastTo(Pointee(_)); - const string prefix = + const std::string prefix = "when dynamic_cast to " + internal::GetTypeName() + ", "; EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); EXPECT_EQ(prefix + "does not point to a value that is anything", @@ -3278,7 +3813,6 @@ Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); } - #endif // GTEST_HAS_RTTI // Minimal const-propagating pointer. @@ -3337,9 +3871,9 @@ } TEST(PointeeTest, CanExplainMatchResult) { - const Matcher m = Pointee(StartsWith("Hi")); + const Matcher m = Pointee(StartsWith("Hi")); - EXPECT_EQ("", Explain(m, static_cast(NULL))); + EXPECT_EQ("", Explain(m, static_cast(NULL))); const Matcher m2 = Pointee(GreaterThan(1)); // NOLINT long n = 3; // NOLINT @@ -3400,21 +3934,28 @@ // Tests that Field(&Foo::field, ...) works when field is non-const. TEST(FieldTest, WorksForNonConstField) { Matcher m = Field(&AStruct::x, Ge(0)); + Matcher m_with_name = Field("x", &AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is const. TEST(FieldTest, WorksForConstField) { AStruct a; Matcher m = Field(&AStruct::y, Ge(0.0)); + Matcher m_with_name = Field("y", &AStruct::y, Ge(0.0)); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); m = Field(&AStruct::y, Le(0.0)); + m_with_name = Field("y", &AStruct::y, Le(0.0)); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is not copyable. @@ -3488,6 +4029,14 @@ EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldTest, CanDescribeSelfWithFieldName) { + Matcher m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the match result. TEST(FieldTest, CanExplainMatchResult) { Matcher m = Field(&AStruct::x, Ge(0)); @@ -3502,6 +4051,19 @@ Explain(m, a)); } +TEST(FieldTest, CanExplainMatchResultWithFieldName) { + Matcher m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Field() works when the argument is a pointer to const. TEST(FieldForPointerTest, WorksForPointerToConst) { Matcher m = Field(&AStruct::x, Ge(0)); @@ -3559,6 +4121,14 @@ EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { + Matcher m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the result of matching a pointer. TEST(FieldForPointerTest, CanExplainMatchResult) { Matcher m = Field(&AStruct::x, Ge(0)); @@ -3574,6 +4144,22 @@ ", which is 1 more than 0", Explain(m, &a)); } +TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { + Matcher m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("", Explain(m, static_cast(NULL))); + EXPECT_EQ( + "which points to an object whose field `field_name` is 1" + OfType("int"), + Explain(m, &a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("which points to an object whose field `field_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // A user-defined class for testing Property(). class AClass { public: @@ -3585,15 +4171,20 @@ void set_n(int new_n) { n_ = new_n; } // A getter that returns a reference to const. - const string& s() const { return s_; } + const std::string& s() const { return s_; } - void set_s(const string& new_s) { s_ = new_s; } +#if GTEST_LANG_CXX11 + const std::string& s_ref() const & { return s_; } +#endif + void set_s(const std::string& new_s) { s_ = new_s; } + // A getter that returns a reference to non-const. double& x() const { return x_; } + private: int n_; - string s_; + std::string s_; static double x_; }; @@ -3612,28 +4203,54 @@ // returns a non-reference. TEST(PropertyTest, WorksForNonReferenceProperty) { Matcher m = Property(&AClass::n, Ge(0)); + Matcher m_with_name = Property("n", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property(&Foo::property, ...) works when property() // returns a reference to const. TEST(PropertyTest, WorksForReferenceToConstProperty) { Matcher m = Property(&AClass::s, StartsWith("hi")); + Matcher m_with_name = + Property("s", &AClass::s, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } +#if GTEST_LANG_CXX11 +// Tests that Property(&Foo::property, ...) works when property() is +// ref-qualified. +TEST(PropertyTest, WorksForRefQualifiedProperty) { + Matcher m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher m_with_name = + Property("s", &AClass::s_ref, StartsWith("hi")); + + AClass a; + a.set_s("hill"); + EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); + + a.set_s("hole"); + EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); +} +#endif + // Tests that Property(&Foo::property, ...) works when property() // returns a reference to non-const. TEST(PropertyTest, WorksForReferenceToNonConstProperty) { @@ -3682,10 +4299,15 @@ Matcher m = Property(&AClass::n, Matcher(Ge(0))); + Matcher m_with_name = + Property("n", &AClass::n, Matcher(Ge(0))); + AClass a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property() can describe itself. @@ -3697,6 +4319,14 @@ DescribeNegation(m)); } +TEST(PropertyTest, CanDescribeSelfWithPropertyName) { + Matcher m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the match result. TEST(PropertyTest, CanExplainMatchResult) { Matcher m = Property(&AClass::n, Ge(0)); @@ -3711,6 +4341,19 @@ Explain(m, a)); } +TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { + Matcher m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Property() works when the argument is a pointer to const. TEST(PropertyForPointerTest, WorksForPointerToConst) { Matcher m = Property(&AClass::n, Ge(0)); @@ -3778,6 +4421,14 @@ DescribeNegation(m)); } +TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { + Matcher m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the result of matching a pointer. TEST(PropertyForPointerTest, CanExplainMatchResult) { Matcher m = Property(&AClass::n, Ge(0)); @@ -3795,14 +4446,32 @@ Explain(m, &a)); } +TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { + Matcher m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("", Explain(m, static_cast(NULL))); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int"), + Explain(m, &a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // Tests ResultOf. // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function pointer. -string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; } +std::string IntToStringFunction(int input) { + return input == 1 ? "foo" : "bar"; +} TEST(ResultOfTest, WorksForFunctionPointers) { - Matcher matcher = ResultOf(&IntToStringFunction, Eq(string("foo"))); + Matcher matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); @@ -3868,12 +4537,12 @@ // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a reference to const. -const string& StringFunction(const string& input) { return input; } +const std::string& StringFunction(const std::string& input) { return input; } TEST(ResultOfTest, WorksForReferenceToConstResults) { - string s = "foo"; - string s2 = s; - Matcher matcher = ResultOf(&StringFunction, Ref(s)); + std::string s = "foo"; + std::string s2 = s; + Matcher matcher = ResultOf(&StringFunction, Ref(s)); EXPECT_TRUE(matcher.Matches(s)); EXPECT_FALSE(matcher.Matches(s2)); @@ -3893,8 +4562,9 @@ // a NULL function pointer. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { EXPECT_DEATH_IF_SUPPORTED( - ResultOf(static_cast(NULL), Eq(string("foo"))), - "NULL function pointer is passed into ResultOf\\(\\)\\."); + ResultOf(static_cast(NULL), + Eq(std::string("foo"))), + "NULL function pointer is passed into ResultOf\\(\\)\\."); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a @@ -3907,26 +4577,27 @@ // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function object. -struct Functor : public ::std::unary_function { +struct Functor : public ::std::unary_function { result_type operator()(argument_type input) const { return IntToStringFunction(input); } }; TEST(ResultOfTest, WorksForFunctors) { - Matcher matcher = ResultOf(Functor(), Eq(string("foo"))); + Matcher matcher = ResultOf(Functor(), Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more then one operator() defined. ResultOf() must work +// functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; int operator()(int n) { return n; } int operator()(const char* s) { return static_cast(strlen(s)); } + std::string operator()(int *p) { return p ? "good ptr" : "null"; } }; TEST(ResultOfTest, WorksForPolymorphicFunctors) { @@ -3941,6 +4612,23 @@ EXPECT_FALSE(matcher_string.Matches("shrt")); } +#if GTEST_LANG_CXX11 +TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { + Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); + + int n = 0; + EXPECT_TRUE(matcher.Matches(&n)); + EXPECT_FALSE(matcher.Matches(nullptr)); +} + +TEST(ResultOfTest, WorksForLambdas) { + Matcher matcher = + ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx"); + EXPECT_TRUE(matcher.Matches(3)); + EXPECT_FALSE(matcher.Matches(1)); +} +#endif + const int* ReferencingFunction(const int& n) { return &n; } struct ReferencingFunctor { @@ -4080,11 +4768,11 @@ } TEST(IsEmptyTest, WorksWithString) { - string text; + std::string text; EXPECT_THAT(text, IsEmpty()); text = "foo"; EXPECT_THAT(text, Not(IsEmpty())); - text = string("\0", 1); + text = std::string("\0", 1); EXPECT_THAT(text, Not(IsEmpty())); } @@ -4102,6 +4790,44 @@ EXPECT_EQ("whose size is 1", Explain(m, container)); } +TEST(IsTrueTest, IsTrueIsFalse) { + EXPECT_THAT(true, IsTrue()); + EXPECT_THAT(false, IsFalse()); + EXPECT_THAT(true, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(0, Not(IsTrue())); + EXPECT_THAT(0, IsFalse()); + EXPECT_THAT(NULL, Not(IsTrue())); + EXPECT_THAT(NULL, IsFalse()); + EXPECT_THAT(-1, IsTrue()); + EXPECT_THAT(-1, Not(IsFalse())); + EXPECT_THAT(1, IsTrue()); + EXPECT_THAT(1, Not(IsFalse())); + EXPECT_THAT(2, IsTrue()); + EXPECT_THAT(2, Not(IsFalse())); + int a = 42; + EXPECT_THAT(a, IsTrue()); + EXPECT_THAT(a, Not(IsFalse())); + EXPECT_THAT(&a, IsTrue()); + EXPECT_THAT(&a, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(true, Not(IsFalse())); +#if GTEST_LANG_CXX11 + EXPECT_THAT(std::true_type(), IsTrue()); + EXPECT_THAT(std::true_type(), Not(IsFalse())); + EXPECT_THAT(std::false_type(), IsFalse()); + EXPECT_THAT(std::false_type(), Not(IsTrue())); + EXPECT_THAT(nullptr, Not(IsTrue())); + EXPECT_THAT(nullptr, IsFalse()); + std::unique_ptr null_unique; + std::unique_ptr nonnull_unique(new int(0)); + EXPECT_THAT(null_unique, Not(IsTrue())); + EXPECT_THAT(null_unique, IsFalse()); + EXPECT_THAT(nonnull_unique, IsTrue()); + EXPECT_THAT(nonnull_unique, Not(IsFalse())); +#endif // GTEST_LANG_CXX11 +} + TEST(SizeIsTest, ImplementsSizeIs) { vector container; EXPECT_THAT(container, SizeIs(0)); @@ -4115,7 +4841,7 @@ } TEST(SizeIsTest, WorksWithMap) { - map container; + map container; EXPECT_THAT(container, SizeIs(0)); EXPECT_THAT(container, Not(SizeIs(1))); container.insert(make_pair("foo", 1)); @@ -4235,7 +4961,7 @@ #endif // GTEST_HAS_TYPED_TEST // Tests that mutliple missing values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; @@ -4248,7 +4974,7 @@ } // Tests that added values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; @@ -4380,13 +5106,13 @@ } TEST(WhenSortedByTest, WorksForNonVectorContainer) { - list words; + list words; words.push_back("say"); words.push_back("hello"); words.push_back("world"); - EXPECT_THAT(words, WhenSortedBy(less(), + EXPECT_THAT(words, WhenSortedBy(less(), ElementsAre("hello", "say", "world"))); - EXPECT_THAT(words, Not(WhenSortedBy(less(), + EXPECT_THAT(words, Not(WhenSortedBy(less(), ElementsAre("say", "hello", "world")))); } @@ -4429,7 +5155,7 @@ } TEST(WhenSortedTest, WorksForNonEmptyContainer) { - list words; + list words; words.push_back("3"); words.push_back("1"); words.push_back("2"); @@ -4439,14 +5165,16 @@ } TEST(WhenSortedTest, WorksForMapTypes) { - map word_counts; - word_counts["and"] = 1; - word_counts["the"] = 1; - word_counts["buffalo"] = 2; - EXPECT_THAT(word_counts, WhenSorted(ElementsAre( - Pair("and", 1), Pair("buffalo", 2), Pair("the", 1)))); - EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre( - Pair("and", 1), Pair("the", 1), Pair("buffalo", 2))))); + map word_counts; + word_counts["and"] = 1; + word_counts["the"] = 1; + word_counts["buffalo"] = 2; + EXPECT_THAT(word_counts, + WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), + Pair("the", 1)))); + EXPECT_THAT(word_counts, + Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), + Pair("buffalo", 2))))); } TEST(WhenSortedTest, WorksForMultiMapTypes) { @@ -4654,6 +5382,250 @@ EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } +TEST(IsSupersetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(superset))); + EXPECT_THAT(superset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); +} + +TEST(IsSupersetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int expected[] = {1, 1}; + EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); + EXPECT_THAT(enough, IsSupersetOf(expected)); +} + +TEST(IsSupersetOfTest, WorksForEmpty) { + vector numbers; + vector expected; + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2, 3, 4, 5}; + Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector expected; + expected.push_back(1); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSupersetOf(expected)); + + expected.push_back(0); + EXPECT_THAT(s, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, IsSupersetOf(expected)); + + expected.push_back(4); + EXPECT_THAT(actual, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, Describe) { + typedef std::vector IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + Describe(IsSupersetOf(expected)), + Eq("a surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, DescribeNegation) { + typedef std::vector IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation(IsSupersetOf(expected)), + Eq("no surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, MatchAndExplain) { + std::vector v; + v.push_back(2); + v.push_back(3); + std::vector expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following matchers don't match any elements:\n" + "matcher #0: is equal to 1")); + + v.push_back(1); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #2 is matched by matcher #0")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSupersetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 3, 6, 2, 4, 5}; + EXPECT_THAT(numbers, IsSupersetOf({1, 2})); + EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); +} +#endif + +TEST(IsSubsetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSubsetOf(subset)); + EXPECT_THAT(subset, IsSubsetOf(superset)); + EXPECT_THAT(superset, Not(IsSubsetOf(subset))); + EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); +} + +TEST(IsSubsetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int actual[] = {1, 1}; + EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); + EXPECT_THAT(actual, IsSubsetOf(enough)); +} + +TEST(IsSubsetOfTest, WorksForEmpty) { + vector numbers; + vector expected; + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(2); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2}; + Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector expected; + expected.push_back(1); + EXPECT_THAT(s, Not(IsSubsetOf(expected))); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, Not(IsSubsetOf(expected))); + + expected.push_back(2); + expected.push_back(4); + EXPECT_THAT(actual, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, Describe) { + typedef std::vector IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + + EXPECT_THAT( + Describe(IsSubsetOf(expected)), + Eq("an injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, DescribeNegation) { + typedef std::vector IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation(IsSubsetOf(expected)), + Eq("no injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, MatchAndExplain) { + std::vector v; + v.push_back(2); + v.push_back(3); + std::vector expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following elements don't match any matchers:\n" + "element #1: 3")); + + expected.push_back(3); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #1 is matched by matcher #2")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSubsetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 2, 3}; + EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); + EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); +} +#endif + // Tests using ElementsAre() and ElementsAreArray() with stream-like // "containers". @@ -4763,7 +5735,7 @@ } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { - const string a[5] = {"a", "b", "c", "d", "e"}; + const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); } @@ -4937,7 +5909,7 @@ } // Test helper for formatting element, matcher index pairs in expectations. -static string EMString(int element, int matcher) { +static std::string EMString(int element, int matcher) { stringstream ss; ss << "(element #" << element << ", matcher #" << matcher << ")"; return ss.str(); @@ -4946,7 +5918,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { // A situation where all elements and matchers have a match // associated with them, but the max matching is not perfect. - std::vector v; + std::vector v; v.push_back("a"); v.push_back("b"); v.push_back("c"); @@ -4955,7 +5927,7 @@ UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) << listener.str(); - string prefix = + std::string prefix = "where no permutation of the elements can satisfy all matchers, " "and the closest match is 2 of 3 matchers with the " "pairings:\n"; @@ -5238,28 +6210,6 @@ EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); } -// Tests JoinAsTuple(). - -TEST(JoinAsTupleTest, JoinsEmptyTuple) { - EXPECT_EQ("", JoinAsTuple(Strings())); -} - -TEST(JoinAsTupleTest, JoinsOneTuple) { - const char* fields[] = {"1"}; - EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); -} - -TEST(JoinAsTupleTest, JoinsTwoTuple) { - const char* fields[] = {"1", "a"}; - EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); -} - -TEST(JoinAsTupleTest, JoinsTenTuple) { - const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; - EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", - JoinAsTuple(Strings(fields, fields + 10))); -} - // Tests FormatMatcherDescription(). TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { @@ -5366,13 +6316,13 @@ EXPECT_THAT(some_vector, Not(Each(3))); EXPECT_THAT(some_vector, Each(Lt(3.5))); - vector another_vector; + vector another_vector; another_vector.push_back("fee"); - EXPECT_THAT(another_vector, Each(string("fee"))); + EXPECT_THAT(another_vector, Each(std::string("fee"))); another_vector.push_back("fie"); another_vector.push_back("foe"); another_vector.push_back("fum"); - EXPECT_THAT(another_vector, Not(Each(string("fee")))); + EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); } TEST(EachTest, MatchesMapWhenAllElementsMatch) { @@ -5381,15 +6331,15 @@ my_map[bar] = 2; EXPECT_THAT(my_map, Each(make_pair(bar, 2))); - map another_map; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + map another_map; + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fee"] = 1; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; - EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); - EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); } @@ -5483,6 +6433,16 @@ EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); } +// Test is effective only with sanitizers. +TEST(PointwiseTest, WorksForVectorOfBool) { + vector rhs(3, false); + rhs[1] = true; + vector lhs = rhs; + EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); + rhs[0] = true; + EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); +} + #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, WorksForRhsInitializerList) { @@ -5648,5 +6608,198 @@ EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); } +// Sample optional type implementation with minimal requirements for use with +// Optional matcher. +class SampleOptionalInt { + public: + typedef int value_type; + explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {} + SampleOptionalInt() : value_(0), has_value_(false) {} + operator bool() const { + return has_value_; + } + const int& operator*() const { + return value_; + } + private: + int value_; + bool has_value_; +}; + +TEST(OptionalTest, DescribesSelf) { + const Matcher m = Optional(Eq(1)); + EXPECT_EQ("value is equal to 1", Describe(m)); +} + +TEST(OptionalTest, ExplainsSelf) { + const Matcher m = Optional(Eq(1)); + EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1))); + EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2))); +} + +TEST(OptionalTest, MatchesNonEmptyOptional) { + const Matcher m1 = Optional(1); + const Matcher m2 = Optional(Eq(2)); + const Matcher m3 = Optional(Lt(3)); + SampleOptionalInt opt(1); + EXPECT_TRUE(m1.Matches(opt)); + EXPECT_FALSE(m2.Matches(opt)); + EXPECT_TRUE(m3.Matches(opt)); +} + +TEST(OptionalTest, DoesNotMatchNullopt) { + const Matcher m = Optional(1); + SampleOptionalInt empty; + EXPECT_FALSE(m.Matches(empty)); +} + +class SampleVariantIntString { + public: + SampleVariantIntString(int i) : i_(i), has_int_(true) {} + SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} + + template + friend bool holds_alternative(const SampleVariantIntString& value) { + return value.has_int_ == internal::IsSame::value; + } + + template + friend const T& get(const SampleVariantIntString& value) { + return value.get_impl(static_cast(NULL)); + } + + private: + const int& get_impl(int*) const { return i_; } + const std::string& get_impl(std::string*) const { return s_; } + + int i_; + std::string s_; + bool has_int_; +}; + +TEST(VariantTest, DescribesSelf) { + const Matcher m = VariantWith(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(VariantTest, ExplainsSelf) { + const Matcher m = VariantWith(Eq(1)); + EXPECT_THAT(Explain(m, SampleVariantIntString(1)), + ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleVariantIntString("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleVariantIntString(2)), + "whose value 2 doesn't match"); +} + +TEST(VariantTest, FullMatch) { + Matcher m = VariantWith(Eq(1)); + EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); + + m = VariantWith(Eq("1")); + EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); +} + +TEST(VariantTest, TypeDoesNotMatch) { + Matcher m = VariantWith(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); + + m = VariantWith(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); +} + +TEST(VariantTest, InnerDoesNotMatch) { + Matcher m = VariantWith(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); + + m = VariantWith(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); +} + +class SampleAnyType { + public: + explicit SampleAnyType(int i) : index_(0), i_(i) {} + explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} + + template + friend const T* any_cast(const SampleAnyType* any) { + return any->get_impl(static_cast(NULL)); + } + + private: + int index_; + int i_; + std::string s_; + + const int* get_impl(int*) const { return index_ == 0 ? &i_ : NULL; } + const std::string* get_impl(std::string*) const { + return index_ == 1 ? &s_ : NULL; + } +}; + +TEST(AnyWithTest, FullMatch) { + Matcher m = AnyWith(Eq(1)); + EXPECT_TRUE(m.Matches(SampleAnyType(1))); +} + +TEST(AnyWithTest, TestBadCastType) { + Matcher m = AnyWith(Eq("fail")); + EXPECT_FALSE(m.Matches(SampleAnyType(1))); +} + +#if GTEST_LANG_CXX11 +TEST(AnyWithTest, TestUseInContainers) { + std::vector a; + a.emplace_back(1); + a.emplace_back(2); + a.emplace_back(3); + EXPECT_THAT( + a, ElementsAreArray({AnyWith(1), AnyWith(2), AnyWith(3)})); + + std::vector b; + b.emplace_back("hello"); + b.emplace_back("merhaba"); + b.emplace_back("salut"); + EXPECT_THAT(b, ElementsAreArray({AnyWith("hello"), + AnyWith("merhaba"), + AnyWith("salut")})); +} +#endif // GTEST_LANG_CXX11 +TEST(AnyWithTest, TestCompare) { + EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); +} + +TEST(AnyWithTest, DescribesSelf) { + const Matcher m = AnyWith(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(AnyWithTest, ExplainsSelf) { + const Matcher m = AnyWith(Eq(1)); + + EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleAnyType("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); +} + +#if GTEST_LANG_CXX11 + +TEST(PointeeTest, WorksOnMoveOnlyType) { + std::unique_ptr p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +TEST(NotTest, WorksOnMoveOnlyType) { + std::unique_ptr p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +#endif // GTEST_LANG_CXX11 + } // namespace gmock_matchers_test } // namespace testing