Fix Unit test problem.

This commit is contained in:
KomachiSion 2025-01-10 14:35:50 +08:00
parent 7712c07e09
commit 7ccf2fbf53
38 changed files with 196 additions and 228 deletions

View File

@ -395,6 +395,7 @@ public class CacheData {
return stringBuilder.toString(); return stringBuilder.toString();
} }
@SuppressWarnings("PMD.MethodTooLongRule")
private void safeNotifyListener(final String dataId, final String group, final String content, final String type, 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 String md5, final String encryptedDataKey, final ManagerListenerWrap listenerWrap) {
final Listener listener = listenerWrap.listener; final Listener listener = listenerWrap.listener;

View File

@ -998,6 +998,7 @@ public class ClientWorker implements Closeable {
} }
} }
@SuppressWarnings("PMD.MethodTooLongRule")
private boolean checkListenCache(Map<String, List<CacheData>> listenCachesMap) throws NacosException { private boolean checkListenCache(Map<String, List<CacheData>> listenCachesMap) throws NacosException {
final AtomicBoolean hasChangedKeys = new AtomicBoolean(false); final AtomicBoolean hasChangedKeys = new AtomicBoolean(false);

View File

@ -87,21 +87,5 @@
</includes> </includes>
</resource> </resource>
</resources> </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> </build>
</project> </project>

View File

@ -236,6 +236,7 @@ public abstract class RpcClient implements Closeable {
/** /**
* Start this client. * Start this client.
*/ */
@SuppressWarnings("PMD.MethodTooLongRule")
public final void start() throws NacosException { public final void start() throws NacosException {
boolean success = rpcClientStatus.compareAndSet(RpcClientStatus.INITIALIZED, RpcClientStatus.STARTING); boolean success = rpcClientStatus.compareAndSet(RpcClientStatus.INITIALIZED, RpcClientStatus.STARTING);
@ -288,9 +289,9 @@ public abstract class RpcClient implements Closeable {
break; break;
} }
boolean statusFLowSuccess = RpcClient.this.rpcClientStatus boolean statusFlowSuccess = RpcClient.this.rpcClientStatus
.compareAndSet(rpcClientStatus, RpcClientStatus.UNHEALTHY); .compareAndSet(rpcClientStatus, RpcClientStatus.UNHEALTHY);
if (statusFLowSuccess) { if (statusFlowSuccess) {
reconnectContext = new ReconnectContext(null, false); reconnectContext = new ReconnectContext(null, false);
} else { } else {
continue; continue;
@ -470,6 +471,7 @@ public abstract class RpcClient implements Closeable {
/** /**
* switch server . * switch server .
*/ */
@SuppressWarnings("PMD.MethodTooLongRule")
protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequestFail) { protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequestFail) {
try { try {

View File

@ -31,8 +31,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -70,41 +68,15 @@ class TlsFileWatcherTest {
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap"); watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap");
watchFilesMapField.setAccessible(true); 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 = TlsFileWatcher.getInstance().getClass().getDeclaredField("fileMd5Map");
fileMd5MapField.setAccessible(true); fileMd5MapField.setAccessible(true);
serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service"); serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service");
serviceField.setAccessible(true); 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 = TlsFileWatcher.getInstance().getClass().getDeclaredField("started");
startedField.setAccessible(true); startedField.setAccessible(true);
Field modifiersField3 = Field.class.getDeclaredField("modifiers");
modifiersField3.setAccessible(true);
modifiersField3.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
} }
@BeforeEach @BeforeEach

View File

@ -144,14 +144,6 @@
</dependencies> </dependencies>
<build> <build>
<plugins> <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> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>

View File

@ -142,6 +142,7 @@ public class ConfigGrayModelMigrateService {
} }
} }
@SuppressWarnings("PMD.MethodTooLongRule")
private void doCheckMigrate() throws Exception { private void doCheckMigrate() throws Exception {
int migrateMulti = EnvUtil.getProperty("nacos.gray.migrate.executor.multi", Integer.class, Integer.valueOf(4)); int migrateMulti = EnvUtil.getProperty("nacos.gray.migrate.executor.multi", Integer.class, Integer.valueOf(4));

View File

@ -40,7 +40,7 @@ import static com.alibaba.nacos.config.server.constant.Constants.NULL;
* *
* @author shiyiyue * @author shiyiyue
*/ */
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") @SuppressWarnings({"PMD.ServiceOrDaoClassShouldEndWithImplRule", "PMD.LowerCamelCaseVariableNamingRule"})
public class ConfigRocksDbDiskService implements ConfigDiskService { public class ConfigRocksDbDiskService implements ConfigDiskService {
private static final String ROCKSDB_DATA = File.separator + "rocksdata" + File.separator; private static final String ROCKSDB_DATA = File.separator + "rocksdata" + File.separator;

View File

@ -91,7 +91,7 @@ import static com.alibaba.nacos.persistence.repository.RowMapperManager.MAP_ROW_
* *
* @author lixiaoshuang * @author lixiaoshuang
*/ */
@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"}) @SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength", "PMD.MethodTooLongRule"})
@Conditional(value = ConditionOnEmbeddedStorage.class) @Conditional(value = ConditionOnEmbeddedStorage.class)
@Service("embeddedConfigInfoPersistServiceImpl") @Service("embeddedConfigInfoPersistServiceImpl")
public class EmbeddedConfigInfoPersistServiceImpl implements ConfigInfoPersistService { public class EmbeddedConfigInfoPersistServiceImpl implements ConfigInfoPersistService {

View File

@ -43,6 +43,7 @@ import com.alibaba.nacos.core.namespace.repository.NamespacePersistService;
import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.ServletContext;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@ -62,7 +63,6 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import jakarta.servlet.ServletContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -71,7 +71,7 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals; 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.any;
import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -124,6 +124,7 @@ class ConfigControllerTest {
ReflectionTestUtils.setField(configController, "configOperationService", configOperationService); ReflectionTestUtils.setField(configController, "configOperationService", configOperationService);
ReflectionTestUtils.setField(configController, "inner", inner); ReflectionTestUtils.setField(configController, "inner", inner);
mockmvc = MockMvcBuilders.standaloneSetup(configController).build(); mockmvc = MockMvcBuilders.standaloneSetup(configController).build();
NotifyCenter.deregisterPublisher(ConfigDataChangeEvent.class);
} }
@Test @Test
@ -220,9 +221,9 @@ class ConfigControllerTest {
String data = JacksonUtils.toObj(actualValue).get("data").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString();
assertEquals("200", code); assertEquals("200", code);
assertEquals("true", data); assertEquals("true", data);
Thread.sleep(200L); Thread.sleep(1200L);
//expect //expect
assertTrue(reference.get() != null); assertNotNull(reference.get());
} }
@Test @Test

View File

@ -19,11 +19,14 @@ package com.alibaba.nacos.config.server.exception;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.config.server.controller.v2.HistoryControllerV2; 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.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.MockMvc;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@ -41,9 +44,14 @@ class GlobalExceptionHandlerTest {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
@MockBean @MockitoBean
private HistoryControllerV2 historyControllerV2; private HistoryControllerV2 historyControllerV2;
@BeforeAll
static void beforeAll() {
NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE);
}
@BeforeEach @BeforeEach
void before() { void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
@ -52,8 +60,10 @@ class GlobalExceptionHandlerTest {
@Test @Test
void testNacosRunTimeExceptionHandler() throws Exception { void testNacosRunTimeExceptionHandler() throws Exception {
// 设置HistoryControllerV2的行为使其抛出NacosRuntimeException并被GlobalExceptionHandler捕获处理 // 设置HistoryControllerV2的行为使其抛出NacosRuntimeException并被GlobalExceptionHandler捕获处理
when(historyControllerV2.getConfigsByTenant("test")).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) when(historyControllerV2.getConfigsByTenant("test")).thenThrow(
.thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); 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")); ResultActions resultActions = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test"));

View File

@ -30,6 +30,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Collections; import java.util.Collections;
@ -82,14 +83,27 @@ class ConfigCachePostProcessorDelegateTest {
.thenReturn(Collections.singletonList(mockConfigCacheMd5PostProcessor)); .thenReturn(Collections.singletonList(mockConfigCacheMd5PostProcessor));
Constructor constructor = ConfigCachePostProcessorDelegate.class.getDeclaredConstructor(); Constructor constructor = ConfigCachePostProcessorDelegate.class.getDeclaredConstructor();
constructor.setAccessible(true); 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(); ConfigCachePostProcessorDelegate delegate = (ConfigCachePostProcessorDelegate) constructor.newInstance();
field.set(null, delegate); Field field = ConfigCachePostProcessorDelegate.class.getDeclaredField("INSTANCE");
setStaticFinalField(field, delegate);
ConfigCachePostProcessorDelegate.getInstance().postProcess(null, null); ConfigCachePostProcessorDelegate.getInstance().postProcess(null, null);
verify(mockConfigCacheMd5PostProcessor, times(1)).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);
}
} }

View File

@ -31,6 +31,8 @@ import org.springframework.mock.web.MockHttpServletResponse;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -89,17 +91,30 @@ class Md5ComparatorDelegateTest {
.thenReturn(Collections.singletonList(nacosMd5Comparator)); .thenReturn(Collections.singletonList(nacosMd5Comparator));
Constructor constructor = Md5ComparatorDelegate.class.getDeclaredConstructor(); Constructor constructor = Md5ComparatorDelegate.class.getDeclaredConstructor();
constructor.setAccessible(true); 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(); Md5ComparatorDelegate delegate = (Md5ComparatorDelegate) constructor.newInstance();
field.set(null, delegate); Field field = Md5ComparatorDelegate.class.getDeclaredField("INSTANCE");
setStaticFinalField(field, delegate);
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
HashMap<String, String> clientMd5Map = new HashMap<>(); HashMap<String, String> clientMd5Map = new HashMap<>();
Md5ComparatorDelegate.getInstance().compareMd5(request, response, clientMd5Map); Md5ComparatorDelegate.getInstance().compareMd5(request, response, clientMd5Map);
verify(nacosMd5Comparator, times(1)).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);
}
} }

View File

@ -39,6 +39,7 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.sql.Timestamp;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -72,6 +73,8 @@ public class ConsoleHistoryControllerTest {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup"); 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); when(historyProxy.getConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo);
@ -99,6 +102,8 @@ public class ConsoleHistoryControllerTest {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup"); configHistoryInfo.setGroup("testGroup");
configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis()));
configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis()));
page.setPageItems(Collections.singletonList(configHistoryInfo)); page.setPageItems(Collections.singletonList(configHistoryInfo));
when(historyProxy.listConfigHistory("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1, 100)).thenReturn(page); when(historyProxy.listConfigHistory("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1, 100)).thenReturn(page);
@ -125,6 +130,8 @@ public class ConsoleHistoryControllerTest {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setDataId("testDataId");
configHistoryInfo.setGroup("testGroup"); 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( when(historyProxy.getPreviousConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn(
configHistoryInfo); configHistoryInfo);

View File

@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
@ -47,7 +47,7 @@ class ConsoleExceptionHandlerTest {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
@MockBean @MockitoBean
private HealthControllerV2 healthControllerV2; private HealthControllerV2 healthControllerV2;
@BeforeAll @BeforeAll
@ -64,7 +64,8 @@ class ConsoleExceptionHandlerTest {
void testNacosRunTimeExceptionHandler() throws Exception { void testNacosRunTimeExceptionHandler() throws Exception {
// 设置HealthControllerV2的行为使其抛出NacosRuntimeException并被ConsoleExceptionHandler捕获处理 // 设置HealthControllerV2的行为使其抛出NacosRuntimeException并被ConsoleExceptionHandler捕获处理
when(healthControllerV2.liveness()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) when(healthControllerV2.liveness()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM))
.thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR))
.thenThrow(new NacosRuntimeException(503));
// 执行请求并验证响应码 // 执行请求并验证响应码
ResultActions resultActions = mockMvc.perform(get("/v2/console/health/liveness")); ResultActions resultActions = mockMvc.perform(get("/v2/console/health/liveness"));

View File

@ -26,7 +26,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.MockMvc;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@ -45,7 +45,7 @@ class NacosApiExceptionHandlerTest {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
@MockBean @MockitoBean
private NamespaceControllerV2 namespaceControllerV2; private NamespaceControllerV2 namespaceControllerV2;
@BeforeAll @BeforeAll

View File

@ -0,0 +1,19 @@
#
# Copyright 1999-2023 Alibaba Group Holding Ltd.
#
# Licensed 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.
#
### nacos console port:
server.port=${nacos.console.port:8080}
server.servlet.contextPath=${nacos.console.contextPath:}

View File

@ -67,6 +67,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
@RestController @RestController
@RequestMapping(Commons.NACOS_CORE_CONTEXT_V2 + "/loader") @RequestMapping(Commons.NACOS_CORE_CONTEXT_V2 + "/loader")
@Deprecated @Deprecated
@SuppressWarnings("PMD.MethodTooLongRule")
public class ServerLoaderController { public class ServerLoaderController {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderController.class); private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderController.class);

View File

@ -69,6 +69,7 @@ import static com.alibaba.nacos.core.utils.Commons.NACOS_ADMIN_CORE_CONTEXT_V3;
@NacosApi @NacosApi
@RestController @RestController
@RequestMapping(NACOS_ADMIN_CORE_CONTEXT_V3 + "/loader") @RequestMapping(NACOS_ADMIN_CORE_CONTEXT_V3 + "/loader")
@SuppressWarnings("PMD.MethodTooLongRule")
public class ServerLoaderControllerV3 { public class ServerLoaderControllerV3 {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderControllerV3.class); private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderControllerV3.class);

View File

@ -78,6 +78,7 @@ public class GrpcRequestAcceptor extends RequestGrpc.RequestImplBase {
} }
@Override @Override
@SuppressWarnings("PMD.MethodTooLongRule")
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) { public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
traceIfNecessary(grpcRequest, true); traceIfNecessary(grpcRequest, true);

View File

@ -32,10 +32,6 @@
<url>http://nacos.io</url> <url>http://nacos.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-core</artifactId>
</dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>nacos-naming</artifactId> <artifactId>nacos-naming</artifactId>
@ -49,11 +45,5 @@
<groupId>io.kubernetes</groupId> <groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId> <artifactId>client-java</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.20</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -118,18 +118,11 @@ public class K8sSyncServer {
SharedIndexInformer<V1Service> serviceInformer = SharedIndexInformer<V1Service> serviceInformer =
factory.sharedIndexInformerFor( factory.sharedIndexInformerFor(
(CallGeneratorParams params) -> { (CallGeneratorParams params) -> {
return coreV1Api.listServiceForAllNamespacesCall( CoreV1Api.APIlistServiceForAllNamespacesRequest request = coreV1Api.listServiceForAllNamespaces();
null, request.resourceVersion(params.resourceVersion);
null, request.timeoutSeconds(params.timeoutSeconds);
null, request.watch(params.watch);
null, return request.buildCall(null);
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null);
}, },
V1Service.class, V1Service.class,
V1ServiceList.class); V1ServiceList.class);
@ -137,18 +130,11 @@ public class K8sSyncServer {
SharedIndexInformer<V1Endpoints> endpointInformer = SharedIndexInformer<V1Endpoints> endpointInformer =
factory.sharedIndexInformerFor( factory.sharedIndexInformerFor(
(CallGeneratorParams params) -> { (CallGeneratorParams params) -> {
return coreV1Api.listEndpointsForAllNamespacesCall( CoreV1Api.APIlistEndpointsForAllNamespacesRequest request = coreV1Api.listEndpointsForAllNamespaces();
null, request.resourceVersion(params.resourceVersion);
null, request.timeoutSeconds(params.timeoutSeconds);
null, request.watch(params.watch);
null, return request.buildCall(null);
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null);
}, },
V1Endpoints.class, V1Endpoints.class,
V1EndpointsList.class); V1EndpointsList.class);

View File

@ -22,7 +22,6 @@ import com.alibaba.nacos.api.lock.remote.LockOperationEnum;
import com.alibaba.nacos.api.lock.remote.request.LockOperationRequest; import com.alibaba.nacos.api.lock.remote.request.LockOperationRequest;
import com.alibaba.nacos.api.lock.remote.response.LockOperationResponse; import com.alibaba.nacos.api.lock.remote.response.LockOperationResponse;
import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.remote.RequestHandler; import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.lock.exception.NacosLockException; import com.alibaba.nacos.lock.exception.NacosLockException;
import com.alibaba.nacos.lock.service.LockOperationService; import com.alibaba.nacos.lock.service.LockOperationService;
@ -48,8 +47,10 @@ public class LockRequestHandler extends RequestHandler<LockOperationRequest, Loc
this.lockOperationService = lockOperationService; this.lockOperationService = lockOperationService;
} }
/**
* TODO Support auth.
*/
@Override @Override
@Secured(resource = "grpc/lock")
public LockOperationResponse handle(LockOperationRequest request, RequestMeta meta) throws NacosException { public LockOperationResponse handle(LockOperationRequest request, RequestMeta meta) throws NacosException {
Boolean lock = null; Boolean lock = null;
LOGGER.info("request: {}, instance: {}", request.getLockOperationEnum(), request.getLockInstance()); LOGGER.info("request: {}, instance: {}", request.getLockOperationEnum(), request.getLockInstance());

View File

@ -34,6 +34,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.util.Map; import java.util.Map;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -135,11 +137,14 @@ class Log4J2NacosLoggingAdapterTest {
@Test @Test
void testGetConfigurationSourceForNonFileProtocol() void testGetConfigurationSourceForNonFileProtocol()
throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException { throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException, URISyntaxException {
Method getConfigurationSourceMethod = Log4J2NacosLoggingAdapter.class.getDeclaredMethod("getConfigurationSource", URL.class); Method getConfigurationSourceMethod = Log4J2NacosLoggingAdapter.class.getDeclaredMethod("getConfigurationSource", URL.class);
getConfigurationSourceMethod.setAccessible(true); getConfigurationSourceMethod.setAccessible(true);
URL url = mock(URL.class); URL url = mock(URL.class);
URI uri = mock(URI.class);
InputStream inputStream = mock(InputStream.class); InputStream inputStream = mock(InputStream.class);
when(uri.toURL()).thenReturn(url);
when(url.toURI()).thenReturn(uri);
when(url.openStream()).thenReturn(inputStream); when(url.openStream()).thenReturn(inputStream);
when(url.getProtocol()).thenReturn("http"); when(url.getProtocol()).thenReturn("http");
ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod.invoke(log4J2NacosLoggingAdapter, url); ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod.invoke(log4J2NacosLoggingAdapter, url);

View File

@ -127,28 +127,10 @@
<groupId>io.micrometer</groupId> <groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-influx</artifactId> <artifactId>micrometer-registry-influx</artifactId>
</dependency> </dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-actuator</artifactId>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.yaml</groupId>-->
<!-- <artifactId>snakeyaml</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>-->
</dependencies> </dependencies>
<build> <build>
<plugins> <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> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>

View File

@ -340,12 +340,12 @@ public class InstanceController {
String agent = WebUtils.getUserAgent(request); String agent = WebUtils.getUserAgent(request);
String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY); String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY);
String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY); String clientIp = WebUtils.optional(request, "clientIP", StringUtils.EMPTY);
int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0")); int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false")); boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY); String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
Subscriber subscriber = new Subscriber(clientIP + ":" + udpPort, agent, app, clientIP, namespaceId, serviceName, Subscriber subscriber = new Subscriber(clientIp + ":" + udpPort, agent, app, clientIp, namespaceId, serviceName,
udpPort, clusters); udpPort, clusters);
return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly); return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly);
} }

View File

@ -150,7 +150,7 @@ class ServiceControllerTest extends BaseTest {
e.printStackTrace(); e.printStackTrace();
fail(e.getMessage()); fail(e.getMessage());
} }
TimeUnit.SECONDS.sleep(1); TimeUnit.MILLISECONDS.sleep(1200L);
assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass); assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass);
} }

View File

@ -69,8 +69,7 @@ class ServiceQueryRequestHandlerTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
ApplicationUtils applicationUtils = new ApplicationUtils(); ApplicationUtils.injectContext(applicationContext);
applicationUtils.initialize(applicationContext);
Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager);
} }

View File

@ -75,8 +75,7 @@ class SubscribeServiceRequestHandlerTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
ApplicationUtils applicationUtils = new ApplicationUtils(); ApplicationUtils.injectContext(applicationContext);
applicationUtils.initialize(applicationContext);
Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager);
} }

View File

@ -81,8 +81,8 @@ class ExternalDataSourceServiceImplTest {
ReflectionTestUtils.setField(service, "jt", jt); ReflectionTestUtils.setField(service, "jt", jt);
ReflectionTestUtils.setField(service, "tm", tm); ReflectionTestUtils.setField(service, "tm", tm);
ReflectionTestUtils.setField(service, "tjt", tjt); ReflectionTestUtils.setField(service, "tjt", tjt);
ReflectionTestUtils.setField(service, "testMasterJT", testMasterJT); ReflectionTestUtils.setField(service, "testMasterJt", testMasterJT);
ReflectionTestUtils.setField(service, "testMasterWritableJT", testMasterWritableJT); ReflectionTestUtils.setField(service, "testMasterWritableJt", testMasterWritableJT);
List<HikariDataSource> dataSourceList = new ArrayList<>(); List<HikariDataSource> dataSourceList = new ArrayList<>();
dataSourceList.add(new HikariDataSource()); dataSourceList.add(new HikariDataSource());
ReflectionTestUtils.setField(service, "dataSourceList", dataSourceList); ReflectionTestUtils.setField(service, "dataSourceList", dataSourceList);

View File

@ -55,7 +55,7 @@ class NJdbcExceptionTest {
String msg = "test msg"; String msg = "test msg";
String originExceptionName = "OriginException"; String originExceptionName = "OriginException";
NJdbcException exception = new NJdbcException(msg, cause, originExceptionName); NJdbcException exception = new NJdbcException(msg, cause, originExceptionName);
assertEquals("test msg; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); assertEquals("test msg", exception.getMessage());
assertSame(cause, exception.getCause()); assertSame(cause, exception.getCause());
assertEquals(originExceptionName, exception.getOriginExceptionName()); assertEquals(originExceptionName, exception.getOriginExceptionName());
} }
@ -64,7 +64,7 @@ class NJdbcExceptionTest {
public void testConstructorWithMessageAndCause() { public void testConstructorWithMessageAndCause() {
String msg = "test msg"; String msg = "test msg";
NJdbcException exception = new NJdbcException(msg, cause); NJdbcException exception = new NJdbcException(msg, cause);
assertEquals("test msg; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); assertEquals("test msg", exception.getMessage());
assertSame(cause, exception.getCause()); assertSame(cause, exception.getCause());
assertNull(exception.getOriginExceptionName()); assertNull(exception.getOriginExceptionName());
} }
@ -72,7 +72,7 @@ class NJdbcExceptionTest {
@Test @Test
public void testConstructorWithCause() { public void testConstructorWithCause() {
NJdbcException exception = new NJdbcException(cause); NJdbcException exception = new NJdbcException(cause);
assertEquals("; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); assertEquals("", exception.getMessage());
assertSame(cause, exception.getCause()); assertSame(cause, exception.getCause());
assertNull(exception.getOriginExceptionName()); assertNull(exception.getOriginExceptionName());
} }

View File

@ -60,8 +60,6 @@ public class NacosRoleServiceImpl {
private static final int DEFAULT_PAGE_NO = 1; private static final int DEFAULT_PAGE_NO = 1;
private static final Set<String> WHITE_PERMISSION = new HashSet<>();
@Autowired @Autowired
private AuthConfigs authConfigs; private AuthConfigs authConfigs;
@ -80,11 +78,6 @@ public class NacosRoleServiceImpl {
private volatile Map<String, List<PermissionInfo>> permissionInfoMap = new ConcurrentHashMap<>(); private volatile Map<String, List<PermissionInfo>> permissionInfoMap = new ConcurrentHashMap<>();
static {
WHITE_PERMISSION.add(AuthConstants.UPDATE_PASSWORD_ENTRY_POINT);
WHITE_PERMISSION.add(AuthConstants.LOCK_OPERATOR_POINT);
}
@Scheduled(initialDelay = 5000, fixedDelay = 15000) @Scheduled(initialDelay = 5000, fixedDelay = 15000)
private void reload() { private void reload() {
try { try {
@ -129,11 +122,6 @@ public class NacosRoleServiceImpl {
* @return true if granted, false otherwise * @return true if granted, false otherwise
*/ */
public boolean hasPermission(NacosUser nacosUser, Permission permission) { public boolean hasPermission(NacosUser nacosUser, Permission permission) {
//white permission
if (WHITE_PERMISSION.contains(permission.getResource().getName())) {
return true;
}
if (isUpdatePasswordPermission(permission)) { if (isUpdatePasswordPermission(permission)) {
return true; return true;
} }

View File

@ -18,7 +18,6 @@ package com.alibaba.nacos.plugin.auth.impl.token;
import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.exception.AccessException;
import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager; import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager;
import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -29,8 +28,6 @@ import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness; import org.mockito.quality.Strictness;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -52,9 +49,6 @@ class TokenManagerDelegateTest {
@Mock @Mock
private CachedJwtTokenManager cachedJwtTokenManager; private CachedJwtTokenManager cachedJwtTokenManager;
@Mock
private JwtTokenManager jwtTokenManager;
@Mock @Mock
private Authentication authentication; private Authentication authentication;
@ -63,8 +57,7 @@ class TokenManagerDelegateTest {
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
tokenManagerDelegate = new TokenManagerDelegate(jwtTokenManager); tokenManagerDelegate = new TokenManagerDelegate(cachedJwtTokenManager);
injectObject("tokenCacheEnabled", Boolean.TRUE);
when(cachedJwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L); when(cachedJwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L);
when(cachedJwtTokenManager.getTokenTtlInSeconds(anyString())).thenReturn(100L); when(cachedJwtTokenManager.getTokenTtlInSeconds(anyString())).thenReturn(100L);
when(cachedJwtTokenManager.getAuthentication(anyString())).thenReturn(authentication); when(cachedJwtTokenManager.getAuthentication(anyString())).thenReturn(authentication);
@ -107,10 +100,4 @@ class TokenManagerDelegateTest {
void testGetTokenValidityInSeconds() throws AccessException { void testGetTokenValidityInSeconds() throws AccessException {
assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0); assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0);
} }
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = TokenManagerDelegate.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(tokenManagerDelegate, value);
}
} }

View File

@ -32,6 +32,8 @@ import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -55,21 +57,31 @@ class ControlManagerCenterTest {
try { try {
//reset instance for reload spi //reset instance for reload spi
Field instanceRuleStorageProxy = RuleStorageProxy.class.getDeclaredField("INSTANCE"); Field instanceRuleStorageProxy = RuleStorageProxy.class.getDeclaredField("INSTANCE");
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(instanceRuleStorageProxy, instanceRuleStorageProxy.getModifiers() & ~Modifier.FINAL);
instanceRuleStorageProxy.setAccessible(true);
Constructor<RuleStorageProxy> constructor = RuleStorageProxy.class.getDeclaredConstructor(); Constructor<RuleStorageProxy> constructor = RuleStorageProxy.class.getDeclaredConstructor();
constructor.setAccessible(true); constructor.setAccessible(true);
Field modifiersFieldConstructor = Constructor.class.getDeclaredField("modifiers"); setStaticFinalField(instanceRuleStorageProxy, constructor.newInstance());
modifiersFieldConstructor.setAccessible(true);
modifiersFieldConstructor.setInt(constructor, constructor.getModifiers() & ~Modifier.PRIVATE);
instanceRuleStorageProxy.set(null, constructor.newInstance());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
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);
}
@Test @Test
void testGetInstance() { void testGetInstance() {
ControlConfigs.getInstance().setControlManagerType("test"); ControlConfigs.getInstance().setControlManagerType("test");
@ -92,7 +104,8 @@ class ControlManagerCenterTest {
@Test @Test
void testReloadTpsControlRule() throws Exception { void testReloadTpsControlRule() throws Exception {
String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator; String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
resetRuleStorageProxy(); resetRuleStorageProxy();
final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance();
@ -178,7 +191,8 @@ class ControlManagerCenterTest {
@Test @Test
void testReloadConnectionControlRule() throws Exception { void testReloadConnectionControlRule() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" + File.separator; EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection"
+ File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
resetRuleStorageProxy(); resetRuleStorageProxy();
ConnectionControlRule connectionLimitRule = new ConnectionControlRule(); ConnectionControlRule connectionLimitRule = new ConnectionControlRule();
@ -209,7 +223,8 @@ class ControlManagerCenterTest {
@Test @Test
void testReloadConnectionControlRuleExternal() throws Exception { void testReloadConnectionControlRuleExternal() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" + File.separator; EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal"
+ File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
ControlConfigs.getInstance().setRuleExternalStorage("test"); ControlConfigs.getInstance().setRuleExternalStorage("test");
resetRuleStorageProxy(); resetRuleStorageProxy();

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.plugin.datasource.mapper.Mapper;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.List; import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@ -84,16 +83,6 @@ class MapperProxyTest {
} }
}; };
Mapper proxy = mapperProxy.createProxy(mapper); Mapper proxy = mapperProxy.createProxy(mapper);
try { assertEquals("select-test", proxy.select(null, null));
Field field = proxy.getClass().getSuperclass().getDeclaredField("h");
field.setAccessible(true);
MapperProxy mapperProxy = (MapperProxy) field.get(proxy);
Field mapperField = mapperProxy.getClass().getDeclaredField("mapper");
mapperField.setAccessible(true);
Class<?> clazz = mapperField.getDeclaringClass();
assertEquals(MapperProxy.class, clazz);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
} }
} }

38
pom.xml
View File

@ -110,7 +110,7 @@
<maven-javadoc-plugin.version>2.10.4</maven-javadoc-plugin.version> <maven-javadoc-plugin.version>2.10.4</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.2.2</maven-jar-plugin.version> <maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
<maven-source-plugin.version>3.0.1</maven-source-plugin.version> <maven-source-plugin.version>3.0.1</maven-source-plugin.version>
<maven-pmd-plugin.version>3.15.0</maven-pmd-plugin.version> <maven-pmd-plugin.version>3.16.0</maven-pmd-plugin.version>
<apache-rat-plugin.version>0.12</apache-rat-plugin.version> <apache-rat-plugin.version>0.12</apache-rat-plugin.version>
<maven-resources-plugin.version>3.0.2</maven-resources-plugin.version> <maven-resources-plugin.version>3.0.2</maven-resources-plugin.version>
<jacoco-maven-plugin.version>0.8.7</jacoco-maven-plugin.version> <jacoco-maven-plugin.version>0.8.7</jacoco-maven-plugin.version>
@ -129,17 +129,16 @@
<!-- dependency version --> <!-- dependency version -->
<nacos.logback.adapter.version>1.1.3</nacos.logback.adapter.version> <nacos.logback.adapter.version>1.1.3</nacos.logback.adapter.version>
<spring-boot-dependencies.version>3.4.1</spring-boot-dependencies.version> <spring-boot-dependencies.version>3.4.1</spring-boot-dependencies.version>
<servlet-api.version>6.1.0</servlet-api.version>
<commons-io.version>2.14.0</commons-io.version> <commons-io.version>2.14.0</commons-io.version>
<commons-collections.version>3.2.2</commons-collections.version> <commons-collections.version>3.2.2</commons-collections.version>
<slf4j-api.version>2.0.13</slf4j-api.version> <slf4j-api.version>2.0.13</slf4j-api.version>
<logback.version>1.5.6</logback.version> <logback.version>1.5.12</logback.version>
<log4j.version>2.17.1</log4j.version> <log4j.version>2.24.3</log4j.version>
<mysql-connector-java.version>8.2.0</mysql-connector-java.version> <mysql-connector-java.version>8.2.0</mysql-connector-java.version>
<derby.version>10.14.2.0</derby.version> <derby.version>10.14.2.0</derby.version>
<jjwt.version>0.11.2</jjwt.version> <jjwt.version>0.11.2</jjwt.version>
<grpc-java.version>1.65.1</grpc-java.version> <grpc-java.version>1.68.2</grpc-java.version>
<proto-google-common-protos.version>2.17.0</proto-google-common-protos.version> <proto-google-common-protos.version>2.17.0</proto-google-common-protos.version>
<protobuf-java.version>3.25.5</protobuf-java.version> <protobuf-java.version>3.25.5</protobuf-java.version>
<protoc-gen-grpc-java.version>${grpc-java.version}</protoc-gen-grpc-java.version> <protoc-gen-grpc-java.version>${grpc-java.version}</protoc-gen-grpc-java.version>
@ -149,7 +148,7 @@
<jraft-core.version>1.3.14</jraft-core.version> <jraft-core.version>1.3.14</jraft-core.version>
<rpc-grpc-impl.version>${jraft-core.version}</rpc-grpc-impl.version> <rpc-grpc-impl.version>${jraft-core.version}</rpc-grpc-impl.version>
<SnakeYaml.version>2.0</SnakeYaml.version> <SnakeYaml.version>2.0</SnakeYaml.version>
<kubernetes.client.version>14.0.0</kubernetes.client.version> <kubernetes.client.version>22.0.0</kubernetes.client.version>
<junit5.version>5.10.2</junit5.version> <junit5.version>5.10.2</junit5.version>
<!-- override dependency version --> <!-- override dependency version -->
@ -317,7 +316,8 @@
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput> <consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError> <failsOnError>true</failsOnError>
<excludes>**/consistency/entity/**,**/nacos/test/**,**/api/grpc/auto/**,**/istio/**,**/protobuf/**</excludes> <excludes>**/consistency/entity/**,**/nacos/test/**,**/api/grpc/auto/**,**/istio/**,**/protobuf/**
</excludes>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>
@ -425,6 +425,15 @@
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
<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> </plugin>
<plugin> <plugin>
<groupId>com.github.spotbugs</groupId> <groupId>com.github.spotbugs</groupId>
@ -847,20 +856,6 @@
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<!-- Jakarta -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
<!-- HikariCP --> <!-- HikariCP -->
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
@ -1080,7 +1075,6 @@
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.9.0</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>

View File

@ -18,12 +18,15 @@ package com.alibaba.nacos.prometheus.controller.exception;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.core.listener.startup.NacosStartUp;
import com.alibaba.nacos.core.listener.startup.NacosStartUpManager;
import com.alibaba.nacos.prometheus.controller.PrometheusController; import com.alibaba.nacos.prometheus.controller.PrometheusController;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.MockMvc;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@ -41,9 +44,14 @@ public class PrometheusApiExceptionHandlerTest {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
@MockBean @MockitoBean
private PrometheusController prometheusController; private PrometheusController prometheusController;
@BeforeAll
public static void init() {
NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE);
}
@BeforeEach @BeforeEach
public void before() { public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
@ -53,7 +61,8 @@ public class PrometheusApiExceptionHandlerTest {
public void testNacosRunTimeExceptionHandler() throws Exception { public void testNacosRunTimeExceptionHandler() throws Exception {
// 设置PrometheusController的行为使其抛出NacosRuntimeException并被PrometheusApiExceptionHandler捕获处理 // 设置PrometheusController的行为使其抛出NacosRuntimeException并被PrometheusApiExceptionHandler捕获处理
when(prometheusController.metric()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) when(prometheusController.metric()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM))
.thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR))
.thenThrow(new NacosRuntimeException(503));
// 执行请求并验证响应码 // 执行请求并验证响应码
ResultActions resultActions = mockMvc.perform(get("/prometheus")); ResultActions resultActions = mockMvc.perform(get("/prometheus"));

View File

@ -52,6 +52,7 @@ import static com.alibaba.nacos.sys.env.Constants.USE_ONLY_SITE_INTERFACES;
* *
* @author Nacos * @author Nacos
*/ */
@SuppressWarnings("PMD.LowerCamelCaseVariableNamingRule")
public class InetUtils { public class InetUtils {
private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class); private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class);