[ISSUE #673] Add unit tests for Controller. (#765)

This commit is contained in:
zhangjidi2016
2021-08-02 09:43:52 +08:00
committed by GitHub
parent dc67bb93a8
commit 9a8c354301
21 changed files with 706 additions and 147 deletions

View File

@@ -28,6 +28,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
@@ -42,7 +43,11 @@ public abstract class BaseControllerTest extends BaseTest {
protected MQAdminExt mqAdminExt;
@Mock
protected RMQConfigure rMQConfigure;
protected RMQConfigure configure;
protected MockHttpServletRequestBuilder requestBuilder = null;
protected ResultActions perform;
protected abstract Object getTestController();
@@ -54,10 +59,10 @@ public abstract class BaseControllerTest extends BaseTest {
}
protected void mockRmqConfigure() {
when(rMQConfigure.getAccessKey()).thenReturn("12345678");
when(rMQConfigure.getSecretKey()).thenReturn("rocketmq");
when(rMQConfigure.getNamesrvAddr()).thenReturn("127.0.0.1:9876");
when(rMQConfigure.isACLEnabled()).thenReturn(true);
when(configure.getAccessKey()).thenReturn("12345678");
when(configure.getSecretKey()).thenReturn("rocketmq");
when(configure.getNamesrvAddr()).thenReturn("127.0.0.1:9876");
when(configure.isACLEnabled()).thenReturn(true);
}
protected ResultActions performOkExpect(ResultActions perform) throws Exception {

View File

@@ -25,8 +25,6 @@ import org.apache.rocketmq.console.util.MockObjectUtil;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.ArgumentMatchers.anyString;
@@ -39,10 +37,6 @@ public class ClusterControllerTest extends BaseControllerTest {
@InjectMocks
private ClusterController clusterController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private ClusterServiceImpl clusterService;

View File

@@ -1,34 +0,0 @@
/*
* 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.
*/
package org.apache.rocketmq.console.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class ClusterControllerTests {
@Test
public void testList() throws Exception {
//todo add. java.lang.Exception: No runnable methods
}
}

View File

@@ -44,8 +44,6 @@ import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
@@ -64,10 +62,6 @@ public class ConsumerControllerTest extends BaseControllerTest {
@InjectMocks
private ConsumerController consumerController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private ConsumerServiceImpl consumerService;

View File

@@ -0,0 +1,201 @@
/*
* 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.
*/
package org.apache.rocketmq.console.controller;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.rocketmq.console.service.impl.DashboardCollectServiceImpl;
import org.apache.rocketmq.console.service.impl.DashboardServiceImpl;
import org.apache.rocketmq.console.util.JsonUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class DashboardControllerTest extends BaseControllerTest {
@InjectMocks
private DashboardController dashboardController;
@Spy
private DashboardServiceImpl dashboardService;
@Spy
private DashboardCollectServiceImpl dashboardCollectService;
private String nowDateStr;
private String yesterdayDateStr;
private File topicDataFile;
private File brokerDataFile;
@Before
public void init() throws Exception {
super.mockRmqConfigure();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
nowDateStr = format.format(new Date());
yesterdayDateStr = format.format(new Date((System.currentTimeMillis() - 24 * 60 * 60 * 1000)));
// generate today's brokerData and topicData cache file
brokerDataFile = this.createBrokerTestCollectDataFile(nowDateStr);
topicDataFile = this.createTopicTestCollectDataFile(nowDateStr);
when(configure.getConsoleCollectData()).thenReturn("");
}
@After
public void after() {
// delete test file
if (brokerDataFile != null && brokerDataFile.exists()) {
brokerDataFile.delete();
}
if (topicDataFile != null && topicDataFile.exists()) {
topicDataFile.delete();
}
}
@Test
public void testBroker() throws Exception {
final String url = "/dashboard/broker.query";
// 1、no broker cache data
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", yesterdayDateStr);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data").isEmpty());
// 2、the broker's data is cached locally
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", nowDateStr);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data").isNotEmpty())
.andExpect(jsonPath("$.data", hasKey("broker-a:0")))
.andExpect(jsonPath("$.data.broker-a:0").isArray())
.andExpect(jsonPath("$.data.broker-a:0", hasSize(100)));
}
@Test
public void testTopic() throws Exception {
final String url = "/dashboard/topic.query";
// 1、topicName is empty
// 1.1、no topic cache data
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", yesterdayDateStr);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data").isEmpty());
// 1.2、the topic's data is cached locally
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", nowDateStr);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data").isNotEmpty())
.andExpect(jsonPath("$.data", hasKey("topic_test")))
.andExpect(jsonPath("$.data.topic_test").isArray())
.andExpect(jsonPath("$.data.topic_test", hasSize(100)));
// 2、topicName is not empty
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", nowDateStr);
requestBuilder.param("topicName", "topic_test");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isArray())
.andExpect(jsonPath("$.data", hasSize(100)));
// 2、topicName is not empty but the no topic cache data
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("date", nowDateStr);
requestBuilder.param("topicName", "topic_test1");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk());
}
@Test
public void testTopicCurrent() throws Exception {
final String url = "/dashboard/topicCurrent";
requestBuilder = MockMvcRequestBuilders.get(url);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value("topic_test,100"));
}
@Override
protected Object getTestController() {
return dashboardController;
}
private File createBrokerTestCollectDataFile(String date) throws Exception {
File brokerFile = new File(date + ".json");
brokerFile.createNewFile();
Map<String /*brokerName:brokerId*/, List<String/*timestamp,tps*/>> resultMap = Maps.newHashMap();
List<String> brokerData = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
BigDecimal tps = new BigDecimal(i).divide(BigDecimal.valueOf(10), 3, BigDecimal.ROUND_HALF_UP);
brokerData.add((new Date().getTime() + i * 60 * 1000) + "," + tps.toString());
}
resultMap.put("broker-a:0", brokerData);
Files.write(JsonUtil.obj2String(resultMap).getBytes(), brokerFile);
return brokerFile;
}
private File createTopicTestCollectDataFile(String date) throws Exception {
File topicFile = new File(date + "_topic" + ".json");
topicFile.createNewFile();
Map<String /*topicName*/, List<String/*timestamp,inTps,inMsgCntToday,outTps,outMsgCntToday*/>> resultMap = Maps.newHashMap();
List<String> topicData = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
String inTps = new BigDecimal(i).divide(BigDecimal.valueOf(10), 3, BigDecimal.ROUND_HALF_UP).toString();
String outTps = inTps;
StringBuilder sb = new StringBuilder();
sb.append((new Date().getTime() + i * 60 * 1000))
.append(',').append(inTps)
.append(',').append(i)
.append(',').append(outTps)
.append(',').append(i);
topicData.add(sb.toString());
}
resultMap.put("topic_test", topicData);
Files.write(JsonUtil.obj2String(resultMap).getBytes(), topicFile);
return topicFile;
}
}

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.
*/
package org.apache.rocketmq.console.controller;
import java.lang.reflect.Field;
import org.apache.rocketmq.console.model.User;
import org.apache.rocketmq.console.service.impl.UserServiceImpl;
import org.apache.rocketmq.console.util.WebUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class LoginControllerTest extends BaseControllerTest {
@InjectMocks
private LoginController loginController;
@Spy
private UserServiceImpl userService;
private String contextPath = "/rocketmq-console";
@Before
public void init() {
super.mockRmqConfigure();
when(configure.isLoginRequired()).thenReturn(true);
when(configure.getRocketMqConsoleDataPath()).thenReturn("");
Field contextPathField = ReflectionUtils.findField(LoginController.class, "contextPath");
ReflectionUtils.makeAccessible(contextPathField);
ReflectionUtils.setField(contextPathField, loginController, contextPath);
}
@Test
public void testCheck() throws Exception {
final String url = "/login/check.query";
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.sessionAttr(WebUtil.USER_NAME, "admin");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.logined").value(true))
.andExpect(jsonPath("$.data.loginRequired").value(true));
}
@Test
public void testLogin() throws Exception {
final String url = "/login/login.do";
final String username = "admin";
final String rightPwd = "admin";
final String wrongPwd = "rocketmq";
{
UserServiceImpl.FileBasedUserInfoStore store
= new UserServiceImpl.FileBasedUserInfoStore(configure);
User user = store.queryByName(username);
Assert.assertNotNull(user);
Assert.assertEquals(user.getPassword(), rightPwd);
ReflectionTestUtils.setField(userService, "fileBasedUserInfoStore", store);
}
// 1、login fail
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("username", username)
.param("password", wrongPwd);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").doesNotExist())
.andExpect(jsonPath("$.status").value(-1))
.andExpect(jsonPath("$.errMsg").value("Bad username or password!"));
// 2、login success
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("username", username)
.param("password", rightPwd);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(contextPath));
}
@Test
public void testLogout() throws Exception {
final String url = "/login/logout.do";
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.sessionAttr(WebUtil.USER_NAME, "root");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(contextPath));
}
@Override protected Object getTestController() {
return loginController;
}
}

View File

@@ -46,8 +46,6 @@ import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
@@ -65,14 +63,11 @@ public class MessageControllerTest extends BaseControllerTest {
@InjectMocks
private MessageController messageController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private MessageServiceImpl messageService;
private Set<MessageQueue> messageQueues;
private DefaultMQPullConsumer defaultMQPullConsumer;
@Before

View File

@@ -0,0 +1,131 @@
/*
* 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.
*/
package org.apache.rocketmq.console.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.rocketmq.client.QueryResult;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.trace.TraceType;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.console.service.impl.MessageServiceImpl;
import org.apache.rocketmq.console.service.impl.MessageTraceServiceImpl;
import org.apache.rocketmq.console.util.MockObjectUtil;
import org.apache.rocketmq.tools.admin.api.MessageTrack;
import org.apache.rocketmq.tools.admin.api.TrackType;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class MessageTraceControllerTest extends BaseControllerTest {
@InjectMocks
private MessageTraceController messageTraceController;
@Spy
private MessageServiceImpl messageService;
@Spy
private MessageTraceServiceImpl messageTraceService;
@Before
public void init() throws MQClientException, InterruptedException {
super.mockRmqConfigure();
when(configure.getMsgTrackTopicName()).thenReturn(null);
List<MessageExt> messageList = new ArrayList<>(2);
MessageExt messageExt = MockObjectUtil.createMessageExt();
messageExt.setBody(MockObjectUtil.createTraceData().getBytes());
messageList.add(messageExt);
QueryResult queryResult = new QueryResult(System.currentTimeMillis(), messageList);
when(mqAdminExt.queryMessage(anyString(), anyString(), anyInt(), anyLong(), anyLong()))
.thenReturn(queryResult);
}
@Test
public void testViewMessage() throws Exception {
final String url = "/messageTrace/viewMessage.query";
{
MessageExt messageExt = MockObjectUtil.createMessageExt();
when(mqAdminExt.viewMessage(anyString(), anyString()))
.thenThrow(new MQClientException(208, "no message"))
.thenReturn(messageExt);
MessageTrack track = new MessageTrack();
track.setConsumerGroup("group_test");
track.setTrackType(TrackType.CONSUMED);
List<MessageTrack> tracks = new ArrayList<>();
tracks.add(track);
when(mqAdminExt.messageTrackDetail(any()))
.thenReturn(tracks);
}
// no message
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("topic", "topic_test");
requestBuilder.param("msgId", "0A9A003F00002A9F0000000000000319");
perform = mockMvc.perform(requestBuilder);
performErrorExpect(perform);
// query message success
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.messageView.topic").value("topic_test"))
.andExpect(jsonPath("$.data.messageView.msgId").value("0A9A003F00002A9F0000000000000319"));
}
@Test
public void testViewMessageTraceDetail() throws Exception {
final String url = "/messageTrace/viewMessageTraceDetail.query";
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("msgId", "0A9A003F00002A9F0000000000000319");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data", hasSize(4)))
.andExpect(jsonPath("$.data[0].traceType").value(TraceType.Pub.name()))
.andExpect(jsonPath("$.data[1].traceType").value(TraceType.SubBefore.name()))
.andExpect(jsonPath("$.data[2].traceType").value(TraceType.SubAfter.name()))
.andExpect(jsonPath("$.data[3].traceType").value(TraceType.EndTransaction.name()));
}
@Test
public void testViewMessageTraceGraph() throws Exception {
final String url = "/messageTrace/viewMessageTraceGraph.query";
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("msgId", "0A9A003F00002A9F0000000000000319");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data.producerNode.groupName").value("PID_test"))
.andExpect(jsonPath("$.data.subscriptionNodeList", hasSize(1)))
.andExpect(jsonPath("$.data.subscriptionNodeList[0].subscriptionGroup").value("group_test"))
.andExpect(jsonPath("$.data.messageTraceViews").isArray())
.andExpect(jsonPath("$.data.messageTraceViews", hasSize(4)));
}
@Override protected Object getTestController() {
return messageTraceController;
}
}

View File

@@ -0,0 +1,141 @@
/*
* 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.
*/
package org.apache.rocketmq.console.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.console.model.ConsumerMonitorConfig;
import org.apache.rocketmq.console.service.impl.MonitorServiceImpl;
import org.apache.rocketmq.console.util.JsonUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class MonitorControllerTest extends BaseControllerTest {
@InjectMocks
private MonitorController monitorController;
@Spy
private MonitorServiceImpl monitorService;
private String filePath;
private String consumeGroupName = "group_test";
private String consumeGroupName1 = "group_test1";
@Before
public void init() {
super.mockRmqConfigure();
when(configure.getRocketMqConsoleDataPath()).thenReturn("");
Map<String, ConsumerMonitorConfig> configMap = new ConcurrentHashMap<>();
configMap.put(consumeGroupName, new ConsumerMonitorConfig(0, 100));
configMap.put(consumeGroupName1, new ConsumerMonitorConfig(10, 200));
ReflectionTestUtils.setField(monitorService, "configMap", configMap);
filePath = configure.getRocketMqConsoleDataPath()
+ File.separatorChar + "monitor" + File.separatorChar + "consumerMonitorConfig.json";
}
@Test
public void testCreateOrUpdateConsumerMonitor() throws Exception {
final String url = "/monitor/createOrUpdateConsumerMonitor.do";
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("consumeGroupName", consumeGroupName)
.param("minCount", String.valueOf(0))
.param("maxDiffTotal", String.valueOf(100));
perform = mockMvc.perform(requestBuilder);
Map<String, ConsumerMonitorConfig> map =
JsonUtil.string2Obj(MixAll.file2String(filePath),
new TypeReference<Map<String, ConsumerMonitorConfig>>() {
});
Assert.assertEquals(map.size(), 2);
Assert.assertEquals(map.get(consumeGroupName).getMaxDiffTotal(), 100);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(true));
}
@Test
public void testConsumerMonitorConfig() throws Exception {
final String url = "/monitor/consumerMonitorConfig.query";
requestBuilder = MockMvcRequestBuilders.get(url);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isMap())
.andExpect(jsonPath("$.data.group_test.minCount").value(0))
.andExpect(jsonPath("$.data.group_test.maxDiffTotal").value(100));
}
@Test
public void testConsumerMonitorConfigByGroupName() throws Exception {
final String url = "/monitor/consumerMonitorConfigByGroupName.query";
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("consumeGroupName", consumeGroupName);
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.minCount").value(0))
.andExpect(jsonPath("$.data.maxDiffTotal").value(100));
}
@Test
public void testDeleteConsumerMonitor() throws Exception {
final String url = "/monitor/deleteConsumerMonitor.do";
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("consumeGroupName", consumeGroupName);
perform = mockMvc.perform(requestBuilder);
Map<String, ConsumerMonitorConfig> map =
JsonUtil.string2Obj(MixAll.file2String(filePath),
new TypeReference<Map<String, ConsumerMonitorConfig>>() {
});
Assert.assertEquals(map.size(), 1);
Assert.assertEquals(map.get(consumeGroupName1).getMaxDiffTotal(), 200);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(true));
}
@After
public void after() {
File file = new File(filePath);
File bakFile = new File(filePath + ".bak");
if (file != null && file.exists()) {
file.delete();
}
if (bakFile != null && bakFile.exists()) {
bakFile.delete();
}
}
@Override protected Object getTestController() {
return monitorController;
}
}

View File

@@ -22,8 +22,6 @@ import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
public class NamesvrControllerTest extends BaseControllerTest {
@@ -31,10 +29,6 @@ public class NamesvrControllerTest extends BaseControllerTest {
@InjectMocks
private NamesvrController namesvrController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private OpsServiceImpl opsService;

View File

@@ -29,8 +29,6 @@ import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
@@ -43,10 +41,6 @@ public class OpsControllerTest extends BaseControllerTest {
@InjectMocks
private OpsController opsController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private OpsServiceImpl opsService;
@@ -72,21 +66,21 @@ public class OpsControllerTest extends BaseControllerTest {
public void testUpdateNameSvrAddr() throws Exception {
final String url = "/ops/updateNameSvrAddr.do";
{
doNothing().when(rMQConfigure).setNamesrvAddr(anyString());
doNothing().when(configure).setNamesrvAddr(anyString());
}
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("nameSvrAddrList", "127.0.0.1:9876");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(true));
Assert.assertEquals(rMQConfigure.getNamesrvAddr(), "127.0.0.1:9876");
Assert.assertEquals(configure.getNamesrvAddr(), "127.0.0.1:9876");
}
@Test
public void testUpdateIsVIPChannel() throws Exception {
final String url = "/ops/updateIsVIPChannel.do";
{
doNothing().when(rMQConfigure).setIsVIPChannel(anyString());
doNothing().when(configure).setIsVIPChannel(anyString());
}
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("useVIPChannel", "true");

View File

@@ -26,8 +26,6 @@ import org.apache.rocketmq.remoting.protocol.LanguageCode;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
@@ -41,10 +39,6 @@ public class ProducerControllerTest extends BaseControllerTest {
@InjectMocks
private ProducerController producerController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private ProducerServiceImpl producerService;

View File

@@ -49,8 +49,6 @@ import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
@@ -69,10 +67,6 @@ public class TopicControllerTest extends BaseControllerTest {
@InjectMocks
private TopicController topicController;
private MockHttpServletRequestBuilder requestBuilder = null;
private ResultActions perform;
@Spy
private TopicServiceImpl topicService;

View File

@@ -27,6 +27,9 @@ import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.trace.TraceConstants;
import org.apache.rocketmq.client.trace.TraceType;
import org.apache.rocketmq.common.DataVersion;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.admin.ConsumeStats;
@@ -36,6 +39,7 @@ import org.apache.rocketmq.common.admin.TopicStatsTable;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.message.MessageType;
import org.apache.rocketmq.common.protocol.body.ClusterInfo;
import org.apache.rocketmq.common.protocol.body.Connection;
import org.apache.rocketmq.common.protocol.body.ConsumeStatus;
@@ -204,4 +208,55 @@ public class MockObjectUtil {
messageExt.setReconsumeTimes(0);
return messageExt;
}
public static String createTraceData() {
StringBuilder sb = new StringBuilder(100);
// pub trace data
sb.append(TraceType.Pub.name()).append(TraceConstants.CONTENT_SPLITOR)
.append("1627568812564").append(TraceConstants.CONTENT_SPLITOR)
.append("DefaultRegion").append(TraceConstants.CONTENT_SPLITOR)
.append("PID_test").append(TraceConstants.CONTENT_SPLITOR)
.append("topic_test").append(TraceConstants.CONTENT_SPLITOR)
.append("0A9A003F00002A9F0000000000000319").append(TraceConstants.CONTENT_SPLITOR)
.append("TagA").append(TraceConstants.CONTENT_SPLITOR)
.append("KeyA").append(TraceConstants.CONTENT_SPLITOR)
.append("127.0.0.1:10911").append(TraceConstants.CONTENT_SPLITOR)
.append("16").append(TraceConstants.CONTENT_SPLITOR)
.append("1224").append(TraceConstants.CONTENT_SPLITOR)
.append("0").append(TraceConstants.CONTENT_SPLITOR)
.append("0A9A003F00002A9F0000000000000000").append(TraceConstants.CONTENT_SPLITOR)
.append("true").append(TraceConstants.FIELD_SPLITOR);
// subBefore trace data
sb.append(TraceType.SubBefore.name()).append(TraceConstants.CONTENT_SPLITOR)
.append("1627569868519").append(TraceConstants.CONTENT_SPLITOR)
.append("DefaultRegion").append(TraceConstants.CONTENT_SPLITOR)
.append("group_test").append(TraceConstants.CONTENT_SPLITOR)
.append("7F000001752818B4AAC2951341580000").append(TraceConstants.CONTENT_SPLITOR)
.append("0A9A003F00002A9F0000000000000319").append(TraceConstants.CONTENT_SPLITOR)
.append("0").append(TraceConstants.CONTENT_SPLITOR)
.append("KeyA").append(TraceConstants.FIELD_SPLITOR);
// subAfter trace data
sb.append(TraceType.SubAfter.name()).append(TraceConstants.CONTENT_SPLITOR)
.append("7F000001752818B4AAC2951341580000").append(TraceConstants.CONTENT_SPLITOR)
.append("0A9A003F00002A9F0000000000000319").append(TraceConstants.CONTENT_SPLITOR)
.append("200").append(TraceConstants.CONTENT_SPLITOR)
.append("true").append(TraceConstants.CONTENT_SPLITOR)
.append("KeyA").append(TraceConstants.CONTENT_SPLITOR)
.append("0").append(TraceConstants.FIELD_SPLITOR);
// endTransaction trace data
sb.append(TraceType.EndTransaction.name()).append(TraceConstants.CONTENT_SPLITOR)
.append("1627569868519").append(TraceConstants.CONTENT_SPLITOR)
.append("DefaultRegion").append(TraceConstants.CONTENT_SPLITOR)
.append("group_test").append(TraceConstants.CONTENT_SPLITOR)
.append("topic_test").append(TraceConstants.CONTENT_SPLITOR)
.append("0A9A003F00002A9F0000000000000319").append(TraceConstants.CONTENT_SPLITOR)
.append("TagA").append(TraceConstants.CONTENT_SPLITOR)
.append("KeyA").append(TraceConstants.CONTENT_SPLITOR)
.append("127.0.0.1:10911").append(TraceConstants.CONTENT_SPLITOR)
.append(2).append(TraceConstants.CONTENT_SPLITOR)
.append("7F000001752818B4AAC2951341580000").append(TraceConstants.CONTENT_SPLITOR)
.append(LocalTransactionState.COMMIT_MESSAGE).append(TraceConstants.CONTENT_SPLITOR)
.append("true").append(TraceConstants.FIELD_SPLITOR);
return sb.toString();
}
}