Skip to content

Commit

Permalink
Fix Unit test problem.
Browse files Browse the repository at this point in the history
  • Loading branch information
KomachiSion committed Jan 10, 2025
1 parent 7712c07 commit 7ccf2fb
Show file tree
Hide file tree
Showing 38 changed files with 196 additions and 228 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ private static String getTrace(StackTraceElement[] stackTrace, int traceDeep) {
return stringBuilder.toString();
}

@SuppressWarnings("PMD.MethodTooLongRule")
private void safeNotifyListener(final String dataId, final String group, final String content, final String type,
final String md5, final String encryptedDataKey, final ManagerListenerWrap listenerWrap) {
final Listener listener = listenerWrap.listener;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,7 @@ private void checkRemoveListenCache(Map<String, List<CacheData>> removeListenCac
}
}

@SuppressWarnings("PMD.MethodTooLongRule")
private boolean checkListenCache(Map<String, List<CacheData>> listenCachesMap) throws NacosException {

final AtomicBoolean hasChangedKeys = new AtomicBoolean(false);
Expand Down
20 changes: 2 additions & 18 deletions common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
Expand All @@ -74,7 +74,7 @@
<artifactId>mysql-connector-j</artifactId>
<scope>test</scope>
</dependency>

</dependencies>
<build>
<resources>
Expand All @@ -87,21 +87,5 @@
</includes>
</resource>
</resources>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.lang.reflect=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.nio=ALL-UNNAMED
--add-opens java.base/sun.nio.ch=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ public void onServerListChange() {
/**
* Start this client.
*/
@SuppressWarnings("PMD.MethodTooLongRule")
public final void start() throws NacosException {

boolean success = rpcClientStatus.compareAndSet(RpcClientStatus.INITIALIZED, RpcClientStatus.STARTING);
Expand Down Expand Up @@ -288,9 +289,9 @@ public final void start() throws NacosException {
break;
}

boolean statusFLowSuccess = RpcClient.this.rpcClientStatus
boolean statusFlowSuccess = RpcClient.this.rpcClientStatus
.compareAndSet(rpcClientStatus, RpcClientStatus.UNHEALTHY);
if (statusFLowSuccess) {
if (statusFlowSuccess) {
reconnectContext = new ReconnectContext(null, false);
} else {
continue;
Expand Down Expand Up @@ -470,6 +471,7 @@ protected void switchServerAsync(final ServerInfo recommendServerInfo, boolean o
/**
* switch server .
*/
@SuppressWarnings("PMD.MethodTooLongRule")
protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequestFail) {

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -70,41 +68,15 @@ static void setUpBeforeClass()
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap");
watchFilesMapField.setAccessible(true);
Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
getDeclaredFields0.setAccessible(true);
Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
Field modifiersField1 = null;
for (Field each : fields) {
if ("modifiers".equals(each.getName())) {
modifiersField1 = each;
}
}
if (modifiersField1 != null) {
modifiersField1.setAccessible(true);
modifiersField1.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
}

fileMd5MapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("fileMd5Map");
fileMd5MapField.setAccessible(true);

serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service");
serviceField.setAccessible(true);
Field modifiersField2 = null;
for (Field each : fields) {
if ("modifiers".equals(each.getName())) {
modifiersField2 = each;
}
}
if (modifiersField2 != null) {
modifiersField2.setAccessible(true);
modifiersField2.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
}

startedField = TlsFileWatcher.getInstance().getClass().getDeclaredField("started");
startedField.setAccessible(true);
Field modifiersField3 = Field.class.getDeclaredField("modifiers");
modifiersField3.setAccessible(true);
modifiersField3.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
}

@BeforeEach
Expand Down
8 changes: 0 additions & 8 deletions config/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,6 @@
</dependencies>
<build>
<plugins>
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
<argLine>-Dnacos.standalone=true</argLine>
</configuration>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ public void checkMigrateTag(String dataId, String group, String tenant, String t
}
}

@SuppressWarnings("PMD.MethodTooLongRule")
private void doCheckMigrate() throws Exception {

int migrateMulti = EnvUtil.getProperty("nacos.gray.migrate.executor.multi", Integer.class, Integer.valueOf(4));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
*
* @author shiyiyue
*/
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
@SuppressWarnings({"PMD.ServiceOrDaoClassShouldEndWithImplRule", "PMD.LowerCamelCaseVariableNamingRule"})
public class ConfigRocksDbDiskService implements ConfigDiskService {

private static final String ROCKSDB_DATA = File.separator + "rocksdata" + File.separator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
*
* @author lixiaoshuang
*/
@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"})
@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength", "PMD.MethodTooLongRule"})
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Service("embeddedConfigInfoPersistServiceImpl")
public class EmbeddedConfigInfoPersistServiceImpl implements ConfigInfoPersistService {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.ServletContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -62,7 +63,6 @@
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import jakarta.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
Expand All @@ -71,7 +71,7 @@
import java.util.concurrent.atomic.AtomicReference;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
Expand Down Expand Up @@ -124,6 +124,7 @@ void setUp() {
ReflectionTestUtils.setField(configController, "configOperationService", configOperationService);
ReflectionTestUtils.setField(configController, "inner", inner);
mockmvc = MockMvcBuilders.standaloneSetup(configController).build();
NotifyCenter.deregisterPublisher(ConfigDataChangeEvent.class);
}

@Test
Expand Down Expand Up @@ -220,9 +221,9 @@ public Class<? extends Event> subscribeType() {
String data = JacksonUtils.toObj(actualValue).get("data").toString();
assertEquals("200", code);
assertEquals("true", data);
Thread.sleep(200L);
Thread.sleep(1200L);
//expect
assertTrue(reference.get() != null);
assertNotNull(reference.get());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.config.server.controller.v2.HistoryControllerV2;
import com.alibaba.nacos.core.listener.startup.NacosStartUp;
import com.alibaba.nacos.core.listener.startup.NacosStartUpManager;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
Expand All @@ -41,9 +44,14 @@ class GlobalExceptionHandlerTest {
@Autowired
private WebApplicationContext context;

@MockBean
@MockitoBean
private HistoryControllerV2 historyControllerV2;

@BeforeAll
static void beforeAll() {
NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE);
}

@BeforeEach
void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
Expand All @@ -52,8 +60,10 @@ void before() {
@Test
void testNacosRunTimeExceptionHandler() throws Exception {
// 设置HistoryControllerV2的行为,使其抛出NacosRuntimeException并被GlobalExceptionHandler捕获处理
when(historyControllerV2.getConfigsByTenant("test")).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM))
.thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503));
when(historyControllerV2.getConfigsByTenant("test")).thenThrow(
new NacosRuntimeException(NacosException.INVALID_PARAM))
.thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR))
.thenThrow(new NacosRuntimeException(503));

// 执行请求并验证响应码
ResultActions resultActions = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;

Expand Down Expand Up @@ -82,14 +83,27 @@ void test2()
.thenReturn(Collections.singletonList(mockConfigCacheMd5PostProcessor));
Constructor constructor = ConfigCachePostProcessorDelegate.class.getDeclaredConstructor();
constructor.setAccessible(true);
Field field = ConfigCachePostProcessorDelegate.class.getDeclaredField("INSTANCE");
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
field.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
ConfigCachePostProcessorDelegate delegate = (ConfigCachePostProcessorDelegate) constructor.newInstance();
field.set(null, delegate);
Field field = ConfigCachePostProcessorDelegate.class.getDeclaredField("INSTANCE");
setStaticFinalField(field, delegate);
ConfigCachePostProcessorDelegate.getInstance().postProcess(null, null);
verify(mockConfigCacheMd5PostProcessor, times(1)).postProcess(null, null);
}

private void setStaticFinalField(Field finalField, Object value)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
getDeclaredFields0.setAccessible(true);
Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
Field modifiers = null;
for (Field each : fields) {
if ("modifiers".equals(each.getName())) {
modifiers = each;
}
}
modifiers.setAccessible(true);
modifiers.setInt(finalField, finalField.getModifiers() & ~Modifier.FINAL);
finalField.setAccessible(true);
finalField.set(null, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -89,17 +91,30 @@ public void test2() throws Exception {
.thenReturn(Collections.singletonList(nacosMd5Comparator));
Constructor constructor = Md5ComparatorDelegate.class.getDeclaredConstructor();
constructor.setAccessible(true);
Field field = Md5ComparatorDelegate.class.getDeclaredField("INSTANCE");
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
field.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
Md5ComparatorDelegate delegate = (Md5ComparatorDelegate) constructor.newInstance();
field.set(null, delegate);
Field field = Md5ComparatorDelegate.class.getDeclaredField("INSTANCE");
setStaticFinalField(field, delegate);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HashMap<String, String> clientMd5Map = new HashMap<>();
Md5ComparatorDelegate.getInstance().compareMd5(request, response, clientMd5Map);
verify(nacosMd5Comparator, times(1)).compareMd5(request, response, clientMd5Map);
}

private void setStaticFinalField(Field finalField, Object value)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
getDeclaredFields0.setAccessible(true);
Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
Field modifiers = null;
for (Field each : fields) {
if ("modifiers".equals(each.getName())) {
modifiers = each;
}
}
modifiers.setAccessible(true);
modifiers.setInt(finalField, finalField.getModifiers() & ~Modifier.FINAL);
finalField.setAccessible(true);
finalField.set(null, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;

Expand Down Expand Up @@ -72,6 +73,8 @@ void testGetConfigHistoryInfo() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup");
configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis()));
configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));

when(historyProxy.getConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo);

Expand Down Expand Up @@ -99,6 +102,8 @@ void testListConfigHistory() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup");
configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis()));
configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));
page.setPageItems(Collections.singletonList(configHistoryInfo));

when(historyProxy.listConfigHistory("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1, 100)).thenReturn(page);
Expand All @@ -125,6 +130,8 @@ void testGetPreviousConfigHistoryInfo() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup");
configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis()));
configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));

when(historyProxy.getPreviousConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn(
configHistoryInfo);
Expand Down
Loading

0 comments on commit 7ccf2fb

Please sign in to comment.