Skip to content

Commit b28e98f

Browse files
authored
Fix unit test. (#13289)
1 parent 0e38e50 commit b28e98f

File tree

13 files changed

+86
-51
lines changed

13 files changed

+86
-51
lines changed

api/src/main/java/com/alibaba/nacos/api/ai/model/mcp/McpServerBasicInfo.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public class McpServerBasicInfo {
5050
*/
5151
private Map<String, Object> localServerConfig;
5252

53-
private boolean enabled;
53+
private boolean enabled = true;
5454

5555
/**
5656
* Auto discovery capabilities by Nacos. No need to set when create or update Mcp server.

api/src/main/java/com/alibaba/nacos/api/ai/model/mcp/McpToolMeta.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public class McpToolMeta {
2727

2828
private Map<String, String> invokeContext;
2929

30-
private boolean enabled;
30+
private boolean enabled = true;
3131

3232
private Map<String, Object> templates;
3333

client/src/main/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxy.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -277,8 +277,8 @@ public boolean serverHealthy() {
277277
try {
278278
String result = reqApi(UtilAndComs.webContext + "/v3/admin/core/state/liveness", new HashMap<>(8), HttpMethod.GET);
279279
JsonNode json = JacksonUtils.toObj(result);
280-
String serverStatus = json.get("status").asText();
281-
return "UP".equals(serverStatus);
280+
int statusCode = json.get("code").asInt();
281+
return 0 == statusCode;
282282
} catch (Exception e) {
283283
return false;
284284
}

client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java

+14-34
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,10 @@
5353
import org.mockito.MockedStatic;
5454
import org.mockito.Mockito;
5555
import org.mockito.junit.jupiter.MockitoExtension;
56-
import org.slf4j.Logger;
5756

5857
import java.io.File;
5958
import java.lang.reflect.Field;
6059
import java.lang.reflect.Method;
61-
import java.lang.reflect.Modifier;
6260
import java.util.ArrayList;
6361
import java.util.Arrays;
6462
import java.util.Collections;
@@ -70,6 +68,7 @@
7068
import java.util.concurrent.atomic.AtomicReference;
7169

7270
import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE;
71+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
7372
import static org.junit.jupiter.api.Assertions.assertEquals;
7473
import static org.junit.jupiter.api.Assertions.assertFalse;
7574
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -103,17 +102,14 @@ class ClientWorkerTest {
103102

104103
private ClientWorker clientWorkerSpy;
105104

106-
@Mock
107-
private Logger logger;
108-
109105
@BeforeEach
110106
void before() throws Exception {
111107
rpcClientFactoryMockedStatic = Mockito.mockStatic(RpcClientFactory.class);
112108

113-
rpcClientFactoryMockedStatic.when(
114-
() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class), any(GrpcClientConfig.class))).thenReturn(rpcClient);
115-
rpcClientFactoryMockedStatic.when(
116-
() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class), any(GrpcClientConfig.class))).thenReturn(rpcClient);
109+
rpcClientFactoryMockedStatic.when(() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class),
110+
any(GrpcClientConfig.class))).thenReturn(rpcClient);
111+
rpcClientFactoryMockedStatic.when(() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class),
112+
any(GrpcClientConfig.class))).thenReturn(rpcClient);
117113
localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class);
118114
Properties properties = new Properties();
119115
properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE);
@@ -126,14 +122,6 @@ void before() throws Exception {
126122
throw new RuntimeException(e);
127123
}
128124
clientWorkerSpy = Mockito.spy(clientWorker);
129-
130-
Field loggerField = ClientWorker.class.getDeclaredField("LOGGER");
131-
loggerField.setAccessible(true);
132-
133-
Field modifiersField = Field.class.getDeclaredField("modifiers");
134-
modifiersField.setAccessible(true);
135-
modifiersField.setInt(loggerField, loggerField.getModifiers() & ~Modifier.FINAL);
136-
loggerField.set(null, logger);
137125
}
138126

139127
@AfterEach
@@ -250,8 +238,7 @@ void testPublishConfigSuccess() throws NacosException {
250238
String casMd5 = "1111";
251239

252240
String type = "properties";
253-
Mockito.when(rpcClient.request(any(ConfigPublishRequest.class)))
254-
.thenReturn(new ConfigPublishResponse());
241+
Mockito.when(rpcClient.request(any(ConfigPublishRequest.class))).thenReturn(new ConfigPublishResponse());
255242
boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5,
256243
type);
257244
assertTrue(b);
@@ -575,11 +562,10 @@ public void receiveConfigInfo(String configInfo) {
575562

576563
RpcClient rpcClientInner = Mockito.mock(RpcClient.class);
577564
Mockito.when(rpcClientInner.isWaitInitiated()).thenReturn(true, false);
578-
rpcClientFactoryMockedStatic.when(
579-
() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class), any(GrpcClientConfig.class))).thenReturn(rpcClientInner);
565+
rpcClientFactoryMockedStatic.when(() -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class),
566+
any(GrpcClientConfig.class))).thenReturn(rpcClientInner);
580567
// mock listen and remove listen request
581-
Mockito.when(rpcClientInner.request(any(ConfigBatchListenRequest.class)))
582-
.thenReturn(response, response);
568+
Mockito.when(rpcClientInner.request(any(ConfigBatchListenRequest.class))).thenReturn(response, response);
583569
// mock query changed config
584570
ConfigQueryResponse configQueryResponse = new ConfigQueryResponse();
585571
configQueryResponse.setContent("content" + System.currentTimeMillis());
@@ -789,8 +775,7 @@ void testResponse403() throws NacosException {
789775

790776
ConfigRemoveResponse response = ConfigRemoveResponse.buildFailResponse("accessToken invalid");
791777
response.setErrorCode(ConfigQueryResponse.NO_RIGHT);
792-
Mockito.when(rpcClient.request(any(ConfigRemoveRequest.class)))
793-
.thenReturn(response);
778+
Mockito.when(rpcClient.request(any(ConfigRemoveRequest.class))).thenReturn(response);
794779
boolean result = clientWorker.removeConfig("a", "b", "c", "tag");
795780
assertFalse(result);
796781
}
@@ -889,12 +874,7 @@ void testMetricsMonitorSetThrowsException() throws NacosException {
889874
RuntimeException exception = new RuntimeException("Mocked exception");
890875
doThrow(exception).when(mockGaugeChild).set(0);
891876

892-
clientWorker.removeCache(dataId, group, tenant);
893-
894-
String groupKey = GroupKey.getKeyTenant(dataId, group, tenant);
895-
896-
verify(logger, times(1)).info("[{}] [unsubscribe] {}", null, groupKey);
897-
verify(logger, times(1)).error("Failed to update metrics for listen config count", exception);
877+
assertDoesNotThrow(() -> clientWorker.removeCache(dataId, group, tenant));
898878
}
899879
}
900880

@@ -915,16 +895,16 @@ public void testAddCacheDataIfAbsentEnableClientMetricsTrue() throws NacosExcept
915895
Gauge.Child mockGaugeChild = mock(Gauge.Child.class);
916896
try (MockedStatic<MetricsMonitor> mockedMetricsMonitor = Mockito.mockStatic(MetricsMonitor.class)) {
917897
mockedMetricsMonitor.when(MetricsMonitor::getListenConfigCountMonitor).thenReturn(mockGaugeChild);
918-
898+
919899
clientWorker.addCacheDataIfAbsent(dataId, group, tenant);
920-
900+
921901
verify(mockGaugeChild, times(1)).set(1);
922902
}
923903
}
924904

925905
@Test
926906
public void testAddCacheDataIfAbsentEnableClientMetricsFalse() throws NacosException {
927-
907+
928908
String dataId = "testDataId";
929909
String group = "testGroup";
930910
String tenant = "testTenant";

client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@
6666
import static org.mockito.Mockito.when;
6767

6868
@ExtendWith(MockitoExtension.class)
69-
// todo remove strictness lenient
7069
@MockitoSettings(strictness = Strictness.LENIENT)
7170
class NamingHttpClientProxyTest {
7271

@@ -370,7 +369,7 @@ void testServerHealthy() throws Exception {
370369
//given
371370
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
372371
HttpRestResult<Object> a = new HttpRestResult<Object>();
373-
a.setData("{\"status\":\"UP\"}");
372+
a.setData("{\"code\":0,\"message\":\"success\",\"data\":\"ok\"}");
374373
a.setCode(200);
375374
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
376375

@@ -381,7 +380,7 @@ void testServerHealthy() throws Exception {
381380
//when
382381
boolean serverHealthy = clientProxy.serverHealthy();
383382
//then
384-
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/operator/metrics"), any(), any(), any(),
383+
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/v3/admin/core/state/liveness"), any(), any(), any(),
385384
eq(HttpMethod.GET), any());
386385
assertTrue(serverHealthy);
387386
}

config/src/test/java/com/alibaba/nacos/config/server/service/dump/processor/DumpAllGrayProcessorTest.java

+9-5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package com.alibaba.nacos.config.server.service.dump.processor;
1818

19+
import com.alibaba.nacos.api.model.Page;
1920
import com.alibaba.nacos.common.task.NacosTask;
2021
import com.alibaba.nacos.common.utils.MD5Utils;
2122
import com.alibaba.nacos.config.server.model.CacheItem;
@@ -30,7 +31,6 @@
3031
import com.alibaba.nacos.config.server.utils.PropertyUtil;
3132
import com.alibaba.nacos.persistence.datasource.DataSourceService;
3233
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
33-
import com.alibaba.nacos.persistence.model.Page;
3434
import com.alibaba.nacos.plugin.datasource.constants.CommonConstant;
3535
import com.alibaba.nacos.sys.env.EnvUtil;
3636
import org.junit.jupiter.api.AfterEach;
@@ -103,7 +103,8 @@ void init() throws Exception {
103103

104104
when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService);
105105

106-
dumpService = new ExternalDumpService(configInfoPersistService, null, null, configInfoGrayPersistService, null);
106+
dumpService = new ExternalDumpService(configInfoPersistService, null, null, configInfoGrayPersistService, null,
107+
null);
107108

108109
dumpAllProcessor = new DumpAllProcessor(configInfoPersistService);
109110
envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("memory_limit_file_path"),
@@ -211,8 +212,10 @@ void testDumpAllGrayOnCheckAll() throws Exception {
211212
String tenant2 = configInfoGrayWrapper2.getTenant();
212213
String content2 = configInfoGrayWrapper2.getContent();
213214

214-
ConfigCacheService.dumpGray(dataId1, group1, tenant1, grayName1, grayRule1, content1, latterTimestamp, encryptedDataKey);
215-
ConfigCacheService.dumpGray(dataId2, group2, tenant2, grayName2, grayRule2, content2, earlierTimestamp, encryptedDataKey);
215+
ConfigCacheService.dumpGray(dataId1, group1, tenant1, grayName1, grayRule1, content1, latterTimestamp,
216+
encryptedDataKey);
217+
ConfigCacheService.dumpGray(dataId2, group2, tenant2, grayName2, grayRule2, content2, earlierTimestamp,
218+
encryptedDataKey);
216219

217220
DumpAllGrayTask dumpAllTask = new DumpAllGrayTask();
218221
boolean process = dumpAllGrayProcessor.process(dumpAllTask);
@@ -234,7 +237,8 @@ void testDumpAllGrayOnCheckAll() throws Exception {
234237
GroupKey2.getKey(configInfoGrayWrapper2.getDataId(), configInfoGrayWrapper2.getGroup(),
235238
configInfoGrayWrapper2.getTenant()));
236239
assertEquals(md52, contentCache2.getConfigCacheGray().get(grayName2).getMd5());
237-
assertEquals(configInfoGrayWrapper2.getLastModified(), contentCache2.getConfigCacheGray().get(grayName2).getLastModifiedTs());
240+
assertEquals(configInfoGrayWrapper2.getLastModified(),
241+
contentCache2.getConfigCacheGray().get(grayName2).getLastModifiedTs());
238242

239243
String contentFromDisk2 = ConfigDiskServiceFactory.getInstance()
240244
.getGrayContent(configInfoGrayWrapper2.getDataId(), configInfoGrayWrapper2.getGroup(),

console/src/test/java/com/alibaba/nacos/console/cluster/RemoteServerMemberManagerTest.java

+16
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
import com.alibaba.nacos.core.cluster.Member;
2121
import com.alibaba.nacos.core.cluster.MemberLookup;
2222
import com.alibaba.nacos.core.cluster.MembersChangeEvent;
23+
import com.alibaba.nacos.plugin.auth.constant.Constants;
24+
import com.alibaba.nacos.sys.env.EnvUtil;
25+
import org.junit.jupiter.api.AfterEach;
2326
import org.junit.jupiter.api.BeforeEach;
2427
import org.junit.jupiter.api.Test;
2528
import org.junit.jupiter.api.extension.ExtendWith;
@@ -28,6 +31,8 @@
2831
import org.mockito.MockedStatic;
2932
import org.mockito.Mockito;
3033
import org.mockito.junit.jupiter.MockitoExtension;
34+
import org.springframework.core.env.ConfigurableEnvironment;
35+
import org.springframework.mock.env.MockEnvironment;
3136
import org.springframework.test.util.ReflectionTestUtils;
3237

3338
import java.util.Collection;
@@ -42,16 +47,27 @@
4247
@ExtendWith(MockitoExtension.class)
4348
class RemoteServerMemberManagerTest {
4449

50+
private ConfigurableEnvironment cachedEnvironment;
51+
4552
private RemoteServerMemberManager memberManager;
4653

4754
@Mock
4855
private MemberLookup mockLookup;
4956

5057
@BeforeEach
5158
void setUp() throws Exception {
59+
cachedEnvironment = EnvUtil.getEnvironment();
60+
MockEnvironment environment = new MockEnvironment();
61+
environment.setProperty(Constants.Auth.NACOS_CORE_AUTH_ADMIN_ENABLED, "false");
62+
EnvUtil.setEnvironment(environment);
5263
memberManager = new RemoteServerMemberManager();
5364
}
5465

66+
@AfterEach
67+
void tearDown() {
68+
EnvUtil.setEnvironment(cachedEnvironment);
69+
}
70+
5571
@Test
5672
void testInitAndStartLookup() throws Exception {
5773
memberManager.init();

console/src/test/java/com/alibaba/nacos/console/config/ConsoleWebConfigTest.java

+11
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
import com.alibaba.nacos.core.code.ControllerMethodsCache;
2121
import com.alibaba.nacos.core.controller.compatibility.ApiCompatibilityFilter;
2222
import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter;
23+
import com.alibaba.nacos.plugin.auth.constant.Constants;
24+
import com.alibaba.nacos.sys.env.EnvUtil;
2325
import org.junit.jupiter.api.BeforeEach;
2426
import org.junit.jupiter.api.Test;
2527
import org.junit.jupiter.api.extension.ExtendWith;
@@ -28,7 +30,9 @@
2830
import org.mockito.junit.jupiter.MockitoExtension;
2931
import org.mockito.stubbing.Answer;
3032
import org.springframework.boot.web.servlet.FilterRegistrationBean;
33+
import org.springframework.core.env.ConfigurableEnvironment;
3134
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
35+
import org.springframework.mock.env.MockEnvironment;
3236
import org.springframework.security.config.Customizer;
3337
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
3438
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
@@ -51,17 +55,24 @@ class ConsoleWebConfigTest {
5155
@Mock
5256
private ControllerMethodsCache methodsCache;
5357

58+
private ConfigurableEnvironment cachedEnvironment;
59+
5460
ConsoleWebConfig consoleWebConfig;
5561

5662
@BeforeEach
5763
void setUp() {
64+
cachedEnvironment = EnvUtil.getEnvironment();
65+
MockEnvironment environment = new MockEnvironment();
66+
environment.setProperty(Constants.Auth.NACOS_CORE_AUTH_ADMIN_ENABLED, "false");
67+
EnvUtil.setEnvironment(environment);
5868
consoleWebConfig = new ConsoleWebConfig(methodsCache);
5969
}
6070

6171
@Test
6272
void init() {
6373
consoleWebConfig.init();
6474
verify(methodsCache).initClassMethod("com.alibaba.nacos.console.controller");
75+
EnvUtil.setEnvironment(cachedEnvironment);
6576
}
6677

6778
@Test

console/src/test/java/com/alibaba/nacos/console/handler/impl/remote/ConsoleMaintainerClientAuthPluginTest.java

+11
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,16 @@
2121
import com.alibaba.nacos.auth.config.NacosAuthConfigHolder;
2222
import com.alibaba.nacos.console.config.NacosConsoleAuthConfig;
2323
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
24+
import com.alibaba.nacos.plugin.auth.constant.Constants;
25+
import com.alibaba.nacos.sys.env.EnvUtil;
2426
import org.junit.jupiter.api.AfterEach;
2527
import org.junit.jupiter.api.BeforeEach;
2628
import org.junit.jupiter.api.Test;
2729
import org.junit.jupiter.api.extension.ExtendWith;
2830
import org.mockito.Mock;
2931
import org.mockito.junit.jupiter.MockitoExtension;
32+
import org.springframework.core.env.ConfigurableEnvironment;
33+
import org.springframework.mock.env.MockEnvironment;
3034
import org.springframework.test.util.ReflectionTestUtils;
3135

3236
import java.util.Map;
@@ -44,6 +48,8 @@ class ConsoleMaintainerClientAuthPluginTest {
4448

4549
private static final String MOCK_IDENTITY_VALUE = "mockIdentityValue";
4650

51+
private ConfigurableEnvironment cachedEnvironment;
52+
4753
@Mock
4854
NacosConsoleAuthConfig mockNacosAuthConfig;
4955

@@ -53,6 +59,10 @@ class ConsoleMaintainerClientAuthPluginTest {
5359

5460
@BeforeEach
5561
void setUp() {
62+
cachedEnvironment = EnvUtil.getEnvironment();
63+
MockEnvironment environment = new MockEnvironment();
64+
environment.setProperty(Constants.Auth.NACOS_CORE_AUTH_ADMIN_ENABLED, "false");
65+
EnvUtil.setEnvironment(environment);
5666
authPlugin = new ConsoleMaintainerClientAuthPlugin();
5767
cachedConsoleAuthConfig = NacosAuthConfigHolder.getInstance()
5868
.getNacosAuthConfigByScope(NacosConsoleAuthConfig.NACOS_CONSOLE_AUTH_SCOPE);
@@ -67,6 +77,7 @@ void tearDown() throws NacosException {
6777
NacosAuthConfigHolder.getInstance(), "nacosAuthConfigMap");
6878
nacosAuthConfigMap.put(NacosConsoleAuthConfig.NACOS_CONSOLE_AUTH_SCOPE, cachedConsoleAuthConfig);
6979
authPlugin.shutdown();
80+
EnvUtil.setEnvironment(cachedEnvironment);
7081
}
7182

7283
@Test

console/src/test/java/com/alibaba/nacos/console/handler/impl/remote/NacosMaintainerClientHolderTest.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.alibaba.nacos.maintainer.client.ai.AiMaintainerService;
2424
import com.alibaba.nacos.maintainer.client.config.ConfigMaintainerService;
2525
import com.alibaba.nacos.maintainer.client.naming.NamingMaintainerService;
26+
import com.alibaba.nacos.plugin.auth.constant.Constants;
2627
import com.alibaba.nacos.sys.env.EnvUtil;
2728
import org.junit.jupiter.api.AfterEach;
2829
import org.junit.jupiter.api.BeforeEach;
@@ -53,7 +54,9 @@ class NacosMaintainerClientHolderTest {
5354
@BeforeEach
5455
void setUp() throws NacosException {
5556
cachedEnvironment = EnvUtil.getEnvironment();
56-
EnvUtil.setEnvironment(new MockEnvironment());
57+
MockEnvironment environment = new MockEnvironment();
58+
environment.setProperty(Constants.Auth.NACOS_CORE_AUTH_ADMIN_ENABLED, "false");
59+
EnvUtil.setEnvironment(environment);
5760
Member member = new Member();
5861
member.setIp("127.0.0.1");
5962
member.setPort(3306);

0 commit comments

Comments
 (0)