Unverified Commit edadfecd authored by Akash Patel's avatar Akash Patel Committed by GitHub
Browse files

Update gtest to 1.11.0 (#1086)

Properly resolves #1083, #996.
parent 26e3b704
......@@ -31,7 +31,7 @@
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
#include "gmock/gmock-generated-function-mockers.h"
#include "gmock/gmock-function-mocker.h"
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
......@@ -40,8 +40,11 @@
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
#include <functional>
#include <map>
#include <string>
#include <type_traits>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
......@@ -101,6 +104,20 @@ class FooInterface {
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0;
virtual int (*ReturnsFunctionPointer1(int))(bool) = 0;
using fn_ptr = int (*)(bool);
virtual fn_ptr ReturnsFunctionPointer2(int) = 0;
virtual int RefQualifiedConstRef() const& = 0;
virtual int RefQualifiedConstRefRef() const&& = 0;
virtual int RefQualifiedRef() & = 0;
virtual int RefQualifiedRefRef() && = 0;
virtual int RefQualifiedOverloaded() const& = 0;
virtual int RefQualifiedOverloaded() const&& = 0;
virtual int RefQualifiedOverloaded() & = 0;
virtual int RefQualifiedOverloaded() && = 0;
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
......@@ -159,6 +176,9 @@ class MockFoo : public FooInterface {
MOCK_METHOD(int, TypeWithTemplatedCopyCtor,
(const TemplatedCopyable<int>&)); // NOLINT
MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());
MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());
#if GTEST_OS_WINDOWS
MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));
......@@ -171,189 +191,301 @@ class MockFoo : public FooInterface {
(Calltype(STDMETHODCALLTYPE)));
#endif // GTEST_OS_WINDOWS
// Test reference qualified functions.
MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override));
MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override));
MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override));
MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
class LegacyMockFoo : public FooInterface {
public:
LegacyMockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
MOCK_METHOD0(Nullary, int()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD1(Unary, bool(int)); // NOLINT
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str));
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
MOCK_METHOD1(TakesConstReference, std::string(const int&));
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
MOCK_CONST_METHOD1(ReturnTypeWithComma,
std::map<int, std::string>(int)); // NOLINT
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
int(bool b, char c, short d, int e, // NOLINT
long f, float g, double h, // NOLINT
unsigned i, char* j, const std::string& k));
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,
char(int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
std::map<int, std::string>());
#endif // GTEST_OS_WINDOWS
// We can't mock these with the old macros, but we need to define them to make
// it concrete.
int RefQualifiedConstRef() const& override { return 0; }
int RefQualifiedConstRefRef() const&& override { return 0; }
int RefQualifiedRef() & override { return 0; }
int RefQualifiedRefRef() && override { return 0; }
int RefQualifiedOverloaded() const& override { return 0; }
int RefQualifiedOverloaded() const&& override { return 0; }
int RefQualifiedOverloaded() & override { return 0; }
int RefQualifiedOverloaded() && override { return 0; }
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo);
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
class MockMethodFunctionMockerTest : public testing::Test {
template <class T>
class FunctionMockerTest : public testing::Test {
protected:
MockMethodFunctionMockerTest() : foo_(&mock_foo_) {}
FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
MockFoo mock_foo_;
T mock_foo_;
};
using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;
TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);
// Tests mocking a void-returning function.
TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0);
TYPED_TEST(FunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));
this->foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary())
TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(this->mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary());
EXPECT_EQ(0, this->foo_->Nullary());
EXPECT_EQ(1, this->foo_->Nullary());
}
// Tests mocking a unary function.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2)))
.Times(2)
.WillOnce(Return(true));
TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2));
EXPECT_TRUE(this->foo_->Unary(2));
EXPECT_FALSE(this->foo_->Unary(2));
}
// Tests mocking a binary function.
TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _))
.WillOnce(Return(3));
TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1));
EXPECT_EQ(3, this->foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(this->mock_foo_,
Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5));
EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking a function that takes a non-const reference.
TEST_F(MockMethodFunctionMockerTest,
MocksFunctionWithNonConstReferenceArgument) {
TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a));
EXPECT_TRUE(this->foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a));
EXPECT_EQ("Hello", this->foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
.WillOnce(DoDefault());
TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5));
EXPECT_FALSE(this->foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest,
MocksFunctionsOverloadedOnConstnessOfThis) {
EXPECT_CALL(mock_foo_, OverloadedOnConstness());
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());
EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
EXPECT_EQ(0, this->foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());
}
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) {
TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));
EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));
}
TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))
.WillOnce(Return(true));
EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary())
TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(this->mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary());
EXPECT_EQ(-1, this->foo_->CTNullary());
EXPECT_EQ(0, this->foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2));
EXPECT_TRUE(this->foo_->CTUnary(2));
EXPECT_FALSE(this->foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_))
.WillOnce(Return('a'));
TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0));
EXPECT_EQ('a', Const(*this->foo_).CTConst(0));
}
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
TEST(FunctionMockerTest, RefQualified) {
MockFoo mock_foo;
EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1));
EXPECT_CALL(std::move(mock_foo), // NOLINT
RefQualifiedConstRefRef)
.WillOnce(Return(2));
EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3));
EXPECT_CALL(std::move(mock_foo), // NOLINT
RefQualifiedRefRef)
.WillOnce(Return(4));
EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(5));
EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(6));
EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(7));
EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(8));
EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1);
EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); // NOLINT
EXPECT_EQ(mock_foo.RefQualifiedRef(), 3);
EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); // NOLINT
EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5);
EXPECT_EQ(std::move(std::cref(mock_foo).get()) // NOLINT
.RefQualifiedOverloaded(),
6);
EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7);
EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); // NOLINT
}
class MockB {
public:
MockB() {}
......@@ -364,20 +496,33 @@ class MockB {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
class LegacyMockB {
public:
LegacyMockB() {}
MOCK_METHOD0(DoB, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB);
};
template <typename T>
class ExpectCallTest : public ::testing::Test {};
using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;
TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);
// Tests that functions with no EXPECT_CALL() rules can be called any
// number of times.
TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{
MockB b;
}
TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{ TypeParam b; }
{
MockB b;
TypeParam b;
b.DoB();
}
{
MockB b;
TypeParam b;
b.DoB();
b.DoB();
}
......@@ -416,9 +561,33 @@ class MockStack : public StackInterface<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
};
template <typename T>
class LegacyMockStack : public StackInterface<T> {
public:
LegacyMockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
MOCK_CONST_METHOD0_T(GetTop, const T&());
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack);
};
template <typename T>
class TemplateMockTest : public ::testing::Test {};
using TemplateMockTestTypes =
::testing::Types<MockStack<int>, LegacyMockStack<int>>;
TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);
// Tests that template mock works.
TEST(MockMethodTemplateMockTest, Works) {
MockStack<int> mock;
TYPED_TEST(TemplateMockTest, Works) {
TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
......@@ -439,8 +608,8 @@ TEST(MockMethodTemplateMockTest, Works) {
EXPECT_EQ(0, mock.GetSize());
}
TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock;
TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
TypeParam mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
......@@ -484,9 +653,31 @@ class MockStackWithCallType : public StackInterfaceWithCallType<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
};
template <typename T>
class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
LegacyMockStackWithCallType() {}
MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType);
};
template <typename T>
class TemplateMockTestWithCallType : public ::testing::Test {};
using TemplateMockTestWithCallTypeTypes =
::testing::Types<MockStackWithCallType<int>,
LegacyMockStackWithCallType<int>>;
TYPED_TEST_SUITE(TemplateMockTestWithCallType,
TemplateMockTestWithCallTypeTypes);
// Tests that template mock with calltype works.
TEST(MockMethodTemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock;
TYPED_TEST(TemplateMockTestWithCallType, Works) {
TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
......@@ -513,6 +704,11 @@ TEST(MockMethodTemplateMockTestWithCallType, Works) {
MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n))
#define LEGACY_MY_MOCK_METHODS1_ \
MOCK_METHOD0(Overloaded, void()); \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD2(Overloaded, bool(bool f, int n))
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() {}
......@@ -523,8 +719,25 @@ class MockOverloadedOnArgNumber {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
};
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
MockOverloadedOnArgNumber mock;
class LegacyMockOverloadedOnArgNumber {
public:
LegacyMockOverloadedOnArgNumber() {}
LEGACY_MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber);
};
template <typename T>
class OverloadedMockMethodTest : public ::testing::Test {};
using OverloadedMockMethodTestTypes =
::testing::Types<MockOverloadedOnArgNumber,
LegacyMockOverloadedOnArgNumber>;
TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);
TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
TypeParam mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
......@@ -632,6 +845,68 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
}
namespace {
template <typename Expected, typename F>
static constexpr bool IsMockFunctionTemplateArgumentDeducedTo(
const internal::MockFunction<F>&) {
return std::is_same<F, Expected>::value;
}
} // namespace
template <typename F>
class MockMethodMockFunctionSignatureTest : public Test {};
using MockMethodMockFunctionSignatureTypes =
Types<void(), int(), void(int), int(int), int(bool, int),
int(bool, char, int, int, int, int, int, char, int, bool)>;
TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,
MockMethodMockFunctionSignatureTypes);
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForRawSignature) {
using Argument = TypeParam;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForStdFunction) {
using Argument = std::function<TypeParam>;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(
MockMethodMockFunctionSignatureTest,
IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction =
decltype(&MockFunction<std::function<TypeParam>>::Call);
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
}
template <typename F>
struct AlternateCallable {
};
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
using Argument = AlternateCallable<TypeParam>;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(
MockMethodMockFunctionSignatureTest,
IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction =
decltype(&MockFunction<std::function<TypeParam>>::Call);
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
}
struct MockMethodSizes0 {
MOCK_METHOD(void, func, ());
......@@ -649,11 +924,62 @@ struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int));
};
struct LegacyMockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct LegacyMockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct LegacyMockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct LegacyMockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct LegacyMockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
}
void hasTwoParams(int, int);
void MaybeThrows();
void DoesntThrow() noexcept;
struct MockMethodNoexceptSpecifier {
MOCK_METHOD(void, func1, (), (noexcept));
MOCK_METHOD(void, func2, (), (noexcept(true)));
MOCK_METHOD(void, func3, (), (noexcept(false)));
MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows()))));
MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow()))));
MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const));
MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow()))));
// Put commas in the noexcept expression
MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const));
};
TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func1()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func2()));
EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func3()));
EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func4()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func5()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func6()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func7()));
EXPECT_EQ(noexcept(std::declval<MockMethodNoexceptSpecifier>().func8()),
noexcept(hasTwoParams(1, 2)));
}
} // namespace gmock_function_mocker_test
......
......@@ -36,11 +36,11 @@
#include <stdlib.h>
#include <cstdint>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
#include "gmock/gmock.h"
......@@ -124,20 +124,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
ConvertIdentifierNameToWords("_Chapter11Section_1_"));
}
TEST(PointeeOfTest, WorksForSmartPointers) {
EXPECT_TRUE(
(std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value));
EXPECT_TRUE(
(std::is_same<std::string,
PointeeOf<std::shared_ptr<std::string>>::type>::value));
}
TEST(PointeeOfTest, WorksForRawPointers) {
EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value));
EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value));
EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value));
}
TEST(GetRawPointerTest, WorksForSmartPointers) {
const char* const raw_p1 = new const char('a'); // NOLINT
const std::unique_ptr<const char> p1(raw_p1);
......@@ -173,9 +159,9 @@ TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
// ssize_t is not defined on Windows and possibly some other OSes.
......@@ -223,11 +209,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
// Unsigned => larger unsigned is fine.
EXPECT_TRUE(
(LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT
EXPECT_TRUE((LosslessArithmeticConvertible<
unsigned short, uint64_t>::value)); // NOLINT
// Signed => unsigned is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<
short, uint64_t>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<
signed char, unsigned int>::value)); // NOLINT
......@@ -243,12 +230,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible<
unsigned char, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
// Larger size => smaller size is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));
}
TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
......@@ -267,7 +254,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
}
......
......@@ -41,10 +41,12 @@
#endif
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-matchers.h"
#include <string.h>
#include <time.h>
#include <array>
#include <cstdint>
#include <deque>
#include <forward_list>
#include <functional>
......@@ -58,11 +60,15 @@
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gmock/gmock-more-matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_matchers_test {
......@@ -83,6 +89,7 @@ using std::vector;
using testing::internal::DummyMatchResultListener;
using testing::internal::ElementMatcherPair;
using testing::internal::ElementMatcherPairs;
using testing::internal::ElementsAreArrayMatcher;
using testing::internal::ExplainMatchFailureTupleTo;
using testing::internal::FloatingEqMatcher;
using testing::internal::FormatMatcherDescription;
......@@ -136,7 +143,7 @@ Matcher<int> GreaterThan(int n) {
std::string OfType(const std::string& type_name) {
#if GTEST_HAS_RTTI
return " (of type " + type_name + ")";
return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
#else
return "";
#endif
......@@ -347,43 +354,43 @@ TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
EXPECT_FALSE(m2.Matches("hello"));
}
#if GTEST_HAS_ABSL
#if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a C-string literal can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
Matcher<absl::string_view> m1 = "cats";
Matcher<internal::StringView> m1 = "cats";
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = "cats";
Matcher<const internal::StringView&> m2 = "cats";
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
// Tests that a std::string object can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
Matcher<absl::string_view> m1 = std::string("cats");
Matcher<internal::StringView> m1 = std::string("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = std::string("cats");
Matcher<const internal::StringView&> m2 = std::string("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
// Tests that a absl::string_view object can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
// Tests that a StringView object can be implicitly converted to a
// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
Matcher<absl::string_view> m1 = absl::string_view("cats");
Matcher<internal::StringView> m1 = internal::StringView("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = absl::string_view("cats");
Matcher<const internal::StringView&> m2 = internal::StringView("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
#endif // GTEST_HAS_ABSL
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a std::reference_wrapper<std::string> object can be implicitly
// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
......@@ -403,7 +410,7 @@ TEST(StringMatcherTest,
// MatcherInterface* without requiring the user to explicitly
// write the type.
TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
const MatcherInterface<int>* dummy_impl = nullptr;
const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
Matcher<int> m = MakeMatcher(dummy_impl);
}
......@@ -761,10 +768,11 @@ TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
Matcher<int> m1 = Eq(0);
Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
Matcher<std::unique_ptr<int>> m1 = IsNull();
Matcher<const std::unique_ptr<int>&> m2 =
SafeMatcherCast<const std::unique_ptr<int>&>(m1);
EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
......@@ -1066,7 +1074,12 @@ struct MoveHelper {
MOCK_METHOD1(Call, void(MoveOnly));
};
// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
#if defined(_MSC_VER) && (_MSC_VER < 1910)
TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
#else
TEST(ComparisonBaseTest, WorksWithMoveOnly) {
#endif
MoveOnly m{0};
MoveHelper helper;
......@@ -1221,6 +1234,25 @@ TEST(RefTest, ExplainsResult) {
// Tests string comparison matchers.
template <typename T = std::string>
std::string FromStringLike(internal::StringLike<T> str) {
return std::string(str);
}
TEST(StringLike, TestConversions) {
EXPECT_EQ("foo", FromStringLike("foo"));
EXPECT_EQ("foo", FromStringLike(std::string("foo")));
#if GTEST_INTERNAL_HAS_STRING_VIEW
EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Non deducible types.
EXPECT_EQ("", FromStringLike({}));
EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
const char buf[] = "foo";
EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
}
TEST(StrEqTest, MatchesEqualString) {
Matcher<const char*> m = StrEq(std::string("Hello"));
EXPECT_TRUE(m.Matches("Hello"));
......@@ -1231,17 +1263,18 @@ TEST(StrEqTest, MatchesEqualString) {
EXPECT_TRUE(m2.Matches("Hello"));
EXPECT_FALSE(m2.Matches("Hi"));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view&> 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()));
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView&> m3 =
StrEq(internal::StringView("Hello"));
EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
EXPECT_FALSE(m3.Matches(internal::StringView()));
Matcher<const absl::string_view&> m_empty = StrEq("");
EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
EXPECT_TRUE(m_empty.Matches(absl::string_view()));
EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
#endif // GTEST_HAS_ABSL
Matcher<const internal::StringView&> m_empty = StrEq("");
EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
EXPECT_TRUE(m_empty.Matches(internal::StringView()));
EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrEqTest, CanDescribeSelf) {
......@@ -1268,12 +1301,12 @@ TEST(StrNeTest, MatchesUnequalString) {
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hello"));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view> 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
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
EXPECT_TRUE(m3.Matches(internal::StringView("")));
EXPECT_TRUE(m3.Matches(internal::StringView()));
EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrNeTest, CanDescribeSelf) {
......@@ -1292,13 +1325,14 @@ TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hi"));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view&> 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
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView&> m3 =
StrCaseEq(internal::StringView("Hello"));
EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
EXPECT_FALSE(m3.Matches(internal::StringView()));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
......@@ -1342,13 +1376,14 @@ TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
EXPECT_TRUE(m2.Matches(""));
EXPECT_FALSE(m2.Matches("Hello"));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view> 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
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView> m3 =
StrCaseNe(internal::StringView("Hello"));
EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
EXPECT_TRUE(m3.Matches(internal::StringView()));
EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrCaseNeTest, CanDescribeSelf) {
......@@ -1389,25 +1424,26 @@ TEST(HasSubstrTest, WorksForCStrings) {
EXPECT_FALSE(m_empty.Matches(nullptr));
}
#if GTEST_HAS_ABSL
// Tests that HasSubstr() works for matching absl::string_view-typed values.
#if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that HasSubstr() works for matching StringView-typed values.
TEST(HasSubstrTest, WorksForStringViewClasses) {
const Matcher<absl::string_view> 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<internal::StringView> m1 =
HasSubstr(internal::StringView("foo"));
EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
EXPECT_FALSE(m1.Matches(internal::StringView()));
const Matcher<const absl::string_view&> 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<const internal::StringView&> m2 = HasSubstr("foo");
EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
EXPECT_FALSE(m2.Matches(internal::StringView()));
const Matcher<const absl::string_view&> m3 = HasSubstr("");
EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
EXPECT_TRUE(m3.Matches(absl::string_view("")));
EXPECT_TRUE(m3.Matches(absl::string_view()));
const Matcher<const internal::StringView&> m3 = HasSubstr("");
EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
EXPECT_TRUE(m3.Matches(internal::StringView("")));
EXPECT_TRUE(m3.Matches(internal::StringView()));
}
#endif // GTEST_HAS_ABSL
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest, CanDescribeSelf) {
......@@ -1612,6 +1648,147 @@ TEST(PairTest, InsideContainsUsingMap) {
EXPECT_THAT(container, Not(Contains(Pair(3, _))));
}
TEST(FieldsAreTest, MatchesCorrectly) {
std::tuple<int, std::string, double> p(25, "foo", .5);
// All fields match.
EXPECT_THAT(p, FieldsAre(25, "foo", .5));
EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
// Some don't match.
EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
}
TEST(FieldsAreTest, CanDescribeSelf) {
Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
EXPECT_EQ(
"has field #0 that is equal to \"foo\""
", and has field #1 that is equal to 42",
Describe(m1));
EXPECT_EQ(
"has field #0 that isn't equal to \"foo\""
", or has field #1 that isn't equal to 42",
DescribeNegation(m1));
}
TEST(FieldsAreTest, CanExplainMatchResultTo) {
// The first one that fails is the one that gives the error.
Matcher<std::tuple<int, int, int>> m =
FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
Explain(m, std::make_tuple(-1, -2, -3)));
EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
Explain(m, std::make_tuple(1, -2, -3)));
EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
Explain(m, std::make_tuple(1, 2, -3)));
// If they all match, we get a long explanation of success.
EXPECT_EQ(
"whose all elements match, "
"where field #0 is a value which is 1 more than 0"
", and field #1 is a value which is 2 more than 0"
", and field #2 is a value which is 3 more than 0",
Explain(m, std::make_tuple(1, 2, 3)));
// Only print those that have an explanation.
m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
EXPECT_EQ(
"whose all elements match, "
"where field #0 is a value which is 1 more than 0"
", and field #2 is a value which is 3 more than 0",
Explain(m, std::make_tuple(1, 0, 3)));
// If only one has an explanation, then print that one.
m = FieldsAre(0, GreaterThan(0), 0);
EXPECT_EQ(
"whose all elements match, "
"where field #1 is a value which is 1 more than 0",
Explain(m, std::make_tuple(0, 1, 0)));
}
#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
TEST(FieldsAreTest, StructuredBindings) {
// testing::FieldsAre can also match aggregates and such with C++17 and up.
struct MyType {
int i;
std::string str;
};
EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
// Test all the supported arities.
struct MyVarType1 {
int a;
};
EXPECT_THAT(MyVarType1{}, FieldsAre(0));
struct MyVarType2 {
int a, b;
};
EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
struct MyVarType3 {
int a, b, c;
};
EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
struct MyVarType4 {
int a, b, c, d;
};
EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
struct MyVarType5 {
int a, b, c, d, e;
};
EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
struct MyVarType6 {
int a, b, c, d, e, f;
};
EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
struct MyVarType7 {
int a, b, c, d, e, f, g;
};
EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
struct MyVarType8 {
int a, b, c, d, e, f, g, h;
};
EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType9 {
int a, b, c, d, e, f, g, h, i;
};
EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType10 {
int a, b, c, d, e, f, g, h, i, j;
};
EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType11 {
int a, b, c, d, e, f, g, h, i, j, k;
};
EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType12 {
int a, b, c, d, e, f, g, h, i, j, k, l;
};
EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType13 {
int a, b, c, d, e, f, g, h, i, j, k, l, m;
};
EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType14 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
};
EXPECT_THAT(MyVarType14{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType15 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
};
EXPECT_THAT(MyVarType15{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType16 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
};
EXPECT_THAT(MyVarType16{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
}
#endif
TEST(ContainsTest, WorksWithMoveOnly) {
ContainerHelper helper;
EXPECT_CALL(helper, Call(Contains(Pointee(2))));
......@@ -1644,12 +1821,13 @@ TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
EXPECT_FALSE(m2.Matches("H"));
EXPECT_FALSE(m2.Matches(" Hi"));
#if GTEST_HAS_ABSL
const Matcher<absl::string_view> m_empty = StartsWith("");
EXPECT_TRUE(m_empty.Matches(absl::string_view()));
EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
#endif // GTEST_HAS_ABSL
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<internal::StringView> m_empty =
StartsWith(internal::StringView(""));
EXPECT_TRUE(m_empty.Matches(internal::StringView()));
EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StartsWithTest, CanDescribeSelf) {
......@@ -1672,13 +1850,14 @@ TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
EXPECT_FALSE(m2.Matches("i"));
EXPECT_FALSE(m2.Matches("Hi "));
#if GTEST_HAS_ABSL
const Matcher<const absl::string_view&> m4 = EndsWith("");
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m4 =
EndsWith(internal::StringView(""));
EXPECT_TRUE(m4.Matches("Hi"));
EXPECT_TRUE(m4.Matches(""));
EXPECT_TRUE(m4.Matches(absl::string_view()));
EXPECT_TRUE(m4.Matches(absl::string_view("")));
#endif // GTEST_HAS_ABSL
EXPECT_TRUE(m4.Matches(internal::StringView()));
EXPECT_TRUE(m4.Matches(internal::StringView("")));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(EndsWithTest, CanDescribeSelf) {
......@@ -1699,16 +1878,17 @@ TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
EXPECT_FALSE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1az"));
#if GTEST_HAS_ABSL
const Matcher<const absl::string_view&> 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")));
EXPECT_FALSE(m3.Matches(absl::string_view()));
const Matcher<const absl::string_view&> m4 = MatchesRegex("");
EXPECT_TRUE(m4.Matches(absl::string_view("")));
EXPECT_TRUE(m4.Matches(absl::string_view()));
#endif // GTEST_HAS_ABSL
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
EXPECT_TRUE(m3.Matches(internal::StringView("az")));
EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
EXPECT_FALSE(m3.Matches(internal::StringView()));
const Matcher<const internal::StringView&> m4 =
MatchesRegex(internal::StringView(""));
EXPECT_TRUE(m4.Matches(internal::StringView("")));
EXPECT_TRUE(m4.Matches(internal::StringView()));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(MatchesRegexTest, CanDescribeSelf) {
......@@ -1718,10 +1898,10 @@ TEST(MatchesRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
#endif // GTEST_HAS_ABSL
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests ContainsRegex().
......@@ -1737,16 +1917,18 @@ TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
EXPECT_TRUE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1a"));
#if GTEST_HAS_ABSL
const Matcher<const absl::string_view&> 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")));
EXPECT_FALSE(m3.Matches(absl::string_view()));
const Matcher<const absl::string_view&> m4 = ContainsRegex("");
EXPECT_TRUE(m4.Matches(absl::string_view("")));
EXPECT_TRUE(m4.Matches(absl::string_view()));
#endif // GTEST_HAS_ABSL
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m3 =
ContainsRegex(new RE("a.*z"));
EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
EXPECT_FALSE(m3.Matches(internal::StringView()));
const Matcher<const internal::StringView&> m4 =
ContainsRegex(internal::StringView(""));
EXPECT_TRUE(m4.Matches(internal::StringView("")));
EXPECT_TRUE(m4.Matches(internal::StringView()));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(ContainsRegexTest, CanDescribeSelf) {
......@@ -1756,10 +1938,10 @@ TEST(ContainsRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
#if GTEST_HAS_ABSL
Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
#if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
#endif // GTEST_HAS_ABSL
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests for wide strings.
......@@ -2054,6 +2236,114 @@ TEST(PairMatchBaseTest, WorksWithMoveOnly) {
EXPECT_TRUE(matcher.Matches(pointers));
}
// Tests that IsNan() matches a NaN, with float.
TEST(IsNan, FloatMatchesNan) {
float quiet_nan = std::numeric_limits<float>::quiet_NaN();
float other_nan = std::nanf("1");
float real_value = 1.0f;
Matcher<float> m = IsNan();
EXPECT_TRUE(m.Matches(quiet_nan));
EXPECT_TRUE(m.Matches(other_nan));
EXPECT_FALSE(m.Matches(real_value));
Matcher<float&> m_ref = IsNan();
EXPECT_TRUE(m_ref.Matches(quiet_nan));
EXPECT_TRUE(m_ref.Matches(other_nan));
EXPECT_FALSE(m_ref.Matches(real_value));
Matcher<const float&> m_cref = IsNan();
EXPECT_TRUE(m_cref.Matches(quiet_nan));
EXPECT_TRUE(m_cref.Matches(other_nan));
EXPECT_FALSE(m_cref.Matches(real_value));
}
// Tests that IsNan() matches a NaN, with double.
TEST(IsNan, DoubleMatchesNan) {
double quiet_nan = std::numeric_limits<double>::quiet_NaN();
double other_nan = std::nan("1");
double real_value = 1.0;
Matcher<double> m = IsNan();
EXPECT_TRUE(m.Matches(quiet_nan));
EXPECT_TRUE(m.Matches(other_nan));
EXPECT_FALSE(m.Matches(real_value));
Matcher<double&> m_ref = IsNan();
EXPECT_TRUE(m_ref.Matches(quiet_nan));
EXPECT_TRUE(m_ref.Matches(other_nan));
EXPECT_FALSE(m_ref.Matches(real_value));
Matcher<const double&> m_cref = IsNan();
EXPECT_TRUE(m_cref.Matches(quiet_nan));
EXPECT_TRUE(m_cref.Matches(other_nan));
EXPECT_FALSE(m_cref.Matches(real_value));
}
// Tests that IsNan() matches a NaN, with long double.
TEST(IsNan, LongDoubleMatchesNan) {
long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
long double other_nan = std::nan("1");
long double real_value = 1.0;
Matcher<long double> m = IsNan();
EXPECT_TRUE(m.Matches(quiet_nan));
EXPECT_TRUE(m.Matches(other_nan));
EXPECT_FALSE(m.Matches(real_value));
Matcher<long double&> m_ref = IsNan();
EXPECT_TRUE(m_ref.Matches(quiet_nan));
EXPECT_TRUE(m_ref.Matches(other_nan));
EXPECT_FALSE(m_ref.Matches(real_value));
Matcher<const long double&> m_cref = IsNan();
EXPECT_TRUE(m_cref.Matches(quiet_nan));
EXPECT_TRUE(m_cref.Matches(other_nan));
EXPECT_FALSE(m_cref.Matches(real_value));
}
// Tests that IsNan() works with Not.
TEST(IsNan, NotMatchesNan) {
Matcher<float> mf = Not(IsNan());
EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
EXPECT_FALSE(mf.Matches(std::nanf("1")));
EXPECT_TRUE(mf.Matches(1.0));
Matcher<double> md = Not(IsNan());
EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
EXPECT_FALSE(md.Matches(std::nan("1")));
EXPECT_TRUE(md.Matches(1.0));
Matcher<long double> mld = Not(IsNan());
EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
EXPECT_FALSE(mld.Matches(std::nanl("1")));
EXPECT_TRUE(mld.Matches(1.0));
}
// Tests that IsNan() can describe itself.
TEST(IsNan, CanDescribeSelf) {
Matcher<float> mf = IsNan();
EXPECT_EQ("is NaN", Describe(mf));
Matcher<double> md = IsNan();
EXPECT_EQ("is NaN", Describe(md));
Matcher<long double> mld = IsNan();
EXPECT_EQ("is NaN", Describe(mld));
}
// Tests that IsNan() can describe itself with Not.
TEST(IsNan, CanDescribeSelfWithNot) {
Matcher<float> mf = Not(IsNan());
EXPECT_EQ("isn't NaN", Describe(mf));
Matcher<double> md = Not(IsNan());
EXPECT_EQ("isn't NaN", Describe(md));
Matcher<long double> mld = Not(IsNan());
EXPECT_EQ("isn't NaN", Describe(mld));
}
// Tests that FloatEq() matches a 2-tuple where
// FloatEq(first field) matches the second field.
TEST(FloatEq2Test, MatchesEqualArguments) {
......@@ -2699,6 +2989,13 @@ TEST(TrulyTest, WorksForByRefArguments) {
EXPECT_FALSE(m.Matches(n));
}
// Tests that Truly(predicate) provides a helpful reason when it fails.
TEST(TrulyTest, ExplainsFailures) {
StringMatchResultListener listener;
EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
}
// Tests that Matches(m) is a predicate satisfied by whatever that
// matches matcher m.
TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
......@@ -2763,6 +3060,33 @@ TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
EXPECT_EQ("", listener2.str());
}
MATCHER(ConstructNoArg, "") { return true; }
MATCHER_P(Construct1Arg, arg1, "") { return true; }
MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
TEST(MatcherConstruct, ExplicitVsImplicit) {
{
// No arg constructor can be constructed with empty brace.
ConstructNoArgMatcher m = {};
(void)m;
// And with no args
ConstructNoArgMatcher m2;
(void)m2;
}
{
// The one arg constructor has an explicit constructor.
// This is to prevent the implicit conversion.
using M = Construct1ArgMatcherP<int>;
EXPECT_TRUE((std::is_constructible<M, int>::value));
EXPECT_FALSE((std::is_convertible<int, M>::value));
}
{
// Multiple arg matchers can be constructed with an implicit construction.
Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
(void)m;
}
}
MATCHER_P(Really, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg, result_listener);
}
......@@ -2876,18 +3200,13 @@ TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
static unsigned short n; // NOLINT
n = 5;
// VC++ prior to version 8.0 SP1 has a bug where it will not see any
// functions declared in the namespace scope from within nested classes.
// EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
// namespace-level functions invoked inside them need to be explicitly
// resolved.
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
"Value of: n\n"
"Expected: is > 10\n"
" Actual: 5" + OfType("unsigned short"));
n = 0;
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
"Value of: n\n"
"Expected: (is <= 7) and (is >= 5)\n"
" Actual: 0" + OfType("unsigned short"));
......@@ -2901,11 +3220,11 @@ TEST(MatcherAssertionTest, WorksForByRefArguments) {
static int n;
n = 0;
EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
"Value of: n\n"
"Expected: does not reference the variable @");
// Tests the "Actual" part.
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
"Actual: 0" + OfType("int") + ", which is located @");
}
......@@ -3409,6 +3728,105 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) {
EXPECT_FALSE(m.Matches(p));
}
TEST(PointeeTest, SmartPointer) {
const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
std::unique_ptr<int> n(new int(1));
EXPECT_TRUE(m.Matches(n));
}
TEST(PointeeTest, SmartPointerToConst) {
const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
// There's no implicit conversion from unique_ptr<int> to const
// unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
// matcher.
std::unique_ptr<const int> n(new int(1));
EXPECT_TRUE(m.Matches(n));
}
TEST(PointerTest, RawPointer) {
int n = 1;
const Matcher<int*> m = Pointer(Eq(&n));
EXPECT_TRUE(m.Matches(&n));
int* p = nullptr;
EXPECT_FALSE(m.Matches(p));
EXPECT_FALSE(m.Matches(nullptr));
}
TEST(PointerTest, RawPointerToConst) {
int n = 1;
const Matcher<const int*> m = Pointer(Eq(&n));
EXPECT_TRUE(m.Matches(&n));
int* p = nullptr;
EXPECT_FALSE(m.Matches(p));
EXPECT_FALSE(m.Matches(nullptr));
}
TEST(PointerTest, SmartPointer) {
std::unique_ptr<int> n(new int(10));
int* raw_n = n.get();
const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
EXPECT_TRUE(m.Matches(n));
}
TEST(PointerTest, SmartPointerToConst) {
std::unique_ptr<const int> n(new int(10));
const int* raw_n = n.get();
const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
// There's no implicit conversion from unique_ptr<int> to const
// unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
// matcher.
std::unique_ptr<const int> p(new int(10));
EXPECT_FALSE(m.Matches(p));
}
TEST(AddressTest, NonConst) {
int n = 1;
const Matcher<int> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n));
int other = 5;
EXPECT_FALSE(m.Matches(other));
int& n_ref = n;
EXPECT_TRUE(m.Matches(n_ref));
}
TEST(AddressTest, Const) {
const int n = 1;
const Matcher<int> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n));
int other = 5;
EXPECT_FALSE(m.Matches(other));
}
TEST(AddressTest, MatcherDoesntCopy) {
std::unique_ptr<int> n(new int(1));
const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n));
}
TEST(AddressTest, Describe) {
Matcher<int> matcher = Address(_);
EXPECT_EQ("has address that is anything", Describe(matcher));
EXPECT_EQ("does not have address that is anything",
DescribeNegation(matcher));
}
MATCHER_P(FieldIIs, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg.i, result_listener);
}
......@@ -3610,17 +4028,11 @@ struct AStruct {
const double y; // A const field.
Uncopyable z; // An uncopyable field.
const char* p; // A pointer field.
private:
GTEST_DISALLOW_ASSIGN_(AStruct);
};
// A derived struct for testing Field().
struct DerivedStruct : public AStruct {
char ch;
private:
GTEST_DISALLOW_ASSIGN_(DerivedStruct);
};
// Tests that Field(&Foo::field, ...) works when field is non-const.
......@@ -4590,20 +5002,18 @@ TEST(SizeIsTest, ExplainsResult) {
Matcher<vector<int> > m1 = SizeIs(2);
Matcher<vector<int> > m2 = SizeIs(Lt(2u));
Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
Matcher<vector<int> > m4 = SizeIs(Gt(1u));
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
Explain(m4, container));
EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
Explain(m4, container));
EXPECT_EQ("whose size 2 matches", Explain(m4, container));
}
#if GTEST_HAS_TYPED_TEST
......@@ -5093,14 +5503,14 @@ TEST(WhenSortedTest, WorksForStreamlike) {
// Streamlike 'container' provides only minimal iterator support.
// Its iterators are tagged with input_iterator_tag.
const int a[5] = {2, 1, 4, 5, 3};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
}
TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
const int a[] = {2, 1, 4, 5, 3};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
EXPECT_THAT(s, WhenSorted(vector_match));
EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
......@@ -5145,7 +5555,7 @@ TEST(IsSupersetOfTest, WorksForEmpty) {
TEST(IsSupersetOfTest, WorksForStreamlike) {
const int a[5] = {1, 2, 3, 4, 5};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
vector<int> expected;
expected.push_back(1);
......@@ -5273,7 +5683,7 @@ TEST(IsSubsetOfTest, WorksForEmpty) {
TEST(IsSubsetOfTest, WorksForStreamlike) {
const int a[5] = {1, 2};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
vector<int> expected;
expected.push_back(1);
......@@ -5367,14 +5777,14 @@ TEST(IsSubsetOfTest, WorksWithMoveOnly) {
TEST(ElemensAreStreamTest, WorksForStreamlike) {
const int a[5] = {1, 2, 3, 4, 5};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
}
TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
const int a[5] = {1, 2, 3, 4, 5};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
vector<int> expected;
expected.push_back(1);
......@@ -5421,7 +5831,7 @@ TEST(ElementsAreTest, TakesStlContainer) {
TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
const int a[] = {0, 1, 2, 3, 4};
std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
std::vector<int> s(std::begin(a), std::end(a));
do {
StringMatchResultListener listener;
EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
......@@ -5432,8 +5842,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
TEST(UnorderedElementsAreArrayTest, VectorBool) {
const bool a[] = {0, 1, 0, 1, 1};
const bool b[] = {1, 0, 1, 1, 0};
std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
std::vector<bool> expected(std::begin(a), std::end(a));
std::vector<bool> actual(std::begin(b), std::end(b));
StringMatchResultListener listener;
EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
actual, &listener)) << listener.str();
......@@ -5444,7 +5854,7 @@ TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
// Its iterators are tagged with input_iterator_tag, and it has no
// size() or empty() methods.
const int a[5] = {2, 1, 4, 5, 3};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
::std::vector<int> expected;
expected.push_back(1);
......@@ -5527,7 +5937,7 @@ TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
const int a[] = {1, 2, 3};
std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
std::vector<int> s(std::begin(a), std::end(a));
do {
StringMatchResultListener listener;
EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
......@@ -5537,7 +5947,7 @@ TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
const int a[] = {1, 2, 3};
std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
std::vector<int> s(std::begin(a), std::end(a));
std::vector<Matcher<int> > mv;
mv.push_back(1);
mv.push_back(2);
......@@ -5553,7 +5963,7 @@ TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
// Its iterators are tagged with input_iterator_tag, and it has no
// size() or empty() methods.
const int a[5] = {2, 1, 4, 5, 3};
Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
Streamlike<int> s(std::begin(a), std::end(a));
EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
......@@ -5869,8 +6279,9 @@ TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
// :.......:
// 0 1 2
MatchMatrix g(4, 3);
static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
{{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
for (size_t i = 0; i < kEdges.size(); ++i) {
g.SetEdge(kEdges[i][0], kEdges[i][1], true);
}
EXPECT_THAT(FindBacktrackingMaxBPM(g),
......@@ -5916,9 +6327,9 @@ TEST_P(BipartiteRandomTest, LargerNets) {
int iters = GetParam().second;
MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
auto seed = static_cast<testing::internal::UInt32>(GTEST_FLAG(random_seed));
auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
if (seed == 0) {
seed = static_cast<testing::internal::UInt32>(time(nullptr));
seed = static_cast<uint32_t>(time(nullptr));
}
for (; iters > 0; --iters, ++seed) {
......@@ -6777,7 +7188,8 @@ TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
EXPECT_FALSE(result); // Implicit cast to bool.
std::string expect =
"Value of: dummy-name\nExpected: [DescribeTo]\n"
" Actual: 1, [MatchAndExplain]";
" Actual: 1" +
OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message());
}
......@@ -6788,10 +7200,1359 @@ TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
"Value of: dummy-name\nExpected: [DescribeTo]\n"
" The matcher failed on the initial attempt; but passed when rerun to "
"generate the explanation.\n"
" Actual: 2, [MatchAndExplain]";
" Actual: 2" +
OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message());
}
// Tests for ElementsAre().
TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
Matcher<const vector<int>&> m = ElementsAre();
EXPECT_EQ("is empty", Describe(m));
}
TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
Matcher<vector<int>> m = ElementsAre(Gt(5));
EXPECT_EQ("has 1 element that is > 5", Describe(m));
}
TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
EXPECT_EQ(
"has 2 elements where\n"
"element #0 is equal to \"one\",\n"
"element #1 is equal to \"two\"",
Describe(m));
}
TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
Matcher<vector<int>> m = ElementsAre();
EXPECT_EQ("isn't empty", DescribeNegation(m));
}
TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
Matcher<const list<int>&> m = ElementsAre(Gt(5));
EXPECT_EQ(
"doesn't have 1 element, or\n"
"element #0 isn't > 5",
DescribeNegation(m));
}
TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
Matcher<const list<std::string>&> m = ElementsAre("one", "two");
EXPECT_EQ(
"doesn't have 2 elements, or\n"
"element #0 isn't equal to \"one\", or\n"
"element #1 isn't equal to \"two\"",
DescribeNegation(m));
}
TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
list<int> test_list;
test_list.push_back(1);
test_list.push_back(3);
EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
}
TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
Matcher<const vector<int>&> m =
ElementsAre(GreaterThan(1), 0, GreaterThan(2));
const int a[] = {10, 0, 100};
vector<int> test_vector(std::begin(a), std::end(a));
EXPECT_EQ(
"whose element #0 matches, which is 9 more than 1,\n"
"and whose element #2 matches, which is 98 more than 2",
Explain(m, test_vector));
}
TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
Matcher<const list<int>&> m = ElementsAre(1, 3);
list<int> test_list;
// No need to explain when the container is empty.
EXPECT_EQ("", Explain(m, test_list));
test_list.push_back(1);
EXPECT_EQ("which has 1 element", Explain(m, test_list));
}
TEST(ElementsAreTest, CanExplainMismatchRightSize) {
Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
vector<int> v;
v.push_back(2);
v.push_back(1);
EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
v[0] = 1;
EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
Explain(m, v));
}
TEST(ElementsAreTest, MatchesOneElementVector) {
vector<std::string> test_vector;
test_vector.push_back("test string");
EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
}
TEST(ElementsAreTest, MatchesOneElementList) {
list<std::string> test_list;
test_list.push_back("test string");
EXPECT_THAT(test_list, ElementsAre("test string"));
}
TEST(ElementsAreTest, MatchesThreeElementVector) {
vector<std::string> test_vector;
test_vector.push_back("one");
test_vector.push_back("two");
test_vector.push_back("three");
EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
}
TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
vector<int> test_vector;
test_vector.push_back(4);
EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
}
TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
vector<int> test_vector;
test_vector.push_back(4);
EXPECT_THAT(test_vector, ElementsAre(_));
}
TEST(ElementsAreTest, MatchesOneElementValue) {
vector<int> test_vector;
test_vector.push_back(4);
EXPECT_THAT(test_vector, ElementsAre(4));
}
TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
vector<int> test_vector;
test_vector.push_back(1);
test_vector.push_back(2);
test_vector.push_back(3);
EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
}
TEST(ElementsAreTest, MatchesTenElementVector) {
const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> test_vector(std::begin(a), std::end(a));
EXPECT_THAT(test_vector,
// The element list can contain values and/or matchers
// of different types.
ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
}
TEST(ElementsAreTest, DoesNotMatchWrongSize) {
vector<std::string> test_vector;
test_vector.push_back("test string");
test_vector.push_back("test string");
Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
EXPECT_FALSE(m.Matches(test_vector));
}
TEST(ElementsAreTest, DoesNotMatchWrongValue) {
vector<std::string> test_vector;
test_vector.push_back("other string");
Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
EXPECT_FALSE(m.Matches(test_vector));
}
TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
vector<std::string> test_vector;
test_vector.push_back("one");
test_vector.push_back("three");
test_vector.push_back("two");
Matcher<vector<std::string>> m =
ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
EXPECT_FALSE(m.Matches(test_vector));
}
TEST(ElementsAreTest, WorksForNestedContainer) {
constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
vector<list<char>> nested;
for (const auto& s : strings) {
nested.emplace_back(s, s + strlen(s));
}
EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
ElementsAre('w', 'o', _, _, 'd')));
EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
ElementsAre('w', 'o', _, _, 'd'))));
}
TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
int a[] = {0, 1, 2};
vector<int> v(std::begin(a), std::end(a));
EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
}
TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
int a[] = {0, 1, 2};
vector<int> v(std::begin(a), std::end(a));
EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
}
TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
int array[] = {0, 1, 2};
EXPECT_THAT(array, ElementsAre(0, 1, _));
EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
EXPECT_THAT(array, Not(ElementsAre(0, _)));
}
class NativeArrayPassedAsPointerAndSize {
public:
NativeArrayPassedAsPointerAndSize() {}
MOCK_METHOD(void, Helper, (int* array, int size));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
};
TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
int array[] = {0, 1};
::std::tuple<int*, size_t> array_as_tuple(array, 2);
EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
NativeArrayPassedAsPointerAndSize helper;
EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
helper.Helper(array, 2);
}
TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
const char a2[][3] = {"hi", "lo"};
EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
ElementsAre('l', 'o', '\0')));
EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
ElementsAre('l', 'o', '\0')));
}
TEST(ElementsAreTest, AcceptsStringLiteral) {
std::string array[] = {"hi", "one", "two"};
EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
}
// Declared here with the size unknown. Defined AFTER the following test.
extern const char kHi[];
TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
// The size of kHi is not known in this test, but ElementsAre() should
// still accept it.
std::string array1[] = {"hi"};
EXPECT_THAT(array1, ElementsAre(kHi));
std::string array2[] = {"ho"};
EXPECT_THAT(array2, Not(ElementsAre(kHi)));
}
const char kHi[] = "hi";
TEST(ElementsAreTest, MakesCopyOfArguments) {
int x = 1;
int y = 2;
// This should make a copy of x and y.
::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
polymorphic_matcher = ElementsAre(x, y);
// Changing x and y now shouldn't affect the meaning of the above matcher.
x = y = 0;
const int array1[] = {1, 2};
EXPECT_THAT(array1, polymorphic_matcher);
const int array2[] = {0, 0};
EXPECT_THAT(array2, Not(polymorphic_matcher));
}
// Tests for ElementsAreArray(). Since ElementsAreArray() shares most
// of the implementation with ElementsAre(), we don't test it as
// thoroughly here.
TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
const int a[] = {1, 2, 3};
vector<int> test_vector(std::begin(a), std::end(a));
EXPECT_THAT(test_vector, ElementsAreArray(a));
test_vector[2] = 0;
EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
std::array<const char*, 3> a = {{"one", "two", "three"}};
vector<std::string> test_vector(std::begin(a), std::end(a));
EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
const char** p = a.data();
test_vector[0] = "1";
EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
const char* a[] = {"one", "two", "three"};
vector<std::string> test_vector(std::begin(a), std::end(a));
EXPECT_THAT(test_vector, ElementsAreArray(a));
test_vector[0] = "1";
EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
StrEq("three")};
vector<std::string> test_vector;
test_vector.push_back("one");
test_vector.push_back("two");
test_vector.push_back("three");
EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
test_vector.push_back("three");
EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
const int a[] = {1, 2, 3};
vector<int> test_vector(std::begin(a), std::end(a));
const vector<int> expected(std::begin(a), std::end(a));
EXPECT_THAT(test_vector, ElementsAreArray(expected));
test_vector.push_back(4);
EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
}
TEST(ElementsAreArrayTest, TakesInitializerList) {
const int a[5] = {1, 2, 3, 4, 5};
EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
}
TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
const std::string a[5] = {"a", "b", "c", "d", "e"};
EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
}
TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
const int a[5] = {1, 2, 3, 4, 5};
EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
}
TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
const int a[5] = {1, 2, 3, 4, 5};
// The compiler cannot infer the type of the initializer list if its
// elements have different types. We must explicitly specify the
// unified element type in this case.
EXPECT_THAT(
a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
{Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
const int a[] = {1, 2, 3};
const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
vector<int> test_vector(std::begin(a), std::end(a));
const vector<Matcher<int>> expected(std::begin(kMatchers),
std::end(kMatchers));
EXPECT_THAT(test_vector, ElementsAreArray(expected));
test_vector.push_back(4);
EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
}
TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
const int a[] = {1, 2, 3};
const vector<int> test_vector(std::begin(a), std::end(a));
const vector<int> expected(std::begin(a), std::end(a));
EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
// Pointers are iterators, too.
EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
// The empty range of NULL pointers should also be okay.
int* const null_int = nullptr;
EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
}
// Since ElementsAre() and ElementsAreArray() share much of the
// implementation, we only do a sanity test for native arrays here.
TEST(ElementsAreArrayTest, WorksWithNativeArray) {
::std::string a[] = {"hi", "ho"};
::std::string b[] = {"hi", "ho"};
EXPECT_THAT(a, ElementsAreArray(b));
EXPECT_THAT(a, ElementsAreArray(b, 2));
EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
}
TEST(ElementsAreArrayTest, SourceLifeSpan) {
const int a[] = {1, 2, 3};
vector<int> test_vector(std::begin(a), std::end(a));
vector<int> expect(std::begin(a), std::end(a));
ElementsAreArrayMatcher<int> matcher_maker =
ElementsAreArray(expect.begin(), expect.end());
EXPECT_THAT(test_vector, matcher_maker);
// Changing in place the values that initialized matcher_maker should not
// affect matcher_maker anymore. It should have made its own copy of them.
for (int& i : expect) {
i += 10;
}
EXPECT_THAT(test_vector, matcher_maker);
test_vector.push_back(3);
EXPECT_THAT(test_vector, Not(matcher_maker));
}
// Tests for the MATCHER*() macro family.
// Tests that a simple MATCHER() definition works.
MATCHER(IsEven, "") { return (arg % 2) == 0; }
TEST(MatcherMacroTest, Works) {
const Matcher<int> m = IsEven();
EXPECT_TRUE(m.Matches(6));
EXPECT_FALSE(m.Matches(7));
EXPECT_EQ("is even", Describe(m));
EXPECT_EQ("not (is even)", DescribeNegation(m));
EXPECT_EQ("", Explain(m, 6));
EXPECT_EQ("", Explain(m, 7));
}
// This also tests that the description string can reference 'negation'.
MATCHER(IsEven2, negation ? "is odd" : "is even") {
if ((arg % 2) == 0) {
// Verifies that we can stream to result_listener, a listener
// supplied by the MATCHER macro implicitly.
*result_listener << "OK";
return true;
} else {
*result_listener << "% 2 == " << (arg % 2);
return false;
}
}
// This also tests that the description string can reference matcher
// parameters.
MATCHER_P2(EqSumOf, x, y,
std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
PrintToString(x) + " and " + PrintToString(y)) {
if (arg == (x + y)) {
*result_listener << "OK";
return true;
} else {
// Verifies that we can stream to the underlying stream of
// result_listener.
if (result_listener->stream() != nullptr) {
*result_listener->stream() << "diff == " << (x + y - arg);
}
return false;
}
}
// Tests that the matcher description can reference 'negation' and the
// matcher parameters.
TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
const Matcher<int> m1 = IsEven2();
EXPECT_EQ("is even", Describe(m1));
EXPECT_EQ("is odd", DescribeNegation(m1));
const Matcher<int> m2 = EqSumOf(5, 9);
EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
}
// Tests explaining match result in a MATCHER* macro.
TEST(MatcherMacroTest, CanExplainMatchResult) {
const Matcher<int> m1 = IsEven2();
EXPECT_EQ("OK", Explain(m1, 4));
EXPECT_EQ("% 2 == 1", Explain(m1, 5));
const Matcher<int> m2 = EqSumOf(1, 2);
EXPECT_EQ("OK", Explain(m2, 3));
EXPECT_EQ("diff == -1", Explain(m2, 4));
}
// Tests that the body of MATCHER() can reference the type of the
// value being matched.
MATCHER(IsEmptyString, "") {
StaticAssertTypeEq<::std::string, arg_type>();
return arg.empty();
}
MATCHER(IsEmptyStringByRef, "") {
StaticAssertTypeEq<const ::std::string&, arg_type>();
return arg.empty();
}
TEST(MatcherMacroTest, CanReferenceArgType) {
const Matcher<::std::string> m1 = IsEmptyString();
EXPECT_TRUE(m1.Matches(""));
const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
EXPECT_TRUE(m2.Matches(""));
}
// Tests that MATCHER() can be used in a namespace.
namespace matcher_test {
MATCHER(IsOdd, "") { return (arg % 2) != 0; }
} // namespace matcher_test
TEST(MatcherMacroTest, WorksInNamespace) {
Matcher<int> m = matcher_test::IsOdd();
EXPECT_FALSE(m.Matches(4));
EXPECT_TRUE(m.Matches(5));
}
// Tests that Value() can be used to compose matchers.
MATCHER(IsPositiveOdd, "") {
return Value(arg, matcher_test::IsOdd()) && arg > 0;
}
TEST(MatcherMacroTest, CanBeComposedUsingValue) {
EXPECT_THAT(3, IsPositiveOdd());
EXPECT_THAT(4, Not(IsPositiveOdd()));
EXPECT_THAT(-1, Not(IsPositiveOdd()));
}
// Tests that a simple MATCHER_P() definition works.
MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
TEST(MatcherPMacroTest, Works) {
const Matcher<int> m = IsGreaterThan32And(5);
EXPECT_TRUE(m.Matches(36));
EXPECT_FALSE(m.Matches(5));
EXPECT_EQ("is greater than 32 and 5", Describe(m));
EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
EXPECT_EQ("", Explain(m, 36));
EXPECT_EQ("", Explain(m, 5));
}
// Tests that the description is calculated correctly from the matcher name.
MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
const Matcher<int> m = _is_Greater_Than32and_(5);
EXPECT_EQ("is greater than 32 and 5", Describe(m));
EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
EXPECT_EQ("", Explain(m, 36));
EXPECT_EQ("", Explain(m, 5));
}
// Tests that a MATCHER_P matcher can be explicitly instantiated with
// a reference parameter type.
class UncopyableFoo {
public:
explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
UncopyableFoo(const UncopyableFoo&) = delete;
void operator=(const UncopyableFoo&) = delete;
private:
char value_;
};
MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
UncopyableFoo foo1('1'), foo2('2');
const Matcher<const UncopyableFoo&> m =
ReferencesUncopyable<const UncopyableFoo&>(foo1);
EXPECT_TRUE(m.Matches(foo1));
EXPECT_FALSE(m.Matches(foo2));
// We don't want the address of the parameter printed, as most
// likely it will just annoy the user. If the address is
// interesting, the user should consider passing the parameter by
// pointer instead.
EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
}
// Tests that the body of MATCHER_Pn() can reference the parameter
// types.
MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
StaticAssertTypeEq<int, foo_type>();
StaticAssertTypeEq<long, bar_type>(); // NOLINT
StaticAssertTypeEq<char, baz_type>();
return arg == 0;
}
TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
}
// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
// reference parameter types.
MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
return &arg == &variable1 || &arg == &variable2;
}
TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
UncopyableFoo foo1('1'), foo2('2'), foo3('3');
const Matcher<const UncopyableFoo&> const_m =
ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
EXPECT_TRUE(const_m.Matches(foo1));
EXPECT_TRUE(const_m.Matches(foo2));
EXPECT_FALSE(const_m.Matches(foo3));
const Matcher<UncopyableFoo&> m =
ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
EXPECT_TRUE(m.Matches(foo1));
EXPECT_TRUE(m.Matches(foo2));
EXPECT_FALSE(m.Matches(foo3));
}
TEST(MatcherPnMacroTest,
GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
UncopyableFoo foo1('1'), foo2('2');
const Matcher<const UncopyableFoo&> m =
ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
// We don't want the addresses of the parameters printed, as most
// likely they will just annoy the user. If the addresses are
// interesting, the user should consider passing the parameters by
// pointers instead.
EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
Describe(m));
}
// Tests that a simple MATCHER_P2() definition works.
MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
TEST(MatcherPnMacroTest, Works) {
const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
EXPECT_TRUE(m.Matches(36L));
EXPECT_FALSE(m.Matches(15L));
EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
EXPECT_EQ("", Explain(m, 36L));
EXPECT_EQ("", Explain(m, 15L));
}
// Tests that MATCHER*() definitions can be overloaded on the number
// of parameters; also tests MATCHER_Pn() where n >= 3.
MATCHER(EqualsSumOf, "") { return arg == 0; }
MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
return arg == a + b + c + d + e + f;
}
MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
return arg == a + b + c + d + e + f + g;
}
MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
return arg == a + b + c + d + e + f + g + h;
}
MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
return arg == a + b + c + d + e + f + g + h + i;
}
MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
return arg == a + b + c + d + e + f + g + h + i + j;
}
TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
EXPECT_THAT(0, EqualsSumOf());
EXPECT_THAT(1, EqualsSumOf(1));
EXPECT_THAT(12, EqualsSumOf(10, 2));
EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
EXPECT_THAT("abcdef",
EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
EXPECT_THAT("abcdefg",
EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
'f', 'g', "h"));
EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
'f', 'g', "h", 'i'));
EXPECT_THAT("abcdefghij",
EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
'i', ::std::string("j")));
EXPECT_THAT(1, Not(EqualsSumOf()));
EXPECT_THAT(-1, Not(EqualsSumOf(1)));
EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
EXPECT_THAT("abcdef ",
Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
"e", 'f', 'g')));
EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
"e", 'f', 'g', "h")));
EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
"e", 'f', 'g', "h", 'i')));
EXPECT_THAT("abcdefghij ",
Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
"h", 'i', ::std::string("j"))));
}
// Tests that a MATCHER_Pn() definition can be instantiated with any
// compatible parameter types.
TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
}
// Tests that the matcher body can promote the parameter types.
MATCHER_P2(EqConcat, prefix, suffix, "") {
// The following lines promote the two parameters to desired types.
std::string prefix_str(prefix);
char suffix_char = static_cast<char>(suffix);
return arg == prefix_str + suffix_char;
}
TEST(MatcherPnMacroTest, SimpleTypePromotion) {
Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
EXPECT_FALSE(no_promo.Matches("fool"));
EXPECT_FALSE(promo.Matches("fool"));
EXPECT_TRUE(no_promo.Matches("foot"));
EXPECT_TRUE(promo.Matches("foot"));
}
// Verifies the type of a MATCHER*.
TEST(MatcherPnMacroTest, TypesAreCorrect) {
// EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
EqualsSumOfMatcher a0 = EqualsSumOf();
// EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
// EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
// variable, and so on.
EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
EqualsSumOf(1, 2, 3, 4, '5');
EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
EqualsSumOf(1, 2, 3, 4, 5, '6');
EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
// Avoid "unused variable" warnings.
(void)a0;
(void)a1;
(void)a2;
(void)a3;
(void)a4;
(void)a5;
(void)a6;
(void)a7;
(void)a8;
(void)a9;
(void)a10;
}
// Tests that matcher-typed parameters can be used in Value() inside a
// MATCHER_Pn definition.
// Succeeds if arg matches exactly 2 of the 3 matchers.
MATCHER_P3(TwoOf, m1, m2, m3, "") {
const int count = static_cast<int>(Value(arg, m1)) +
static_cast<int>(Value(arg, m2)) +
static_cast<int>(Value(arg, m3));
return count == 2;
}
TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
}
// Tests Contains().
TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
list<int> some_list;
some_list.push_back(3);
some_list.push_back(1);
some_list.push_back(2);
EXPECT_THAT(some_list, Contains(1));
EXPECT_THAT(some_list, Contains(Gt(2.5)));
EXPECT_THAT(some_list, Contains(Eq(2.0f)));
list<std::string> another_list;
another_list.push_back("fee");
another_list.push_back("fie");
another_list.push_back("foe");
another_list.push_back("fum");
EXPECT_THAT(another_list, Contains(std::string("fee")));
}
TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
list<int> some_list;
some_list.push_back(3);
some_list.push_back(1);
EXPECT_THAT(some_list, Not(Contains(4)));
}
TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
set<int> some_set;
some_set.insert(3);
some_set.insert(1);
some_set.insert(2);
EXPECT_THAT(some_set, Contains(Eq(1.0)));
EXPECT_THAT(some_set, Contains(Eq(3.0f)));
EXPECT_THAT(some_set, Contains(2));
set<std::string> another_set;
another_set.insert("fee");
another_set.insert("fie");
another_set.insert("foe");
another_set.insert("fum");
EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
}
TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
set<int> some_set;
some_set.insert(3);
some_set.insert(1);
EXPECT_THAT(some_set, Not(Contains(4)));
set<std::string> c_string_set;
c_string_set.insert("hello");
EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
}
TEST(ContainsTest, ExplainsMatchResultCorrectly) {
const int a[2] = {1, 2};
Matcher<const int(&)[2]> m = Contains(2);
EXPECT_EQ("whose element #1 matches", Explain(m, a));
m = Contains(3);
EXPECT_EQ("", Explain(m, a));
m = Contains(GreaterThan(0));
EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
m = Contains(GreaterThan(10));
EXPECT_EQ("", Explain(m, a));
}
TEST(ContainsTest, DescribesItselfCorrectly) {
Matcher<vector<int>> m = Contains(1);
EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
Matcher<vector<int>> m2 = Not(m);
EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
}
TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
map<std::string, int> my_map;
const char* bar = "a string";
my_map[bar] = 2;
EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
map<std::string, int> another_map;
another_map["fee"] = 1;
another_map["fie"] = 2;
another_map["foe"] = 3;
another_map["fum"] = 4;
EXPECT_THAT(another_map,
Contains(pair<const std::string, int>(std::string("fee"), 1)));
EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
}
TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
map<int, int> some_map;
some_map[1] = 11;
some_map[2] = 22;
EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
}
TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
const char* string_array[] = {"fee", "fie", "foe", "fum"};
EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
}
TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
int int_array[] = {1, 2, 3, 4};
EXPECT_THAT(int_array, Not(Contains(5)));
}
TEST(ContainsTest, AcceptsMatcher) {
const int a[] = {1, 2, 3};
EXPECT_THAT(a, Contains(Gt(2)));
EXPECT_THAT(a, Not(Contains(Gt(4))));
}
TEST(ContainsTest, WorksForNativeArrayAsTuple) {
const int a[] = {1, 2};
const int* const pointer = a;
EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
}
TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
int a[][3] = {{1, 2, 3}, {4, 5, 6}};
EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
EXPECT_THAT(a, Contains(Contains(5)));
EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
EXPECT_THAT(a, Contains(Not(Contains(5))));
}
TEST(AllOfArrayTest, BasicForms) {
// Iterator
std::vector<int> v0{};
std::vector<int> v1{1};
std::vector<int> v2{2, 3};
std::vector<int> v3{4, 4, 4};
EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
// Pointer + size
int ar[6] = {1, 2, 3, 4, 4, 4};
EXPECT_THAT(0, AllOfArray(ar, 0));
EXPECT_THAT(1, AllOfArray(ar, 1));
EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
EXPECT_THAT(4, AllOfArray(ar + 3, 3));
// Array
// int ar0[0]; Not usable
int ar1[1] = {1};
int ar2[2] = {2, 3};
int ar3[3] = {4, 4, 4};
// EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
EXPECT_THAT(1, AllOfArray(ar1));
EXPECT_THAT(2, Not(AllOfArray(ar1)));
EXPECT_THAT(3, Not(AllOfArray(ar2)));
EXPECT_THAT(4, AllOfArray(ar3));
// Container
EXPECT_THAT(0, AllOfArray(v0));
EXPECT_THAT(1, AllOfArray(v1));
EXPECT_THAT(2, Not(AllOfArray(v1)));
EXPECT_THAT(3, Not(AllOfArray(v2)));
EXPECT_THAT(4, AllOfArray(v3));
// Initializer
EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
EXPECT_THAT(1, AllOfArray({1}));
EXPECT_THAT(2, Not(AllOfArray({1})));
EXPECT_THAT(3, Not(AllOfArray({2, 3})));
EXPECT_THAT(4, AllOfArray({4, 4, 4}));
}
TEST(AllOfArrayTest, Matchers) {
// vector
std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
EXPECT_THAT(0, Not(AllOfArray(matchers)));
EXPECT_THAT(1, AllOfArray(matchers));
EXPECT_THAT(2, Not(AllOfArray(matchers)));
// initializer_list
EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
}
TEST(AnyOfArrayTest, BasicForms) {
// Iterator
std::vector<int> v0{};
std::vector<int> v1{1};
std::vector<int> v2{2, 3};
EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
// Pointer + size
int ar[3] = {1, 2, 3};
EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
EXPECT_THAT(1, AnyOfArray(ar, 1));
EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
// Array
// int ar0[0]; Not usable
int ar1[1] = {1};
int ar2[2] = {2, 3};
// EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
EXPECT_THAT(1, AnyOfArray(ar1));
EXPECT_THAT(2, Not(AnyOfArray(ar1)));
EXPECT_THAT(3, AnyOfArray(ar2));
EXPECT_THAT(4, Not(AnyOfArray(ar2)));
// Container
EXPECT_THAT(0, Not(AnyOfArray(v0)));
EXPECT_THAT(1, AnyOfArray(v1));
EXPECT_THAT(2, Not(AnyOfArray(v1)));
EXPECT_THAT(3, AnyOfArray(v2));
EXPECT_THAT(4, Not(AnyOfArray(v2)));
// Initializer
EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
EXPECT_THAT(1, AnyOfArray({1}));
EXPECT_THAT(2, Not(AnyOfArray({1})));
EXPECT_THAT(3, AnyOfArray({2, 3}));
EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
}
TEST(AnyOfArrayTest, Matchers) {
// We negate test AllOfArrayTest.Matchers.
// vector
std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
EXPECT_THAT(0, AnyOfArray(matchers));
EXPECT_THAT(1, Not(AnyOfArray(matchers)));
EXPECT_THAT(2, AnyOfArray(matchers));
// initializer_list
EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
}
TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
// AnyOfArray and AllOfArry use the same underlying template-template,
// thus it is sufficient to test one here.
const std::vector<int> v0{};
const std::vector<int> v1{1};
const std::vector<int> v2{2, 3};
const Matcher<int> m0 = AnyOfArray(v0);
const Matcher<int> m1 = AnyOfArray(v1);
const Matcher<int> m2 = AnyOfArray(v2);
EXPECT_EQ("", Explain(m0, 0));
EXPECT_EQ("", Explain(m1, 1));
EXPECT_EQ("", Explain(m1, 2));
EXPECT_EQ("", Explain(m2, 3));
EXPECT_EQ("", Explain(m2, 4));
EXPECT_EQ("()", Describe(m0));
EXPECT_EQ("(is equal to 1)", Describe(m1));
EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
EXPECT_EQ("()", DescribeNegation(m0));
EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
// Explain with matchers
const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
// Explains the first positiv match and all prior negative matches...
EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
EXPECT_EQ("which is the same as 1", Explain(g1, 1));
EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
Explain(g2, 0));
EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
Explain(g2, 1));
EXPECT_EQ("which is 1 more than 1", // Only the first
Explain(g2, 2));
}
TEST(AllOfTest, HugeMatcher) {
// Verify that using AllOf with many arguments doesn't cause
// the compiler to exceed template instantiation depth limit.
EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
}
TEST(AnyOfTest, HugeMatcher) {
// Verify that using AnyOf with many arguments doesn't cause
// the compiler to exceed template instantiation depth limit.
EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
}
namespace adl_test {
// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
// don't issue unqualified recursive calls. If they do, the argument dependent
// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
// as a candidate and the compilation will break due to an ambiguous overload.
// The matcher must be in the same namespace as AllOf/AnyOf to make argument
// dependent lookup find those.
MATCHER(M, "") {
(void)arg;
return true;
}
template <typename T1, typename T2>
bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
return true;
}
TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
EXPECT_THAT(42,
testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
}
template <typename T1, typename T2>
bool AnyOf(const T1&, const T2&) {
return true;
}
TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
EXPECT_THAT(42,
testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
}
} // namespace adl_test
TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
}
TEST(AnyOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
}
MATCHER(IsNotNull, "") { return arg != nullptr; }
// Verifies that a matcher defined using MATCHER() can work on
// move-only types.
TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, IsNotNull());
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
}
MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
// Verifies that a matcher defined using MATCHER_P*() can work on
// move-only types.
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, UniquePointee(3));
EXPECT_THAT(p, Not(UniquePointee(2)));
}
#if GTEST_HAS_EXCEPTIONS
// std::function<void()> is used below for compatibility with older copies of
// GCC. Normally, a raw lambda is all that is needed.
// Test that examples from documentation compile
TEST(ThrowsTest, Examples) {
EXPECT_THAT(
std::function<void()>([]() { throw std::runtime_error("message"); }),
Throws<std::runtime_error>());
EXPECT_THAT(
std::function<void()>([]() { throw std::runtime_error("message"); }),
ThrowsMessage<std::runtime_error>(HasSubstr("message")));
}
TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
Throws<std::exception>());
}
TEST(ThrowsTest, CallableExecutedExactlyOnce) {
size_t a = 0;
EXPECT_THAT(std::function<void()>([&a]() {
a++;
throw 10;
}),
Throws<int>());
EXPECT_EQ(a, 1u);
EXPECT_THAT(std::function<void()>([&a]() {
a++;
throw std::runtime_error("message");
}),
Throws<std::runtime_error>());
EXPECT_EQ(a, 2u);
EXPECT_THAT(std::function<void()>([&a]() {
a++;
throw std::runtime_error("message");
}),
ThrowsMessage<std::runtime_error>(HasSubstr("message")));
EXPECT_EQ(a, 3u);
EXPECT_THAT(std::function<void()>([&a]() {
a++;
throw std::runtime_error("message");
}),
Throws<std::runtime_error>(
Property(&std::runtime_error::what, HasSubstr("message"))));
EXPECT_EQ(a, 4u);
}
TEST(ThrowsTest, Describe) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
std::stringstream ss;
matcher.DescribeTo(&ss);
auto explanation = ss.str();
EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
}
TEST(ThrowsTest, Success) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
StringMatchResultListener listener;
EXPECT_TRUE(matcher.MatchAndExplain(
[]() { throw std::runtime_error("error message"); }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
}
TEST(ThrowsTest, FailWrongType) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain(
[]() { throw std::logic_error("error message"); }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
}
TEST(ThrowsTest, FailWrongTypeNonStd) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
EXPECT_THAT(listener.str(),
HasSubstr("throws an exception of an unknown type"));
}
TEST(ThrowsTest, FailNoThrow) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
}
class ThrowsPredicateTest
: public TestWithParam<Matcher<std::function<void()>>> {};
TEST_P(ThrowsPredicateTest, Describe) {
Matcher<std::function<void()>> matcher = GetParam();
std::stringstream ss;
matcher.DescribeTo(&ss);
auto explanation = ss.str();
EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
EXPECT_THAT(explanation, HasSubstr("error message"));
}
TEST_P(ThrowsPredicateTest, Success) {
Matcher<std::function<void()>> matcher = GetParam();
StringMatchResultListener listener;
EXPECT_TRUE(matcher.MatchAndExplain(
[]() { throw std::runtime_error("error message"); }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
}
TEST_P(ThrowsPredicateTest, FailWrongType) {
Matcher<std::function<void()>> matcher = GetParam();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain(
[]() { throw std::logic_error("error message"); }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
}
TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
Matcher<std::function<void()>> matcher = GetParam();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
EXPECT_THAT(listener.str(),
HasSubstr("throws an exception of an unknown type"));
}
TEST_P(ThrowsPredicateTest, FailWrongMessage) {
Matcher<std::function<void()>> matcher = GetParam();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain(
[]() { throw std::runtime_error("wrong message"); }, &listener));
EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
}
TEST_P(ThrowsPredicateTest, FailNoThrow) {
Matcher<std::function<void()>> matcher = GetParam();
StringMatchResultListener listener;
EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
}
INSTANTIATE_TEST_SUITE_P(
AllMessagePredicates, ThrowsPredicateTest,
Values(Matcher<std::function<void()>>(
ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
{
Matcher<std::function<void()>> matcher =
ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
EXPECT_TRUE(
matcher.Matches([]() { throw std::runtime_error("error message"); }));
EXPECT_FALSE(
matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
}
{
Matcher<uint64_t> inner = Eq(10);
Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
}
}
// Tests that ThrowsMessage("message") is equivalent
// to ThrowsMessage(Eq<std::string>("message")).
TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
Matcher<std::function<void()>> matcher =
ThrowsMessage<std::runtime_error>("error message");
EXPECT_TRUE(
matcher.Matches([]() { throw std::runtime_error("error message"); }));
EXPECT_FALSE(matcher.Matches(
[]() { throw std::runtime_error("wrong error message"); }));
}
#endif // GTEST_HAS_EXCEPTIONS
} // namespace
} // namespace gmock_matchers_test
} // namespace testing
......
......@@ -27,46 +27,54 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the built-in actions generated by a script.
// This file tests the built-in actions in gmock-actions.h.
#include "gmock/gmock-generated-actions.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4577)
#endif
#include "gmock/gmock-more-actions.h"
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_generated_actions_test {
namespace gmock_more_actions_test {
using ::std::plus;
using ::std::string;
using testing::_;
using testing::Action;
using testing::ActionInterface;
using testing::ByRef;
using testing::DoAll;
using testing::DeleteArg;
using testing::Invoke;
using testing::Return;
using testing::ReturnNew;
using testing::SetArgPointee;
using testing::StaticAssertTypeEq;
using testing::ReturnArg;
using testing::ReturnPointee;
using testing::SaveArg;
using testing::SaveArgPointee;
using testing::SetArgReferee;
using testing::Unused;
using testing::WithArg;
using testing::WithoutArgs;
// For suppressing compiler warnings on conversion possibly losing precision.
inline short Short(short n) { return n; } // NOLINT
inline char Char(char ch) { return ch; }
// Sample functions and functors for testing various actions.
// Sample functions and functors for testing Invoke() and etc.
int Nullary() { return 1; }
bool g_done = false;
bool Unary(int x) { return x < 0; }
bool ByConstRef(const std::string& s) { return s == "Hi"; }
const double g_double = 0;
......@@ -78,6 +86,12 @@ struct UnaryFunctor {
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
struct SumOf5Functor {
......@@ -86,11 +100,6 @@ struct SumOf5Functor {
}
};
std::string Concat5(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5) {
return std::string(s1) + s2 + s3 + s4 + s5;
}
int SumOf6(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
......@@ -101,11 +110,6 @@ struct SumOf6Functor {
}
};
std::string Concat6(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6) {
return std::string(s1) + s2 + s3 + s4 + s5 + s6;
}
std::string Concat7(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7) {
......@@ -131,15 +135,562 @@ std::string Concat10(const char* s1, const char* s2, const char* s3,
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
}
class Foo {
public:
Foo() : value_(123) {}
int Nullary() const { return value_; }
short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT
std::string Binary(const std::string& str, char c) const { return str + c; }
int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
int SumOf4(int a, int b, int c, int d) const {
return a + b + c + d + value_;
}
int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; }
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
int SumOf6(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
std::string Concat7(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7) {
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
}
std::string Concat8(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7, const char* s8) {
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
}
std::string Concat9(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7, const char* s8, const char* s9) {
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
}
std::string Concat10(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7, const char* s8, const char* s9,
const char* s10) {
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
}
private:
int value_;
};
// Tests using Invoke() with a nullary function.
TEST(InvokeTest, Nullary) {
Action<int()> a = Invoke(Nullary); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple()));
}
// Tests using Invoke() with a unary function.
TEST(InvokeTest, Unary) {
Action<bool(int)> a = Invoke(Unary); // NOLINT
EXPECT_FALSE(a.Perform(std::make_tuple(1)));
EXPECT_TRUE(a.Perform(std::make_tuple(-1)));
}
// Tests using Invoke() with a binary function.
TEST(InvokeTest, Binary) {
Action<const char*(const char*, short)> a = Invoke(Binary); // NOLINT
const char* p = "Hello";
EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2))));
}
// Tests using Invoke() with a ternary function.
TEST(InvokeTest, Ternary) {
Action<int(int, char, short)> a = Invoke(Ternary); // NOLINT
EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3))));
}
// Tests using Invoke() with a 4-argument function.
TEST(InvokeTest, FunctionThatTakes4Arguments) {
Action<int(int, int, int, int)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4)));
}
// Tests using Invoke() with a 5-argument function.
TEST(InvokeTest, FunctionThatTakes5Arguments) {
Action<int(int, int, int, int, int)> a = Invoke(SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
}
// Tests using Invoke() with a 6-argument function.
TEST(InvokeTest, FunctionThatTakes6Arguments) {
Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); // NOLINT
EXPECT_EQ(123456,
a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));
}
// A helper that turns the type of a C-string literal from const
// char[N] to const char*.
inline const char* CharPtr(const char* s) { return s; }
// Tests using Invoke() with a 7-argument function.
TEST(InvokeTest, FunctionThatTakes7Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*)>
a = Invoke(Concat7);
EXPECT_EQ("1234567",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"))));
}
// Tests using Invoke() with a 8-argument function.
TEST(InvokeTest, FunctionThatTakes8Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*)>
a = Invoke(Concat8);
EXPECT_EQ("12345678",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"))));
}
// Tests using Invoke() with a 9-argument function.
TEST(InvokeTest, FunctionThatTakes9Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*)>
a = Invoke(Concat9);
EXPECT_EQ("123456789", a.Perform(std::make_tuple(
CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"), CharPtr("9"))));
}
// Tests using Invoke() with a 10-argument function.
TEST(InvokeTest, FunctionThatTakes10Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*, const char*)>
a = Invoke(Concat10);
EXPECT_EQ("1234567890",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"), CharPtr("9"),
CharPtr("0"))));
}
// Tests using Invoke() with functions with parameters declared as Unused.
TEST(InvokeTest, FunctionWithUnusedParameters) {
Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);
std::tuple<int, int, double, std::string> dummy =
std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 =
Invoke(SumOfFirst2);
EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
}
// Tests using Invoke() with methods with parameters declared as Unused.
TEST(InvokeTest, MethodWithUnusedParameters) {
Foo foo;
Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2)));
Action<int(char, double, int, int)> a2 =
Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3)));
}
// Tests using Invoke() with a functor.
TEST(InvokeTest, Functor) {
Action<long(long, int)> a = Invoke(plus<long>()); // NOLINT
EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2)));
}
// Tests using Invoke(f) as an action of a compatible type.
TEST(InvokeTest, FunctionWithCompatibleType) {
Action<long(int, short, char, bool)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));
}
// Tests using Invoke() with an object pointer and a method pointer.
// Tests using Invoke() with a nullary method.
TEST(InvokeMethodTest, Nullary) {
Foo foo;
Action<int()> a = Invoke(&foo, &Foo::Nullary); // NOLINT
EXPECT_EQ(123, a.Perform(std::make_tuple()));
}
// Tests using Invoke() with a unary method.
TEST(InvokeMethodTest, Unary) {
Foo foo;
Action<short(long)> a = Invoke(&foo, &Foo::Unary); // NOLINT
EXPECT_EQ(4123, a.Perform(std::make_tuple(4000)));
}
// Tests using Invoke() with a binary method.
TEST(InvokeMethodTest, Binary) {
Foo foo;
Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary);
std::string s("Hell");
std::tuple<std::string, char> dummy = std::make_tuple(s, 'o');
EXPECT_EQ("Hello", a.Perform(dummy));
}
// Tests using Invoke() with a ternary method.
TEST(InvokeMethodTest, Ternary) {
Foo foo;
Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary); // NOLINT
EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1))));
}
// Tests using Invoke() with a 4-argument method.
TEST(InvokeMethodTest, MethodThatTakes4Arguments) {
Foo foo;
Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4); // NOLINT
EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4)));
}
// Tests using Invoke() with a 5-argument method.
TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
Foo foo;
Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
}
// Tests using Invoke() with a 6-argument method.
TEST(InvokeMethodTest, MethodThatTakes6Arguments) {
Foo foo;
Action<int(int, int, int, int, int, int)> a = // NOLINT
Invoke(&foo, &Foo::SumOf6);
EXPECT_EQ(123456,
a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));
}
// Tests using Invoke() with a 7-argument method.
TEST(InvokeMethodTest, MethodThatTakes7Arguments) {
Foo foo;
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*)>
a = Invoke(&foo, &Foo::Concat7);
EXPECT_EQ("1234567",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"))));
}
// Tests using Invoke() with a 8-argument method.
TEST(InvokeMethodTest, MethodThatTakes8Arguments) {
Foo foo;
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*)>
a = Invoke(&foo, &Foo::Concat8);
EXPECT_EQ("12345678",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"))));
}
// Tests using Invoke() with a 9-argument method.
TEST(InvokeMethodTest, MethodThatTakes9Arguments) {
Foo foo;
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*)>
a = Invoke(&foo, &Foo::Concat9);
EXPECT_EQ("123456789", a.Perform(std::make_tuple(
CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"), CharPtr("9"))));
}
// Tests using Invoke() with a 10-argument method.
TEST(InvokeMethodTest, MethodThatTakes10Arguments) {
Foo foo;
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*, const char*)>
a = Invoke(&foo, &Foo::Concat10);
EXPECT_EQ("1234567890",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
CharPtr("7"), CharPtr("8"), CharPtr("9"),
CharPtr("0"))));
}
// Tests using Invoke(f) as an action of a compatible type.
TEST(InvokeMethodTest, MethodWithCompatibleType) {
Foo foo;
Action<long(int, short, char, bool)> a = // NOLINT
Invoke(&foo, &Foo::SumOf4);
EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));
}
// Tests using WithoutArgs with an action that takes no argument.
TEST(WithoutArgsTest, NoArg) {
Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
}
// Tests using WithArg with an action that takes 1 argument.
TEST(WithArgTest, OneArg) {
Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); // NOLINT
EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1)));
EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1)));
}
TEST(ReturnArgActionTest, WorksForOneArgIntArg0) {
const Action<int(int)> a = ReturnArg<0>();
EXPECT_EQ(5, a.Perform(std::make_tuple(5)));
}
TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) {
const Action<bool(bool, bool, bool)> a = ReturnArg<0>();
EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false)));
}
TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {
const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>();
EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8)));
}
TEST(SaveArgActionTest, WorksForSameType) {
int result = 0;
const Action<void(int n)> a1 = SaveArg<0>(&result);
a1.Perform(std::make_tuple(5));
EXPECT_EQ(5, result);
}
TEST(SaveArgActionTest, WorksForCompatibleType) {
int result = 0;
const Action<void(bool, char)> a1 = SaveArg<1>(&result);
a1.Perform(std::make_tuple(true, 'a'));
EXPECT_EQ('a', result);
}
TEST(SaveArgPointeeActionTest, WorksForSameType) {
int result = 0;
const int value = 5;
const Action<void(const int*)> a1 = SaveArgPointee<0>(&result);
a1.Perform(std::make_tuple(&value));
EXPECT_EQ(5, result);
}
TEST(SaveArgPointeeActionTest, WorksForCompatibleType) {
int result = 0;
char value = 'a';
const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result);
a1.Perform(std::make_tuple(true, &value));
EXPECT_EQ('a', result);
}
TEST(SetArgRefereeActionTest, WorksForSameType) {
int value = 0;
const Action<void(int&)> a1 = SetArgReferee<0>(1);
a1.Perform(std::tuple<int&>(value));
EXPECT_EQ(1, value);
}
TEST(SetArgRefereeActionTest, WorksForCompatibleType) {
int value = 0;
const Action<void(int, int&)> a1 = SetArgReferee<1>('a');
a1.Perform(std::tuple<int, int&>(0, value));
EXPECT_EQ('a', value);
}
TEST(SetArgRefereeActionTest, WorksWithExtraArguments) {
int value = 0;
const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a');
a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, "hi"));
EXPECT_EQ('a', value);
}
// A class that can be used to verify that its destructor is called: it will set
// the bool provided to the constructor to true when destroyed.
class DeletionTester {
public:
explicit DeletionTester(bool* is_deleted)
: is_deleted_(is_deleted) {
// Make sure the bit is set to false.
*is_deleted_ = false;
}
~DeletionTester() {
*is_deleted_ = true;
}
private:
bool* is_deleted_;
};
TEST(DeleteArgActionTest, OneArg) {
bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT
EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(t));
EXPECT_TRUE(is_deleted);
}
TEST(DeleteArgActionTest, TenArgs) {
bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(bool, int, int, const char*, bool,
int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>();
EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
EXPECT_TRUE(is_deleted);
}
#if GTEST_HAS_EXCEPTIONS
TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) {
const Action<void(int n)> a = Throw('a');
EXPECT_THROW(a.Perform(std::make_tuple(0)), char);
}
class MyException {};
TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) {
const Action<double(char ch)> a = Throw(MyException());
EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException);
}
TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) {
const Action<double()> a = Throw(MyException());
EXPECT_THROW(a.Perform(std::make_tuple()), MyException);
}
class Object {
public:
virtual ~Object() {}
virtual void Func() {}
};
class MockObject : public Object {
public:
~MockObject() override {}
MOCK_METHOD(void, Func, (), (override));
};
TEST(ThrowActionTest, Times0) {
EXPECT_NONFATAL_FAILURE(
[] {
try {
MockObject m;
ON_CALL(m, Func()).WillByDefault([] { throw "something"; });
EXPECT_CALL(m, Func()).Times(0);
m.Func();
} catch (...) {
// Exception is caught but Times(0) still triggers a failure.
}
}(),
"");
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests that SetArrayArgument<N>(first, last) sets the elements of the array
// pointed to by the N-th (0-based) argument to values in range [first, last).
TEST(SetArrayArgumentTest, SetsTheNthArray) {
using MyFunction = void(bool, int*, char*);
int numbers[] = { 1, 2, 3 };
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
int n[4] = {};
int* pn = n;
char ch[4] = {};
char* pch = ch;
a.Perform(std::make_tuple(true, pn, pch));
EXPECT_EQ(1, n[0]);
EXPECT_EQ(2, n[1]);
EXPECT_EQ(3, n[2]);
EXPECT_EQ(0, n[3]);
EXPECT_EQ('\0', ch[0]);
EXPECT_EQ('\0', ch[1]);
EXPECT_EQ('\0', ch[2]);
EXPECT_EQ('\0', ch[3]);
// Tests first and last are iterators.
std::string letters = "abc";
a = SetArrayArgument<2>(letters.begin(), letters.end());
std::fill_n(n, 4, 0);
std::fill_n(ch, 4, '\0');
a.Perform(std::make_tuple(true, pn, pch));
EXPECT_EQ(0, n[0]);
EXPECT_EQ(0, n[1]);
EXPECT_EQ(0, n[2]);
EXPECT_EQ(0, n[3]);
EXPECT_EQ('a', ch[0]);
EXPECT_EQ('b', ch[1]);
EXPECT_EQ('c', ch[2]);
EXPECT_EQ('\0', ch[3]);
}
// Tests SetArrayArgument<N>(first, last) where first == last.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
using MyFunction = void(bool, int*);
int numbers[] = { 1, 2, 3 };
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
int n[4] = {};
int* pn = n;
a.Perform(std::make_tuple(true, pn));
EXPECT_EQ(0, n[0]);
EXPECT_EQ(0, n[1]);
EXPECT_EQ(0, n[2]);
EXPECT_EQ(0, n[3]);
}
// Tests SetArrayArgument<N>(first, last) where *first is convertible
// (but not equal) to the argument type.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
using MyFunction = void(bool, int*);
char chars[] = { 97, 98, 99 };
Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
int codes[4] = { 111, 222, 333, 444 };
int* pcodes = codes;
a.Perform(std::make_tuple(true, pcodes));
EXPECT_EQ(97, codes[0]);
EXPECT_EQ(98, codes[1]);
EXPECT_EQ(99, codes[2]);
EXPECT_EQ(444, codes[3]);
}
// Test SetArrayArgument<N>(first, last) with iterator as argument.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
using MyFunction = void(bool, std::back_insert_iterator<std::string>);
std::string letters = "abc";
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
std::string s;
a.Perform(std::make_tuple(true, back_inserter(s)));
EXPECT_EQ(letters, s);
}
TEST(ReturnPointeeTest, Works) {
int n = 42;
const Action<int()> a = ReturnPointee(&n);
EXPECT_EQ(42, a.Perform(std::make_tuple()));
n = 43;
EXPECT_EQ(43, a.Perform(std::make_tuple()));
}
// Tests InvokeArgument<N>(...).
// Tests using InvokeArgument with a nullary function.
TEST(InvokeArgumentTest, Function0) {
Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT
Action<int(int, int (*)())> a = InvokeArgument<1>(); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
}
......@@ -151,7 +702,7 @@ TEST(InvokeArgumentTest, Functor1) {
// Tests using InvokeArgument with a 5-ary function.
TEST(InvokeArgumentTest, Function5) {
Action<int(int(*)(int, int, int, int, int))> a = // NOLINT
Action<int(int (*)(int, int, int, int, int))> a = // NOLINT
InvokeArgument<0>(10000, 2000, 300, 40, 5);
EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));
}
......@@ -165,7 +716,7 @@ TEST(InvokeArgumentTest, Functor5) {
// Tests using InvokeArgument with a 6-ary function.
TEST(InvokeArgumentTest, Function6) {
Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT
Action<int(int (*)(int, int, int, int, int, int))> a = // NOLINT
InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));
}
......@@ -215,16 +766,16 @@ TEST(InvokeArgumentTest, Function10) {
// Tests using InvokeArgument with a function that takes a pointer argument.
TEST(InvokeArgumentTest, ByPointerFunction) {
Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
a = InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
}
// Tests using InvokeArgument with a function that takes a const char*
// by passing it a C-string literal.
TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
InvokeArgument<0>("Hi", Short(1));
Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
a = InvokeArgument<0>("Hi", Short(1));
EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
}
......@@ -241,7 +792,7 @@ TEST(InvokeArgumentTest, ByConstReferenceFunction) {
// Tests using InvokeArgument with ByRef() and a function that takes a
// const reference.
TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
Action<bool(bool(*)(const double& x))> a = // NOLINT
Action<bool(bool (*)(const double& x))> a = // NOLINT
InvokeArgument<0>(ByRef(g_double));
// The above line calls ByRef() on a const value.
EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
......@@ -264,8 +815,7 @@ TEST(DoAllTest, TwoActions) {
TEST(DoAllTest, ThreeActions) {
int m = 0, n = 0;
Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
SetArgPointee<1>(2),
Return(3));
SetArgPointee<1>(2), Return(3));
EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));
EXPECT_EQ(1, m);
EXPECT_EQ(2, n);
......@@ -276,9 +826,7 @@ TEST(DoAllTest, FourActions) {
int m = 0, n = 0;
char ch = '\0';
Action<int(int*, int*, char*)> a = // NOLINT
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
Return(3));
EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));
EXPECT_EQ(1, m);
......@@ -291,11 +839,8 @@ TEST(DoAllTest, FiveActions) {
int m = 0, n = 0;
char a = '\0', b = '\0';
Action<int(int*, int*, char*, char*)> action = // NOLINT
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
Return(3));
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
SetArgPointee<3>('b'), Return(3));
EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));
EXPECT_EQ(1, m);
EXPECT_EQ(2, n);
......@@ -308,12 +853,8 @@ TEST(DoAllTest, SixActions) {
int m = 0, n = 0;
char a = '\0', b = '\0', c = '\0';
Action<int(int*, int*, char*, char*, char*)> action = // NOLINT
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
SetArgPointee<4>('c'),
Return(3));
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3));
EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));
EXPECT_EQ(1, m);
EXPECT_EQ(2, n);
......@@ -327,12 +868,8 @@ TEST(DoAllTest, SevenActions) {
int m = 0, n = 0;
char a = '\0', b = '\0', c = '\0', d = '\0';
Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
SetArgPointee<4>('c'),
SetArgPointee<5>('d'),
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'),
Return(3));
EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));
EXPECT_EQ(1, m);
......@@ -348,15 +885,11 @@ TEST(DoAllTest, EightActions) {
int m = 0, n = 0;
char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
char*)> action =
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
SetArgPointee<4>('c'),
SetArgPointee<5>('d'),
SetArgPointee<6>('e'),
Return(3));
char*)>
action =
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
SetArgPointee<3>('b'), SetArgPointee<4>('c'),
SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3));
EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));
EXPECT_EQ(1, m);
EXPECT_EQ(2, n);
......@@ -372,16 +905,11 @@ TEST(DoAllTest, NineActions) {
int m = 0, n = 0;
char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
char*, char*)> action =
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
SetArgPointee<4>('c'),
SetArgPointee<5>('d'),
SetArgPointee<6>('e'),
SetArgPointee<7>('f'),
Return(3));
char*, char*)>
action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2),
SetArgPointee<2>('a'), SetArgPointee<3>('b'),
SetArgPointee<4>('c'), SetArgPointee<5>('d'),
SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3));
EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
EXPECT_EQ(1, m);
EXPECT_EQ(2, n);
......@@ -399,17 +927,12 @@ TEST(DoAllTest, TenActions) {
char a = '\0', b = '\0', c = '\0', d = '\0';
char e = '\0', f = '\0', g = '\0';
Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
char*, char*, char*)> action =
DoAll(SetArgPointee<0>(1),
SetArgPointee<1>(2),
SetArgPointee<2>('a'),
SetArgPointee<3>('b'),
SetArgPointee<4>('c'),
SetArgPointee<5>('d'),
SetArgPointee<6>('e'),
SetArgPointee<7>('f'),
SetArgPointee<8>('g'),
Return(3));
char*, char*, char*)>
action =
DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
SetArgPointee<3>('b'), SetArgPointee<4>('c'),
SetArgPointee<5>('d'), SetArgPointee<6>('e'),
SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3));
EXPECT_EQ(
3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
EXPECT_EQ(1, m);
......@@ -423,6 +946,33 @@ TEST(DoAllTest, TenActions) {
EXPECT_EQ('g', g);
}
TEST(DoAllTest, NoArgs) {
bool ran_first = false;
Action<bool()> a =
DoAll([&] { ran_first = true; }, [&] { return ran_first; });
EXPECT_TRUE(a.Perform({}));
}
TEST(DoAllTest, MoveOnlyArgs) {
bool ran_first = false;
Action<int(std::unique_ptr<int>)> a =
DoAll(InvokeWithoutArgs([&] { ran_first = true; }),
[](std::unique_ptr<int> p) { return *p; });
EXPECT_EQ(7, a.Perform(std::make_tuple(std::unique_ptr<int>(new int(7)))));
EXPECT_TRUE(ran_first);
}
TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
bool ran_first = false;
// Action<void(std::vector<int>)> isn't an
// Action<void(const std::vector<int>&) but can be converted.
Action<void(std::vector<int>)> first = [&] { ran_first = true; };
Action<int(std::vector<int>)> a =
DoAll(first, [](std::vector<int> arg) { return arg.front(); });
EXPECT_EQ(7, a.Perform(std::make_tuple(std::vector<int>{7})));
EXPECT_TRUE(ran_first);
}
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
......@@ -430,9 +980,9 @@ TEST(DoAllTest, TenActions) {
// we suppress them here.
// Also suppress C4503 decorated name length exceeded, name was truncated
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
# pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#endif
// Tests the ACTION*() macro family.
......@@ -487,9 +1037,13 @@ TEST(ActionMacroTest, CanReferenceArgumentTuple) {
EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));
}
namespace {
// Tests that the body of ACTION() can reference the mock function
// type.
int Dummy(bool flag) { return flag? 1 : 0; }
int Dummy(bool flag) { return flag ? 1 : 0; }
} // namespace
ACTION(InvokeDummy) {
StaticAssertTypeEq<int(bool), function_type>();
......@@ -608,7 +1162,7 @@ ACTION_P2(OverloadedAction, true_value, false_value) {
}
TEST(ActionMacroTest, CanDefineOverloadedActions) {
typedef Action<const char*(bool, const char*)> MyAction;
using MyAction = Action<const char*(bool, const char*)>;
const MyAction a1 = OverloadedAction();
EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world"))));
......@@ -739,11 +1293,11 @@ template <typename T1, typename T2>
// ConcatImplActionP3 is the class template ACTION_P3 uses to
// implement ConcatImpl. We shouldn't change the name as this
// pattern requires the user to use it directly.
ConcatImplActionP3<std::string, T1, T2>
Concat(const std::string& a, T1 b, T2 c) {
ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b,
T2 c) {
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (true) {
GTEST_INTENTIONAL_CONST_COND_POP_()
GTEST_INTENTIONAL_CONST_COND_POP_()
// This branch verifies that ConcatImpl() can be invoked without
// explicit template arguments.
return ConcatImpl(a, b, c);
......@@ -758,8 +1312,7 @@ Concat(const std::string& a, T1 b, T2 c) {
// Defines another partially specialized wrapper that restricts the
// second parameter to int.
template <typename T1, typename T2>
ConcatImplActionP3<T1, int, T2>
Concat(T1 a, int b, T2 c) {
ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) {
return ConcatImpl(a, b, c);
}
......@@ -837,80 +1390,23 @@ TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
a = Plus3<int&, const int&, int&>(x, y, z);
EXPECT_EQ(6, a.Perform(empty));
int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7],
n[8], n[9]);
int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6],
n[7], n[8], n[9]);
EXPECT_EQ(55, a.Perform(empty));
}
class NullaryConstructorClass {
public:
NullaryConstructorClass() : value_(123) {}
int value_;
};
// Tests using ReturnNew() with a nullary constructor.
TEST(ReturnNewTest, NoArgs) {
Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
NullaryConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(123, c->value_);
delete c;
}
class UnaryConstructorClass {
public:
explicit UnaryConstructorClass(int value) : value_(value) {}
int value_;
};
// Tests using ReturnNew() with a unary constructor.
TEST(ReturnNewTest, Unary) {
Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
UnaryConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(4000, c->value_);
delete c;
}
TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
Action<UnaryConstructorClass*(bool, int)> a =
ReturnNew<UnaryConstructorClass>(4000);
UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
EXPECT_EQ(4000, c->value_);
delete c;
}
TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
Action<const UnaryConstructorClass*()> a =
ReturnNew<UnaryConstructorClass>(4000);
const UnaryConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(4000, c->value_);
delete c;
}
class TenArgConstructorClass {
public:
TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10)
: value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {
}
TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
int a8, int a9, int a10)
: value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
int value_;
};
// Tests using ReturnNew() with a 10-argument constructor.
TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
Action<TenArgConstructorClass*()> a =
ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
4000000, 500000, 60000,
7000, 800, 90, 0);
TenArgConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(1234567890, c->value_);
delete c;
}
// Tests that ACTION_TEMPLATE works when there is no value parameter.
ACTION_TEMPLATE(CreateNew,
HAS_1_TEMPLATE_PARAMS(typename, T),
ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
AND_0_VALUE_PARAMS()) {
return new T;
}
......@@ -922,8 +1418,7 @@ TEST(ActionTemplateTest, WorksWithoutValueParam) {
}
// Tests that ACTION_TEMPLATE works when there are value parameters.
ACTION_TEMPLATE(CreateNew,
HAS_1_TEMPLATE_PARAMS(typename, T),
ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
AND_1_VALUE_PARAMS(a0)) {
return new T(a0);
}
......@@ -936,8 +1431,7 @@ TEST(ActionTemplateTest, WorksWithValueParams) {
}
// Tests that ACTION_TEMPLATE works for integral template parameters.
ACTION_TEMPLATE(MyDeleteArg,
HAS_1_TEMPLATE_PARAMS(int, k),
ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k),
AND_0_VALUE_PARAMS()) {
delete std::get<k>(args);
}
......@@ -947,6 +1441,7 @@ class BoolResetter {
public:
explicit BoolResetter(bool* value) : value_(value) {}
~BoolResetter() { *value_ = false; }
private:
bool* value_;
};
......@@ -955,7 +1450,7 @@ TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
int n = 0;
bool b = true;
BoolResetter* resetter = new BoolResetter(&b);
auto* resetter = new BoolResetter(&b);
a.Perform(std::make_tuple(&n, resetter));
EXPECT_FALSE(b); // Verifies that resetter is deleted.
}
......@@ -985,17 +1480,10 @@ struct GiantTemplate {
};
ACTION_TEMPLATE(ReturnGiant,
HAS_10_TEMPLATE_PARAMS(
typename, T1,
typename, T2,
typename, T3,
int, k4,
bool, k5,
unsigned int, k6,
class, T7,
class, T8,
class, T9,
template <typename T> class, T10),
HAS_10_TEMPLATE_PARAMS(typename, T1, typename, T2, typename, T3,
int, k4, bool, k5, unsigned int, k6,
class, T7, class, T8, class, T9,
template <typename T> class, T10),
AND_1_VALUE_PARAMS(value)) {
return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
}
......@@ -1010,8 +1498,7 @@ TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
}
// Tests that ACTION_TEMPLATE works for 10 value parameters.
ACTION_TEMPLATE(ReturnSum,
HAS_1_TEMPLATE_PARAMS(typename, Number),
ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
}
......@@ -1028,20 +1515,17 @@ ACTION(ReturnSum) { return 0; }
ACTION_P(ReturnSum, x) { return x; }
ACTION_TEMPLATE(ReturnSum,
HAS_1_TEMPLATE_PARAMS(typename, Number),
ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
AND_2_VALUE_PARAMS(v1, v2)) {
return static_cast<Number>(v1) + v2;
}
ACTION_TEMPLATE(ReturnSum,
HAS_1_TEMPLATE_PARAMS(typename, Number),
ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
AND_3_VALUE_PARAMS(v1, v2, v3)) {
return static_cast<Number>(v1) + v2 + v3;
}
ACTION_TEMPLATE(ReturnSum,
HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
return static_cast<Number>(v1) + v2 + v3 + v4 + k;
}
......@@ -1059,6 +1543,5 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
EXPECT_EQ(12345, a4.Perform(std::make_tuple()));
}
} // namespace gmock_generated_actions_test
} // namespace gmock_more_actions_test
} // namespace testing
......@@ -67,6 +67,12 @@ class NotDefaultConstructible {
explicit NotDefaultConstructible(int) {}
};
class CallsMockMethodInDestructor {
public:
~CallsMockMethodInDestructor() { OnDestroy(); }
MOCK_METHOD(void, OnDestroy, ());
};
// Defines some mock classes needed by the tests.
class Foo {
......@@ -302,6 +308,13 @@ TEST(NiceMockTest, AcceptsClassNamedMock) {
nice.DoThis();
}
TEST(NiceMockTest, IsNiceInDestructor) {
{
NiceMock<CallsMockMethodInDestructor> nice_on_destroy;
// Don't add an expectation for the call before the mock goes out of scope.
}
}
TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
NiceMock<MockFoo> nice_foo;
EXPECT_FALSE(Mock::IsNaggy(&nice_foo));
......@@ -405,6 +418,22 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
naggy.DoThis();
}
TEST(NaggyMockTest, IsNaggyInDestructor) {
const std::string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
CaptureStdout();
{
NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy;
// Don't add an expectation for the call before the mock goes out of scope.
}
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));
......@@ -489,6 +518,16 @@ TEST(StrictMockTest, AcceptsClassNamedMock) {
strict.DoThis();
}
TEST(StrictMockTest, IsStrictInDestructor) {
EXPECT_NONFATAL_FAILURE(
{
StrictMock<CallsMockMethodInDestructor> strict_on_destroy;
// Don't add an expectation for the call before the mock goes out of
// scope.
},
"Uninteresting mock function call");
}
TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {
StrictMock<MockFoo> strict_foo;
EXPECT_FALSE(Mock::IsNaggy(&strict_foo));
......
#include "gmock/internal/gmock-pp.h"
// Used to test MSVC treating __VA_ARGS__ with a comma in it as one value
#define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma ,
#define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \
GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x)
// Static assertions.
namespace testing {
namespace internal {
......@@ -17,6 +22,11 @@ static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, "");
static_assert(!GMOCK_PP_HAS_COMMA(), "");
static_assert(GMOCK_PP_HAS_COMMA(b, ), "");
static_assert(!GMOCK_PP_HAS_COMMA((, )), "");
static_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)),
"");
static_assert(
GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))),
"");
static_assert(!GMOCK_PP_IS_EMPTY(, ), "");
static_assert(!GMOCK_PP_IS_EMPTY(a), "");
static_assert(!GMOCK_PP_IS_EMPTY(()), "");
......
......@@ -69,8 +69,8 @@ using testing::AtMost;
using testing::Between;
using testing::Cardinality;
using testing::CardinalityInterface;
using testing::ContainsRegex;
using testing::Const;
using testing::ContainsRegex;
using testing::DoAll;
using testing::DoDefault;
using testing::Eq;
......@@ -2179,8 +2179,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
"https://github.com/google/googletest/blob/master/googlemock/docs/"
"cook_book.md#"
"https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#"
"knowing-when-to-expect for details.";
// A void-returning function.
......
......@@ -37,9 +37,6 @@
// below list of actual *_test.cc files might change).
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc"
......
......@@ -112,8 +112,8 @@
// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
// gmock_link2_test.cc to avoid producing linker errors.
#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_
#define GMOCK_TEST_GMOCK_LINK_TEST_H_
#ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#include "gmock/gmock.h"
......@@ -687,4 +687,4 @@ TEST(LinkTest, TestMatcherCast) {
EXPECT_TRUE(m.Matches(nullptr));
}
#endif // GMOCK_TEST_GMOCK_LINK_TEST_H_
#endif // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
......@@ -75,14 +75,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
......@@ -266,14 +266,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
......@@ -314,4 +314,4 @@ Expected: is pair (is >= 48, true)
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment