first commit

This commit is contained in:
lnk
2026-07-10 14:13:02 +08:00
commit b61388443f
459 changed files with 143602 additions and 0 deletions

View File

@@ -0,0 +1,93 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
project(test)
SET(SUB_DIRS)
file(GLOB children ${CMAKE_SOURCE_DIR}/src/*)
FOREACH (child ${children})
IF (IS_DIRECTORY ${child})
LIST(APPEND SUB_DIRS ${child})
ENDIF ()
ENDFOREACH ()
LIST(APPEND SUB_DIRS ${CMAKE_SOURCE_DIR}/src)
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${SUB_DIRS})
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/test/bin)
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${Boost_INCLUDE_DIRS})
set(Gtest_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/bin/include/gtest)
set(Gmock_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/bin/include/gmock)
include_directories(${Gtest_INCLUDE_DIR})
include_directories(${Gtest_INCLUDE_DIR}/internal)
include_directories(${Gmock_INCLUDE_DIR})
include_directories(${Gmock_INCLUDE_DIR}/internal)
set(Gtest_LIBRARY_DIRS ${CMAKE_SOURCE_DIR}/bin/lib)
set(Gtest_LIBRARIES ${Gtest_LIBRARY_DIRS}/libgtest_main.a;${Gtest_LIBRARY_DIRS}/libgtest.a)
set(Gmock_LIBRARIES ${Gtest_LIBRARY_DIRS}/libgmock_main.a;${Gtest_LIBRARY_DIRS}/libgmock.a)
message(STATUS "** Gmock_LIBRARIES: ${Gmock_LIBRARIES}")
link_directories(${Boost_LIBRARY_DIRS})
link_directories(${OPENSSL_LIBRARIES_DIR})
link_directories(${LIBEVENT_LIBRARY})
link_directories(${JSONCPP_LIBRARY})
set(ROCKETMQ_LIBRARIES ${CMAKE_SOURCE_DIR}/bin/librocketmq.a)
message(STATUS "** ROCKETMQ_LIBRARIES ${ROCKETMQ_LIBRARIES}")
function(compile files)
foreach (file ${files})
get_filename_component(basename ${file} NAME_WE)
add_executable(${basename} ${file})
add_test(NAME rocketmq-${basename} COMMAND ${basename})
if (MSVC)
if (CMAKE_CONFIGURATION_TYPES STREQUAL "Release")
set_target_properties(${basename} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:LIBCMT")
else ()
set_target_properties(${basename} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:LIBCMTD")
endif ()
endif ()
if (MSVC)
if (BUILD_ROCKETMQ_SHARED)
target_link_libraries(${basename} rocketmq_shared ${deplibs}
${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${LIBEVENT_LIBRARIES} ${JSONCPP_LIBRARIES} ${x`})
else ()
target_link_libraries(${basename} rocketmq_static ${deplibs}
${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${LIBEVENT_LIBRARIES} ${JSONCPP_LIBRARIES} ${Gtest_LIBRARIES})
endif ()
else ()
target_link_libraries(${basename} rocketmq_shared ${deplibs})
target_link_libraries(${basename} rocketmq_shared ${Gtest_LIBRARIES})
target_link_libraries(${basename} rocketmq_shared ${Gmock_LIBRARIES})
endif ()
endforeach ()
endfunction()
file(GLOB files "src/*.c*")
compile("${files}")
file(GLOB files "src/*")
foreach (file ${files})
if (IS_DIRECTORY ${file})
file(GLOB filess "${file}/*.c*")
compile("${filess}")
endif ()
endforeach ()

View File

@@ -0,0 +1,219 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CommunicationMode.h"
#include "MQClientAPIImpl.h"
#include "MQClientException.h"
using namespace std;
using namespace rocketmq;
using rocketmq::CommunicationMode;
using rocketmq::RemotingCommand;
using rocketmq::TcpRemotingClient;
using testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Mock;
using testing::Return;
class MockTcpRemotingClient : public TcpRemotingClient {
public:
MockTcpRemotingClient() : TcpRemotingClient(true, DEFAULT_SSL_PROPERTY_FILE) {}
MOCK_METHOD3(invokeSync, RemotingCommand*(const string&, RemotingCommand&, int));
MOCK_METHOD6(invokeAsync, bool(const string&, RemotingCommand&, std::shared_ptr<AsyncCallbackWrap>, int64, int, int));
};
class MockMQClientAPIImpl : public MQClientAPIImpl {
public:
MockMQClientAPIImpl(const string& mqClientId,
ClientRemotingProcessor* clientRemotingProcessor,
int pullThreadNum,
uint64_t tcpConnectTimeout,
uint64_t tcpTransportTryLockTimeout,
string unitName)
: MQClientAPIImpl(mqClientId, true, DEFAULT_SSL_PROPERTY_FILE) {}
void reInitRemoteClient(TcpRemotingClient* client) { m_pRemotingClient.reset(client); }
};
TEST(MQClientAPIImplTest, getMaxOffset) {
SessionCredentials sc;
MockMQClientAPIImpl* impl = new MockMQClientAPIImpl("testMockAPIImpl", nullptr, 1, 2, 3, "testUnit");
Mock::AllowLeak(impl);
MockTcpRemotingClient* pClient = new MockTcpRemotingClient();
Mock::AllowLeak(pClient);
impl->reInitRemoteClient(pClient);
GetMaxOffsetResponseHeader* pHead = new GetMaxOffsetResponseHeader();
pHead->offset = 4096;
RemotingCommand* pCommandFailed = new RemotingCommand(SYSTEM_ERROR, nullptr);
RemotingCommand* pCommandSuccuss = new RemotingCommand(SUCCESS_VALUE, pHead);
EXPECT_CALL(*pClient, invokeSync(_, _, _))
.Times(3)
.WillOnce(Return(nullptr))
.WillOnce(Return(pCommandFailed))
.WillOnce(Return(pCommandSuccuss));
EXPECT_ANY_THROW(impl->getMaxOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc));
EXPECT_ANY_THROW(impl->getMaxOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc));
int64 offset = impl->getMaxOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc);
EXPECT_EQ(4096, offset);
}
TEST(MQClientAPIImplTest, getMinOffset) {
SessionCredentials sc;
MockMQClientAPIImpl* impl = new MockMQClientAPIImpl("testMockAPIImpl", nullptr, 1, 2, 3, "testUnit");
Mock::AllowLeak(impl);
MockTcpRemotingClient* pClient = new MockTcpRemotingClient();
Mock::AllowLeak(pClient);
impl->reInitRemoteClient(pClient);
GetMinOffsetResponseHeader* pHead = new GetMinOffsetResponseHeader();
pHead->offset = 2048;
RemotingCommand* pCommandFailed = new RemotingCommand(SYSTEM_ERROR, nullptr);
RemotingCommand* pCommandSuccuss = new RemotingCommand(SUCCESS_VALUE, pHead);
EXPECT_CALL(*pClient, invokeSync(_, _, _))
.Times(3)
.WillOnce(Return(nullptr))
.WillOnce(Return(pCommandFailed))
.WillOnce(Return(pCommandSuccuss));
EXPECT_ANY_THROW(impl->getMinOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc));
EXPECT_ANY_THROW(impl->getMinOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc));
int64 offset = impl->getMinOffset("127.0.0.0:10911", "testTopic", 0, 1000, sc);
EXPECT_EQ(2048, offset);
}
class MyMockAutoDeleteSendCallback : public AutoDeleteSendCallBack {
public:
virtual ~MyMockAutoDeleteSendCallback() {}
virtual void onSuccess(SendResult& sendResult) {
std::cout << "send Success" << std::endl;
return;
}
virtual void onException(MQException& e) {
std::cout << "send Exception" << e << std::endl;
return;
}
};
TEST(MQClientAPIImplTest, sendMessage) {
string cid = "testClientId";
SessionCredentials sc;
MockMQClientAPIImpl* impl = new MockMQClientAPIImpl("testMockAPIImpl", nullptr, 1, 2, 3, "testUnit");
Mock::AllowLeak(impl);
MockTcpRemotingClient* pClient = new MockTcpRemotingClient();
Mock::AllowLeak(pClient);
impl->reInitRemoteClient(pClient);
SendMessageResponseHeader* pHead = new SendMessageResponseHeader();
pHead->msgId = "MessageID";
pHead->queueId = 1;
pHead->queueOffset = 409600;
RemotingCommand* pCommandSync = new RemotingCommand(SUCCESS_VALUE, pHead);
EXPECT_CALL(*pClient, invokeSync(_, _, _)).Times(1).WillOnce(Return(pCommandSync));
MQMessage message("testTopic", "Hello, RocketMQ");
string unique_msgId = "UniqMessageID";
message.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, unique_msgId);
SendMessageRequestHeader* requestHeader = new SendMessageRequestHeader();
requestHeader->producerGroup = cid;
requestHeader->topic = (message.getTopic());
requestHeader->defaultTopic = DEFAULT_TOPIC;
requestHeader->defaultTopicQueueNums = 4;
requestHeader->bornTimestamp = UtilAll::currentTimeMillis();
SendResult result =
impl->sendMessage("127.0.0.0:10911", "testBroker", message, requestHeader, 100, 1, ComMode_SYNC, nullptr, sc);
EXPECT_EQ(result.getSendStatus(), SEND_OK);
EXPECT_EQ(result.getMsgId(), unique_msgId);
EXPECT_EQ(result.getQueueOffset(), 409600);
EXPECT_EQ(result.getOffsetMsgId(), "MessageID");
EXPECT_EQ(result.getMessageQueue().getBrokerName(), "testBroker");
EXPECT_EQ(result.getMessageQueue().getTopic(), "testTopic");
// Try to test Async send
EXPECT_CALL(*pClient, invokeAsync(_, _, _, _, _, _))
.Times(7)
.WillOnce(Return(false))
.WillOnce(Return(true))
.WillOnce(Return(false))
.WillOnce(Return(true))
.WillOnce(Return(false))
.WillOnce(Return(false))
.WillOnce(Return(false));
SendMessageRequestHeader* requestHeader2 = new SendMessageRequestHeader();
requestHeader2->producerGroup = cid;
requestHeader2->topic = (message.getTopic());
requestHeader2->defaultTopic = DEFAULT_TOPIC;
requestHeader2->defaultTopicQueueNums = 4;
requestHeader2->bornTimestamp = UtilAll::currentTimeMillis();
EXPECT_ANY_THROW(
impl->sendMessage("127.0.0.0:10911", "testBroker", message, requestHeader2, 100, 1, ComMode_ASYNC, nullptr, sc));
SendMessageRequestHeader* requestHeader3 = new SendMessageRequestHeader();
requestHeader3->producerGroup = cid;
requestHeader3->topic = (message.getTopic());
requestHeader3->defaultTopic = DEFAULT_TOPIC;
requestHeader3->defaultTopicQueueNums = 4;
requestHeader3->bornTimestamp = UtilAll::currentTimeMillis();
SendCallback* pSendCallback = new MyMockAutoDeleteSendCallback();
EXPECT_NO_THROW(impl->sendMessage("127.0.0.0:10911", "testBroker", message, requestHeader3, 100, 1, ComMode_ASYNC,
pSendCallback, sc));
SendMessageRequestHeader* requestHeader4 = new SendMessageRequestHeader();
requestHeader4->producerGroup = cid;
requestHeader4->topic = (message.getTopic());
requestHeader4->defaultTopic = DEFAULT_TOPIC;
requestHeader4->defaultTopicQueueNums = 4;
requestHeader4->bornTimestamp = UtilAll::currentTimeMillis();
SendCallback* pSendCallback2 = new MyMockAutoDeleteSendCallback();
EXPECT_NO_THROW(impl->sendMessage("127.0.0.0:10911", "testBroker", message, requestHeader4, 1000, 2, ComMode_ASYNC,
pSendCallback2, sc));
SendMessageRequestHeader* requestHeader5 = new SendMessageRequestHeader();
requestHeader5->producerGroup = cid;
requestHeader5->topic = (message.getTopic());
requestHeader5->defaultTopic = DEFAULT_TOPIC;
requestHeader5->defaultTopicQueueNums = 4;
requestHeader5->bornTimestamp = UtilAll::currentTimeMillis();
SendCallback* pSendCallback3 = new MyMockAutoDeleteSendCallback();
EXPECT_NO_THROW(impl->sendMessage("127.0.0.0:10911", "testBroker", message, requestHeader5, 1000, 3, ComMode_ASYNC,
pSendCallback3, sc));
}
TEST(MQClientAPIImplTest, consumerSendMessageBack) {
SessionCredentials sc;
MQMessageExt msg;
MockMQClientAPIImpl* impl = new MockMQClientAPIImpl("testMockAPIImpl", nullptr, 1, 2, 3, "testUnit");
Mock::AllowLeak(impl);
MockTcpRemotingClient* pClient = new MockTcpRemotingClient();
Mock::AllowLeak(pClient);
impl->reInitRemoteClient(pClient);
RemotingCommand* pCommandFailed = new RemotingCommand(SYSTEM_ERROR, nullptr);
RemotingCommand* pCommandSuccuss = new RemotingCommand(SUCCESS_VALUE, nullptr);
EXPECT_CALL(*pClient, invokeSync(_, _, _))
.Times(3)
.WillOnce(Return(nullptr))
.WillOnce(Return(pCommandFailed))
.WillOnce(Return(pCommandSuccuss));
EXPECT_ANY_THROW(impl->consumerSendMessageBack("127.0.0.0:10911", msg, "testGroup", 0, 1000, 16, sc));
EXPECT_ANY_THROW(impl->consumerSendMessageBack("127.0.0.0:10911", msg, "testGroup", 0, 1000, 16, sc));
EXPECT_NO_THROW(impl->consumerSendMessageBack("127.0.0.0:10911", msg, "testGroup", 0, 1000, 16, sc));
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "MQClientAPIImplTest.*";
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,132 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ConsumerRunningInfo.h"
#include "DefaultMQPushConsumerImpl.h"
#include "MQClientFactory.h"
using namespace std;
using namespace rocketmq;
using rocketmq::ConsumerRunningInfo;
using rocketmq::DefaultMQPushConsumerImpl;
using rocketmq::MQClientFactory;
using rocketmq::TopicRouteData;
using testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Mock;
using testing::Return;
class MockPushConsumerImpl : public DefaultMQPushConsumerImpl {
public:
MockPushConsumerImpl(const std::string& groupname) : DefaultMQPushConsumerImpl() {}
MOCK_METHOD0(getConsumerRunningInfo, ConsumerRunningInfo*());
};
class MockMQClientAPIImpl : public MQClientAPIImpl {
public:
MockMQClientAPIImpl(const string& mqClientId,
ClientRemotingProcessor* clientRemotingProcessor,
int pullThreadNum,
uint64_t tcpConnectTimeout,
uint64_t tcpTransportTryLockTimeout,
string unitName)
: MQClientAPIImpl(mqClientId, true, DEFAULT_SSL_PROPERTY_FILE) {}
MOCK_METHOD5(getMinOffset, int64(const string&, const string&, int, int, const SessionCredentials&));
MOCK_METHOD3(getTopicRouteInfoFromNameServer, TopicRouteData*(const string&, int, const SessionCredentials&));
};
class MockMQClientFactory : public MQClientFactory {
public:
MockMQClientFactory(const string& mqClientId,
int pullThreadNum,
uint64_t tcpConnectTimeout,
uint64_t tcpTransportTryLockTimeout,
string unitName)
: MQClientFactory(mqClientId, true, DEFAULT_SSL_PROPERTY_FILE) {}
void reInitClientImpl(MQClientAPIImpl* pImpl) { m_pClientAPIImpl.reset(pImpl); }
void addTestConsumer(const string& consumerName, MQConsumer* pMQConsumer) {
addConsumerToTable(consumerName, pMQConsumer);
}
};
TEST(MQClientFactoryTest, minOffset) {
string clientId = "testClientId";
int pullThreadNum = 1;
uint64_t tcpConnectTimeout = 3000;
uint64_t tcpTransportTryLockTimeout = 3000;
string unitName = "central";
MockMQClientFactory* factory =
new MockMQClientFactory(clientId, pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout, unitName);
MockMQClientAPIImpl* pImpl = new MockMQClientAPIImpl(clientId, nullptr, pullThreadNum, tcpConnectTimeout,
tcpTransportTryLockTimeout, unitName);
factory->reInitClientImpl(pImpl);
MQMessageQueue mq;
mq.setTopic("testTopic");
mq.setBrokerName("testBroker");
mq.setQueueId(1);
SessionCredentials session_credentials;
TopicRouteData* pData = new TopicRouteData();
pData->setOrderTopicConf("OrderTopicConf");
QueueData qd;
qd.brokerName = "testBroker";
qd.readQueueNums = 8;
qd.writeQueueNums = 8;
qd.perm = 1;
pData->getQueueDatas().push_back(qd);
BrokerData bd;
bd.brokerName = "testBroker";
bd.brokerAddrs[0] = "127.0.0.1:10091";
bd.brokerAddrs[1] = "127.0.0.2:10092";
pData->getBrokerDatas().push_back(bd);
EXPECT_CALL(*pImpl, getMinOffset(_, _, _, _, _)).Times(1).WillOnce(Return(1024));
EXPECT_CALL(*pImpl, getTopicRouteInfoFromNameServer(_, _, _)).Times(1).WillOnce(Return(pData));
int64 offset = factory->minOffset(mq, session_credentials);
EXPECT_EQ(1024, offset);
delete factory;
}
TEST(MQClientFactoryTest, consumerRunningInfo) {
string clientId = "testClientId";
int pullThreadNum = 1;
uint64_t tcpConnectTimeout = 3000;
uint64_t tcpTransportTryLockTimeout = 3000;
string unitName = "central";
MockMQClientFactory* factory =
new MockMQClientFactory(clientId, pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout, unitName);
MockPushConsumerImpl* mockPushConsumer = new MockPushConsumerImpl(clientId);
Mock::AllowLeak(mockPushConsumer);
factory->addTestConsumer(clientId, mockPushConsumer);
ConsumerRunningInfo* info = new ConsumerRunningInfo();
info->setJstack("Hello,JStack");
EXPECT_CALL(*mockPushConsumer, getConsumerRunningInfo()).Times(1).WillOnce(Return(info));
ConsumerRunningInfo* info2 = factory->consumerRunningInfo(clientId);
EXPECT_EQ(info2->getJstack(), "Hello,JStack");
delete factory;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQClientManager.h"
using namespace std;
using namespace rocketmq;
using rocketmq::MQClientFactory;
using rocketmq::MQClientManager;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
TEST(MQClientManagerTest, getClientFactory) {
string clientId = "testClientId";
string unitName = "central";
MQClientFactory* factory = MQClientManager::getInstance()->getMQClientFactory(clientId, 1, 1000, 3000, unitName, true,
DEFAULT_SSL_PROPERTY_FILE);
MQClientFactory* factory2 = MQClientManager::getInstance()->getMQClientFactory(clientId, 1, 1000, 3000, unitName,
true, DEFAULT_SSL_PROPERTY_FILE);
EXPECT_EQ(factory, factory2);
factory->shutdown();
MQClientManager::getInstance()->removeClientFactory(clientId);
}
TEST(MQClientManagerTest, removeClientFactory) {
string clientId = "testClientId";
MQClientManager::getInstance()->removeClientFactory(clientId);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,60 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ClientRPCHook.h"
#include "CommandHeader.h"
#include "RemotingCommand.h"
#include "SessionCredentials.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::RemotingCommand;
using rocketmq::SendMessageRequestHeader;
using rocketmq::SessionCredentials;
using rocketmq::ClientRPCHook;
TEST(clientRPCHook, doBeforeRequest) {
SessionCredentials sessionCredentials;
sessionCredentials.setAccessKey("accessKey");
sessionCredentials.setSecretKey("secretKey");
sessionCredentials.setAuthChannel("onsChannel");
ClientRPCHook clientRPCHook(sessionCredentials);
RemotingCommand remotingCommand;
clientRPCHook.doBeforeRequest("127.0.0.1:9876", remotingCommand);
SendMessageRequestHeader* sendMessageRequestHeader = new SendMessageRequestHeader();
RemotingCommand headeRremotingCommand(17, sendMessageRequestHeader);
clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
headeRremotingCommand.setMsgBody("1231231");
clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "clientRPCHook.doBeforeRequest";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,45 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQVersion.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQVersion;
using rocketmq::RocketMQCPPClientVersion;
TEST(MQVersionTest, Version2String) {
for (int v = MQVersion::V3_0_0_SNAPSHOT; v <= MQVersion::HIGHER_VERSION; v++) {
EXPECT_STREQ(MQVersion::GetVersionDesc(v), RocketMQCPPClientVersion[v]);
}
EXPECT_STREQ(MQVersion::GetVersionDesc(-100), MQVersion::GetVersionDesc(MQVersion::V3_0_0_SNAPSHOT));
EXPECT_STREQ(MQVersion::GetVersionDesc(MQVersion::V4_6_0), "V4_6_0");
EXPECT_STREQ(MQVersion::GetVersionDesc(MQVersion::HIGHER_VERSION + 100),
MQVersion::GetVersionDesc(MQVersion::HIGHER_VERSION));
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "MQVersionTest.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,175 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "dataBlock.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MemoryBlock;
TEST(memoryBlock, init) {
MemoryBlock memoryBlock;
EXPECT_EQ(memoryBlock.getSize(), 0);
EXPECT_TRUE(memoryBlock.getData() == nullptr);
MemoryBlock twoMemoryBlock(-1, true);
EXPECT_EQ(twoMemoryBlock.getSize(), 0);
EXPECT_TRUE(twoMemoryBlock.getData() == nullptr);
MemoryBlock threeMemoryBlock(10, true);
EXPECT_EQ(threeMemoryBlock.getSize(), 10);
EXPECT_TRUE(threeMemoryBlock.getData() != nullptr);
MemoryBlock frouMemoryBlock(12, false);
EXPECT_EQ(frouMemoryBlock.getSize(), 12);
EXPECT_TRUE(frouMemoryBlock.getData() != nullptr);
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryBlock fiveMemoryBlock(buf, 0);
EXPECT_EQ(fiveMemoryBlock.getSize(), 0);
EXPECT_TRUE(fiveMemoryBlock.getData() == nullptr);
char* bufNull = NULL;
MemoryBlock sixMemoryBlock(bufNull, 16);
EXPECT_EQ(sixMemoryBlock.getSize(), 16);
EXPECT_TRUE(sixMemoryBlock.getData() != nullptr);
buf = (char*)realloc(buf, 20);
MemoryBlock sevenMemoryBlock(buf, 20);
EXPECT_EQ(sevenMemoryBlock.getSize(), 20);
sevenMemoryBlock.getData();
EXPECT_EQ(string(sevenMemoryBlock.getData()), string(buf));
MemoryBlock nineMemoryBlock(sevenMemoryBlock);
EXPECT_EQ(nineMemoryBlock.getSize(), sevenMemoryBlock.getSize());
EXPECT_EQ(string(nineMemoryBlock.getData()), string(sevenMemoryBlock.getData()));
MemoryBlock eightMemoryBlock(fiveMemoryBlock);
EXPECT_EQ(eightMemoryBlock.getSize(), fiveMemoryBlock.getSize());
EXPECT_TRUE(eightMemoryBlock.getData() == nullptr);
free(buf);
}
TEST(memoryBlock, operators) {
MemoryBlock memoryBlock(12, false);
MemoryBlock operaterMemoryBlock = memoryBlock;
EXPECT_TRUE(operaterMemoryBlock == memoryBlock);
char* buf = (char*)malloc(sizeof(char) * 16);
memset(buf, 0, 16);
strcpy(buf, "RocketMQ");
MemoryBlock twoMemoryBlock(buf, 12);
EXPECT_FALSE(memoryBlock == twoMemoryBlock);
MemoryBlock threeMemoryBlock(buf, 16);
EXPECT_FALSE(memoryBlock == threeMemoryBlock);
EXPECT_TRUE(twoMemoryBlock != threeMemoryBlock);
threeMemoryBlock.fillWith(49);
EXPECT_EQ(string(threeMemoryBlock.getData(), 16), "1111111111111111");
threeMemoryBlock.reset();
EXPECT_EQ(threeMemoryBlock.getSize(), 0);
EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
threeMemoryBlock.setSize(16, 0);
EXPECT_EQ(threeMemoryBlock.getSize(), 16);
// EXPECT_EQ(threeMemoryBlock.getData() , buf);
threeMemoryBlock.setSize(0, 0);
EXPECT_EQ(threeMemoryBlock.getSize(), 0);
EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
MemoryBlock appendMemoryBlock;
EXPECT_EQ(appendMemoryBlock.getSize(), 0);
EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
appendMemoryBlock.append(buf, -1);
EXPECT_EQ(appendMemoryBlock.getSize(), 0);
EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
appendMemoryBlock.append(buf, 8);
EXPECT_EQ(appendMemoryBlock.getSize(), 8);
MemoryBlock replaceWithMemoryBlock;
replaceWithMemoryBlock.append(buf, 8);
char* aliyunBuf = (char*)malloc(sizeof(char) * 8);
memset(aliyunBuf, 0, 8);
strcpy(aliyunBuf, "aliyun");
replaceWithMemoryBlock.replaceWith(aliyunBuf, 0);
EXPECT_EQ(replaceWithMemoryBlock.getSize(), 8);
EXPECT_EQ(string(replaceWithMemoryBlock.getData(), 8), "RocketMQ");
replaceWithMemoryBlock.replaceWith(aliyunBuf, 6);
EXPECT_EQ(replaceWithMemoryBlock.getSize(), 6);
EXPECT_EQ(string(replaceWithMemoryBlock.getData(), strlen(aliyunBuf)), "aliyun");
MemoryBlock insertMemoryBlock;
insertMemoryBlock.append(buf, 8);
insertMemoryBlock.insert(aliyunBuf, -1, -1);
EXPECT_EQ(string(insertMemoryBlock.getData(), 8), "RocketMQ");
/* MemoryBlock fourInsertMemoryBlock;
fourInsertMemoryBlock.append(buf , 8);
// 6+ (-1)
fourInsertMemoryBlock.insert(aliyunBuf , 8 , -1);
string fourStr( fourInsertMemoryBlock.getData());
EXPECT_TRUE( fourStr == "liyun");*/
MemoryBlock twoInsertMemoryBlock;
twoInsertMemoryBlock.append(buf, 8);
twoInsertMemoryBlock.insert(aliyunBuf, strlen(aliyunBuf), 0);
EXPECT_EQ(string(twoInsertMemoryBlock.getData(), 8 + strlen(aliyunBuf)), "aliyunRocketMQ");
MemoryBlock threeInsertMemoryBlock;
threeInsertMemoryBlock.append(buf, 8);
threeInsertMemoryBlock.insert(aliyunBuf, 6, 100);
EXPECT_EQ(string(threeInsertMemoryBlock.getData(), 8 + strlen(aliyunBuf)), "RocketMQaliyun");
MemoryBlock removeSectionMemoryBlock(buf, 8);
removeSectionMemoryBlock.removeSection(8, -1);
EXPECT_EQ(string(removeSectionMemoryBlock.getData(), 8), "RocketMQ");
MemoryBlock twoRemoveSectionMemoryBlock(buf, 8);
twoRemoveSectionMemoryBlock.removeSection(1, 4);
string str(twoRemoveSectionMemoryBlock.getData(), 4);
EXPECT_TRUE(str == "RtMQ");
free(buf);
free(aliyunBuf);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "memoryBlock.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,224 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MemoryInputStream.h"
#include "MemoryOutputStream.h"
#include "dataBlock.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MemoryBlock;
using rocketmq::MemoryInputStream;
using rocketmq::MemoryOutputStream;
TEST(memoryOutputStream, init) {
MemoryOutputStream memoryOutput;
EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
EXPECT_TRUE(memoryOutput.getData() != nullptr);
EXPECT_EQ(memoryOutput.getPosition(), 0);
EXPECT_EQ(memoryOutput.getDataSize(), 0);
MemoryOutputStream twoMemoryOutput(512);
EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
MemoryBlock memoryBlock(12, false);
MemoryOutputStream threeMemoryOutput(memoryBlock, false);
EXPECT_EQ(threeMemoryOutput.getPosition(), 0);
EXPECT_EQ(threeMemoryOutput.getDataSize(), 0);
MemoryOutputStream frouMemoryOutput(memoryBlock, true);
EXPECT_EQ(frouMemoryOutput.getPosition(), memoryBlock.getSize());
EXPECT_EQ(frouMemoryOutput.getDataSize(), memoryBlock.getSize());
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryOutputStream fiveMemoryOutputStream(buf, 8);
EXPECT_EQ(fiveMemoryOutputStream.getData(), buf);
fiveMemoryOutputStream.reset();
EXPECT_EQ(memoryOutput.getPosition(), 0);
EXPECT_EQ(memoryOutput.getDataSize(), 0);
free(buf);
}
TEST(memoryOutputStream, flush) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryOutputStream memoryOutput;
memoryOutput.write(buf, 9);
memoryOutput.flush();
EXPECT_FALSE(memoryOutput.getData() == buf);
free(buf);
}
TEST(memoryOutputStream, preallocate) {
MemoryOutputStream memoryOutput;
memoryOutput.preallocate(250);
memoryOutput.preallocate(256);
}
TEST(memoryOutputStream, getMemoryBlock) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryOutputStream memoryOutput;
memoryOutput.write(buf, 9);
MemoryBlock memoryBlock = memoryOutput.getMemoryBlock();
EXPECT_EQ(memoryBlock.getSize(), memoryOutput.getDataSize());
free(buf);
}
TEST(memoryOutputStream, prepareToWriteAndGetData) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryOutputStream memoryOutput(buf, 9);
EXPECT_EQ(memoryOutput.getData(), buf);
// prepareToWrite
// EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
EXPECT_TRUE(memoryOutput.writeByte('r'));
const char* data = static_cast<const char*>(memoryOutput.getData());
EXPECT_EQ(string(data), "rocketMQ");
MemoryOutputStream blockMmoryOutput(8);
char* memoryData = (char*)blockMmoryOutput.getData();
EXPECT_EQ(memoryData[blockMmoryOutput.getDataSize()], 0);
blockMmoryOutput.write(buf, 8);
blockMmoryOutput.write(buf, 8);
data = static_cast<const char*>(blockMmoryOutput.getData());
EXPECT_EQ(string(data), "rocketMQrocketMQ");
free(buf);
}
TEST(memoryOutputStream, position) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryOutputStream memoryOutput;
EXPECT_EQ(memoryOutput.getPosition(), 0);
memoryOutput.write(buf, 8);
EXPECT_EQ(memoryOutput.getPosition(), 8);
EXPECT_FALSE(memoryOutput.setPosition(9));
EXPECT_TRUE(memoryOutput.setPosition(-1));
EXPECT_EQ(memoryOutput.getPosition(), 0);
EXPECT_TRUE(memoryOutput.setPosition(8));
EXPECT_EQ(memoryOutput.getPosition(), 8);
EXPECT_TRUE(memoryOutput.setPosition(7));
EXPECT_EQ(memoryOutput.getPosition(), 7);
free(buf);
}
TEST(memoryOutputStream, write) {
MemoryOutputStream memoryOutput;
MemoryInputStream memoryInput(memoryOutput.getData(), 256, false);
EXPECT_TRUE(memoryOutput.writeBool(true));
EXPECT_TRUE(memoryInput.readBool());
EXPECT_TRUE(memoryOutput.writeBool(false));
EXPECT_FALSE(memoryInput.readBool());
EXPECT_TRUE(memoryOutput.writeByte('a'));
EXPECT_EQ(memoryInput.readByte(), 'a');
EXPECT_TRUE(memoryOutput.writeShortBigEndian(128));
EXPECT_EQ(memoryInput.readShortBigEndian(), 128);
EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
EXPECT_EQ(memoryInput.readIntBigEndian(), 123);
EXPECT_TRUE(memoryOutput.writeInt64BigEndian(123123));
EXPECT_EQ(memoryInput.readInt64BigEndian(), 123123);
EXPECT_TRUE(memoryOutput.writeDoubleBigEndian(12.71));
EXPECT_EQ(memoryInput.readDoubleBigEndian(), 12.71);
EXPECT_TRUE(memoryOutput.writeFloatBigEndian(12.1));
float f = 12.1;
EXPECT_EQ(memoryInput.readFloatBigEndian(), f);
// EXPECT_TRUE(memoryOutput.writeRepeatedByte(8 , 8));
}
TEST(memoryInputStream, info) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryInputStream memoryInput(buf, 8, false);
char* memoryData = (char*)memoryInput.getData();
EXPECT_EQ(memoryData, buf);
EXPECT_EQ(memoryInput.getTotalLength(), 8);
MemoryInputStream twoMemoryInput(buf, 8, true);
EXPECT_NE(twoMemoryInput.getData(), buf);
memoryData = (char*)twoMemoryInput.getData();
EXPECT_NE(&memoryData, &buf);
MemoryBlock memoryBlock(buf, 8);
MemoryInputStream threeMemoryInput(memoryBlock, false);
memoryData = (char*)threeMemoryInput.getData();
EXPECT_EQ(memoryData, threeMemoryInput.getData());
EXPECT_EQ(threeMemoryInput.getTotalLength(), 8);
MemoryInputStream frouMemoryInput(memoryBlock, true);
EXPECT_NE(frouMemoryInput.getData(), memoryBlock.getData());
free(buf);
}
TEST(memoryInputStream, position) {
char* buf = (char*)malloc(sizeof(char) * 9);
strcpy(buf, "RocketMQ");
MemoryInputStream memoryInput(buf, 8, false);
EXPECT_EQ(memoryInput.getPosition(), 0);
EXPECT_FALSE(memoryInput.isExhausted());
memoryInput.setPosition(9);
EXPECT_EQ(memoryInput.getPosition(), 8);
EXPECT_TRUE(memoryInput.isExhausted());
memoryInput.setPosition(-1);
EXPECT_EQ(memoryInput.getPosition(), 0);
free(buf);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "*.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,95 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "NameSpaceUtil.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::NameSpaceUtil;
TEST(NameSpaceUtil, isEndPointURL) {
const string url = "http://rocketmq.nameserver.com";
EXPECT_TRUE(NameSpaceUtil::isEndPointURL(url));
EXPECT_FALSE(NameSpaceUtil::isEndPointURL("rocketmq.nameserver.com"));
EXPECT_FALSE(NameSpaceUtil::isEndPointURL("127.0.0.1"));
}
TEST(NameSpaceUtil, formatNameServerURL) {
string url = "http://rocketmq.nameserver.com";
string urlFormatted = "rocketmq.nameserver.com";
EXPECT_EQ(NameSpaceUtil::formatNameServerURL(url), urlFormatted);
EXPECT_EQ(NameSpaceUtil::formatNameServerURL(urlFormatted), urlFormatted);
}
TEST(NameSpaceUtil, getNameSpaceFromNsURL) {
string url = "http://MQ_INST_UNITTEST.rocketmq.nameserver.com";
string url2 = "MQ_INST_UNITTEST.rocketmq.nameserver.com";
string noInstUrl = "http://rocketmq.nameserver.com";
string inst = "MQ_INST_UNITTEST";
EXPECT_EQ(NameSpaceUtil::getNameSpaceFromNsURL(url), inst);
EXPECT_EQ(NameSpaceUtil::getNameSpaceFromNsURL(url2), inst);
EXPECT_EQ(NameSpaceUtil::getNameSpaceFromNsURL(noInstUrl), "");
}
TEST(NameSpaceUtil, checkNameSpaceExistInNsURL) {
string url = "http://MQ_INST_UNITTEST.rocketmq.nameserver.com";
string url2 = "MQ_INST_UNITTEST.rocketmq.nameserver.com";
string noInstUrl = "http://rocketmq.nameserver.com";
EXPECT_TRUE(NameSpaceUtil::checkNameSpaceExistInNsURL(url));
EXPECT_FALSE(NameSpaceUtil::checkNameSpaceExistInNsURL(url2));
EXPECT_FALSE(NameSpaceUtil::checkNameSpaceExistInNsURL(noInstUrl));
}
TEST(NameSpaceUtil, checkNameSpaceExistInNameServer) {
string url = "http://MQ_INST_UNITTEST.rocketmq.nameserver.com";
string url2 = "MQ_INST_UNITTEST.rocketmq.nameserver.com";
string noInstUrl = "rocketmq.nameserver.com";
string nsIP = "127.0.0.1";
EXPECT_TRUE(NameSpaceUtil::checkNameSpaceExistInNameServer(url));
EXPECT_TRUE(NameSpaceUtil::checkNameSpaceExistInNameServer(url2));
EXPECT_FALSE(NameSpaceUtil::checkNameSpaceExistInNameServer(noInstUrl));
EXPECT_FALSE(NameSpaceUtil::checkNameSpaceExistInNameServer(nsIP));
}
TEST(NameSpaceUtil, withNameSpace) {
string source = "testTopic";
string ns = "MQ_INST_UNITTEST";
string nsSource = "MQ_INST_UNITTEST%testTopic";
EXPECT_EQ(NameSpaceUtil::withNameSpace(source, ns), nsSource);
EXPECT_EQ(NameSpaceUtil::withNameSpace(source, ""), source);
}
TEST(NameSpaceUtil, hasNameSpace) {
string source = "testTopic";
string ns = "MQ_INST_UNITTEST";
string nsSource = "MQ_INST_UNITTEST%testTopic";
string nsTraceSource = "rmq_sys_TRACE_DATA_Region";
EXPECT_TRUE(NameSpaceUtil::hasNameSpace(nsSource, ns));
EXPECT_FALSE(NameSpaceUtil::hasNameSpace(source, ns));
EXPECT_FALSE(NameSpaceUtil::hasNameSpace(source, ""));
EXPECT_TRUE(NameSpaceUtil::hasNameSpace(nsTraceSource, ns));
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "NameSpaceUtil.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,50 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "NamesrvConfig.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::NamesrvConfig;
TEST(namesrvConfig, init) {
NamesrvConfig namesrvConfig;
const string home = "/home/rocketmq";
namesrvConfig.setRocketmqHome(home);
EXPECT_EQ(namesrvConfig.getRocketmqHome(), "/home/rocketmq");
namesrvConfig.setKvConfigPath("/home/rocketmq");
EXPECT_EQ(namesrvConfig.getKvConfigPath(), "/home/rocketmq");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "namesrvConfig.init";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,46 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "PermName.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::PermName;
TEST(permName, perm2String) {
EXPECT_EQ(PermName::perm2String(0), "---");
EXPECT_EQ(PermName::perm2String(1), "--X");
EXPECT_EQ(PermName::perm2String(2), "-W");
EXPECT_EQ(PermName::perm2String(3), "-WX");
EXPECT_EQ(PermName::perm2String(4), "R--");
EXPECT_EQ(PermName::perm2String(5), "R-X");
EXPECT_EQ(PermName::perm2String(6), "RW");
EXPECT_EQ(PermName::perm2String(7), "RWX");
EXPECT_EQ(PermName::perm2String(8), "---");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "permName.perm2String";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,95 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "PullSysFlag.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::PullSysFlag;
TEST(pullSysFlag, flag) {
EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, false), 0);
EXPECT_EQ(PullSysFlag::buildSysFlag(true, false, false, false), 1);
EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, false, false), 3);
EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, false), 7);
EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, true), 15);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, false, false), 2);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, false), 6);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, true), 14);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, false), 4);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, true), 12);
EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, true), 8);
int FLAG_COMMIT_OFFSET = 0x1 << 0;
int FLAG_SUSPEND = 0x1 << 1;
int FLAG_SUBSCRIPTION = 0x1 << 2;
int FLAG_CLASS_FILTER = 0x1 << 3;
for (int i = 0; i < 16; i++) {
if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
} else {
EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
}
if ((i & FLAG_SUSPEND) == FLAG_SUSPEND) {
EXPECT_TRUE(PullSysFlag::hasSuspendFlag(i));
} else {
EXPECT_FALSE(PullSysFlag::hasSuspendFlag(i));
}
if ((i & FLAG_SUBSCRIPTION) == FLAG_SUBSCRIPTION) {
EXPECT_TRUE(PullSysFlag::hasSubscriptionFlag(i));
} else {
EXPECT_FALSE(PullSysFlag::hasSubscriptionFlag(i));
}
if ((i & FLAG_CLASS_FILTER) == FLAG_CLASS_FILTER) {
EXPECT_TRUE(PullSysFlag::hasClassFilterFlag(i));
} else {
EXPECT_FALSE(PullSysFlag::hasClassFilterFlag(i));
}
if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
} else {
EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
}
if (i == 0 || i == 1) {
EXPECT_EQ(PullSysFlag::clearCommitOffsetFlag(i), 0);
} else {
EXPECT_TRUE(PullSysFlag::clearCommitOffsetFlag(i) > 0);
}
}
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "pullSysFlag.flag";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,93 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "PermName.h"
#include "TopicConfig.h"
#include "TopicFilterType.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::PermName;
using rocketmq::TopicConfig;
using rocketmq::TopicFilterType;
TEST(topicConfig, encodeAndDecode) {
TopicConfig topicConfig("testTopic", 4, 4, PermName::PERM_READ);
string str = topicConfig.encode();
TopicConfig topicDecodeConfig;
topicDecodeConfig.decode(str);
EXPECT_EQ(str, topicDecodeConfig.encode());
}
TEST(topicConfig, info) {
TopicConfig topicConfig;
topicConfig.setTopicName("testTopic");
EXPECT_EQ(topicConfig.getTopicName(), "testTopic");
topicConfig.setReadQueueNums(4);
EXPECT_EQ(topicConfig.getReadQueueNums(), 4);
topicConfig.setWriteQueueNums(4);
EXPECT_EQ(topicConfig.getWriteQueueNums(), 4);
topicConfig.setPerm(PermName::PERM_READ);
EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ);
topicConfig.setTopicFilterType(TopicFilterType::MULTI_TAG);
EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::MULTI_TAG);
}
TEST(topicConfig, init) {
TopicConfig topicConfig;
EXPECT_TRUE(topicConfig.getTopicName() == "");
EXPECT_EQ(topicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
EXPECT_EQ(topicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
TopicConfig twoTopicConfig("testTopic");
EXPECT_EQ(twoTopicConfig.getTopicName(), "testTopic");
EXPECT_EQ(twoTopicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
EXPECT_EQ(twoTopicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
EXPECT_EQ(twoTopicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
EXPECT_EQ(twoTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
TopicConfig threeTopicConfig("testTopic", 4, 4, PermName::PERM_READ);
EXPECT_EQ(threeTopicConfig.getTopicName(), "testTopic");
EXPECT_EQ(threeTopicConfig.getReadQueueNums(), 4);
EXPECT_EQ(threeTopicConfig.getWriteQueueNums(), 4);
EXPECT_EQ(threeTopicConfig.getPerm(), PermName::PERM_READ);
EXPECT_EQ(threeTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "topicConfig.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,76 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <unistd.h>
#include "CCommon.h"
#include "CMQException.h"
#include "CMessage.h"
#include "CProducer.h"
#include "CSendResult.h"
#include "TopicConfig.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "url.h"
#include <stdio.h>
#include <unistd.h>
#include "CCommon.h"
#include "CMQException.h"
#include "CMessage.h"
#include "CProducer.h"
#include "CSendResult.h"
using namespace std;
using rocketmq::TopicConfig;
using rocketmq::Url;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
class MockTopicConfig : public TopicConfig {
public:
MOCK_METHOD0(getReadQueueNums, int());
};
TEST(Url, Url) {
Url url_s("172.17.0.2:9876");
EXPECT_EQ(url_s.protocol_, "172.17.0.2:9876");
Url url_z("https://www.aliyun.com/RocketMQ?5.0");
EXPECT_EQ(url_z.protocol_, "https");
EXPECT_EQ(url_z.host_, "www.aliyun.com");
EXPECT_EQ(url_z.port_, "80");
EXPECT_EQ(url_z.path_, "/RocketMQ");
EXPECT_EQ(url_z.query_, "5.0");
Url url_path("https://www.aliyun.com:9876/RocketMQ?5.0");
EXPECT_EQ(url_path.port_, "9876");
MockTopicConfig topicConfig;
EXPECT_CALL(topicConfig, getReadQueueNums()).WillRepeatedly(Return(-1));
int nums = topicConfig.getReadQueueNums();
cout << nums << endl;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "Url.Url";
int itestts = RUN_ALL_TESTS();
;
return itestts;
}

View File

@@ -0,0 +1,120 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "UtilAll.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::UtilAll;
TEST(UtilAll, startsWith_retry) {
string source = "testTopic";
string retrySource = "%RETRY%testTopic";
string noRetrySource = "%DLQ%testTopic";
EXPECT_TRUE(UtilAll::startsWith_retry(retrySource));
EXPECT_FALSE(UtilAll::startsWith_retry(source));
EXPECT_FALSE(UtilAll::startsWith_retry(noRetrySource));
}
TEST(UtilAll, getRetryTopic) {
string source = "testTopic";
string retrySource = "%RETRY%testTopic";
EXPECT_EQ(UtilAll::getRetryTopic(source), retrySource);
}
TEST(UtilAll, Trim) {
string source = "testTopic";
string preSource = " testTopic";
string surSource = "testTopic ";
string allSource = " testTopic ";
UtilAll::Trim(preSource);
UtilAll::Trim(surSource);
UtilAll::Trim(allSource);
EXPECT_EQ(preSource, source);
EXPECT_EQ(surSource, source);
EXPECT_EQ(allSource, source);
}
TEST(UtilAll, hexstr2ull) {
const char* a = "1";
const char* b = "FF";
const char* c = "1a";
const char* d = "101";
EXPECT_EQ(UtilAll::hexstr2ull(a), 1);
EXPECT_EQ(UtilAll::hexstr2ull(b), 255);
EXPECT_EQ(UtilAll::hexstr2ull(c), 26);
EXPECT_EQ(UtilAll::hexstr2ull(d), 257);
}
TEST(UtilAll, SplitURL) {
string source = "127.0.0.1";
string source1 = "127.0.0.1:0";
string source2 = "127.0.0.1:9876";
string addr;
string addr1;
string addr2;
short port;
EXPECT_FALSE(UtilAll::SplitURL(source, addr, port));
EXPECT_FALSE(UtilAll::SplitURL(source1, addr1, port));
EXPECT_TRUE(UtilAll::SplitURL(source2, addr2, port));
EXPECT_EQ(addr2, "127.0.0.1");
EXPECT_EQ(port, 9876);
}
TEST(UtilAll, SplitOne) {
string source = "127.0.0.1:9876";
vector<string> ret;
EXPECT_EQ(UtilAll::Split(ret, source, '.'), 4);
EXPECT_EQ(ret[0], "127");
}
TEST(UtilAll, SplitStr) {
string source = "11AA222AA3333AA44444AA5";
vector<string> ret;
EXPECT_EQ(UtilAll::Split(ret, source, "AA"), 5);
EXPECT_EQ(ret[0], "11");
}
TEST(UtilAll, StringToInt32) {
string source = "123";
int value;
EXPECT_TRUE(UtilAll::StringToInt32(source, value));
EXPECT_EQ(123, value);
EXPECT_FALSE(UtilAll::StringToInt32("123456789X123456789", value));
EXPECT_FALSE(UtilAll::StringToInt32("-1234567890123456789", value));
EXPECT_FALSE(UtilAll::StringToInt32("1234567890123456789", value));
}
TEST(UtilAll, StringToInt64) {
string source = "123";
int64_t value;
EXPECT_TRUE(UtilAll::StringToInt64(source, value));
EXPECT_EQ(123, value);
EXPECT_FALSE(UtilAll::StringToInt64("XXXXXXXXXXX", value));
EXPECT_FALSE(UtilAll::StringToInt64("123456789X123456789", value));
EXPECT_EQ(123456789, value);
EXPECT_FALSE(UtilAll::StringToInt64("-123456789012345678901234567890123456789012345678901234567890", value));
EXPECT_FALSE(UtilAll::StringToInt64("123456789012345678901234567890123456789012345678901234567890", value));
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "UtilAll.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,82 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQClientException.h"
#include "MQMessage.h"
#include "Validators.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQClientException;
using rocketmq::MQMessage;
using rocketmq::Validators;
TEST(validators, regularExpressionMatcher) {
EXPECT_FALSE(Validators::regularExpressionMatcher(string(), string()));
EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string()));
EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string("123")));
}
TEST(validators, getGroupWithRegularExpression) {
EXPECT_EQ(Validators::getGroupWithRegularExpression(string(), string()), "");
}
TEST(validators, checkTopic) {
EXPECT_THROW(Validators::checkTopic(string()), MQClientException);
string exceptionTopic = "1234567890";
for (int i = 0; i < 25; i++) {
exceptionTopic.append("1234567890");
}
EXPECT_THROW(Validators::checkTopic(exceptionTopic), MQClientException);
EXPECT_THROW(Validators::checkTopic("TBW102"), MQClientException);
}
TEST(validators, checkGroup) {
EXPECT_THROW(Validators::checkGroup(string()), MQClientException);
string exceptionTopic = "1234567890";
for (int i = 0; i < 25; i++) {
exceptionTopic.append("1234567890");
}
EXPECT_THROW(Validators::checkGroup(exceptionTopic), MQClientException);
}
TEST(validators, checkMessage) {
MQMessage message("testTopic", string());
EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string()), 1), MQClientException);
EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string("123")), 2), MQClientException);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "validators.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,64 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "VirtualEnvUtil.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::VirtualEnvUtil;
TEST(virtualEnvUtil, buildWithProjectGroup) {
string origin = "origin";
string originWithGroupA = "origin%PROJECT_testGroupA%";
string originWithGroupB = "origin%PROJECT_testGroupB%";
string originWithGroupAB = "origin%PROJECT_testGroupA%%PROJECT_testGroupB%";
string projectGroupA = "testGroupA";
string projectGroupB = "testGroupB";
EXPECT_EQ(VirtualEnvUtil::buildWithProjectGroup(origin, string()), origin);
EXPECT_EQ(VirtualEnvUtil::buildWithProjectGroup(origin, projectGroupA), originWithGroupA);
EXPECT_EQ(VirtualEnvUtil::buildWithProjectGroup(originWithGroupA, projectGroupA), originWithGroupA);
EXPECT_EQ(VirtualEnvUtil::buildWithProjectGroup(originWithGroupA, projectGroupB), originWithGroupAB);
}
TEST(virtualEnvUtil, clearProjectGroup) {
string origin = "origin";
string originWithGroup = "origin%PROJECT_testGroup%";
string projectGroup = "testGroup";
string projectGroupB = "testGroupB";
EXPECT_EQ(VirtualEnvUtil::clearProjectGroup(origin, string()), origin);
EXPECT_EQ(VirtualEnvUtil::clearProjectGroup(originWithGroup, string()), originWithGroup);
EXPECT_EQ(VirtualEnvUtil::clearProjectGroup(originWithGroup, projectGroupB), originWithGroup);
EXPECT_EQ(VirtualEnvUtil::clearProjectGroup(origin, projectGroup), origin);
EXPECT_EQ(VirtualEnvUtil::clearProjectGroup(originWithGroup, projectGroup), origin);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "virtualEnvUtil.*";
int iTest = RUN_ALL_TESTS();
return iTest;
}

View File

@@ -0,0 +1,100 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "big_endian.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::BigEndianReader;
using rocketmq::BigEndianWriter;
TEST(big_endian, bigEndianObject) {
char* buf = (char*)malloc(sizeof(char) * 32);
BigEndianWriter writer(buf, 32);
BigEndianReader reader(buf, 32);
uint8_t* unit8 = (uint8_t*)malloc(sizeof(uint8_t));
EXPECT_TRUE(writer.WriteU8((uint8_t)12));
EXPECT_TRUE(reader.ReadU8(unit8));
EXPECT_EQ(*unit8, 12);
free(unit8);
uint16_t* unit16 = (uint16_t*)malloc(sizeof(uint16_t));
EXPECT_TRUE(writer.WriteU16((uint16_t)1200));
EXPECT_TRUE(reader.ReadU16(unit16));
EXPECT_EQ(*unit16, 1200);
free(unit16);
uint32_t* unit32 = (uint32_t*)malloc(sizeof(uint32_t));
EXPECT_TRUE(writer.WriteU32((uint32_t)120000));
EXPECT_TRUE(reader.ReadU32(unit32));
EXPECT_EQ(*unit32, 120000);
free(unit32);
uint64_t* unit64 = (uint64_t*)malloc(sizeof(uint64_t));
EXPECT_TRUE(writer.WriteU64((uint64_t)120000));
EXPECT_TRUE(reader.ReadU64(unit64));
EXPECT_EQ(*unit64, 120000);
free(unit64);
char* newBuf = (char*)malloc(sizeof(char) * 8);
char* writeBuf = (char*)malloc(sizeof(char) * 8);
strncpy(writeBuf, "RocketMQ", 8);
EXPECT_TRUE(writer.WriteBytes(writeBuf, (size_t)8));
EXPECT_TRUE(reader.ReadBytes(newBuf, (size_t)8));
EXPECT_EQ(*writeBuf, *newBuf);
free(newBuf);
free(writeBuf);
}
TEST(big_endian, bigEndian) {
char writeBuf[8];
/*TODO
char *newBuf = (char *) malloc(sizeof(char) * 8);
strncpy(newBuf, "RocketMQ", 8);
char readBuf[8];
rocketmq::WriteBigEndian(writeBuf, newBuf);
rocketmq::ReadBigEndian(writeBuf, readBuf);
EXPECT_EQ(writeBuf, readBuf);
*/
rocketmq::WriteBigEndian(writeBuf, (uint8_t)12);
uint8_t* out = (uint8_t*)malloc(sizeof(uint8_t));
rocketmq::ReadBigEndian(writeBuf, out);
EXPECT_EQ(*out, 12);
free(out);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "big_endian.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,119 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ConsumeMessageContext.h"
#include "ConsumeMessageHookImpl.h"
#include "DefaultMQProducerImpl.h"
#include "DefaultMQPushConsumerImpl.h"
#include "MQMessageExt.h"
#include "MQMessageQueue.h"
using namespace std;
using namespace rocketmq;
using rocketmq::DefaultMQProducerImpl;
using rocketmq::DefaultMQPushConsumerImpl;
using testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
class MockDefaultMQProducerImpl : public DefaultMQProducerImpl {
public:
MockDefaultMQProducerImpl(const string& groupId) : DefaultMQProducerImpl(groupId) {}
MOCK_METHOD3(send, void(MQMessage&, SendCallback*, bool));
};
TEST(DefaultMQPushConsumerImplTest, init) {
DefaultMQPushConsumerImpl* impl = new DefaultMQPushConsumerImpl("testMQConsumerGroup");
EXPECT_EQ(impl->getGroupName(), "testMQConsumerGroup");
impl->setUnitName("testUnit");
EXPECT_EQ(impl->getUnitName(), "testUnit");
impl->setTcpTransportPullThreadNum(64);
EXPECT_EQ(impl->getTcpTransportPullThreadNum(), 64);
impl->setTcpTransportConnectTimeout(2000);
EXPECT_EQ(impl->getTcpTransportConnectTimeout(), 2000);
impl->setTcpTransportTryLockTimeout(3000);
EXPECT_EQ(impl->getTcpTransportTryLockTimeout(), 3);
impl->setNamesrvAddr("http://rocketmq.nameserver.com");
EXPECT_EQ(impl->getNamesrvAddr(), "rocketmq.nameserver.com");
impl->setNameSpace("MQ_INST_NAMESPACE_TEST");
EXPECT_EQ(impl->getNameSpace(), "MQ_INST_NAMESPACE_TEST");
impl->setMessageTrace(true);
EXPECT_TRUE(impl->getMessageTrace());
impl->setAsyncPull(true);
impl->setConsumeMessageBatchMaxSize(3000);
EXPECT_EQ(impl->getConsumeMessageBatchMaxSize(), 3000);
impl->setConsumeThreadCount(3);
EXPECT_EQ(impl->getConsumeThreadCount(), 3);
impl->setMaxReconsumeTimes(30);
EXPECT_EQ(impl->getMaxReconsumeTimes(), 30);
impl->setMaxCacheMsgSizePerQueue(3000);
EXPECT_EQ(impl->getMaxCacheMsgSizePerQueue(), 3000);
impl->setPullMsgThreadPoolCount(10);
EXPECT_EQ(impl->getPullMsgThreadPoolCount(), 10);
}
TEST(DefaultMQPushConsumerImpl, Trace) {
DefaultMQPushConsumerImpl* impl = new DefaultMQPushConsumerImpl();
MockDefaultMQProducerImpl* implProducer = new MockDefaultMQProducerImpl("testMockProducerTraceGroup");
std::shared_ptr<ConsumeMessageHook> hook(new ConsumeMessageHookImpl());
impl->setMessageTrace(true);
impl->setDefaultMqProducerImpl(implProducer);
impl->registerConsumeMessageHook(hook);
EXPECT_CALL(*implProducer, send(_, _, _)).WillRepeatedly(Return());
ConsumeMessageContext consumeMessageContext;
MQMessageQueue messageQueue("TestTopic", "BrokerA", 0);
MQMessageExt messageExt;
messageExt.setMsgId("MessageID");
messageExt.setKeys("MessageKey");
vector<MQMessageExt> msgs;
consumeMessageContext.setDefaultMQPushConsumer(impl);
consumeMessageContext.setConsumerGroup("testMockProducerTraceGroup");
consumeMessageContext.setMessageQueue(messageQueue);
consumeMessageContext.setMsgList(msgs);
consumeMessageContext.setSuccess(false);
consumeMessageContext.setNameSpace("NameSpace");
impl->executeConsumeMessageHookBefore(&consumeMessageContext);
impl->executeConsumeMessageHookAfter(&consumeMessageContext);
msgs.push_back(messageExt);
consumeMessageContext.setMsgList(msgs);
impl->executeConsumeMessageHookBefore(&consumeMessageContext);
consumeMessageContext.setMsgIndex(0);
consumeMessageContext.setStatus("CONSUME_SUCCESS");
consumeMessageContext.setSuccess(true);
impl->executeConsumeMessageHookAfter(&consumeMessageContext);
EXPECT_TRUE(impl->hasConsumeMessageHook());
delete implProducer;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,106 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CCommon.h"
#include "CMessageExt.h"
#include "MQMessageExt.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessageExt;
TEST(cmessageExt, info) {
MQMessageExt* mqMessageExt = new MQMessageExt();
CMessageExt* messageExt = (CMessageExt*)mqMessageExt;
mqMessageExt->setTopic("testTopic");
EXPECT_EQ(GetMessageTopic(messageExt), mqMessageExt->getTopic());
mqMessageExt->setTags("testTags");
EXPECT_EQ(GetMessageTags(messageExt), mqMessageExt->getTags());
mqMessageExt->setKeys("testKeys");
EXPECT_EQ(GetMessageKeys(messageExt), mqMessageExt->getKeys());
mqMessageExt->setBody("testBody");
EXPECT_EQ(GetMessageBody(messageExt), mqMessageExt->getBody());
mqMessageExt->setProperty("testKey", "testValues");
EXPECT_EQ(GetMessageProperty(messageExt, "testKey"), mqMessageExt->getProperty("testKey"));
mqMessageExt->setMsgId("msgId123456");
EXPECT_EQ(GetMessageId(messageExt), mqMessageExt->getMsgId());
mqMessageExt->setDelayTimeLevel(1);
EXPECT_EQ(GetMessageDelayTimeLevel(messageExt), mqMessageExt->getDelayTimeLevel());
mqMessageExt->setQueueId(4);
EXPECT_EQ(GetMessageQueueId(messageExt), mqMessageExt->getQueueId());
mqMessageExt->setReconsumeTimes(1234567);
EXPECT_EQ(GetMessageReconsumeTimes(messageExt), mqMessageExt->getReconsumeTimes());
mqMessageExt->setStoreSize(127);
EXPECT_EQ(GetMessageStoreSize(messageExt), mqMessageExt->getStoreSize());
mqMessageExt->setBornTimestamp(9876543);
EXPECT_EQ(GetMessageBornTimestamp(messageExt), mqMessageExt->getBornTimestamp());
mqMessageExt->setStoreTimestamp(123123);
EXPECT_EQ(GetMessageStoreTimestamp(messageExt), mqMessageExt->getStoreTimestamp());
mqMessageExt->setQueueOffset(1024);
EXPECT_EQ(GetMessageQueueOffset(messageExt), mqMessageExt->getQueueOffset());
mqMessageExt->setCommitLogOffset(2048);
EXPECT_EQ(GetMessageCommitLogOffset(messageExt), mqMessageExt->getCommitLogOffset());
mqMessageExt->setPreparedTransactionOffset(4096);
EXPECT_EQ(GetMessagePreparedTransactionOffset(messageExt), mqMessageExt->getPreparedTransactionOffset());
delete mqMessageExt;
}
TEST(cmessageExt, null) {
EXPECT_TRUE(GetMessageTopic(NULL) == NULL);
EXPECT_TRUE(GetMessageTags(NULL) == NULL);
EXPECT_TRUE(GetMessageKeys(NULL) == NULL);
EXPECT_TRUE(GetMessageBody(NULL) == NULL);
EXPECT_TRUE(GetMessageProperty(NULL, NULL) == NULL);
EXPECT_TRUE(GetMessageId(NULL) == NULL);
EXPECT_EQ(GetMessageDelayTimeLevel(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageQueueId(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageReconsumeTimes(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageStoreSize(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageBornTimestamp(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageStoreTimestamp(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageQueueOffset(NULL), NULL_POINTER);
EXPECT_EQ(GetMessageCommitLogOffset(NULL), NULL_POINTER);
EXPECT_EQ(GetMessagePreparedTransactionOffset(NULL), NULL_POINTER);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "cmessageExt.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,111 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CCommon.h"
#include "CMessage.h"
#include "MQMessage.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessage;
TEST(cmessages, originMessage) {
CMessage* message = CreateMessage(NULL);
EXPECT_STREQ(GetOriginMessageTopic(message), "");
SetMessageTopic(message, "testTopic");
EXPECT_STREQ(GetOriginMessageTopic(message), "testTopic");
SetMessageTags(message, "testTags");
EXPECT_STREQ(GetOriginMessageTags(message), "testTags");
SetMessageKeys(message, "testKeys");
EXPECT_STREQ(GetOriginMessageKeys(message), "testKeys");
SetMessageBody(message, "testBody");
EXPECT_STREQ(GetOriginMessageBody(message), "testBody");
SetMessageProperty(message, "testKey", "testValue");
EXPECT_STREQ(GetOriginMessageProperty(message, "testKey"), "testValue");
SetDelayTimeLevel(message, 1);
EXPECT_EQ(GetOriginDelayTimeLevel(message), 1);
EXPECT_EQ(DestroyMessage(message), OK);
CMessage* message2 = CreateMessage("testTwoTopic");
EXPECT_STREQ(GetOriginMessageTopic(message2), "testTwoTopic");
EXPECT_EQ(DestroyMessage(message2), OK);
}
TEST(cmessages, info) {
CMessage* message = CreateMessage(NULL);
MQMessage* mqMessage = (MQMessage*)message;
EXPECT_EQ(mqMessage->getTopic(), "");
SetMessageTopic(message, "testTopic");
EXPECT_EQ(mqMessage->getTopic(), "testTopic");
SetMessageTags(message, "testTags");
EXPECT_EQ(mqMessage->getTags(), "testTags");
SetMessageKeys(message, "testKeys");
EXPECT_EQ(mqMessage->getKeys(), "testKeys");
SetMessageBody(message, "testBody");
EXPECT_EQ(mqMessage->getBody(), "testBody");
SetByteMessageBody(message, "testBody", 5);
EXPECT_EQ(mqMessage->getBody(), "testB");
SetMessageProperty(message, "testKey", "testValue");
EXPECT_EQ(mqMessage->getProperty("testKey"), "testValue");
SetDelayTimeLevel(message, 1);
EXPECT_EQ(mqMessage->getDelayTimeLevel(), 1);
EXPECT_EQ(DestroyMessage(message), OK);
CMessage* twomessage = CreateMessage("testTwoTopic");
MQMessage* twoMqMessage = (MQMessage*)twomessage;
EXPECT_EQ(twoMqMessage->getTopic(), "testTwoTopic");
EXPECT_EQ(DestroyMessage(twomessage), OK);
}
TEST(cmessages, null) {
EXPECT_EQ(SetMessageTopic(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetMessageTags(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetMessageKeys(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetMessageBody(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetByteMessageBody(NULL, NULL, 0), NULL_POINTER);
EXPECT_EQ(SetMessageProperty(NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetDelayTimeLevel(NULL, 0), NULL_POINTER);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
// testing::GTEST_FLAG(filter) = "cmessages.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,275 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CMessage.h"
#include "CProducer.h"
#include "CSendResult.h"
#include "AsyncCallback.h"
#include "DefaultMQProducer.h"
#include "MQMessage.h"
#include "MQMessageQueue.h"
#include "MQSelector.h"
#include "SendResult.h"
#include "SessionCredentials.h"
using std::string;
using ::testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Mock;
using testing::Return;
using rocketmq::DefaultMQProducer;
using rocketmq::elogLevel;
using rocketmq::MessageQueueSelector;
using rocketmq::MQMessage;
using rocketmq::MQMessageQueue;
using rocketmq::SendCallback;
using rocketmq::SendResult;
using rocketmq::SendStatus;
using rocketmq::SessionCredentials;
class MockDefaultMQProducer : public DefaultMQProducer {
public:
MockDefaultMQProducer(const string& groupname) : DefaultMQProducer(groupname) {}
MOCK_METHOD0(start, void());
MOCK_METHOD0(shutdown, void());
MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
MOCK_METHOD1(SetProducerLogLevel, void(elogLevel));
MOCK_METHOD2(send, SendResult(MQMessage&, bool));
MOCK_METHOD3(send, void(MQMessage&, SendCallback*, bool));
MOCK_METHOD2(sendOneway, void(MQMessage&, bool));
MOCK_METHOD5(send, SendResult(MQMessage&, MessageQueueSelector*, void*, int, bool));
};
void CSendSuccessCallbackFunc(CSendResult result) {}
void cSendExceptionCallbackFunc(CMQException e) {}
TEST(cProducer, SendMessageAsync) {
MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
CProducer* cProducer = CreateProducer("testGroup");
// cProducer= mockProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
aProducer[0] = mockProducer;
CMessage* msg = (CMessage*)new MQMessage();
EXPECT_EQ(SendMessageAsync(NULL, NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageAsync(cProducer, NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageAsync(cProducer, msg, CSendSuccessCallbackFunc, NULL), NULL_POINTER);
// EXPECT_CALL(*mockProducer, send(_, _)).Times(1);
EXPECT_EQ(SendMessageAsync(cProducer, msg, CSendSuccessCallbackFunc, cSendExceptionCallbackFunc), OK);
Mock::AllowLeak(mockProducer);
DestroyMessage(msg);
}
int QueueSelectorCallbackFunc(int size, CMessage* msg, void* arg) {
return 0;
}
TEST(cProducer, sendMessageOrderly) {
MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
// CProducer* cProducer = (CProducer*)mockProducer;
CProducer* cProducer = CreateOrderlyProducer("testGroup");
// cProducer= mockProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
aProducer[0] = mockProducer;
CMessage* msg = (CMessage*)new MQMessage();
MQMessageQueue messageQueue;
EXPECT_EQ(SendMessageOrderly(NULL, NULL, NULL, msg, 1, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageOrderly(cProducer, NULL, NULL, msg, 1, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageOrderly(cProducer, msg, NULL, msg, 1, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageOrderly(cProducer, msg, QueueSelectorCallbackFunc, NULL, 1, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageOrderly(cProducer, msg, QueueSelectorCallbackFunc, msg, 1, NULL), NULL_POINTER);
EXPECT_CALL(*mockProducer, send(_, _, _, _, _))
.WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)));
// EXPECT_EQ(SendMessageOrderly(cProducer, msg, callback, msg, 1, result), OK);
Mock::AllowLeak(mockProducer);
DestroyMessage(msg);
// free(result);
}
TEST(cProducer, sendOneway) {
MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
// CProducer* cProducer = (CProducer*)mockProducer;
CProducer* cProducer = CreateProducer("testGroup");
// cProducer= mockProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
aProducer[0] = mockProducer;
CMessage* msg = (CMessage*)new MQMessage();
EXPECT_EQ(SendMessageOneway(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageOneway(cProducer, NULL), NULL_POINTER);
EXPECT_CALL(*mockProducer, sendOneway(_, _)).Times(1);
EXPECT_EQ(SendMessageOneway(cProducer, msg), OK);
Mock::AllowLeak(mockProducer);
DestroyMessage(msg);
}
TEST(cProducer, sendMessageSync) {
MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
// CProducer* cProducer = (CProducer*)mockProducer;
CProducer* cProducer = CreateProducer("testGroup");
// cProducer= mockProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
aProducer[0] = mockProducer;
MQMessage* mqMessage = new MQMessage();
CMessage* msg = (CMessage*)mqMessage;
CSendResult* result;
MQMessageQueue messageQueue;
EXPECT_EQ(SendMessageSync(NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageSync(cProducer, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SendMessageSync(cProducer, msg, NULL), NULL_POINTER);
result = (CSendResult*)malloc(sizeof(CSendResult));
EXPECT_CALL(*mockProducer, send(_, _))
.Times(5)
.WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_DISK_TIMEOUT, "1", "offset1", messageQueue, 14)))
.WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_SLAVE_TIMEOUT, "2", "offset1", messageQueue, 14)))
.WillOnce(Return(SendResult(SendStatus::SEND_SLAVE_NOT_AVAILABLE, "3", "offset1", messageQueue, 14)))
.WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)))
.WillOnce(Return(SendResult((SendStatus)-1, "4", "offset1", messageQueue, 14)));
EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_DISK_TIMEOUT);
EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_SLAVE_TIMEOUT);
EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
EXPECT_EQ(result->sendStatus, E_SEND_SLAVE_NOT_AVAILABLE);
EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
EXPECT_EQ(result->sendStatus, E_SEND_OK);
EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
EXPECT_EQ(result->sendStatus, E_SEND_OK);
Mock::AllowLeak(mockProducer);
DestroyMessage(msg);
free(result);
}
TEST(cProducer, infoMock) {
MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
// CProducer* cProducer = (CProducer*)mockProducer;
CProducer* cProducer = CreateProducer("testGroup");
// cProducer= mockProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
aProducer[0] = mockProducer;
EXPECT_CALL(*mockProducer, start()).Times(1);
EXPECT_EQ(StartProducer(cProducer), OK);
EXPECT_CALL(*mockProducer, shutdown()).Times(1);
EXPECT_EQ(ShutdownProducer(cProducer), OK);
EXPECT_CALL(*mockProducer, setLogFileSizeAndNum(_, _)).Times(1);
EXPECT_EQ(SetProducerLogFileNumAndSize(cProducer, 1, 1), OK);
EXPECT_CALL(*mockProducer, SetProducerLogLevel(_)).Times(1);
EXPECT_EQ(SetProducerLogLevel(cProducer, E_LOG_LEVEL_FATAL), OK);
Mock::AllowLeak(mockProducer);
}
TEST(cProducer, info) {
CProducer* cProducer = CreateProducer("groupTest");
// DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)cProducer;
DefaultMQProducer** aProducer = (DefaultMQProducer**)cProducer;
DefaultMQProducer* defaultMQProducer = aProducer[0];
EXPECT_TRUE(cProducer != NULL);
EXPECT_EQ(defaultMQProducer->getGroupName(), "groupTest");
EXPECT_EQ(SetProducerNameServerAddress(cProducer, "127.0.0.1:9876"), OK);
EXPECT_EQ(defaultMQProducer->getNamesrvAddr(), "127.0.0.1:9876");
EXPECT_EQ(SetProducerNameServerDomain(cProducer, "domain"), OK);
EXPECT_EQ(defaultMQProducer->getNamesrvDomain(), "domain");
EXPECT_EQ(SetProducerGroupName(cProducer, "testGroup"), OK);
EXPECT_EQ(defaultMQProducer->getGroupName(), "testGroup");
EXPECT_EQ(SetProducerInstanceName(cProducer, "instance"), OK);
EXPECT_EQ(defaultMQProducer->getInstanceName(), "instance");
EXPECT_EQ(SetProducerSendMsgTimeout(cProducer, 1), OK);
EXPECT_EQ(defaultMQProducer->getSendMsgTimeout(), 1);
EXPECT_EQ(SetProducerMaxMessageSize(cProducer, 2), OK);
EXPECT_EQ(defaultMQProducer->getMaxMessageSize(), 2);
EXPECT_EQ(SetProducerCompressLevel(cProducer, 1), OK);
EXPECT_EQ(defaultMQProducer->getCompressLevel(), 1);
EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerSessionCredentials(cProducer, "accessKey", "secretKey", "channel"), OK);
SessionCredentials sessionCredentials = defaultMQProducer->getSessionCredentials();
EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
EXPECT_EQ(SetProducerMessageTrace(cProducer, OPEN), OK);
EXPECT_EQ(defaultMQProducer->getMessageTrace(), true);
Mock::AllowLeak(defaultMQProducer);
}
TEST(cProducer, null) {
EXPECT_TRUE(CreateProducer(NULL) == NULL);
EXPECT_EQ(StartProducer(NULL), NULL_POINTER);
EXPECT_EQ(ShutdownProducer(NULL), NULL_POINTER);
EXPECT_EQ(SetProducerNameServerAddress(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerNameServerDomain(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerGroupName(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerInstanceName(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
EXPECT_EQ(SetProducerSendMsgTimeout(NULL, 1), NULL_POINTER);
EXPECT_EQ(SetProducerCompressLevel(NULL, 1), NULL_POINTER);
EXPECT_EQ(SetProducerMaxMessageSize(NULL, 2), NULL_POINTER);
EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
EXPECT_EQ(DestroyProducer(NULL), NULL_POINTER);
}
TEST(cProducer, version) {
CProducer* cProducer = CreateProducer("groupTestVersion");
EXPECT_TRUE(cProducer != NULL);
string version(ShowProducerVersion(cProducer));
EXPECT_GT(version.length(), 0);
CProducer* cProducer2 = CreateOrderlyProducer("orderGroupTestVersion");
EXPECT_TRUE(cProducer2 != NULL);
string version2(ShowProducerVersion(cProducer2));
EXPECT_GT(version2.length(), 0);
CProducer* cProducer3 = CreateTransactionProducer("tranGroupTestVersion", NULL, NULL);
EXPECT_TRUE(cProducer3 != NULL);
string version3(ShowProducerVersion(cProducer3));
EXPECT_GT(version3.length(), 0);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "cProducer.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,211 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CCommon.h"
#include "CPullConsumer.h"
#include "DefaultMQPullConsumer.h"
#include "MQClient.h"
#include "MQMessageExt.h"
#include "MQMessageQueue.h"
#include "PullResult.h"
#include "SessionCredentials.h"
using std::string;
using std::vector;
using ::testing::_;
using testing::Expectation;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using testing::SetArgReferee;
using rocketmq::DefaultMQPullConsumer;
using rocketmq::elogLevel;
using rocketmq::MessageModel;
using rocketmq::MQMessageExt;
using rocketmq::MQMessageQueue;
using rocketmq::PullResult;
using rocketmq::PullStatus;
using rocketmq::SessionCredentials;
class MockDefaultMQPullConsumer : public DefaultMQPullConsumer {
public:
MockDefaultMQPullConsumer(const string& groupname) : DefaultMQPullConsumer(groupname) {}
MOCK_METHOD0(start, void());
MOCK_METHOD0(shutdown, void());
MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
MOCK_METHOD1(setLogLevel, void(elogLevel));
MOCK_METHOD2(fetchSubscribeMessageQueues, void(const string&, vector<MQMessageQueue>&));
MOCK_METHOD4(pull, PullResult(const MQMessageQueue&, const string&, int64, int));
};
TEST(cpullConsumer, pull) {
MockDefaultMQPullConsumer* mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
CPullConsumer* pullConsumer = (CPullConsumer*)mqPullConsumer;
CMessageQueue cMessageQueue;
strncpy(cMessageQueue.topic, "testTopic", 8);
strncpy(cMessageQueue.brokerName, "testBroker", 9);
cMessageQueue.queueId = 1;
PullResult timeOutPullResult(PullStatus::BROKER_TIMEOUT, 1, 2, 3);
PullResult noNewMsgPullResult(PullStatus::NO_NEW_MSG, 1, 2, 3);
PullResult noMatchedMsgPullResult(PullStatus::NO_MATCHED_MSG, 1, 2, 3);
PullResult offsetIllegalPullResult(PullStatus::OFFSET_ILLEGAL, 1, 2, 3);
PullResult defaultPullResult((PullStatus)-1, 1, 2, 3);
vector<MQMessageExt> src;
for (int i = 0; i < 5; i++) {
MQMessageExt ext;
src.push_back(ext);
}
PullResult foundPullResult(PullStatus::FOUND, 1, 2, 3, src);
EXPECT_CALL(*mqPullConsumer, pull(_, _, _, _))
.WillOnce(Return(timeOutPullResult))
.WillOnce(Return(noNewMsgPullResult))
.WillOnce(Return(noMatchedMsgPullResult))
.WillOnce(Return(offsetIllegalPullResult))
.WillOnce(Return(defaultPullResult))
//.WillOnce(Return(timeOutPullResult)) //will not called
.WillOnce(Return(foundPullResult));
CPullResult timeOutcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(timeOutcPullResult.pullStatus, E_BROKER_TIMEOUT);
CPullResult noNewMsgcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(noNewMsgcPullResult.pullStatus, E_NO_NEW_MSG);
CPullResult noMatchedMsgcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(noMatchedMsgcPullResult.pullStatus, E_NO_MATCHED_MSG);
CPullResult offsetIllegalcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(offsetIllegalcPullResult.pullStatus, E_OFFSET_ILLEGAL);
CPullResult defaultcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(defaultcPullResult.pullStatus, E_NO_NEW_MSG);
CPullResult exceptionPullResult = Pull(pullConsumer, &cMessageQueue, NULL, 0, 0);
EXPECT_EQ(exceptionPullResult.pullStatus, E_BROKER_TIMEOUT);
CPullResult foundcPullResult = Pull(pullConsumer, &cMessageQueue, "123123", 0, 0);
EXPECT_EQ(foundcPullResult.pullStatus, E_FOUND);
delete mqPullConsumer;
}
TEST(cpullConsumer, infoMock) {
MockDefaultMQPullConsumer* mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
CPullConsumer* pullConsumer = (CPullConsumer*)mqPullConsumer;
Expectation exp = EXPECT_CALL(*mqPullConsumer, start()).Times(1);
EXPECT_EQ(StartPullConsumer(pullConsumer), OK);
EXPECT_CALL(*mqPullConsumer, shutdown()).Times(1);
EXPECT_EQ(ShutdownPullConsumer(pullConsumer), OK);
// EXPECT_CALL(*mqPullConsumer,setLogFileSizeAndNum(_,_)).Times(1);
EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer, 1, 2), OK);
// EXPECT_CALL(*mqPullConsumer,setLogLevel(_)).Times(1);
EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_INFO), OK);
std::vector<MQMessageQueue> fullMQ;
for (int i = 0; i < 5; i++) {
MQMessageQueue queue("testTopic", "testsBroker", i);
fullMQ.push_back(queue);
}
EXPECT_CALL(*mqPullConsumer, fetchSubscribeMessageQueues(_, _)).Times(1).WillOnce(SetArgReferee<1>(fullMQ));
CMessageQueue* mqs = NULL;
int size = 0;
FetchSubscriptionMessageQueues(pullConsumer, "testTopic", &mqs, &size);
EXPECT_EQ(size, 5);
delete mqPullConsumer;
}
TEST(cpullConsumer, init) {
CPullConsumer* pullConsumer = CreatePullConsumer("testGroupId");
DefaultMQPullConsumer* defaultMQPullConsumer = (DefaultMQPullConsumer*)pullConsumer;
EXPECT_FALSE(pullConsumer == NULL);
EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
// EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
}
TEST(cpullConsumer, null) {
CPullConsumer* pullConsumer = CreatePullConsumer("testGroupId");
DefaultMQPullConsumer* defaultMQPullConsumer = (DefaultMQPullConsumer*)pullConsumer;
EXPECT_FALSE(pullConsumer == NULL);
EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
// EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
EXPECT_EQ(DestroyPullConsumer(pullConsumer), OK);
EXPECT_EQ(StartPullConsumer(NULL), NULL_POINTER);
EXPECT_EQ(ShutdownPullConsumer(NULL), NULL_POINTER);
}
TEST(cpullConsumer, version) {
CPullConsumer* pullConsumer = CreatePullConsumer("groupTestVersion");
EXPECT_TRUE(pullConsumer != NULL);
string version(ShowPullConsumerVersion(pullConsumer));
EXPECT_GT(version.length(), 0);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "cpullConsumer.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,163 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CPushConsumer.h"
#include "ConsumeType.h"
#include "DefaultMQPushConsumer.h"
#include "MQMessageListener.h"
#include "SessionCredentials.h"
using std::string;
using ::testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Mock;
using testing::Return;
using rocketmq::DefaultMQPushConsumer;
using rocketmq::elogLevel;
using rocketmq::MessageListenerType;
using rocketmq::MessageModel;
using rocketmq::SessionCredentials;
class MockDefaultMQPushConsumer : public DefaultMQPushConsumer {
public:
MockDefaultMQPushConsumer(const string& groupname) : DefaultMQPushConsumer(groupname) {}
MOCK_METHOD0(start, void());
MOCK_METHOD0(shutdown, void());
MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
MOCK_METHOD1(setLogLevel, void(elogLevel));
};
TEST(cPushComsumer, infomock) {
MockDefaultMQPushConsumer* pushComsumer = new MockDefaultMQPushConsumer("testGroup");
CPushConsumer* consumer = (CPushConsumer*)pushComsumer;
EXPECT_CALL(*pushComsumer, start()).Times(1);
EXPECT_EQ(StartPushConsumer(consumer), OK);
EXPECT_CALL(*pushComsumer, shutdown()).Times(1);
EXPECT_EQ(ShutdownPushConsumer(consumer), OK);
EXPECT_CALL(*pushComsumer, setLogFileSizeAndNum(1, 1)).Times(1);
pushComsumer->setLogFileSizeAndNum(1, 1);
EXPECT_EQ(SetPushConsumerLogFileNumAndSize(consumer, 1, 1), OK);
// EXPECT_CALL(*pushComsumer,setLogLevel(_)).Times(1);
EXPECT_EQ(SetPushConsumerLogLevel(consumer, E_LOG_LEVEL_FATAL), OK);
Mock::AllowLeak(pushComsumer);
}
int MessageCallBackFunc(CPushConsumer* consumer, CMessageExt* msg) {
return 0;
}
TEST(cPushComsumer, info) {
CPushConsumer* cpushConsumer = CreatePushConsumer("testGroup");
DefaultMQPushConsumer* mqPushConsumer = (DefaultMQPushConsumer*)cpushConsumer;
EXPECT_TRUE(cpushConsumer != NULL);
EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroup");
EXPECT_EQ(SetPushConsumerGroupID(cpushConsumer, "testGroupTwo"), OK);
EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroupTwo");
EXPECT_EQ(SetPushConsumerNameServerAddress(cpushConsumer, "127.0.0.1:9876"), OK);
EXPECT_EQ(mqPushConsumer->getNamesrvAddr(), "127.0.0.1:9876");
EXPECT_EQ(SetPushConsumerNameServerDomain(cpushConsumer, "domain"), OK);
EXPECT_EQ(mqPushConsumer->getNamesrvDomain(), "domain");
EXPECT_EQ(Subscribe(cpushConsumer, "testTopic", "testSub"), OK);
EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, MessageCallBackFunc), OK);
EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerOrderly);
EXPECT_EQ(RegisterMessageCallback(cpushConsumer, MessageCallBackFunc), OK);
EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerConcurrently);
EXPECT_EQ(UnregisterMessageCallbackOrderly(cpushConsumer), OK);
EXPECT_EQ(UnregisterMessageCallback(cpushConsumer), OK);
EXPECT_EQ(SetPushConsumerThreadCount(cpushConsumer, 10), OK);
EXPECT_EQ(mqPushConsumer->getConsumeThreadCount(), 10);
EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(cpushConsumer, 1024), OK);
EXPECT_EQ(mqPushConsumer->getConsumeMessageBatchMaxSize(), 1024);
EXPECT_EQ(SetPushConsumerInstanceName(cpushConsumer, "instance"), OK);
EXPECT_EQ(mqPushConsumer->getInstanceName(), "instance");
EXPECT_EQ(SetPushConsumerSessionCredentials(cpushConsumer, "accessKey", "secretKey", "channel"), OK);
SessionCredentials sessionCredentials = mqPushConsumer->getSessionCredentials();
EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
EXPECT_EQ(SetPushConsumerMessageModel(cpushConsumer, BROADCASTING), OK);
EXPECT_EQ(mqPushConsumer->getMessageModel(), MessageModel::BROADCASTING);
EXPECT_EQ(SetPushConsumerMessageTrace(cpushConsumer, CLOSE), OK);
EXPECT_EQ(mqPushConsumer->getMessageTrace(), false);
Mock::AllowLeak(mqPushConsumer);
}
TEST(cPushComsumer, null) {
CPushConsumer* cpushConsumer = CreatePushConsumer("testGroup");
EXPECT_TRUE(CreatePushConsumer(NULL) == NULL);
EXPECT_EQ(DestroyPushConsumer(NULL), NULL_POINTER);
EXPECT_EQ(StartPushConsumer(NULL), NULL_POINTER);
EXPECT_EQ(ShutdownPushConsumer(NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerGroupID(NULL, "testGroup"), NULL_POINTER);
EXPECT_TRUE(GetPushConsumerGroupID(NULL) == NULL);
EXPECT_EQ(SetPushConsumerNameServerAddress(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerNameServerDomain(NULL, NULL), NULL_POINTER);
EXPECT_EQ(Subscribe(NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(RegisterMessageCallbackOrderly(NULL, NULL), NULL_POINTER);
EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, NULL), NULL_POINTER);
EXPECT_EQ(RegisterMessageCallback(NULL, NULL), NULL_POINTER);
EXPECT_EQ(UnregisterMessageCallbackOrderly(NULL), NULL_POINTER);
EXPECT_EQ(UnregisterMessageCallback(NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerThreadCount(NULL, 0), NULL_POINTER);
EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(NULL, 0), NULL_POINTER);
EXPECT_EQ(SetPushConsumerInstanceName(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerLogPath(NULL, NULL), NULL_POINTER);
EXPECT_EQ(SetPushConsumerLogFileNumAndSize(NULL, 1, 1), NULL_POINTER);
EXPECT_EQ(SetPushConsumerLogLevel(NULL, E_LOG_LEVEL_LEVEL_NUM), NULL_POINTER);
EXPECT_EQ(SetPushConsumerMessageModel(NULL, BROADCASTING), NULL_POINTER);
}
TEST(cPushComsumer, version) {
CPushConsumer* pushConsumer = CreatePushConsumer("groupTestVersion");
EXPECT_TRUE(pushConsumer != NULL);
string version(ShowPushConsumerVersion(pushConsumer));
EXPECT_GT(version.length(), 0);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "cPushComsumer.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,72 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include "BatchMessage.h"
#include "MQMessage.h"
#include <map>
using namespace std;
using namespace rocketmq;
using ::testing::InitGoogleTest;
using ::testing::InitGoogleMock;
using testing::Return;
TEST(BatchMessageEncodeTest, encodeMQMessage) {
MQMessage msg1("topic", "*", "test");
// const map<string,string>& properties = msg1.getProperties();
// for (auto& pair : properties) {
// std::cout << pair.first << " : " << pair.second << std::endl;
//}
EXPECT_EQ(msg1.getProperties().size(), 2);
EXPECT_EQ(msg1.getBody().size(), 4);
// 20 + bodyLen + 2 + propertiesLength;
string encodeMessage = BatchMessage::encode(msg1);
EXPECT_EQ(encodeMessage.size(), 43);
msg1.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, "1");
encodeMessage = BatchMessage::encode(msg1);
EXPECT_EQ(encodeMessage.size(), 54);
}
TEST(BatchMessageEncodeTest, encodeMQMessages) {
std::vector<MQMessage> msgs;
MQMessage msg1("topic", "*", "test1");
// const map<string,string>& properties = msg1.getProperties();
// for (auto& pair : properties) {
// std::cout << pair.first << " : " << pair.second << std::endl;
//}
msgs.push_back(msg1);
// 20 + bodyLen + 2 + propertiesLength;
string encodeMessage = BatchMessage::encode(msgs);
EXPECT_EQ(encodeMessage.size(), 86);
MQMessage msg2("topic", "*", "test2");
MQMessage msg3("topic", "*", "test3");
msgs.push_back(msg2);
msgs.push_back(msg3);
encodeMessage = BatchMessage::encode(msgs);
EXPECT_EQ(encodeMessage.size(), 258); // 86*3
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,205 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MemoryInputStream.h"
#include "MemoryOutputStream.h"
#include "CommandHeader.h"
#include "MQDecoder.h"
#include "MQMessage.h"
#include "MQMessageExt.h"
#include "MQMessageId.h"
#include "MessageSysFlag.h"
#include "RemotingCommand.h"
#include "UtilAll.h"
using namespace std;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MemoryBlock;
using rocketmq::MemoryInputStream;
using rocketmq::MemoryOutputStream;
using rocketmq::MessageSysFlag;
using rocketmq::MQDecoder;
using rocketmq::MQMessage;
using rocketmq::MQMessageExt;
using rocketmq::MQMessageId;
using rocketmq::RemotingCommand;
using rocketmq::SendMessageRequestHeader;
using rocketmq::UtilAll;
// TODO
TEST(decoder, messageId) {
int host;
int port;
int64 offset = 1234567890;
string msgIdStr =
MQDecoder::createMessageId(rocketmq::IPPort2socketAddress(ntohl(inet_addr("127.0.0.1")), 10091), offset);
MQMessageId msgId = MQDecoder::decodeMessageId(msgIdStr);
EXPECT_EQ(msgId.getOffset(), offset);
rocketmq::socketAddress2IPPort(msgId.getAddress(), host, port);
EXPECT_EQ(host, ntohl(inet_addr("127.0.0.1")));
EXPECT_EQ(port, 10091);
}
TEST(decoder, decoder) {
MQMessageExt mext;
MemoryOutputStream* memoryOut = new MemoryOutputStream(1024);
// 1 TOTALSIZE 4
memoryOut->writeIntBigEndian(107);
mext.setStoreSize(107);
// 2 MAGICCODE sizeof(int) 8=4+4
memoryOut->writeIntBigEndian(14);
// 3 BODYCRC 12=8+4
memoryOut->writeIntBigEndian(24);
mext.setBodyCRC(24);
// 4 QUEUEID 16=12+4
memoryOut->writeIntBigEndian(4);
mext.setQueueId(4);
// 5 FLAG 20=16+4
memoryOut->writeIntBigEndian(4);
mext.setFlag(4);
// 6 QUEUEOFFSET 28 = 20+8
memoryOut->writeInt64BigEndian((int64)1024);
mext.setQueueOffset(1024);
// 7 PHYSICALOFFSET 36=28+8
memoryOut->writeInt64BigEndian((int64)2048);
mext.setCommitLogOffset(2048);
// 8 SYSFLAG 40=36+4
memoryOut->writeIntBigEndian(0);
mext.setSysFlag(0);
// 9 BORNTIMESTAMP 48 = 40+8
memoryOut->writeInt64BigEndian((int64)4096);
mext.setBornTimestamp(4096);
// 10 BORNHOST 56= 48+8
memoryOut->writeIntBigEndian(ntohl(inet_addr("127.0.0.1")));
memoryOut->writeIntBigEndian(10091);
mext.setBornHost(rocketmq::IPPort2socketAddress(ntohl(inet_addr("127.0.0.1")), 10091));
// 11 STORETIMESTAMP 64 =56+8
memoryOut->writeInt64BigEndian((int64)4096);
mext.setStoreTimestamp(4096);
// 12 STOREHOST 72 = 64+8
memoryOut->writeIntBigEndian(ntohl(inet_addr("127.0.0.2")));
memoryOut->writeIntBigEndian(10092);
mext.setStoreHost(rocketmq::IPPort2socketAddress(ntohl(inet_addr("127.0.0.2")), 10092));
// 13 RECONSUMETIMES 76 = 72+4
mext.setReconsumeTimes(111111);
memoryOut->writeIntBigEndian(mext.getReconsumeTimes());
// 14 Prepared Transaction Offset 84 = 76+8
memoryOut->writeInt64BigEndian((int64)12);
mext.setPreparedTransactionOffset(12);
// 15 BODY 88 = 84+4 10
string* body = new string("1234567890");
mext.setBody(body->c_str());
memoryOut->writeIntBigEndian(10);
memoryOut->write(body->c_str(), body->size());
// 16 TOPIC
memoryOut->writeByte(10);
memoryOut->write(body->c_str(), body->size());
mext.setTopic(body->c_str());
// 17 PROPERTIES
memoryOut->writeShortBigEndian(0);
mext.setMsgId(MQDecoder::createMessageId(mext.getStoreHost(), (int64)mext.getCommitLogOffset()));
vector<MQMessageExt> mqvec;
MemoryBlock block = memoryOut->getMemoryBlock();
MQDecoder::decodes(&block, mqvec);
EXPECT_EQ(mqvec.size(), 1);
std::cout << mext.toString() << "\n";
std::cout << mqvec[0].toString() << "\n";
EXPECT_EQ(mqvec[0].toString(), mext.toString());
mqvec.clear();
MQDecoder::decodes(&block, mqvec, false);
EXPECT_FALSE(mqvec[0].getBody().size());
//===============================================================
// 8 SYSFLAG 40=36+4
mext.setSysFlag(0 | MessageSysFlag::CompressedFlag);
memoryOut->setPosition(36);
memoryOut->writeIntBigEndian(mext.getSysFlag());
// 15 Body 84
string outBody;
string boody("123123123");
UtilAll::deflate(boody, outBody, 5);
mext.setBody(outBody);
memoryOut->setPosition(84);
memoryOut->writeIntBigEndian(outBody.size());
memoryOut->write(outBody.c_str(), outBody.size());
// 16 TOPIC
memoryOut->writeByte(10);
memoryOut->write(body->c_str(), body->size());
mext.setTopic(body->c_str());
// 17 PROPERTIES
map<string, string> properties;
properties["RocketMQ"] = "cpp-client";
properties[MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX] = "123456";
mext.setProperties(properties);
mext.setMsgId("123456");
string proString = MQDecoder::messageProperties2String(properties);
memoryOut->writeShortBigEndian(proString.size());
memoryOut->write(proString.c_str(), proString.size());
mext.setStoreSize(memoryOut->getDataSize());
memoryOut->setPosition(0);
memoryOut->writeIntBigEndian(mext.getStoreSize());
block = memoryOut->getMemoryBlock();
MQDecoder::decodes(&block, mqvec);
EXPECT_EQ(mqvec[0].toString(), mext.toString());
}
TEST(decoder, messagePropertiesAndToString) {
map<string, string> properties;
properties["RocketMQ"] = "cpp-client";
string proString = MQDecoder::messageProperties2String(properties);
map<string, string> newProperties;
MQDecoder::string2messageProperties(proString, newProperties);
EXPECT_EQ(properties, newProperties);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "decoder.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,138 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQMessageExt.h"
#include "MessageSysFlag.h"
#include "SocketUtil.h"
#include "TopicFilterType.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MessageSysFlag;
using rocketmq::MQMessageExt;
using rocketmq::TopicFilterType;
TEST(messageExt, init) {
MQMessageExt messageExt;
EXPECT_EQ(messageExt.getQueueOffset(), 0);
EXPECT_EQ(messageExt.getCommitLogOffset(), 0);
EXPECT_EQ(messageExt.getBornTimestamp(), 0);
EXPECT_EQ(messageExt.getStoreTimestamp(), 0);
EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 0);
EXPECT_EQ(messageExt.getQueueId(), 0);
EXPECT_EQ(messageExt.getStoreSize(), 0);
EXPECT_EQ(messageExt.getReconsumeTimes(), 3);
EXPECT_EQ(messageExt.getBodyCRC(), 0);
EXPECT_EQ(messageExt.getMsgId(), "");
EXPECT_EQ(messageExt.getOffsetMsgId(), "");
messageExt.setQueueOffset(1);
EXPECT_EQ(messageExt.getQueueOffset(), 1);
messageExt.setCommitLogOffset(1024);
EXPECT_EQ(messageExt.getCommitLogOffset(), 1024);
messageExt.setBornTimestamp(1024);
EXPECT_EQ(messageExt.getBornTimestamp(), 1024);
messageExt.setStoreTimestamp(2048);
EXPECT_EQ(messageExt.getStoreTimestamp(), 2048);
messageExt.setPreparedTransactionOffset(4096);
EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 4096);
messageExt.setQueueId(2);
EXPECT_EQ(messageExt.getQueueId(), 2);
messageExt.setStoreSize(12);
EXPECT_EQ(messageExt.getStoreSize(), 12);
messageExt.setReconsumeTimes(48);
EXPECT_EQ(messageExt.getReconsumeTimes(), 48);
messageExt.setBodyCRC(32);
EXPECT_EQ(messageExt.getBodyCRC(), 32);
messageExt.setMsgId("MsgId");
EXPECT_EQ(messageExt.getMsgId(), "MsgId");
messageExt.setOffsetMsgId("offsetMsgId");
EXPECT_EQ(messageExt.getOffsetMsgId(), "offsetMsgId");
messageExt.setBornTimestamp(1111);
EXPECT_EQ(messageExt.getBornTimestamp(), 1111);
messageExt.setStoreTimestamp(2222);
EXPECT_EQ(messageExt.getStoreTimestamp(), 2222);
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(10091);
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
sockaddr bornHost;
memcpy(&bornHost, &sa, sizeof(sockaddr));
messageExt.setBornHost(bornHost);
EXPECT_EQ(messageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
EXPECT_EQ(messageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
struct sockaddr_in storeSa;
storeSa.sin_family = AF_INET;
storeSa.sin_port = htons(10092);
storeSa.sin_addr.s_addr = inet_addr("127.0.0.2");
sockaddr storeHost;
memcpy(&storeHost, &storeSa, sizeof(sockaddr));
messageExt.setStoreHost(storeHost);
EXPECT_EQ(messageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
MQMessageExt twoMessageExt(2, 1024, bornHost, 2048, storeHost, "msgId");
EXPECT_EQ(twoMessageExt.getQueueOffset(), 0);
EXPECT_EQ(twoMessageExt.getCommitLogOffset(), 0);
EXPECT_EQ(twoMessageExt.getBornTimestamp(), 1024);
EXPECT_EQ(twoMessageExt.getStoreTimestamp(), 2048);
EXPECT_EQ(twoMessageExt.getPreparedTransactionOffset(), 0);
EXPECT_EQ(twoMessageExt.getQueueId(), 2);
EXPECT_EQ(twoMessageExt.getStoreSize(), 0);
EXPECT_EQ(twoMessageExt.getReconsumeTimes(), 3);
EXPECT_EQ(twoMessageExt.getBodyCRC(), 0);
EXPECT_EQ(twoMessageExt.getMsgId(), "msgId");
EXPECT_EQ(twoMessageExt.getOffsetMsgId(), "");
EXPECT_EQ(twoMessageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
EXPECT_EQ(twoMessageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
EXPECT_EQ(twoMessageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
EXPECT_EQ(MQMessageExt::parseTopicFilterType(MessageSysFlag::MultiTagsFlag), TopicFilterType::MULTI_TAG);
EXPECT_EQ(MQMessageExt::parseTopicFilterType(0), TopicFilterType::SINGLE_TAG);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "messageExt.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,59 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "MQMessageId.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace std;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessageId;
TEST(messageId, id) {
int host;
int port;
sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
MQMessageId id(addr, 1024);
rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
EXPECT_EQ(host, inet_addr("127.0.0.1"));
EXPECT_EQ(port, 10091);
EXPECT_EQ(id.getOffset(), 1024);
id.setAddress(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.2"), 10092));
id.setOffset(2048);
rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
EXPECT_EQ(host, inet_addr("127.0.0.2"));
EXPECT_EQ(port, 10092);
EXPECT_EQ(id.getOffset(), 2048);
MQMessageId id2 = id;
EXPECT_EQ(id2.getOffset(), 2048);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "messageId.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,86 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQMessageQueue.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessageQueue;
TEST(messageQueue, init) {
MQMessageQueue messageQueue;
EXPECT_EQ(messageQueue.getBrokerName(), "");
EXPECT_EQ(messageQueue.getTopic(), "");
EXPECT_EQ(messageQueue.getQueueId(), -1);
MQMessageQueue twoMessageQueue("testTopic", "testBroker", 1);
EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
MQMessageQueue threeMessageQueue("threeTestTopic", "threeTestBroker", 2);
MQMessageQueue frouMessageQueue(threeMessageQueue);
EXPECT_EQ(frouMessageQueue.getBrokerName(), "threeTestBroker");
EXPECT_EQ(frouMessageQueue.getTopic(), "threeTestTopic");
EXPECT_EQ(frouMessageQueue.getQueueId(), 2);
frouMessageQueue = twoMessageQueue;
EXPECT_EQ(frouMessageQueue.getBrokerName(), "testBroker");
EXPECT_EQ(frouMessageQueue.getTopic(), "testTopic");
EXPECT_EQ(frouMessageQueue.getQueueId(), 1);
frouMessageQueue.setBrokerName("frouTestBroker");
frouMessageQueue.setTopic("frouTestTopic");
frouMessageQueue.setQueueId(4);
EXPECT_EQ(frouMessageQueue.getBrokerName(), "frouTestBroker");
EXPECT_EQ(frouMessageQueue.getTopic(), "frouTestTopic");
EXPECT_EQ(frouMessageQueue.getQueueId(), 4);
}
TEST(messageQueue, operators) {
MQMessageQueue messageQueue;
EXPECT_EQ(messageQueue, messageQueue);
EXPECT_EQ(messageQueue.compareTo(messageQueue), 0);
MQMessageQueue twoMessageQueue;
EXPECT_EQ(messageQueue, twoMessageQueue);
EXPECT_EQ(messageQueue.compareTo(twoMessageQueue), 0);
twoMessageQueue.setTopic("testTopic");
EXPECT_FALSE(messageQueue == twoMessageQueue);
EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
twoMessageQueue.setQueueId(1);
EXPECT_FALSE(messageQueue == twoMessageQueue);
EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
twoMessageQueue.setBrokerName("testBroker");
EXPECT_FALSE(messageQueue == twoMessageQueue);
EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(filter) = "messageQueue.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,170 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <map>
#include <string>
#include "MQMessage.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace std;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessage;
TEST(message, Init) {
MQMessage messageOne;
EXPECT_EQ(messageOne.getTopic(), "");
EXPECT_EQ(messageOne.getBody(), "");
EXPECT_EQ(messageOne.getTags(), "");
EXPECT_EQ(messageOne.getFlag(), 0);
MQMessage messageTwo("test", "testBody");
EXPECT_EQ(messageTwo.getTopic(), "test");
EXPECT_EQ(messageTwo.getBody(), "testBody");
EXPECT_EQ(messageTwo.getTags(), "");
EXPECT_EQ(messageTwo.getFlag(), 0);
MQMessage messageThree("test", "tagTest", "testBody");
EXPECT_EQ(messageThree.getTopic(), "test");
EXPECT_EQ(messageThree.getBody(), "testBody");
EXPECT_EQ(messageThree.getTags(), "tagTest");
EXPECT_EQ(messageThree.getFlag(), 0);
MQMessage messageFour("test", "tagTest", "testKey", "testBody");
EXPECT_EQ(messageFour.getTopic(), "test");
EXPECT_EQ(messageFour.getBody(), "testBody");
EXPECT_EQ(messageFour.getTags(), "tagTest");
EXPECT_EQ(messageFour.getKeys(), "testKey");
EXPECT_EQ(messageFour.getFlag(), 0);
MQMessage messageFive("test", "tagTest", "testKey", 1, "testBody", 2);
EXPECT_EQ(messageFive.getTopic(), "test");
EXPECT_EQ(messageFive.getBody(), "testBody");
EXPECT_EQ(messageFive.getTags(), "tagTest");
EXPECT_EQ(messageFive.getKeys(), "testKey");
EXPECT_EQ(messageFive.getFlag(), 1);
MQMessage messageSix(messageFive);
EXPECT_EQ(messageSix.getTopic(), "test");
EXPECT_EQ(messageSix.getBody(), "testBody");
EXPECT_EQ(messageSix.getTags(), "tagTest");
EXPECT_EQ(messageSix.getKeys(), "testKey");
EXPECT_EQ(messageSix.getFlag(), 1);
MQMessage messageSeven = messageSix;
EXPECT_EQ(messageSeven.getTopic(), "test");
EXPECT_EQ(messageSeven.getBody(), "testBody");
EXPECT_EQ(messageSeven.getTags(), "tagTest");
EXPECT_EQ(messageSeven.getKeys(), "testKey");
EXPECT_EQ(messageSeven.getFlag(), 1);
}
TEST(message, info) {
MQMessage message;
EXPECT_EQ(message.getTopic(), "");
message.setTopic("testTopic");
EXPECT_EQ(message.getTopic(), "testTopic");
string topic = "testTopic";
const char* ctopic = topic.c_str();
message.setTopic(ctopic, 5);
EXPECT_EQ(message.getTopic(), "testT");
EXPECT_EQ(message.getBody(), "");
message.setBody("testBody");
EXPECT_EQ(message.getBody(), "testBody");
string body = "testBody";
const char* b = body.c_str();
message.setBody(b, 5);
EXPECT_EQ(message.getBody(), "testB");
string tags(message.getTags());
EXPECT_EQ(tags, "");
EXPECT_EQ(message.getFlag(), 0);
message.setFlag(2);
EXPECT_EQ(message.getFlag(), 2);
EXPECT_EQ(message.isWaitStoreMsgOK(), true);
message.setWaitStoreMsgOK(false);
EXPECT_EQ(message.isWaitStoreMsgOK(), false);
message.setWaitStoreMsgOK(true);
EXPECT_EQ(message.isWaitStoreMsgOK(), true);
string keys(message.getTags());
EXPECT_EQ(keys, "");
message.setKeys("testKeys");
EXPECT_EQ(message.getKeys(), "testKeys");
EXPECT_EQ(message.getDelayTimeLevel(), 0);
message.setDelayTimeLevel(1);
EXPECT_EQ(message.getDelayTimeLevel(), 1);
message.setSysFlag(1);
EXPECT_EQ(message.getSysFlag(), 1);
}
TEST(message, properties) {
MQMessage message;
EXPECT_EQ(message.getProperties().size(), 1);
EXPECT_STREQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED).c_str(), "");
message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "true");
EXPECT_EQ(message.getProperties().size(), 2);
EXPECT_EQ(message.getSysFlag(), 4);
EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "false");
EXPECT_EQ(message.getProperties().size(), 2);
EXPECT_EQ(message.getSysFlag(), 0);
EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
map<string, string> newProperties;
newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "true";
message.setProperties(newProperties);
EXPECT_EQ(message.getSysFlag(), 4);
EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "false";
message.setProperties(newProperties);
EXPECT_EQ(message.getSysFlag(), 0);
EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
}
TEST(message, Keys) {
MQMessage message;
vector<string> keys;
keys.push_back("abc");
keys.push_back("efg");
keys.push_back("hij");
message.setKeys(keys);
EXPECT_EQ(message.getKeys(), "abc efg hij");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
// testing::GTEST_FLAG(filter) = "message.info";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,232 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "DefaultMQProducerImpl.h"
#include "MQClientFactory.h"
#include "TopicPublishInfo.h"
using namespace std;
using namespace rocketmq;
using rocketmq::DefaultMQProducerImpl;
using rocketmq::MQClientAPIImpl;
using rocketmq::MQClientFactory;
using rocketmq::TopicPublishInfo;
using testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
class MySendCallback : public SendCallback {
virtual void onSuccess(SendResult& sendResult) {}
virtual void onException(MQException& e) {}
};
class MyMessageQueueSelector : public MessageQueueSelector {
virtual MQMessageQueue select(const std::vector<MQMessageQueue>& mqs, const MQMessage& msg, void* arg) {
return MQMessageQueue("TestTopic", "BrokerA", 0);
}
};
class MockMQClientFactory : public MQClientFactory {
public:
MockMQClientFactory(const string& mqClientId) : MQClientFactory(mqClientId, true, DEFAULT_SSL_PROPERTY_FILE) {}
MOCK_METHOD0(start, void());
MOCK_METHOD0(shutdown, void());
MOCK_METHOD0(sendHeartbeatToAllBroker, void());
MOCK_METHOD0(getMQClientAPIImpl, MQClientAPIImpl*());
MOCK_METHOD1(registerProducer, bool(MQProducer*));
MOCK_METHOD1(unregisterProducer, void(MQProducer*));
MOCK_METHOD1(findBrokerAddressInPublish, string(const string&));
MOCK_METHOD2(tryToFindTopicPublishInfo,
boost::shared_ptr<TopicPublishInfo>(const string&, const SessionCredentials&));
};
class MockMQClientAPIImpl : public MQClientAPIImpl {
public:
MockMQClientAPIImpl() : MQClientAPIImpl("testMockMQClientAPIImpl", true, DEFAULT_SSL_PROPERTY_FILE) {}
MOCK_METHOD9(sendMessage,
SendResult(const string&,
const string&,
const MQMessage&,
SendMessageRequestHeader*,
int,
int,
int,
SendCallback*,
const SessionCredentials&));
};
TEST(DefaultMQProducerImplTest, init) {
DefaultMQProducerImpl* impl = new DefaultMQProducerImpl("testMQProducerGroup");
EXPECT_EQ(impl->getGroupName(), "testMQProducerGroup");
impl->setUnitName("testUnit");
EXPECT_EQ(impl->getUnitName(), "testUnit");
impl->setTcpTransportPullThreadNum(64);
EXPECT_EQ(impl->getTcpTransportPullThreadNum(), 64);
impl->setTcpTransportConnectTimeout(2000);
EXPECT_EQ(impl->getTcpTransportConnectTimeout(), 2000);
impl->setTcpTransportTryLockTimeout(3000);
// need fix the unit
EXPECT_EQ(impl->getTcpTransportTryLockTimeout(), 3);
impl->setRetryTimes4Async(4);
EXPECT_EQ(impl->getRetryTimes4Async(), 4);
impl->setRetryTimes(2);
EXPECT_EQ(impl->getRetryTimes(), 2);
impl->setSendMsgTimeout(1000);
EXPECT_EQ(impl->getSendMsgTimeout(), 1000);
impl->setCompressMsgBodyOverHowmuch(1024);
EXPECT_EQ(impl->getCompressMsgBodyOverHowmuch(), 1024);
impl->setCompressLevel(2);
EXPECT_EQ(impl->getCompressLevel(), 2);
impl->setMaxMessageSize(2048);
EXPECT_EQ(impl->getMaxMessageSize(), 2048);
impl->setNamesrvAddr("http://rocketmq.nameserver.com");
EXPECT_EQ(impl->getNamesrvAddr(), "rocketmq.nameserver.com");
impl->setNameSpace("MQ_INST_NAMESPACE_TEST");
EXPECT_EQ(impl->getNameSpace(), "MQ_INST_NAMESPACE_TEST");
impl->setMessageTrace(true);
EXPECT_TRUE(impl->getMessageTrace());
}
TEST(DefaultMQProducerImplTest, Sends) {
DefaultMQProducerImpl* impl = new DefaultMQProducerImpl("testMockSendMQProducerGroup");
MockMQClientFactory* mockFactory = new MockMQClientFactory("testClientId");
MockMQClientAPIImpl* apiImpl = new MockMQClientAPIImpl();
impl->setFactory(mockFactory);
impl->setNamesrvAddr("http://rocketmq.nameserver.com");
// prepare send
boost::shared_ptr<TopicPublishInfo> topicPublishInfo = boost::make_shared<TopicPublishInfo>();
MQMessageQueue mqA("TestTopic", "BrokerA", 0);
MQMessageQueue mqB("TestTopic", "BrokerB", 0);
topicPublishInfo->updateMessageQueueList(mqA);
topicPublishInfo->updateMessageQueueList(mqB);
SendResult okMQAResult(SEND_OK, "MSSAGEID", "OFFSETID", mqA, 1024, "DEFAULT_REGION");
SendResult okMQBResult(SEND_OK, "MSSAGEID", "OFFSETID", mqB, 2048);
okMQBResult.setRegionId("DEFAULT_REGION");
okMQBResult.toString();
SendResult errorMQBResult(SEND_SLAVE_NOT_AVAILABLE, "MSSAGEID", "OFFSETID", mqB, 2048);
EXPECT_CALL(*mockFactory, start()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, shutdown()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, registerProducer(_)).Times(1).WillOnce(Return(true));
EXPECT_CALL(*mockFactory, unregisterProducer(_)).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, sendHeartbeatToAllBroker()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, tryToFindTopicPublishInfo(_, _)).WillRepeatedly(Return(topicPublishInfo));
EXPECT_CALL(*mockFactory, findBrokerAddressInPublish(_)).WillRepeatedly(Return("BrokerA"));
EXPECT_CALL(*mockFactory, getMQClientAPIImpl()).WillRepeatedly(Return(apiImpl));
EXPECT_CALL(*apiImpl, sendMessage(_, _, _, _, _, _, _, _, _))
.WillOnce(Return(okMQAResult))
.WillOnce(Return(okMQBResult))
.WillOnce(Return(errorMQBResult))
.WillOnce(Return(okMQAResult))
.WillOnce(Return(okMQAResult))
.WillRepeatedly(Return(okMQAResult));
// Start Producer.
impl->start();
MQMessage msg("testTopic", "testTag", "testKey", "testBodysA");
SendResult s1 = impl->send(msg);
EXPECT_EQ(s1.getSendStatus(), SEND_OK);
EXPECT_EQ(s1.getQueueOffset(), 1024);
SendResult s2 = impl->send(msg, mqB);
EXPECT_EQ(s2.getSendStatus(), SEND_OK);
EXPECT_EQ(s2.getQueueOffset(), 2048);
MessageQueueSelector* pSelect = new MyMessageQueueSelector();
SendResult s3 = impl->send(msg, pSelect, nullptr, 3, true);
EXPECT_EQ(s3.getSendStatus(), SEND_OK);
EXPECT_EQ(s3.getQueueOffset(), 1024);
SendResult s33 = impl->send(msg, pSelect, nullptr);
EXPECT_EQ(s33.getSendStatus(), SEND_OK);
EXPECT_EQ(s33.getQueueOffset(), 1024);
SendCallback* pCallback = new MySendCallback();
EXPECT_NO_THROW(impl->send(msg, pCallback, true));
EXPECT_NO_THROW(impl->send(msg, pSelect, nullptr, pCallback));
EXPECT_NO_THROW(impl->send(msg, mqA, pCallback));
EXPECT_NO_THROW(impl->sendOneway(msg));
EXPECT_NO_THROW(impl->sendOneway(msg, mqA));
EXPECT_NO_THROW(impl->sendOneway(msg, pSelect, nullptr));
MQMessage msgB("testTopic", "testTag", "testKey", "testBodysB");
vector<MQMessage> msgs;
msgs.push_back(msg);
msgs.push_back(msgB);
SendResult s4 = impl->send(msgs);
EXPECT_EQ(s4.getSendStatus(), SEND_OK);
EXPECT_EQ(s4.getQueueOffset(), 1024);
SendResult s5 = impl->send(msgs, mqA);
EXPECT_EQ(s5.getSendStatus(), SEND_OK);
EXPECT_EQ(s5.getQueueOffset(), 1024);
impl->shutdown();
delete mockFactory;
delete apiImpl;
}
TEST(DefaultMQProducerImplTest, Trace) {
DefaultMQProducerImpl* impl = new DefaultMQProducerImpl("testMockProducerTraceGroup");
MockMQClientFactory* mockFactory = new MockMQClientFactory("testTraceClientId");
MockMQClientAPIImpl* apiImpl = new MockMQClientAPIImpl();
impl->setFactory(mockFactory);
impl->setNamesrvAddr("http://rocketmq.nameserver.com");
impl->setMessageTrace(true);
// prepare send
boost::shared_ptr<TopicPublishInfo> topicPublishInfo = boost::make_shared<TopicPublishInfo>();
MQMessageQueue mqA("TestTraceTopic", "BrokerA", 0);
MQMessageQueue mqB("TestTraceTopic", "BrokerB", 0);
topicPublishInfo->updateMessageQueueList(mqA);
topicPublishInfo->updateMessageQueueList(mqB);
SendResult okMQAResult(SEND_OK, "MSSAGEID", "OFFSETID", mqA, 1024, "DEFAULT_REGION");
EXPECT_CALL(*mockFactory, start()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, shutdown()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, registerProducer(_)).Times(1).WillOnce(Return(true));
EXPECT_CALL(*mockFactory, unregisterProducer(_)).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, sendHeartbeatToAllBroker()).Times(1).WillOnce(Return());
EXPECT_CALL(*mockFactory, tryToFindTopicPublishInfo(_, _)).WillRepeatedly(Return(topicPublishInfo));
EXPECT_CALL(*mockFactory, findBrokerAddressInPublish(_)).WillRepeatedly(Return("BrokerA"));
EXPECT_CALL(*mockFactory, getMQClientAPIImpl()).WillRepeatedly(Return(apiImpl));
EXPECT_CALL(*apiImpl, sendMessage(_, _, _, _, _, _, _, _, _)).WillRepeatedly(Return(okMQAResult));
// Start Producer.
impl->start();
MQMessage msg("TestTraceTopic", "testTag", "testKey", "testBodysA");
SendResult s1 = impl->send(msg);
EXPECT_EQ(s1.getSendStatus(), SEND_OK);
impl->shutdown();
delete mockFactory;
delete apiImpl;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,40 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "StringIdMaker.h"
using namespace std;
using namespace rocketmq;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
TEST(StringIdMakerTest, get_unique_id) {
string unique_id = StringIdMaker::getInstance().createUniqID();
cout << "unique_id: " << unique_id << endl;
EXPECT_EQ(unique_id.size(), 32);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,97 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQMessageQueue.h"
#include "TopicPublishInfo.h"
using namespace std;
using namespace rocketmq;
using rocketmq::MQMessageQueue;
using rocketmq::TopicPublishInfo;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
TEST(TopicPublishInfoTest, testAll) {
TopicPublishInfo* info = new TopicPublishInfo();
MQMessageQueue mqA("TestTopicA", "BrokerA", 0);
MQMessageQueue mqB("TestTopicA", "BrokerB", 0);
int index = -1;
EXPECT_EQ(info->getWhichQueue(), 0);
EXPECT_FALSE(info->ok());
EXPECT_EQ(info->selectOneMessageQueue(mqA, index), MQMessageQueue());
EXPECT_EQ(info->selectOneActiveMessageQueue(mqA, index), MQMessageQueue());
info->updateMessageQueueList(mqA);
info->updateMessageQueueList(mqB);
EXPECT_TRUE(info->ok());
EXPECT_EQ(info->getMessageQueueList().size(), 2);
EXPECT_EQ(info->selectOneMessageQueue(mqA, index), MQMessageQueue());
EXPECT_EQ(info->selectOneActiveMessageQueue(mqA, index), MQMessageQueue());
index = 0;
MQMessageQueue mqSelect1 = info->selectOneMessageQueue(MQMessageQueue(), index);
EXPECT_EQ(index, 0);
EXPECT_EQ(mqSelect1, mqA);
EXPECT_EQ(info->getWhichQueue(), 1);
MQMessageQueue mqSelect2 = info->selectOneMessageQueue(mqSelect1, index);
EXPECT_EQ(index, 1);
EXPECT_EQ(mqSelect2, mqB);
EXPECT_EQ(info->getWhichQueue(), 3);
index = 0;
MQMessageQueue mqActiveSelect1 = info->selectOneActiveMessageQueue(MQMessageQueue(), index);
EXPECT_EQ(index, 0);
EXPECT_EQ(mqActiveSelect1, mqA);
MQMessageQueue mqActiveSelect2 = info->selectOneActiveMessageQueue(mqActiveSelect1, index);
EXPECT_EQ(index, 1);
EXPECT_EQ(mqActiveSelect2, mqB);
EXPECT_EQ(info->getWhichQueue(), 6);
info->updateNonServiceMessageQueue(mqA, 1000);
info->updateNonServiceMessageQueue(mqA, 1000);
index = 0;
MQMessageQueue mqActiveSelect3 = info->selectOneActiveMessageQueue(mqActiveSelect1, index);
EXPECT_EQ(index, 1);
EXPECT_EQ(mqActiveSelect3, mqB);
MQMessageQueue mqActiveSelect4 = info->selectOneActiveMessageQueue(mqActiveSelect2, index);
EXPECT_EQ(index, 1);
EXPECT_EQ(mqActiveSelect4, mqA);
info->updateNonServiceMessageQueue(mqB, 1000);
index = 0;
MQMessageQueue mqSelect3 = info->selectOneMessageQueue(MQMessageQueue(), index);
EXPECT_EQ(index, 0);
EXPECT_EQ(mqSelect3, mqA);
index = 0;
MQMessageQueue mqActiveSelect5 = info->selectOneActiveMessageQueue(MQMessageQueue(), index);
EXPECT_EQ(index, 1);
EXPECT_EQ(mqActiveSelect5, mqA);
index = 0;
MQMessageQueue mqActiveSelect6 = info->selectOneActiveMessageQueue(mqB, index);
EXPECT_EQ(index, 0);
EXPECT_EQ(mqActiveSelect6, mqA);
info->updateMessageQueueList(mqSelect3);
info->resumeNonServiceMessageQueueList();
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -0,0 +1,558 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "json/value.h"
#include "json/writer.h"
#include "CommandHeader.h"
#include "dataBlock.h"
using std::shared_ptr;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using Json::FastWriter;
using Json::Value;
using rocketmq::CheckTransactionStateRequestHeader;
using rocketmq::CommandHeader;
using rocketmq::ConsumerSendMsgBackRequestHeader;
using rocketmq::CreateTopicRequestHeader;
using rocketmq::EndTransactionRequestHeader;
using rocketmq::GetConsumerListByGroupRequestHeader;
using rocketmq::GetConsumerListByGroupResponseBody;
using rocketmq::GetConsumerListByGroupResponseHeader;
using rocketmq::GetConsumerRunningInfoRequestHeader;
using rocketmq::GetEarliestMsgStoretimeRequestHeader;
using rocketmq::GetEarliestMsgStoretimeResponseHeader;
using rocketmq::GetMaxOffsetRequestHeader;
using rocketmq::GetMaxOffsetResponseHeader;
using rocketmq::GetMinOffsetRequestHeader;
using rocketmq::GetMinOffsetResponseHeader;
using rocketmq::GetRouteInfoRequestHeader;
using rocketmq::MemoryBlock;
using rocketmq::NotifyConsumerIdsChangedRequestHeader;
using rocketmq::PullMessageRequestHeader;
using rocketmq::PullMessageResponseHeader;
using rocketmq::QueryConsumerOffsetRequestHeader;
using rocketmq::QueryConsumerOffsetResponseHeader;
using rocketmq::ResetOffsetRequestHeader;
using rocketmq::SearchOffsetRequestHeader;
using rocketmq::SearchOffsetResponseHeader;
using rocketmq::SendMessageRequestHeader;
using rocketmq::SendMessageRequestHeaderV2;
using rocketmq::SendMessageResponseHeader;
using rocketmq::UnregisterClientRequestHeader;
using rocketmq::UpdateConsumerOffsetRequestHeader;
using rocketmq::ViewMessageRequestHeader;
TEST(commandHeader, ConsumerSendMsgBackRequestHeader) {
string group = "testGroup";
int delayLevel = 2;
int64 offset = 3027;
bool unitMode = true;
string originMsgId = "testOriginMsgId";
string originTopic = "testTopic";
int maxReconsumeTimes = 12;
ConsumerSendMsgBackRequestHeader header;
header.group = group;
header.delayLevel = delayLevel;
header.offset = offset;
header.unitMode = unitMode;
header.originMsgId = originMsgId;
header.originTopic = originTopic;
header.maxReconsumeTimes = maxReconsumeTimes;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["group"], group);
EXPECT_EQ(requestMap["delayLevel"], "2");
EXPECT_EQ(requestMap["offset"], "3027");
EXPECT_EQ(requestMap["unitMode"], "1");
EXPECT_EQ(requestMap["originMsgId"], originMsgId);
EXPECT_EQ(requestMap["originTopic"], originTopic);
EXPECT_EQ(requestMap["maxReconsumeTimes"], "12");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["group"], group);
EXPECT_EQ(outData["delayLevel"], 2);
EXPECT_EQ(outData["offset"], "3027");
EXPECT_EQ(outData["unitMode"], "1");
EXPECT_EQ(outData["originMsgId"], originMsgId);
EXPECT_EQ(outData["originTopic"], originTopic);
EXPECT_EQ(outData["maxReconsumeTimes"], 12);
}
TEST(commandHeader, GetRouteInfoRequestHeader) {
GetRouteInfoRequestHeader header("testTopic");
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["topic"], "testTopic");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["topic"], "testTopic");
}
TEST(commandHeader, UnregisterClientRequestHeader) {
UnregisterClientRequestHeader header("testGroup", "testProducer", "testConsumer");
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["clientID"], "testGroup");
EXPECT_EQ(requestMap["producerGroup"], "testProducer");
EXPECT_EQ(requestMap["consumerGroup"], "testConsumer");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["clientID"], "testGroup");
EXPECT_EQ(outData["producerGroup"], "testProducer");
EXPECT_EQ(outData["consumerGroup"], "testConsumer");
}
TEST(commandHeader, CreateTopicRequestHeader) {
string topic = "testTopic";
string defaultTopic = "defaultTopic";
int readQueueNums = 4;
int writeQueueNums = 6;
int perm = 8;
string topicFilterType = "filterType";
CreateTopicRequestHeader header;
header.topic = topic;
header.defaultTopic = defaultTopic;
header.readQueueNums = readQueueNums;
header.writeQueueNums = writeQueueNums;
header.perm = perm;
header.topicFilterType = topicFilterType;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["topic"], topic);
EXPECT_EQ(requestMap["defaultTopic"], defaultTopic);
EXPECT_EQ(requestMap["readQueueNums"], "4");
EXPECT_EQ(requestMap["writeQueueNums"], "6");
EXPECT_EQ(requestMap["perm"], "8");
EXPECT_EQ(requestMap["topicFilterType"], topicFilterType);
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["topic"], topic);
EXPECT_EQ(outData["defaultTopic"], defaultTopic);
EXPECT_EQ(outData["readQueueNums"], readQueueNums);
EXPECT_EQ(outData["writeQueueNums"], writeQueueNums);
EXPECT_EQ(outData["perm"], perm);
EXPECT_EQ(outData["topicFilterType"], topicFilterType);
}
TEST(commandHeader, CheckTransactionStateRequestHeader) {
CheckTransactionStateRequestHeader header(2000, 1000, "ABC", "DEF", "GHI");
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["msgId"], "ABC");
EXPECT_EQ(requestMap["transactionId"], "DEF");
EXPECT_EQ(requestMap["offsetMsgId"], "GHI");
EXPECT_EQ(requestMap["commitLogOffset"], "1000");
EXPECT_EQ(requestMap["tranStateTableOffset"], "2000");
Value value;
value["msgId"] = "ABC";
value["transactionId"] = "DEF";
value["offsetMsgId"] = "GHI";
value["commitLogOffset"] = "1000";
value["tranStateTableOffset"] = "2000";
shared_ptr<CheckTransactionStateRequestHeader> headerDecode(
static_cast<CheckTransactionStateRequestHeader*>(CheckTransactionStateRequestHeader::Decode(value)));
EXPECT_EQ(headerDecode->m_msgId, "ABC");
EXPECT_EQ(headerDecode->m_commitLogOffset, 1000);
EXPECT_EQ(headerDecode->m_tranStateTableOffset, 2000);
EXPECT_EQ(headerDecode->toString(), header.toString());
}
TEST(commandHeader, EndTransactionRequestHeader) {
EndTransactionRequestHeader header("testProducer", 1000, 2000, 3000, true, "ABC", "DEF");
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["msgId"], "ABC");
EXPECT_EQ(requestMap["transactionId"], "DEF");
EXPECT_EQ(requestMap["producerGroup"], "testProducer");
EXPECT_EQ(requestMap["tranStateTableOffset"], "1000");
EXPECT_EQ(requestMap["commitLogOffset"], "2000");
EXPECT_EQ(requestMap["commitOrRollback"], "3000");
EXPECT_EQ(requestMap["fromTransactionCheck"], "1");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["msgId"], "ABC");
EXPECT_EQ(outData["transactionId"], "DEF");
EXPECT_EQ(outData["producerGroup"], "testProducer");
EXPECT_EQ(outData["tranStateTableOffset"], "1000");
EXPECT_EQ(outData["commitLogOffset"], "2000");
EXPECT_EQ(outData["commitOrRollback"], "3000");
EXPECT_EQ(outData["fromTransactionCheck"], "1");
EXPECT_NO_THROW(header.toString());
}
TEST(commandHeader, SendMessageRequestHeader) {
string producerGroup = "testProducer";
string topic = "testTopic";
string defaultTopic = "defaultTopic";
int defaultTopicQueueNums = 1;
int queueId = 2;
int sysFlag = 3;
int64 bornTimestamp = 4;
int flag = 5;
string properties = "testProperty";
int reconsumeTimes = 6;
bool unitMode = true;
bool batch = false;
SendMessageRequestHeader header;
header.producerGroup = producerGroup;
header.topic = topic;
header.defaultTopic = defaultTopic;
header.defaultTopicQueueNums = defaultTopicQueueNums;
header.queueId = queueId;
header.sysFlag = sysFlag;
header.bornTimestamp = bornTimestamp;
header.flag = flag;
header.properties = properties;
header.reconsumeTimes = reconsumeTimes;
header.unitMode = unitMode;
header.batch = batch;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["topic"], topic);
EXPECT_EQ(requestMap["producerGroup"], producerGroup);
EXPECT_EQ(requestMap["defaultTopic"], defaultTopic);
EXPECT_EQ(requestMap["defaultTopicQueueNums"], "1");
EXPECT_EQ(requestMap["queueId"], "2");
EXPECT_EQ(requestMap["sysFlag"], "3");
EXPECT_EQ(requestMap["bornTimestamp"], "4");
EXPECT_EQ(requestMap["flag"], "5");
EXPECT_EQ(requestMap["properties"], properties);
EXPECT_EQ(requestMap["reconsumeTimes"], "6");
EXPECT_EQ(requestMap["unitMode"], "1");
EXPECT_EQ(requestMap["batch"], "0");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["topic"], topic);
EXPECT_EQ(outData["producerGroup"], producerGroup);
EXPECT_EQ(outData["defaultTopic"], defaultTopic);
EXPECT_EQ(outData["defaultTopicQueueNums"], defaultTopicQueueNums);
EXPECT_EQ(outData["queueId"], queueId);
EXPECT_EQ(outData["sysFlag"], sysFlag);
EXPECT_EQ(outData["bornTimestamp"], "4");
EXPECT_EQ(outData["flag"], flag);
EXPECT_EQ(outData["properties"], properties);
EXPECT_EQ(outData["reconsumeTimes"], "6");
EXPECT_EQ(outData["unitMode"], "1");
EXPECT_EQ(outData["batch"], "0");
}
TEST(commandHeader, SendMessageRequestHeaderV2) {
string producerGroup = "testProducer";
string topic = "testTopic";
string defaultTopic = "defaultTopic";
int defaultTopicQueueNums = 1;
int queueId = 2;
int sysFlag = 3;
int64 bornTimestamp = 4;
int flag = 5;
string properties = "testProperty";
int reconsumeTimes = 6;
bool unitMode = true;
bool batch = false;
SendMessageRequestHeaderV2 header;
header.a = producerGroup;
header.b = topic;
header.c = defaultTopic;
header.d = defaultTopicQueueNums;
header.e = queueId;
header.f = sysFlag;
header.g = bornTimestamp;
header.h = flag;
header.i = properties;
header.j = reconsumeTimes;
header.k = unitMode;
header.m = batch;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["a"], producerGroup);
EXPECT_EQ(requestMap["b"], topic);
EXPECT_EQ(requestMap["c"], defaultTopic);
EXPECT_EQ(requestMap["d"], "1");
EXPECT_EQ(requestMap["e"], "2");
EXPECT_EQ(requestMap["f"], "3");
EXPECT_EQ(requestMap["g"], "4");
EXPECT_EQ(requestMap["h"], "5");
EXPECT_EQ(requestMap["i"], properties);
EXPECT_EQ(requestMap["j"], "6");
EXPECT_EQ(requestMap["k"], "1");
EXPECT_EQ(requestMap["m"], "0");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["a"], producerGroup);
EXPECT_EQ(outData["b"], topic);
EXPECT_EQ(outData["c"], defaultTopic);
EXPECT_EQ(outData["d"], defaultTopicQueueNums);
EXPECT_EQ(outData["e"], queueId);
EXPECT_EQ(outData["f"], sysFlag);
EXPECT_EQ(outData["g"], "4");
EXPECT_EQ(outData["h"], flag);
EXPECT_EQ(outData["i"], properties);
EXPECT_EQ(outData["j"], "6");
EXPECT_EQ(outData["k"], "1");
EXPECT_EQ(outData["m"], "0");
SendMessageRequestHeader v1;
header.CreateSendMessageRequestHeaderV1(v1);
EXPECT_EQ(v1.producerGroup, producerGroup);
EXPECT_EQ(v1.queueId, queueId);
EXPECT_EQ(v1.batch, batch);
SendMessageRequestHeaderV2 v2(v1);
EXPECT_EQ(header.a, v2.a);
EXPECT_EQ(header.e, v2.e);
EXPECT_EQ(header.m, v2.m);
EXPECT_EQ(header.g, v2.g);
}
TEST(commandHeader, SendMessageResponseHeader) {
SendMessageResponseHeader header;
header.msgId = "ABCDEFG";
header.queueId = 1;
header.queueOffset = 2;
header.transactionId = "ID";
header.regionId = "public";
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["msgId"], "ABCDEFG");
EXPECT_EQ(requestMap["queueId"], "1");
EXPECT_EQ(requestMap["queueOffset"], "2");
EXPECT_EQ(requestMap["transactionId"], "ID");
EXPECT_EQ(requestMap["MSG_REGION"], "public");
Value value;
value["msgId"] = "EFGHIJK";
value["queueId"] = "3";
value["queueOffset"] = "4";
value["transactionId"] = "transactionId";
value["MSG_REGION"] = "MSG_REGION";
shared_ptr<SendMessageResponseHeader> headerDecode(
static_cast<SendMessageResponseHeader*>(SendMessageResponseHeader::Decode(value)));
EXPECT_EQ(headerDecode->msgId, "EFGHIJK");
EXPECT_EQ(headerDecode->queueId, 3);
EXPECT_EQ(headerDecode->queueOffset, 4);
EXPECT_EQ(headerDecode->transactionId, "transactionId");
EXPECT_EQ(headerDecode->regionId, "MSG_REGION");
}
TEST(commandHeader, PullMessageRequestHeader) {
PullMessageRequestHeader header;
header.consumerGroup = "testConsumer";
header.topic = "testTopic";
header.queueId = 1;
header.maxMsgNums = 2;
header.sysFlag = 3;
header.subscription = "testSub";
header.queueOffset = 4;
header.commitOffset = 5;
header.suspendTimeoutMillis = 6;
header.subVersion = 7;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["consumerGroup"], "testConsumer");
EXPECT_EQ(requestMap["topic"], "testTopic");
EXPECT_EQ(requestMap["queueId"], "1");
EXPECT_EQ(requestMap["maxMsgNums"], "2");
EXPECT_EQ(requestMap["sysFlag"], "3");
EXPECT_EQ(requestMap["subscription"], "testSub");
EXPECT_EQ(requestMap["queueOffset"], "4");
EXPECT_EQ(requestMap["commitOffset"], "5");
EXPECT_EQ(requestMap["suspendTimeoutMillis"], "6");
EXPECT_EQ(requestMap["subVersion"], "7");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["consumerGroup"], "testConsumer");
EXPECT_EQ(outData["topic"], "testTopic");
EXPECT_EQ(outData["queueId"], 1);
EXPECT_EQ(outData["maxMsgNums"], 2);
EXPECT_EQ(outData["sysFlag"], 3);
EXPECT_EQ(outData["subscription"], "testSub");
EXPECT_EQ(outData["queueOffset"], "4");
EXPECT_EQ(outData["commitOffset"], "5");
EXPECT_EQ(outData["suspendTimeoutMillis"], "6");
EXPECT_EQ(outData["subVersion"], "7");
}
TEST(commandHeader, PullMessageResponseHeader) {
PullMessageResponseHeader header;
header.suggestWhichBrokerId = 100;
header.nextBeginOffset = 200;
header.minOffset = 3000;
header.maxOffset = 5000;
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["suggestWhichBrokerId"], "100");
EXPECT_EQ(requestMap["nextBeginOffset"], "200");
EXPECT_EQ(requestMap["minOffset"], "3000");
EXPECT_EQ(requestMap["maxOffset"], "5000");
Value value;
value["suggestWhichBrokerId"] = "5";
value["nextBeginOffset"] = "102400";
value["minOffset"] = "1";
value["maxOffset"] = "123456789";
shared_ptr<PullMessageResponseHeader> headerDecode(
static_cast<PullMessageResponseHeader*>(PullMessageResponseHeader::Decode(value)));
EXPECT_EQ(headerDecode->suggestWhichBrokerId, 5);
EXPECT_EQ(headerDecode->nextBeginOffset, 102400);
EXPECT_EQ(headerDecode->minOffset, 1);
EXPECT_EQ(headerDecode->maxOffset, 123456789);
}
TEST(commandHeader, GetConsumerListByGroupResponseBody) {
Value value;
value[0] = "body";
value[1] = 1;
Value root;
root["consumerIdList"] = value;
FastWriter writer;
string data = writer.write(root);
MemoryBlock* mem = new MemoryBlock(data.c_str(), data.size());
vector<string> cids;
GetConsumerListByGroupResponseBody::Decode(mem, cids);
EXPECT_EQ(cids.size(), 1);
delete mem;
}
TEST(commandHeader, ResetOffsetRequestHeader) {
ResetOffsetRequestHeader header;
header.setTopic("testTopic");
EXPECT_EQ(header.getTopic(), "testTopic");
header.setGroup("testGroup");
EXPECT_EQ(header.getGroup(), "testGroup");
header.setTimeStamp(123);
EXPECT_EQ(header.getTimeStamp(), 123);
header.setForceFlag(true);
EXPECT_TRUE(header.getForceFlag());
Value value;
value["isForce"] = "false";
shared_ptr<ResetOffsetRequestHeader> headersh(
static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
EXPECT_EQ(headersh->getTopic(), "");
EXPECT_EQ(headersh->getGroup(), "");
// EXPECT_EQ(headersh->getTimeStamp(), 0);
EXPECT_FALSE(headersh->getForceFlag());
value["topic"] = "testTopic";
headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
EXPECT_EQ(headersh->getTopic(), "testTopic");
EXPECT_EQ(headersh->getGroup(), "");
// EXPECT_EQ(headersh->getTimeStamp(), 0);
EXPECT_FALSE(headersh->getForceFlag());
value["topic"] = "testTopic";
value["group"] = "testGroup";
headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
EXPECT_EQ(headersh->getTopic(), "testTopic");
EXPECT_EQ(headersh->getGroup(), "testGroup");
// EXPECT_EQ(headersh->getTimeStamp(), 0);
EXPECT_FALSE(headersh->getForceFlag());
value["topic"] = "testTopic";
value["group"] = "testGroup";
value["timestamp"] = "123";
headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
EXPECT_EQ(headersh->getTopic(), "testTopic");
EXPECT_EQ(headersh->getGroup(), "testGroup");
EXPECT_EQ(headersh->getTimeStamp(), 123);
EXPECT_FALSE(headersh->getForceFlag());
value["topic"] = "testTopic";
value["group"] = "testGroup";
value["timestamp"] = "123";
value["isForce"] = "1";
headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
EXPECT_EQ(headersh->getTopic(), "testTopic");
EXPECT_EQ(headersh->getGroup(), "testGroup");
EXPECT_EQ(headersh->getTimeStamp(), 123);
EXPECT_TRUE(headersh->getForceFlag());
}
TEST(commandHeader, GetConsumerRunningInfoRequestHeader) {
GetConsumerRunningInfoRequestHeader header;
header.setClientId("testClientId");
header.setConsumerGroup("testConsumer");
header.setJstackEnable(true);
map<string, string> requestMap;
header.SetDeclaredFieldOfCommandHeader(requestMap);
EXPECT_EQ(requestMap["clientId"], "testClientId");
EXPECT_EQ(requestMap["consumerGroup"], "testConsumer");
EXPECT_EQ(requestMap["jstackEnable"], "1");
Value outData;
header.Encode(outData);
EXPECT_EQ(outData["clientId"], "testClientId");
EXPECT_EQ(outData["consumerGroup"], "testConsumer");
EXPECT_TRUE(outData["jstackEnable"].asBool());
shared_ptr<GetConsumerRunningInfoRequestHeader> decodeHeader(
static_cast<GetConsumerRunningInfoRequestHeader*>(GetConsumerRunningInfoRequestHeader::Decode(outData)));
EXPECT_EQ(decodeHeader->getClientId(), "testClientId");
EXPECT_EQ(decodeHeader->getConsumerGroup(), "testConsumer");
EXPECT_TRUE(decodeHeader->isJstackEnable());
}
TEST(commandHeader, NotifyConsumerIdsChangedRequestHeader) {
Json::Value ext;
shared_ptr<NotifyConsumerIdsChangedRequestHeader> header(
static_cast<NotifyConsumerIdsChangedRequestHeader*>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
EXPECT_EQ(header->getGroup(), "");
ext["consumerGroup"] = "testGroup";
header.reset(static_cast<NotifyConsumerIdsChangedRequestHeader*>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
EXPECT_EQ(header->getGroup(), "testGroup");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "commandHeader.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,116 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "map"
#include "string"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "json/reader.h"
#include "json/value.h"
#include "ConsumerRunningInfo.h"
#include "MessageQueue.h"
#include "ProcessQueueInfo.h"
#include "SubscriptionData.h"
using std::map;
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using Json::Reader;
using Json::Value;
using rocketmq::ConsumerRunningInfo;
using rocketmq::MessageQueue;
using rocketmq::ProcessQueueInfo;
using rocketmq::SubscriptionData;
TEST(ConsumerRunningInfo, init) {
ConsumerRunningInfo info;
// jstack
info.setJstack("jstack");
EXPECT_EQ(info.getJstack(), "jstack");
// property
EXPECT_TRUE(info.getProperties().empty());
info.setProperty("testKey", "testValue");
map<string, string> properties = info.getProperties();
EXPECT_EQ(properties["testKey"], "testValue");
info.setProperties(map<string, string>());
EXPECT_TRUE(info.getProperties().empty());
info.setProperty("testKey", "testValue");
map<string, string> properties2 = info.getProperties();
EXPECT_EQ(properties2["testKey"], "testValue");
// subscription
EXPECT_TRUE(info.getSubscriptionSet().empty());
vector<SubscriptionData> subscriptionSet;
SubscriptionData sData1("testTopic", "testSub");
sData1.putTagsSet("testTag");
sData1.putCodeSet("11234");
subscriptionSet.push_back(sData1);
SubscriptionData sData2("testTopic2", "testSub2");
sData2.putTagsSet("testTag2");
sData2.putCodeSet("21234");
subscriptionSet.push_back(sData2);
info.setSubscriptionSet(subscriptionSet);
EXPECT_EQ(info.getSubscriptionSet().size(), 2);
// mqtable
EXPECT_TRUE(info.getMqTable().empty());
MessageQueue messageQueue1("testTopic", "testBrokerA", 3);
ProcessQueueInfo processQueueInfo1;
processQueueInfo1.commitOffset = 1024;
info.setMqTable(messageQueue1, processQueueInfo1);
MessageQueue messageQueue2("testTopic", "testBrokerB", 4);
ProcessQueueInfo processQueueInfo2;
processQueueInfo2.cachedMsgCount = 1023;
info.setMqTable(messageQueue2, processQueueInfo2);
map<MessageQueue, ProcessQueueInfo> mqTable = info.getMqTable();
EXPECT_EQ(mqTable.size(), 2);
EXPECT_EQ(mqTable[messageQueue1].commitOffset, 1024);
EXPECT_EQ(mqTable[messageQueue2].cachedMsgCount, 1023);
// encode start
info.setProperty(ConsumerRunningInfo::PROP_NAMESERVER_ADDR, "127.0.0.1:9876");
info.setProperty(ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE, "core_size");
info.setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "consume_orderly");
info.setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE, "consume_type");
info.setProperty(ConsumerRunningInfo::PROP_CLIENT_VERSION, "client_version");
info.setProperty(ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP, "127");
info.setProperty(ConsumerRunningInfo::PROP_CLIENT_SDK_VERSION, "sdk_version");
// encode
string outStr = info.encode();
EXPECT_GT(outStr.length(), 1);
EXPECT_NE(outStr.find("testTopic"), string::npos);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "ConsumerRunningInfo.*";
int iTests = RUN_ALL_TESTS();
return iTests;
}

View File

@@ -0,0 +1,115 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "vector"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ConsumeType.h"
#include "HeartbeatData.h"
#include "SubscriptionData.h"
using std::vector;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::ConsumeFromWhere;
using rocketmq::ConsumerData;
using rocketmq::ConsumeType;
using rocketmq::HeartbeatData;
using rocketmq::MessageModel;
using rocketmq::ProducerData;
using rocketmq::SubscriptionData;
TEST(heartbeatData, ProducerData) {
ProducerData producerData;
producerData.groupName = "testGroup";
Json::Value outJson = producerData.toJson();
EXPECT_EQ(outJson["groupName"], "testGroup");
}
TEST(heartbeatData, ConsumerData) {
ConsumerData consumerData;
consumerData.groupName = "testGroup";
consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
consumerData.messageModel = MessageModel::BROADCASTING;
consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
vector<SubscriptionData> subs;
subs.push_back(SubscriptionData("testTopic", "sub"));
consumerData.subscriptionDataSet = subs;
Json::Value outJson = consumerData.toJson();
EXPECT_EQ(outJson["groupName"], "testGroup");
EXPECT_EQ(outJson["consumeType"].asInt(), ConsumeType::CONSUME_ACTIVELY);
EXPECT_EQ(outJson["messageModel"].asInt(), MessageModel::BROADCASTING);
EXPECT_EQ(outJson["consumeFromWhere"].asInt(), ConsumeFromWhere::CONSUME_FROM_TIMESTAMP);
Json::Value subsValue = outJson["subscriptionDataSet"];
EXPECT_EQ(subsValue[0]["topic"], "testTopic");
EXPECT_EQ(subsValue[0]["subString"], "sub");
}
TEST(heartbeatData, HeartbeatData) {
HeartbeatData heartbeatData;
heartbeatData.setClientID("testClientId");
ProducerData producerData;
producerData.groupName = "testGroup";
EXPECT_TRUE(heartbeatData.isProducerDataSetEmpty());
heartbeatData.insertDataToProducerDataSet(producerData);
EXPECT_FALSE(heartbeatData.isProducerDataSetEmpty());
ConsumerData consumerData;
consumerData.groupName = "testGroup";
consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
consumerData.messageModel = MessageModel::BROADCASTING;
consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
vector<SubscriptionData> subs;
subs.push_back(SubscriptionData("testTopic", "sub"));
consumerData.subscriptionDataSet = subs;
EXPECT_TRUE(heartbeatData.isConsumerDataSetEmpty());
heartbeatData.insertDataToConsumerDataSet(consumerData);
EXPECT_FALSE(heartbeatData.isConsumerDataSetEmpty());
string outData;
heartbeatData.Encode(outData);
Json::Value root;
Json::Reader reader;
reader.parse(outData, root);
EXPECT_EQ(root["clientID"], "testClientId");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "heartbeatData.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,51 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "KVTable.h"
using std::map;
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::KVTable;
TEST(KVTable, init) {
KVTable table;
EXPECT_EQ(table.getTable().size(), 0);
map<string, string> maps;
maps["string"] = "string";
table.setTable(maps);
EXPECT_EQ(table.getTable().size(), 1);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "KVTable.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,123 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "vector"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "LockBatchBody.h"
#include "MQMessageQueue.h"
#include "dataBlock.h"
using std::vector;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::LockBatchRequestBody;
using rocketmq::LockBatchResponseBody;
using rocketmq::MemoryBlock;
using rocketmq::MQMessageQueue;
using rocketmq::UnlockBatchRequestBody;
TEST(lockBatchBody, LockBatchRequestBody) {
LockBatchRequestBody lockBatchRequestBody;
lockBatchRequestBody.setClientId("testClientId");
EXPECT_EQ(lockBatchRequestBody.getClientId(), "testClientId");
lockBatchRequestBody.setConsumerGroup("testGroup");
EXPECT_EQ(lockBatchRequestBody.getConsumerGroup(), "testGroup");
vector<MQMessageQueue> vectorMessageQueue;
vectorMessageQueue.push_back(MQMessageQueue());
vectorMessageQueue.push_back(MQMessageQueue());
lockBatchRequestBody.setMqSet(vectorMessageQueue);
EXPECT_EQ(lockBatchRequestBody.getMqSet(), vectorMessageQueue);
Json::Value outJson = lockBatchRequestBody.toJson(MQMessageQueue("topicTest", "testBroker", 10));
EXPECT_EQ(outJson["topic"], "topicTest");
EXPECT_EQ(outJson["brokerName"], "testBroker");
EXPECT_EQ(outJson["queueId"], 10);
string outData;
lockBatchRequestBody.Encode(outData);
Json::Value root;
Json::Reader reader;
reader.parse(outData, root);
EXPECT_EQ(root["clientId"], "testClientId");
EXPECT_EQ(root["consumerGroup"], "testGroup");
}
TEST(lockBatchBody, UnlockBatchRequestBody) {
UnlockBatchRequestBody uRB;
uRB.setClientId("testClient");
EXPECT_EQ(uRB.getClientId(), "testClient");
uRB.setConsumerGroup("testGroup");
EXPECT_EQ(uRB.getConsumerGroup(), "testGroup");
// message queue
EXPECT_TRUE(uRB.getMqSet().empty());
vector<MQMessageQueue> mqs;
MQMessageQueue mqA("testTopic", "testBrokerA", 1);
mqs.push_back(mqA);
MQMessageQueue mqB("testTopic", "testBrokerB", 2);
mqs.push_back(mqB);
uRB.setMqSet(mqs);
EXPECT_EQ(uRB.getMqSet().size(), 2);
string outData;
uRB.Encode(outData);
EXPECT_GT(outData.length(), 1);
EXPECT_NE(outData.find("testTopic"), string::npos);
}
TEST(lockBatchBody, LockBatchResponseBody) {
Json::Value root;
Json::Value mqs;
Json::Value mq;
mq["topic"] = "testTopic";
mq["brokerName"] = "testBroker";
mq["queueId"] = 1;
mqs[0] = mq;
root["lockOKMQSet"] = mqs;
Json::FastWriter fastwrite;
string outData = fastwrite.write(root);
MemoryBlock* mem = new MemoryBlock(outData.c_str(), outData.size());
LockBatchResponseBody lockBatchResponseBody;
vector<MQMessageQueue> messageQueues;
LockBatchResponseBody::Decode(mem, messageQueues);
MQMessageQueue messageQueue("testTopic", "testBroker", 1);
EXPECT_EQ(messageQueue, messageQueues[0]);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "lockBatchBody.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,89 @@
/*"
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MessageQueue.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MessageQueue;
TEST(messageExt, init) {
MessageQueue messageQueue;
EXPECT_EQ(messageQueue.getQueueId(), -1);
MessageQueue twoMessageQueue("testTopic", "testBroker", 1);
EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
MessageQueue threeMessageQueue(twoMessageQueue);
EXPECT_EQ(threeMessageQueue.getQueueId(), 1);
EXPECT_EQ(threeMessageQueue.getTopic(), "testTopic");
EXPECT_EQ(threeMessageQueue.getBrokerName(), "testBroker");
Json::Value outJson = twoMessageQueue.toJson();
EXPECT_EQ(outJson["queueId"], 1);
EXPECT_EQ(outJson["topic"], "testTopic");
EXPECT_EQ(outJson["brokerName"], "testBroker");
MessageQueue fiveMessageQueue = threeMessageQueue;
EXPECT_EQ(fiveMessageQueue.getQueueId(), 1);
EXPECT_EQ(fiveMessageQueue.getTopic(), "testTopic");
EXPECT_EQ(fiveMessageQueue.getBrokerName(), "testBroker");
}
TEST(messageExt, info) {
MessageQueue messageQueue;
messageQueue.setQueueId(11);
EXPECT_EQ(messageQueue.getQueueId(), 11);
messageQueue.setTopic("testTopic");
EXPECT_EQ(messageQueue.getTopic(), "testTopic");
messageQueue.setBrokerName("testBroker");
EXPECT_EQ(messageQueue.getBrokerName(), "testBroker");
}
TEST(messageExt, operators) {
MessageQueue messageQueue;
EXPECT_TRUE(messageQueue == messageQueue);
MessageQueue twoMessageQueue;
EXPECT_TRUE(messageQueue == twoMessageQueue);
twoMessageQueue.setTopic("testTopic");
EXPECT_FALSE(messageQueue == twoMessageQueue);
messageQueue.setQueueId(11);
EXPECT_FALSE(messageQueue == twoMessageQueue);
messageQueue.setBrokerName("testBroker");
EXPECT_FALSE(messageQueue == twoMessageQueue);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "messageExt.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,78 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MQMessageExt.h"
#include "ProcessQueueInfo.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::MQMessageExt;
using rocketmq::ProcessQueueInfo;
TEST(processQueueInfo, init) {
ProcessQueueInfo processQueueInfo;
EXPECT_EQ(processQueueInfo.commitOffset, 0);
EXPECT_EQ(processQueueInfo.cachedMsgMinOffset, 0);
EXPECT_EQ(processQueueInfo.cachedMsgMaxOffset, 0);
EXPECT_EQ(processQueueInfo.cachedMsgCount, 0);
EXPECT_EQ(processQueueInfo.transactionMsgMinOffset, 0);
EXPECT_EQ(processQueueInfo.transactionMsgMaxOffset, 0);
EXPECT_EQ(processQueueInfo.transactionMsgCount, 0);
EXPECT_EQ(processQueueInfo.locked, false);
EXPECT_EQ(processQueueInfo.tryUnlockTimes, 0);
EXPECT_EQ(processQueueInfo.lastLockTimestamp, 123);
EXPECT_EQ(processQueueInfo.droped, false);
EXPECT_EQ(processQueueInfo.lastPullTimestamp, 0);
EXPECT_EQ(processQueueInfo.lastConsumeTimestamp, 0);
processQueueInfo.setLocked(true);
EXPECT_EQ(processQueueInfo.isLocked(), true);
processQueueInfo.setDroped(true);
EXPECT_EQ(processQueueInfo.isDroped(), true);
processQueueInfo.setCommitOffset(456);
EXPECT_EQ(processQueueInfo.getCommitOffset(), 456);
Json::Value outJson = processQueueInfo.toJson();
EXPECT_EQ(outJson["commitOffset"], "456");
EXPECT_EQ(outJson["cachedMsgMinOffset"], "0");
EXPECT_EQ(outJson["cachedMsgMaxOffset"], "0");
EXPECT_EQ(outJson["cachedMsgCount"].asInt(), 0);
EXPECT_EQ(outJson["transactionMsgMinOffset"], "0");
EXPECT_EQ(outJson["transactionMsgMaxOffset"], "0");
EXPECT_EQ(outJson["transactionMsgCount"].asInt(), 0);
EXPECT_EQ(outJson["locked"].asBool(), true);
EXPECT_EQ(outJson["tryUnlockTimes"].asInt(), 0);
EXPECT_EQ(outJson["lastLockTimestamp"], "123");
EXPECT_EQ(outJson["droped"].asBool(), true);
EXPECT_EQ(outJson["lastPullTimestamp"], "0");
EXPECT_EQ(outJson["lastConsumeTimestamp"], "0");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "processQueueInfo.init";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,258 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <iostream>
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "CommandHeader.h"
#include "MQProtos.h"
#include "MQVersion.h"
#include "MemoryOutputStream.h"
#include "RemotingCommand.h"
#include "dataBlock.h"
using std::shared_ptr;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::CommandHeader;
using rocketmq::GetConsumerRunningInfoRequestHeader;
using rocketmq::GetEarliestMsgStoretimeResponseHeader;
using rocketmq::GetMaxOffsetResponseHeader;
using rocketmq::GetMinOffsetResponseHeader;
using rocketmq::GetRouteInfoRequestHeader;
using rocketmq::MemoryBlock;
using rocketmq::MemoryOutputStream;
using rocketmq::MQRequestCode;
using rocketmq::MQVersion;
using rocketmq::NotifyConsumerIdsChangedRequestHeader;
using rocketmq::PullMessageResponseHeader;
using rocketmq::QueryConsumerOffsetResponseHeader;
using rocketmq::RemotingCommand;
using rocketmq::ResetOffsetRequestHeader;
using rocketmq::SearchOffsetResponseHeader;
using rocketmq::SendMessageResponseHeader;
TEST(remotingCommand, init) {
RemotingCommand remotingCommand;
EXPECT_EQ(remotingCommand.getCode(), 0);
RemotingCommand twoRemotingCommand(13);
EXPECT_EQ(twoRemotingCommand.getCode(), 13);
EXPECT_EQ(twoRemotingCommand.getOpaque(), 0);
EXPECT_EQ(twoRemotingCommand.getRemark(), "");
EXPECT_EQ(twoRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
// EXPECT_EQ(twoRemotingCommand.getFlag() , 0);
EXPECT_EQ(twoRemotingCommand.getMsgBody(), "");
EXPECT_TRUE(twoRemotingCommand.getCommandHeader() == nullptr);
RemotingCommand threeRemotingCommand(13, new GetRouteInfoRequestHeader("topic"));
EXPECT_FALSE(threeRemotingCommand.getCommandHeader() == nullptr);
RemotingCommand frouRemotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark",
new GetRouteInfoRequestHeader("topic"));
EXPECT_EQ(frouRemotingCommand.getCode(), 13);
EXPECT_EQ(frouRemotingCommand.getOpaque(), 12);
EXPECT_EQ(frouRemotingCommand.getRemark(), "remark");
EXPECT_EQ(frouRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
EXPECT_EQ(frouRemotingCommand.getFlag(), 3);
EXPECT_EQ(frouRemotingCommand.getMsgBody(), "");
EXPECT_FALSE(frouRemotingCommand.getCommandHeader() == nullptr);
RemotingCommand sixRemotingCommand(frouRemotingCommand);
EXPECT_EQ(sixRemotingCommand.getCode(), 13);
EXPECT_EQ(sixRemotingCommand.getOpaque(), 12);
EXPECT_EQ(sixRemotingCommand.getRemark(), "remark");
EXPECT_EQ(sixRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
EXPECT_EQ(sixRemotingCommand.getFlag(), 3);
EXPECT_EQ(sixRemotingCommand.getMsgBody(), "");
EXPECT_TRUE(sixRemotingCommand.getCommandHeader() == nullptr);
RemotingCommand* sevenRemotingCommand = &sixRemotingCommand;
EXPECT_EQ(sevenRemotingCommand->getCode(), 13);
EXPECT_EQ(sevenRemotingCommand->getOpaque(), 12);
EXPECT_EQ(sevenRemotingCommand->getRemark(), "remark");
EXPECT_EQ(sevenRemotingCommand->getVersion(), MQVersion::s_CurrentVersion);
EXPECT_EQ(sevenRemotingCommand->getFlag(), 3);
EXPECT_EQ(sevenRemotingCommand->getMsgBody(), "");
EXPECT_TRUE(sevenRemotingCommand->getCommandHeader() == nullptr);
}
TEST(remotingCommand, info) {
RemotingCommand remotingCommand;
remotingCommand.setCode(13);
EXPECT_EQ(remotingCommand.getCode(), 13);
remotingCommand.setOpaque(12);
EXPECT_EQ(remotingCommand.getOpaque(), 12);
remotingCommand.setRemark("123");
EXPECT_EQ(remotingCommand.getRemark(), "123");
remotingCommand.setMsgBody("msgBody");
EXPECT_EQ(remotingCommand.getMsgBody(), "msgBody");
remotingCommand.addExtField("key", "value");
}
TEST(remotingCommand, flag) {
RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 0, "remark",
new GetRouteInfoRequestHeader("topic"));
;
EXPECT_EQ(remotingCommand.getFlag(), 0);
remotingCommand.markResponseType();
int bits = 1 << 0;
int flag = 0;
flag |= bits;
EXPECT_EQ(remotingCommand.getFlag(), flag);
EXPECT_TRUE(remotingCommand.isResponseType());
bits = 1 << 1;
flag |= bits;
remotingCommand.markOnewayRPC();
EXPECT_EQ(remotingCommand.getFlag(), flag);
EXPECT_TRUE(remotingCommand.isOnewayRPC());
}
TEST(remotingCommand, encodeAndDecode) {
RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", NULL);
remotingCommand.SetBody("123123", 6);
remotingCommand.Encode();
// no delete
const MemoryBlock* head = remotingCommand.GetHead();
const MemoryBlock* body = remotingCommand.GetBody();
unique_ptr<MemoryOutputStream> result(new MemoryOutputStream(1024));
result->write(head->getData() + 4, head->getSize() - 4);
result->write(body->getData(), body->getSize());
shared_ptr<RemotingCommand> decodeRemtingCommand(RemotingCommand::Decode(result->getMemoryBlock()));
EXPECT_EQ(remotingCommand.getCode(), decodeRemtingCommand->getCode());
EXPECT_EQ(remotingCommand.getOpaque(), decodeRemtingCommand->getOpaque());
EXPECT_EQ(remotingCommand.getRemark(), decodeRemtingCommand->getRemark());
EXPECT_EQ(remotingCommand.getVersion(), decodeRemtingCommand->getVersion());
EXPECT_EQ(remotingCommand.getFlag(), decodeRemtingCommand->getFlag());
EXPECT_TRUE(decodeRemtingCommand->getCommandHeader() == NULL);
// ~RemotingCommand delete
GetConsumerRunningInfoRequestHeader* requestHeader = new GetConsumerRunningInfoRequestHeader();
requestHeader->setClientId("client");
requestHeader->setConsumerGroup("consumerGroup");
requestHeader->setJstackEnable(false);
RemotingCommand encodeRemotingCommand(307, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", requestHeader);
encodeRemotingCommand.SetBody("123123", 6);
encodeRemotingCommand.Encode();
// no delete
const MemoryBlock* phead = encodeRemotingCommand.GetHead();
const MemoryBlock* pbody = encodeRemotingCommand.GetBody();
unique_ptr<MemoryOutputStream> results(new MemoryOutputStream(1024));
results->write(phead->getData() + 4, phead->getSize() - 4);
results->write(pbody->getData(), pbody->getSize());
shared_ptr<RemotingCommand> decodeRemtingCommandTwo(RemotingCommand::Decode(results->getMemoryBlock()));
decodeRemtingCommandTwo->SetExtHeader(encodeRemotingCommand.getCode());
GetConsumerRunningInfoRequestHeader* header =
reinterpret_cast<GetConsumerRunningInfoRequestHeader*>(decodeRemtingCommandTwo->getCommandHeader());
EXPECT_EQ(requestHeader->getClientId(), header->getClientId());
EXPECT_EQ(requestHeader->getConsumerGroup(), header->getConsumerGroup());
}
TEST(remotingCommand, SetExtHeader) {
shared_ptr<RemotingCommand> remotingCommand(new RemotingCommand());
remotingCommand->SetExtHeader(-1);
EXPECT_TRUE(remotingCommand->getCommandHeader() == NULL);
Json::Value object;
Json::Value extFields;
extFields["id"] = 1;
object["extFields"] = extFields;
remotingCommand->setParsedJson(object);
remotingCommand->SetExtHeader(MQRequestCode::SEND_MESSAGE);
SendMessageResponseHeader* sendMessageResponseHeader =
reinterpret_cast<SendMessageResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(sendMessageResponseHeader->msgId, "");
remotingCommand->SetExtHeader(MQRequestCode::PULL_MESSAGE);
PullMessageResponseHeader* pullMessageResponseHeader =
reinterpret_cast<PullMessageResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(pullMessageResponseHeader->suggestWhichBrokerId, 0);
remotingCommand->SetExtHeader(MQRequestCode::GET_MIN_OFFSET);
GetMinOffsetResponseHeader* getMinOffsetResponseHeader =
reinterpret_cast<GetMinOffsetResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(getMinOffsetResponseHeader->offset, 0);
remotingCommand->SetExtHeader(MQRequestCode::GET_MAX_OFFSET);
GetMaxOffsetResponseHeader* getMaxOffsetResponseHeader =
reinterpret_cast<GetMaxOffsetResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(getMaxOffsetResponseHeader->offset, 0);
remotingCommand->SetExtHeader(MQRequestCode::SEARCH_OFFSET_BY_TIMESTAMP);
SearchOffsetResponseHeader* searchOffsetResponseHeader =
reinterpret_cast<SearchOffsetResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(searchOffsetResponseHeader->offset, 0);
remotingCommand->SetExtHeader(MQRequestCode::GET_EARLIEST_MSG_STORETIME);
GetEarliestMsgStoretimeResponseHeader* getEarliestMsgStoretimeResponseHeader =
reinterpret_cast<GetEarliestMsgStoretimeResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(getEarliestMsgStoretimeResponseHeader->timestamp, 0);
remotingCommand->SetExtHeader(MQRequestCode::QUERY_CONSUMER_OFFSET);
QueryConsumerOffsetResponseHeader* queryConsumerOffsetResponseHeader =
reinterpret_cast<QueryConsumerOffsetResponseHeader*>(remotingCommand->getCommandHeader());
EXPECT_EQ(queryConsumerOffsetResponseHeader->offset, 0);
extFields["isForce"] = "true";
object["extFields"] = extFields;
remotingCommand->setParsedJson(object);
remotingCommand->SetExtHeader(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
ResetOffsetRequestHeader* resetOffsetRequestHeader =
reinterpret_cast<ResetOffsetRequestHeader*>(remotingCommand->getCommandHeader());
resetOffsetRequestHeader->setGroup("group");
remotingCommand->SetExtHeader(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
GetConsumerRunningInfoRequestHeader* getConsumerRunningInfoRequestHeader =
reinterpret_cast<GetConsumerRunningInfoRequestHeader*>(remotingCommand->getCommandHeader());
getConsumerRunningInfoRequestHeader->setClientId("id");
remotingCommand->SetExtHeader(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED);
NotifyConsumerIdsChangedRequestHeader* notifyConsumerIdsChangedRequestHeader =
reinterpret_cast<NotifyConsumerIdsChangedRequestHeader*>(remotingCommand->getCommandHeader());
notifyConsumerIdsChangedRequestHeader->setGroup("group");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "remotingCommand.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,93 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "TopicRouteData.h"
#include "dataBlock.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::BrokerData;
using rocketmq::MemoryBlock;
using rocketmq::QueueData;
using rocketmq::TopicRouteData;
TEST(topicRouteData, topicRouteData) {
Json::Value root;
root["orderTopicConf"] = "orderTopicConf";
Json::Value queueDatas;
Json::Value queueData;
queueData["brokerName"] = "brokerTest";
queueData["readQueueNums"] = 8;
queueData["writeQueueNums"] = 8;
queueData["perm"] = 7;
queueDatas[0] = queueData;
root["queueDatas"] = queueDatas;
Json::Value brokerDatas;
Json::Value brokerData;
brokerData["brokerName"] = "testBroker";
Json::Value brokerAddrs;
brokerAddrs["0"] = "127.0.0.1:10091";
brokerAddrs["1"] = "127.0.0.2:10092";
brokerData["brokerAddrs"] = brokerAddrs;
brokerDatas[0] = brokerData;
root["brokerDatas"] = brokerDatas;
string out = root.toStyledString();
MemoryBlock* block = new MemoryBlock(out.c_str(), out.size());
TopicRouteData* topicRouteData = TopicRouteData::Decode(block);
EXPECT_EQ(root["orderTopicConf"], topicRouteData->getOrderTopicConf());
BrokerData broker;
broker.brokerName = "testBroker";
broker.brokerAddrs[0] = "127.0.0.1:10091";
broker.brokerAddrs[1] = "127.0.0.2:10092";
vector<BrokerData> brokerDataSt = topicRouteData->getBrokerDatas();
EXPECT_EQ(broker, brokerDataSt[0]);
QueueData queue;
queue.brokerName = "brokerTest";
queue.readQueueNums = 8;
queue.writeQueueNums = 8;
queue.perm = 7;
vector<QueueData> queueDataSt = topicRouteData->getQueueDatas();
EXPECT_EQ(queue, queueDataSt[0]);
EXPECT_EQ(topicRouteData->selectBrokerAddr(), "127.0.0.1:10091");
delete block;
delete topicRouteData;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "topicRouteData.topicRouteData";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,77 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "TraceBean.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::TraceBean;
using rocketmq::TraceMessageType;
TEST(TraceBean, Init) {
std::string m_topic("topic");
std::string m_msgId("msgid");
std::string m_offsetMsgId("offsetmsgid");
std::string m_tags("tag");
std::string m_keys("ksy");
std::string m_storeHost("storehost");
std::string m_clientHost("clienthost");
TraceMessageType m_msgType = TraceMessageType::TRACE_NORMAL_MSG;
long long m_storeTime = 100;
int m_retryTimes = 2;
int m_bodyLength = 1024;
TraceBean bean;
bean.setTopic(m_topic);
bean.setMsgId(m_msgId);
bean.setOffsetMsgId(m_offsetMsgId);
bean.setTags(m_tags);
bean.setKeys(m_keys);
bean.setStoreHost(m_storeHost);
bean.setClientHost(m_clientHost);
bean.setMsgType(m_msgType);
bean.setStoreTime(m_storeTime);
bean.setRetryTimes(m_retryTimes);
bean.setBodyLength(m_bodyLength);
EXPECT_EQ(bean.getTopic(), m_topic);
EXPECT_EQ(bean.getMsgId(), m_msgId);
EXPECT_EQ(bean.getOffsetMsgId(), m_offsetMsgId);
EXPECT_EQ(bean.getTags(), m_tags);
EXPECT_EQ(bean.getKeys(), m_keys);
EXPECT_EQ(bean.getStoreHost(), m_storeHost);
EXPECT_EQ(bean.getClientHost(), m_clientHost);
EXPECT_EQ(bean.getMsgType(), m_msgType);
EXPECT_EQ(bean.getStoreTime(), m_storeTime);
EXPECT_EQ(bean.getRetryTimes(), m_retryTimes);
EXPECT_EQ(bean.getBodyLength(), m_bodyLength);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "TraceBean.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "TraceContant.h"
#include "TraceUtil.h"
using std::string;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::TraceBean;
using rocketmq::TraceContant;
using rocketmq::TraceContext;
using rocketmq::TraceMessageType;
using rocketmq::TraceTransferBean;
using rocketmq::TraceType;
using rocketmq::TraceUtil;
TEST(TraceUtil, CovertTraceTypeToString) {
EXPECT_EQ(TraceUtil::CovertTraceTypeToString(TraceType::Pub), TraceContant::TRACE_TYPE_PUB);
EXPECT_EQ(TraceUtil::CovertTraceTypeToString(TraceType::SubBefore), TraceContant::TRACE_TYPE_BEFORE);
EXPECT_EQ(TraceUtil::CovertTraceTypeToString(TraceType::SubAfter), TraceContant::TRACE_TYPE_AFTER);
EXPECT_EQ(TraceUtil::CovertTraceTypeToString((TraceType)5), TraceContant::TRACE_TYPE_PUB);
}
TEST(TraceUtil, CovertTraceContextToTransferBean) {
TraceContext context;
TraceBean bean;
bean.setMsgType(TraceMessageType::TRACE_NORMAL_MSG);
bean.setMsgId("MessageID");
bean.setKeys("MessageKey");
context.setRegionId("region");
context.setMsgType(TraceMessageType::TRACE_TRANS_COMMIT_MSG);
context.setTraceType(TraceType::Pub);
context.setGroupName("PubGroup");
context.setCostTime(50);
context.setStatus(true);
context.setTraceBean(bean);
context.setTraceBeanIndex(1);
TraceTransferBean beanPub = TraceUtil::CovertTraceContextToTransferBean(&context);
EXPECT_GT(beanPub.getTransKey().size(), 0);
context.setTraceType(TraceType::SubBefore);
TraceTransferBean beanBefore = TraceUtil::CovertTraceContextToTransferBean(&context);
EXPECT_GT(beanBefore.getTransKey().size(), 0);
context.setTraceType(TraceType::SubAfter);
TraceTransferBean beanAfter = TraceUtil::CovertTraceContextToTransferBean(&context);
EXPECT_GT(beanAfter.getTransKey().size(), 0);
TraceContext contextFailed("testGroup");
contextFailed.setMsgType(context.getMsgType());
contextFailed.setTraceType((TraceType)5);
contextFailed.setRequestId(context.getRegionId());
contextFailed.setTimeStamp(context.getTimeStamp());
contextFailed.setTraceBeanIndex(context.getTraceBeanIndex());
TraceTransferBean beanWrong = TraceUtil::CovertTraceContextToTransferBean(&contextFailed);
EXPECT_EQ(beanWrong.getTransKey().size(), 0);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "TraceUtil.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,246 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "map"
#include "string.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "json/value.h"
#include "json/writer.h"
#include "ClientRPCHook.h"
#include "ClientRemotingProcessor.h"
#include "ConsumerRunningInfo.h"
#include "MQClientFactory.h"
#include "MQMessageQueue.h"
#include "MQProtos.h"
#include "RemotingCommand.h"
#include "SessionCredentials.h"
#include "UtilAll.h"
#include "dataBlock.h"
using std::map;
using std::string;
using ::testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Mock;
using testing::Return;
using testing::SetArgReferee;
using Json::FastWriter;
using Json::Value;
using rocketmq::ClientRemotingProcessor;
using rocketmq::ClientRPCHook;
using rocketmq::ConsumerRunningInfo;
using rocketmq::GetConsumerRunningInfoRequestHeader;
using rocketmq::MemoryBlock;
using rocketmq::MQClientFactory;
using rocketmq::MQMessageQueue;
using rocketmq::MQRequestCode;
using rocketmq::MQResponseCode;
using rocketmq::NotifyConsumerIdsChangedRequestHeader;
using rocketmq::RemotingCommand;
using rocketmq::ResetOffsetBody;
using rocketmq::ResetOffsetRequestHeader;
using rocketmq::SessionCredentials;
using rocketmq::UtilAll;
class MockClientRemotingProcessor : public ClientRemotingProcessor {
public:
MockClientRemotingProcessor(MQClientFactory* factrory) : ClientRemotingProcessor(factrory) {}
MOCK_METHOD1(resetOffset, RemotingCommand*(RemotingCommand* request));
MOCK_METHOD1(getConsumerRunningInfo, RemotingCommand*(RemotingCommand* request));
MOCK_METHOD1(notifyConsumerIdsChanged, RemotingCommand*(RemotingCommand* request));
};
class MockMQClientFactory : public MQClientFactory {
public:
MockMQClientFactory(const string& clientID,
int pullThreadNum,
uint64_t tcpConnectTimeout,
uint64_t tcpTransportTryLockTimeout,
string unitName)
: MQClientFactory(clientID,
pullThreadNum,
tcpConnectTimeout,
tcpTransportTryLockTimeout,
unitName,
true,
rocketmq::DEFAULT_SSL_PROPERTY_FILE) {}
MOCK_METHOD3(resetOffset,
void(const string& group, const string& topic, const map<MQMessageQueue, int64>& offsetTable));
MOCK_METHOD1(consumerRunningInfo, ConsumerRunningInfo*(const string& consumerGroup));
MOCK_METHOD2(getSessionCredentialFromConsumer,
bool(const string& consumerGroup, SessionCredentials& sessionCredentials));
MOCK_METHOD1(doRebalanceByConsumerGroup, void(const string& consumerGroup));
};
TEST(clientRemotingProcessor, processRequest) {
MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
ClientRemotingProcessor clientRemotingProcessor(factory);
string addr = "127.0.0.1:9876";
RemotingCommand* command = new RemotingCommand();
RemotingCommand* pResponse = new RemotingCommand(13);
pResponse->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
command->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
EXPECT_EQ(nullptr, clientRemotingProcessor.processRequest(addr, command));
NotifyConsumerIdsChangedRequestHeader* header = new NotifyConsumerIdsChangedRequestHeader();
header->setGroup("testGroup");
RemotingCommand* twoCommand = new RemotingCommand(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED, header);
EXPECT_EQ(NULL, clientRemotingProcessor.processRequest(addr, twoCommand));
command->setCode(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
// EXPECT_EQ(NULL , clientRemotingProcessor.processRequest(addr, command));
command->setCode(MQRequestCode::CHECK_TRANSACTION_STATE);
EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
command->setCode(MQRequestCode::GET_CONSUMER_STATUS_FROM_CLIENT);
EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
command->setCode(MQRequestCode::CONSUME_MESSAGE_DIRECTLY);
EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
command->setCode(1);
EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
delete twoCommand;
delete command;
delete pResponse;
}
TEST(clientRemotingProcessor, resetOffset) {
MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
Mock::AllowLeak(factory);
ClientRemotingProcessor clientRemotingProcessor(factory);
Value root;
Value messageQueues;
Value messageQueue;
messageQueue["brokerName"] = "testBroker";
messageQueue["queueId"] = 4;
messageQueue["topic"] = "testTopic";
messageQueue["offset"] = 1024;
messageQueues.append(messageQueue);
root["offsetTable"] = messageQueues;
FastWriter wrtier;
string strData = wrtier.write(root);
ResetOffsetRequestHeader* header = new ResetOffsetRequestHeader();
RemotingCommand* request = new RemotingCommand(13, header);
EXPECT_CALL(*factory, resetOffset(_, _, _)).Times(1);
clientRemotingProcessor.resetOffset(request);
request->SetBody(strData.c_str(), strData.size() - 2);
clientRemotingProcessor.resetOffset(request);
request->SetBody(strData.c_str(), strData.size());
clientRemotingProcessor.resetOffset(request);
// here header no need delete, it will managered by RemotingCommand
// delete header;
delete request;
}
TEST(clientRemotingProcessor, getConsumerRunningInfoFailed) {
MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
Mock::AllowLeak(factory);
ConsumerRunningInfo* info = new ConsumerRunningInfo();
EXPECT_CALL(*factory, consumerRunningInfo(_)).Times(2).WillOnce(Return(info)).WillOnce(Return(info));
EXPECT_CALL(*factory, getSessionCredentialFromConsumer(_, _))
.Times(2); //.WillRepeatedly(SetArgReferee<1>(sessionCredentials));
ClientRemotingProcessor clientRemotingProcessor(factory);
GetConsumerRunningInfoRequestHeader* header = new GetConsumerRunningInfoRequestHeader();
header->setConsumerGroup("testGroup");
header->setClientId("testClientId");
header->setJstackEnable(false);
RemotingCommand* request = new RemotingCommand(14, header);
RemotingCommand* command = clientRemotingProcessor.getConsumerRunningInfo("127.0.0.1:9876", request);
EXPECT_EQ(command->getCode(), MQResponseCode::SYSTEM_ERROR);
EXPECT_EQ(command->getRemark(), "The Consumer Group not exist in this consumer");
delete command;
delete request;
}
TEST(clientRemotingProcessor, notifyConsumerIdsChanged) {
MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
Mock::AllowLeak(factory);
ClientRemotingProcessor clientRemotingProcessor(factory);
NotifyConsumerIdsChangedRequestHeader* header = new NotifyConsumerIdsChangedRequestHeader();
header->setGroup("testGroup");
RemotingCommand* request = new RemotingCommand(14, header);
EXPECT_CALL(*factory, doRebalanceByConsumerGroup(_)).Times(1);
clientRemotingProcessor.notifyConsumerIdsChanged(request);
delete request;
}
TEST(clientRemotingProcessor, resetOffsetBody) {
MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
ClientRemotingProcessor clientRemotingProcessor(factory);
Value root;
Value messageQueues;
Value messageQueue;
messageQueue["brokerName"] = "testBroker";
messageQueue["queueId"] = 4;
messageQueue["topic"] = "testTopic";
messageQueue["offset"] = 1024;
messageQueues.append(messageQueue);
root["offsetTable"] = messageQueues;
FastWriter wrtier;
string strData = wrtier.write(root);
MemoryBlock* mem = new MemoryBlock(strData.c_str(), strData.size());
ResetOffsetBody* resetOffset = ResetOffsetBody::Decode(mem);
map<MQMessageQueue, int64> map = resetOffset->getOffsetTable();
MQMessageQueue mqmq("testTopic", "testBroker", 4);
EXPECT_EQ(map[mqmq], 1024);
Mock::AllowLeak(factory);
delete resetOffset;
delete mem;
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "clientRemotingProcessor.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,123 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "AsyncCallback.h"
#include "AsyncCallbackWrap.h"
#include "MQClientAPIImpl.h"
#include "MQMessage.h"
#include "RemotingCommand.h"
#include "ResponseFuture.h"
#include "TcpRemotingClient.h"
#include "UtilAll.h"
using ::testing::_;
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
using rocketmq::AsyncCallback;
using rocketmq::AsyncCallbackStatus;
using rocketmq::asyncCallBackType;
using rocketmq::AsyncCallbackWrap;
using rocketmq::MQClientAPIImpl;
using rocketmq::MQMessage;
using rocketmq::RemotingCommand;
using rocketmq::ResponseFuture;
using rocketmq::SendCallbackWrap;
using rocketmq::TcpRemotingClient;
using rocketmq::UtilAll;
class MockAsyncCallbackWrap : public SendCallbackWrap {
public:
MockAsyncCallbackWrap(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI)
: SendCallbackWrap("", MQMessage(), pAsyncCallback, pclientAPI) {}
MOCK_METHOD2(operationComplete, void(ResponseFuture*, bool));
MOCK_METHOD0(onException, void());
asyncCallBackType getCallbackType() { return asyncCallBackType::sendCallbackWrap; }
};
TEST(responseFuture, init) {
ResponseFuture responseFuture(13, 4, NULL, 1000);
EXPECT_EQ(responseFuture.getRequestCode(), 13);
EXPECT_EQ(responseFuture.getOpaque(), 4);
EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
EXPECT_FALSE(responseFuture.isSendRequestOK());
EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 1);
EXPECT_EQ(responseFuture.getRetrySendTimes(), 1);
EXPECT_EQ(responseFuture.getBrokerAddr(), "");
EXPECT_FALSE(responseFuture.getAsyncFlag());
EXPECT_TRUE(responseFuture.getAsyncCallbackWrap() == nullptr);
// ~ResponseFuture delete pcall
std::shared_ptr<AsyncCallbackWrap> callBack = std::make_shared<SendCallbackWrap>("", MQMessage(), nullptr, nullptr);
ResponseFuture twoResponseFuture(13, 4, nullptr, 1000, true, callBack);
EXPECT_TRUE(twoResponseFuture.getAsyncFlag());
EXPECT_FALSE(twoResponseFuture.getAsyncCallbackWrap() == nullptr);
}
TEST(responseFuture, info) {
ResponseFuture responseFuture(13, 4, NULL, 1000);
responseFuture.setBrokerAddr("127.0.0.1:9876");
EXPECT_EQ(responseFuture.getBrokerAddr(), "127.0.0.1:9876");
responseFuture.setMaxRetrySendTimes(3000);
EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 3000);
responseFuture.setRetrySendTimes(3000);
EXPECT_EQ(responseFuture.getRetrySendTimes(), 3000);
responseFuture.setSendRequestOK(true);
EXPECT_TRUE(responseFuture.isSendRequestOK());
}
TEST(responseFuture, response) {
// m_bAsync = false m_syncResponse
ResponseFuture responseFuture(13, 4, NULL, 1000);
EXPECT_FALSE(responseFuture.getAsyncFlag());
RemotingCommand* pResponseCommand = NULL;
responseFuture.setResponse(pResponseCommand);
EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
// m_bAsync = true m_syncResponse
ResponseFuture twoResponseFuture(13, 4, NULL, 1000, true);
EXPECT_TRUE(twoResponseFuture.getAsyncFlag());
ResponseFuture threeResponseFuture(13, 4, NULL, 1000);
uint64_t millis = UtilAll::currentTimeMillis();
RemotingCommand* remotingCommand = threeResponseFuture.waitResponse(10);
uint64_t useTime = UtilAll::currentTimeMillis() - millis;
EXPECT_LT(useTime, 30);
EXPECT_EQ(NULL, remotingCommand);
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "responseFuture.*";
int itestts = RUN_ALL_TESTS();
return itestts;
}

View File

@@ -0,0 +1,47 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "SocketUtil.h"
using ::testing::InitGoogleMock;
using ::testing::InitGoogleTest;
using testing::Return;
TEST(socketUtil, init) {
sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
EXPECT_EQ(rocketmq::socketAddress2IPPort(addr), "1.0.0.127:10091");
int host;
int port;
rocketmq::socketAddress2IPPort(addr, host, port);
EXPECT_EQ(host, inet_addr("127.0.0.1"));
EXPECT_EQ(port, 10091);
EXPECT_EQ(rocketmq::socketAddress2String(addr), "1.0.0.127");
}
int main(int argc, char* argv[]) {
InitGoogleMock(&argc, argv);
testing::GTEST_FLAG(throw_on_failure) = true;
testing::GTEST_FLAG(filter) = "socketUtil.init";
int itestts = RUN_ALL_TESTS();
return itestts;
}