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();
}
@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;

View File

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

View File

@ -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>

View File

@ -236,6 +236,7 @@ public abstract class RpcClient implements Closeable {
/**
* Start this client.
*/
@SuppressWarnings("PMD.MethodTooLongRule")
public final void start() throws NacosException {
boolean success = rpcClientStatus.compareAndSet(RpcClientStatus.INITIALIZED, RpcClientStatus.STARTING);
@ -288,9 +289,9 @@ public abstract class RpcClient implements Closeable {
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;
@ -470,6 +471,7 @@ public abstract class RpcClient implements Closeable {
/**
* switch server .
*/
@SuppressWarnings("PMD.MethodTooLongRule")
protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequestFail) {
try {

View File

@ -31,8 +31,6 @@ import java.io.File;
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;
@ -70,41 +68,15 @@ class TlsFileWatcherTest {
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

View File

@ -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>

View File

@ -142,6 +142,7 @@ public class ConfigGrayModelMigrateService {
}
}
@SuppressWarnings("PMD.MethodTooLongRule")
private void doCheckMigrate() throws Exception {
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
*/
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
@SuppressWarnings({"PMD.ServiceOrDaoClassShouldEndWithImplRule", "PMD.LowerCamelCaseVariableNamingRule"})
public class ConfigRocksDbDiskService implements ConfigDiskService {
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
*/
@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"})
@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength", "PMD.MethodTooLongRule"})
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Service("embeddedConfigInfoPersistServiceImpl")
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.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;
@ -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.setup.MockMvcBuilders;
import jakarta.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@ -71,7 +71,7 @@ import java.util.Map;
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;
@ -124,6 +124,7 @@ class ConfigControllerTest {
ReflectionTestUtils.setField(configController, "configOperationService", configOperationService);
ReflectionTestUtils.setField(configController, "inner", inner);
mockmvc = MockMvcBuilders.standaloneSetup(configController).build();
NotifyCenter.deregisterPublisher(ConfigDataChangeEvent.class);
}
@Test
@ -220,9 +221,9 @@ class ConfigControllerTest {
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

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.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;
@ -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();
@ -52,8 +60,10 @@ class GlobalExceptionHandlerTest {
@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"));

View File

@ -30,6 +30,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
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;
@ -82,14 +83,27 @@ class ConfigCachePostProcessorDelegateTest {
.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);
}
}

View File

@ -31,6 +31,8 @@ import org.springframework.mock.web.MockHttpServletResponse;
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;
@ -89,17 +91,30 @@ class Md5ComparatorDelegateTest {
.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);
}
}

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.setup.MockMvcBuilders;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
@ -72,6 +73,8 @@ public class ConsoleHistoryControllerTest {
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);
@ -99,6 +102,8 @@ public class ConsoleHistoryControllerTest {
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);
@ -125,6 +130,8 @@ public class ConsoleHistoryControllerTest {
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);

View File

@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
@ -47,7 +47,7 @@ class ConsoleExceptionHandlerTest {
@Autowired
private WebApplicationContext context;
@MockBean
@MockitoBean
private HealthControllerV2 healthControllerV2;
@BeforeAll
@ -64,7 +64,8 @@ class ConsoleExceptionHandlerTest {
void testNacosRunTimeExceptionHandler() throws Exception {
// 设置HealthControllerV2的行为使其抛出NacosRuntimeException并被ConsoleExceptionHandler捕获处理
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"));

View File

@ -26,7 +26,7 @@ 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;
@ -45,7 +45,7 @@ class NacosApiExceptionHandlerTest {
@Autowired
private WebApplicationContext context;
@MockBean
@MockitoBean
private NamespaceControllerV2 namespaceControllerV2;
@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
@RequestMapping(Commons.NACOS_CORE_CONTEXT_V2 + "/loader")
@Deprecated
@SuppressWarnings("PMD.MethodTooLongRule")
public class ServerLoaderController {
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
@RestController
@RequestMapping(NACOS_ADMIN_CORE_CONTEXT_V3 + "/loader")
@SuppressWarnings("PMD.MethodTooLongRule")
public class ServerLoaderControllerV3 {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderControllerV3.class);

View File

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

View File

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

View File

@ -118,18 +118,11 @@ public class K8sSyncServer {
SharedIndexInformer<V1Service> serviceInformer =
factory.sharedIndexInformerFor(
(CallGeneratorParams params) -> {
return coreV1Api.listServiceForAllNamespacesCall(
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null);
CoreV1Api.APIlistServiceForAllNamespacesRequest request = coreV1Api.listServiceForAllNamespaces();
request.resourceVersion(params.resourceVersion);
request.timeoutSeconds(params.timeoutSeconds);
request.watch(params.watch);
return request.buildCall(null);
},
V1Service.class,
V1ServiceList.class);
@ -137,18 +130,11 @@ public class K8sSyncServer {
SharedIndexInformer<V1Endpoints> endpointInformer =
factory.sharedIndexInformerFor(
(CallGeneratorParams params) -> {
return coreV1Api.listEndpointsForAllNamespacesCall(
null,
null,
null,
null,
null,
null,
params.resourceVersion,
null,
params.timeoutSeconds,
params.watch,
null);
CoreV1Api.APIlistEndpointsForAllNamespacesRequest request = coreV1Api.listEndpointsForAllNamespaces();
request.resourceVersion(params.resourceVersion);
request.timeoutSeconds(params.timeoutSeconds);
request.watch(params.watch);
return request.buildCall(null);
},
V1Endpoints.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.response.LockOperationResponse;
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.lock.exception.NacosLockException;
import com.alibaba.nacos.lock.service.LockOperationService;
@ -48,8 +47,10 @@ public class LockRequestHandler extends RequestHandler<LockOperationRequest, Loc
this.lockOperationService = lockOperationService;
}
/**
* TODO Support auth.
*/
@Override
@Secured(resource = "grpc/lock")
public LockOperationResponse handle(LockOperationRequest request, RequestMeta meta) throws NacosException {
Boolean lock = null;
LOGGER.info("request: {}, instance: {}", request.getLockOperationEnum(), request.getLockInstance());

View File

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

View File

@ -127,28 +127,10 @@
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-influx</artifactId>
</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>
<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>

View File

@ -340,12 +340,12 @@ public class InstanceController {
String agent = WebUtils.getUserAgent(request);
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"));
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
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);
return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -60,8 +60,6 @@ public class NacosRoleServiceImpl {
private static final int DEFAULT_PAGE_NO = 1;
private static final Set<String> WHITE_PERMISSION = new HashSet<>();
@Autowired
private AuthConfigs authConfigs;
@ -80,11 +78,6 @@ public class NacosRoleServiceImpl {
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)
private void reload() {
try {
@ -129,11 +122,6 @@ public class NacosRoleServiceImpl {
* @return true if granted, false otherwise
*/
public boolean hasPermission(NacosUser nacosUser, Permission permission) {
//white permission
if (WHITE_PERMISSION.contains(permission.getResource().getName())) {
return true;
}
if (isUpdatePasswordPermission(permission)) {
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.impl.token.impl.CachedJwtTokenManager;
import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -29,8 +28,6 @@ import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -52,9 +49,6 @@ class TokenManagerDelegateTest {
@Mock
private CachedJwtTokenManager cachedJwtTokenManager;
@Mock
private JwtTokenManager jwtTokenManager;
@Mock
private Authentication authentication;
@ -63,8 +57,7 @@ class TokenManagerDelegateTest {
@BeforeEach
void setUp() throws Exception {
tokenManagerDelegate = new TokenManagerDelegate(jwtTokenManager);
injectObject("tokenCacheEnabled", Boolean.TRUE);
tokenManagerDelegate = new TokenManagerDelegate(cachedJwtTokenManager);
when(cachedJwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L);
when(cachedJwtTokenManager.getTokenTtlInSeconds(anyString())).thenReturn(100L);
when(cachedJwtTokenManager.getAuthentication(anyString())).thenReturn(authentication);
@ -107,10 +100,4 @@ class TokenManagerDelegateTest {
void testGetTokenValidityInSeconds() throws AccessException {
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.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.concurrent.TimeUnit;
@ -55,21 +57,31 @@ class ControlManagerCenterTest {
try {
//reset instance for reload spi
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.setAccessible(true);
Field modifiersFieldConstructor = Constructor.class.getDeclaredField("modifiers");
modifiersFieldConstructor.setAccessible(true);
modifiersFieldConstructor.setInt(constructor, constructor.getModifiers() & ~Modifier.PRIVATE);
instanceRuleStorageProxy.set(null, constructor.newInstance());
setStaticFinalField(instanceRuleStorageProxy, constructor.newInstance());
} catch (Exception e) {
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
void testGetInstance() {
ControlConfigs.getInstance().setControlManagerType("test");
@ -92,7 +104,8 @@ class ControlManagerCenterTest {
@Test
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);
resetRuleStorageProxy();
final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance();
@ -178,7 +191,8 @@ class ControlManagerCenterTest {
@Test
void testReloadConnectionControlRule() throws Exception {
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);
resetRuleStorageProxy();
ConnectionControlRule connectionLimitRule = new ConnectionControlRule();
@ -209,7 +223,8 @@ class ControlManagerCenterTest {
@Test
void testReloadConnectionControlRuleExternal() throws Exception {
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().setRuleExternalStorage("test");
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.Test;
import java.lang.reflect.Field;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -84,16 +83,6 @@ class MapperProxyTest {
}
};
Mapper proxy = mapperProxy.createProxy(mapper);
try {
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();
}
assertEquals("select-test", proxy.select(null, null));
}
}

38
pom.xml
View File

@ -110,7 +110,7 @@
<maven-javadoc-plugin.version>2.10.4</maven-javadoc-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-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>
<maven-resources-plugin.version>3.0.2</maven-resources-plugin.version>
<jacoco-maven-plugin.version>0.8.7</jacoco-maven-plugin.version>
@ -129,17 +129,16 @@
<!-- dependency version -->
<nacos.logback.adapter.version>1.1.3</nacos.logback.adapter.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-collections.version>3.2.2</commons-collections.version>
<slf4j-api.version>2.0.13</slf4j-api.version>
<logback.version>1.5.6</logback.version>
<log4j.version>2.17.1</log4j.version>
<logback.version>1.5.12</logback.version>
<log4j.version>2.24.3</log4j.version>
<mysql-connector-java.version>8.2.0</mysql-connector-java.version>
<derby.version>10.14.2.0</derby.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>
<protobuf-java.version>3.25.5</protobuf-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>
<rpc-grpc-impl.version>${jraft-core.version}</rpc-grpc-impl.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>
<!-- override dependency version -->
@ -317,7 +316,8 @@
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<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>
<executions>
<execution>
@ -425,6 +425,15 @@
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<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>
<groupId>com.github.spotbugs</groupId>
@ -847,20 +856,6 @@
<version>${project.version}</version>
</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 -->
<dependency>
<groupId>com.zaxxer</groupId>
@ -1080,7 +1075,6 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
<scope>compile</scope>
</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.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 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;
@ -41,9 +44,14 @@ public class PrometheusApiExceptionHandlerTest {
@Autowired
private WebApplicationContext context;
@MockBean
@MockitoBean
private PrometheusController prometheusController;
@BeforeAll
public static void init() {
NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE);
}
@BeforeEach
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
@ -53,7 +61,8 @@ public class PrometheusApiExceptionHandlerTest {
public void testNacosRunTimeExceptionHandler() throws Exception {
// 设置PrometheusController的行为使其抛出NacosRuntimeException并被PrometheusApiExceptionHandler捕获处理
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"));

View File

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