----初始化项目

This commit is contained in:
2025-09-19 20:49:14 +08:00
parent b345d2828d
commit df7765c400
2867 changed files with 359313 additions and 89 deletions

47
test/core-test/pom.xml Normal file
View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 1999-2020 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>nacos-test</artifactId>
<groupId>com.alibaba.nacos</groupId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<name>nacos-core-test ${project.version}</name>
<url>https://nacos.io</url>
<artifactId>core-test</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<reuseForks>false</reuseForks>
<forkCount>1</forkCount>
<argLine>-Dnacos.standalone=true -Dnacos.server.ip=127.0.0.1</argLine>
<useUnlimitedThreads>true</useUnlimitedThreads>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,48 @@
/*
* Copyright 1999-2020 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.
*/
package com.alibaba.nacos.test;
import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
import com.alibaba.nacos.sys.utils.DiskUtils;
import java.io.File;
import java.io.IOException;
/**
* Cache files to clear tool classes.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConfigCleanUtils {
public static void cleanClientCache() throws IOException {
DiskUtils.deleteDirThenMkdir(LocalConfigInfoProcessor.LOCAL_SNAPSHOT_PATH);
}
/**
* Change test env to new nacos home.
*
* @param caseName test case name
*/
public static String changeToNewTestNacosHome(String caseName) {
String userHome = System.getProperty("user.home");
String testNacosHome = userHome + File.separator + "nacos" + File.separator + caseName;
System.setProperty("nacos.home", testNacosHome);
return testNacosHome;
}
}

View File

@ -0,0 +1,313 @@
/*
* 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.
*/
package com.alibaba.nacos.test.ability;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.ability.constant.AbilityKey;
import com.alibaba.nacos.api.ability.constant.AbilityStatus;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest;
import com.alibaba.nacos.api.config.remote.response.ConfigQueryResponse;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.request.SetupAckRequest;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.ability.AbstractAbilityControlManager;
import com.alibaba.nacos.common.ability.discover.NacosAbilityManagerHolder;
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.ServerListFactory;
import com.alibaba.nacos.common.remote.client.ServerRequestHandler;
import com.alibaba.nacos.common.remote.client.grpc.GrpcClient;
import com.alibaba.nacos.core.remote.ConnectionManager;
import com.alibaba.nacos.core.remote.RequestFilters;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.core.remote.RequestHandlerRegistry;
import com.alibaba.nacos.test.ability.component.TestServerAbilityControlManager;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@SuppressWarnings("all")
public class AbilityDiscovery {
@LocalServerPort
private int port;
@Resource
private RequestHandlerRegistry requestHandlerRegistry;
@Resource
private RequestFilters filters;
@Resource
private ConnectionManager connectionManager;
private RpcClient client;
private RpcClient clusterClient;
private ConfigService configService;
private AbstractAbilityControlManager oldInstance;
/**
* test server judge client abilities
*/
private volatile boolean serverSuccess = false;
private volatile boolean clientSuccess = false;
private volatile boolean clusterSuccess = false;
private Field abstractAbilityControlManager;
private Field registryHandlerFields;
private Field serverReuqestHandlersField;
private Field currentConnField;
private Field setupRequestHandlerField;
@Before
public void setup() throws NoSuchFieldException, IllegalAccessException, NacosException {
// load class
oldInstance = NacosAbilityManagerHolder.getInstance();
// replace
abstractAbilityControlManager = NacosAbilityManagerHolder.class
.getDeclaredField("abstractAbilityControlManager");
abstractAbilityControlManager.setAccessible(true);
abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, new TestServerAbilityControlManager());
// get registry field
registryHandlerFields = RequestHandlerRegistry.class.getDeclaredField("registryHandlers");
registryHandlerFields.setAccessible(true);
// currentConn
currentConnField = RpcClient.class.getDeclaredField("currentConnection");
currentConnField.setAccessible(true);
// init config service
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
configService = NacosFactory.createConfigService(properties);
// server request handler
serverReuqestHandlersField = RpcClient.class.getDeclaredField("serverRequestHandlers");
serverReuqestHandlersField.setAccessible(true);
// setupRequestHandler
setupRequestHandlerField = GrpcClient.class.getDeclaredField("setupRequestHandler");
setupRequestHandlerField.setAccessible(true);
// init client
client = RpcClientFactory.createClient(UUID.randomUUID().toString(), ConnectionType.GRPC, new HashMap<>());
client.serverListFactory(new ServerListFactory() {
@Override
public String genNextServer() {
return "127.0.0.1:" + port;
}
@Override
public String getCurrentServer() {
return "127.0.0.1:" + port;
}
@Override
public List<String> getServerList() {
return Collections.singletonList("127.0.0.1:" + port);
}
});
// connect to server
client.start();
clusterClient = RpcClientFactory.createClusterClient(UUID.randomUUID().toString(), ConnectionType.GRPC, new HashMap<>());
clusterClient.serverListFactory(new ServerListFactory() {
@Override
public String genNextServer() {
return "127.0.0.1:" + port;
}
@Override
public String getCurrentServer() {
return "127.0.0.1:" + port;
}
@Override
public List<String> getServerList() {
return Collections.singletonList("127.0.0.1:" + port);
}
});
// connect to server
clusterClient.start();
}
@Test
public void testClientDiscovery() throws NacosException {
// client judge ability
Assert.assertEquals(client.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED);
Assert.assertEquals(client.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED);
}
@Test
public void testServerDiscoveryAndJudge() throws Exception {
Map<String, RequestHandler> handlers = (Map<String, RequestHandler>) registryHandlerFields
.get(requestHandlerRegistry);
// set handler
RequestHandler oldRequestHandler = handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), new ClientRequestHandler(filters));
configService.getConfig("test", "DEFAULT_GROUP", 2000);
// wait server invoke
Thread.sleep(3000);
Assert.assertTrue(serverSuccess);
// recover
handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler);
}
@Test
public void testClientJudge() throws Exception {
List<ServerRequestHandler> handlers = (List<ServerRequestHandler>) serverReuqestHandlersField.get(client);
handlers.clear();
// register
client.registerServerRequestHandler(new ServerRequestHandler() {
@Override
public Response requestReply(Request request, Connection connection) {
if (connection.getConnectionAbility(AbilityKey.SERVER_TEST_1).equals(AbilityStatus.SUPPORTED) && connection
.getConnectionAbility(AbilityKey.SERVER_TEST_2).equals(AbilityStatus.NOT_SUPPORTED)) {
clientSuccess = true;
}
return new Response(){};
}
});
// get id
Connection conn = (Connection) currentConnField.get(client);
com.alibaba.nacos.core.remote.Connection connection = connectionManager.getConnection(conn.getConnectionId());
try {
connection.request(new NotifySubscriberRequest(), 2000L);
} catch (NacosException e) {
// nothing to do
}
// wait client react
Thread.sleep(4000);
Assert.assertTrue(clientSuccess);
}
@Test
public void testClusterClient() throws IllegalAccessException, NacosException, InterruptedException, NoSuchFieldException {
Map<String, RequestHandler> handlers = (Map<String, RequestHandler>) registryHandlerFields
.get(requestHandlerRegistry);
// set handler
RequestHandler oldRequestHandler = handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), new ClusterClientRequestHandler(filters));
configService.getConfig("test", "DEFAULT_GROUP", 2000);
// wait server invoke
Thread.sleep(3000);
Assert.assertTrue(clusterSuccess);
// recover
handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler);
}
@Test
public void testNegotiationTimeout() throws Exception {
Object origin = setupRequestHandlerField.get(client);
// set null for setupRequestHandlerField
setupRequestHandlerField.set(client, null);
// try connect
Connection connection = client.connectToServer(new RpcClient.ServerInfo("127.0.0.1", port));
Assert.assertNull(connection);
// recovery
setupRequestHandlerField.set(client, origin);
}
@After
public void recover() throws IllegalAccessException, NacosException {
abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, oldInstance);
client.shutdown();
}
/**
* just to test ability
*/
class ClientRequestHandler extends RequestHandler<ConfigQueryRequest, ConfigQueryResponse> {
public ClientRequestHandler(RequestFilters requestFilters) throws NoSuchFieldException, IllegalAccessException {
Field declaredField = RequestHandler.class.getDeclaredField("requestFilters");
declaredField.setAccessible(true);
declaredField.set(this, requestFilters);
}
@Override
public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException {
if (meta.getConnectionAbility(AbilityKey.SDK_CLIENT_TEST_1).equals(AbilityStatus.SUPPORTED)) {
serverSuccess = true;
}
return new ConfigQueryResponse();
}
}
/**
* just to test ability.
*/
class ClusterClientRequestHandler extends RequestHandler<ConfigQueryRequest, ConfigQueryResponse> {
public ClusterClientRequestHandler(RequestFilters requestFilters) throws NoSuchFieldException, IllegalAccessException {
Field declaredField = RequestHandler.class.getDeclaredField("requestFilters");
declaredField.setAccessible(true);
declaredField.set(this, requestFilters);
}
@Override
public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException {
if (meta.getConnectionAbility(AbilityKey.CLUSTER_CLIENT_TEST_1).equals(AbilityStatus.SUPPORTED)) {
clusterSuccess = true;
}
return new ConfigQueryResponse();
}
}
}

View File

@ -0,0 +1,45 @@
/*
* 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.
*/
package com.alibaba.nacos.test.ability.component;
import com.alibaba.nacos.api.ability.constant.AbilityKey;
import com.alibaba.nacos.api.ability.constant.AbilityMode;
import com.alibaba.nacos.core.ability.control.ServerAbilityControlManager;
import java.util.HashMap;
import java.util.Map;
public class TestServerAbilityControlManager extends ServerAbilityControlManager {
@Override
protected Map<AbilityMode, Map<AbilityKey, Boolean>> initCurrentNodeAbilities() {
Map<AbilityKey, Boolean> map = new HashMap<>();
map.put(AbilityKey.SERVER_TEST_1, true);
map.put(AbilityKey.SERVER_TEST_2, false);
HashMap res = new HashMap<>();
res.put(AbilityMode.SERVER, map);
Map<AbilityKey, Boolean> map1 = new HashMap<>();
map1.put(AbilityKey.SDK_CLIENT_TEST_1, true);
res.put(AbilityMode.SDK_CLIENT, map1);
Map<AbilityKey, Boolean> map2 = new HashMap<>();
map2.put(AbilityKey.CLUSTER_CLIENT_TEST_1, true);
res.put(AbilityMode.CLUSTER_CLIENT, map2);
return res;
}
}

View File

@ -0,0 +1,67 @@
/*
* Copyright 1999-2020 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.
*/
package com.alibaba.nacos.test.base;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URL;
/**
* Http client for test module
*
* @author nkorange
* @since 1.2.0
*/
public class HttpClient4Test {
protected URL base;
@Autowired
protected TestRestTemplate restTemplate;
protected <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz) {
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> entity = new HttpEntity<T>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path)
.queryParams(params);
return this.restTemplate.exchange(
builder.toUriString(), HttpMethod.GET, entity, clazz);
}
protected <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz, HttpMethod httpMethod) {
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> entity = new HttpEntity<T>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path)
.queryParams(params);
return this.restTemplate.exchange(
builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright 1999-2020 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.
*/
package com.alibaba.nacos.test.base;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author nkorange
*/
public class Params {
private MultiValueMap<String, String> paramMap;
public static Params newParams() {
Params params = new Params();
params.paramMap = new LinkedMultiValueMap<String, String>();
return params;
}
public Params appendParam(String name, String value) {
this.paramMap.add(name, value);
return this;
}
public MultiValueMap<String, String> done() {
return paramMap;
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.base;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.api.config.PropertyChangeType;
import com.alibaba.nacos.api.config.listener.ConfigChangeParser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TextChangeParser implements ConfigChangeParser {
@Override
public boolean isResponsibleFor(String type) {
return (null == type || "text".equalsIgnoreCase(type));
}
@Override
public Map<String, ConfigChangeItem> doParse(String oldContent, String newContent, String type) throws IOException {
Map<String, ConfigChangeItem> map = new HashMap<>(4);
final String key = "content";
ConfigChangeItem cci = new ConfigChangeItem(key, oldContent, newContent);
if (null == oldContent && null != newContent) {
cci.setType(PropertyChangeType.ADDED);
} else if (null != oldContent && null != newContent && !oldContent.equals(newContent)) {
cci.setType(PropertyChangeType.MODIFIED);
} else if (null != oldContent && null == newContent) {
cci.setType(PropertyChangeType.DELETED);
}
map.put(key, cci);
return map;
}
}

View File

@ -0,0 +1,138 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.client;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig;
import com.alibaba.nacos.test.ConfigCleanUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* use configPublishRequest for communication verification between client and server
*
* @author githubcheng2978
*/
@RunWith(SpringRunner.class)
@TestConfiguration
@SpringBootTest(classes = {Nacos.class},
properties = {
"server.servlet.context-path=/nacos",
RpcServerTlsConfig.PREFIX+".compatibility=false",
RpcServerTlsConfig.PREFIX+".enableTls=true",
RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem",
RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem",
},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Ignore("TODO, Fix cert expired problem")
public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@LocalServerPort
private int port;
@BeforeClass
public static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV1ServerNonCompatibility_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
public void test_a_TlsServer() throws Exception {
RpcClient client = RpcClientFactory.createClient("testTlsServer", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), null);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
Assert.assertNull(connection);
}
@Test
public void test_b_ServerTlsTrustAll() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustAll(true);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
String content = UUID.randomUUID().toString();
configPublishRequest.setContent(content);
configPublishRequest.setGroup("test-group" + increment.getAndIncrement());
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
Response response = connectionTrustCa.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(response.isSuccess());
connectionTrustCa.close();
}
@Test
public void test_c_ServerTlsTrustCa() throws Exception {
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem");
RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequestCa = new ConfigPublishRequest();
String contentCa = UUID.randomUUID().toString();
configPublishRequestCa.setContent(contentCa);
configPublishRequestCa.setGroup("test-group" + increment.getAndIncrement());
configPublishRequestCa.setDataId("test-data" + increment.getAndIncrement());
Response responseCa = connectionTrustCa.request(configPublishRequestCa, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(responseCa.isSuccess());
connectionTrustCa.close();
}
}

View File

@ -0,0 +1,123 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.client;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig;
import com.alibaba.nacos.test.ConfigCleanUtils;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* use configPublishRequest for communication verification between client and server
*
* @author githubcheng2978
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class},
properties = {
"nacos.standalone=true",
RpcServerTlsConfig.PREFIX+".mutualAuthEnable=true",
RpcServerTlsConfig.PREFIX+".compatibility=false",
RpcServerTlsConfig.PREFIX+".enableTls=true",
RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem",
RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem",
RpcServerTlsConfig.PREFIX+".trustCollectionCertFile=test-ca-cert.pem",
},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigIntegrationV2MutualAuth_CITCase {
@LocalServerPort
private int port;
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV2MutualAuth_CITCase.class.getSimpleName());
}
@After
public void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
@Ignore("TODO, fix the cert expired problem")
public void test_d_MutualAuth() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setMutualAuthEnable(true);
tlsConfig.setCertChainFile("test-client-cert.pem");
tlsConfig.setCertPrivateKey("test-client-key.pem");
tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem");
RpcClient client = RpcClientFactory.createClient("testMutualAuth", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
String content = UUID.randomUUID().toString();
configPublishRequest.setContent(content);
configPublishRequest.setGroup("test-group"+increment.getAndIncrement());
configPublishRequest.setDataId("test-data"+increment.getAndIncrement());
configPublishRequest.setRequestId(content);
Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(5));
Assert.assertTrue(response.isSuccess());
connection.close();
}
@Test
public void test_e_ServerMutualAuthOnly() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem");
RpcClient client = RpcClientFactory.createClient("testServerMutualAuthNoly", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
Assert.assertNull(connection);
TimeUnit.SECONDS.sleep(3);
}
}

View File

@ -0,0 +1,142 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.client;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.remote.client.Connection;
import com.alibaba.nacos.common.remote.client.RpcClient;
import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.test.ConfigCleanUtils;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* use configPublishRequest for communication verification between client and server
*
* @author githubcheng2978
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class},
properties = {
"nacos.standalone=true",
RpcServerTlsConfig.PREFIX+".enableTls=true",
RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem",
RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem"
},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigIntegrationV3_CITCase {
@LocalServerPort
private int port;
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV3_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
public void test_e_TlsServerAndPlainClient() throws Exception {
RpcClient client = RpcClientFactory.createClient("testTlsServerAndPlainClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), null);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
String content = UUID.randomUUID().toString();
configPublishRequest.setContent(content);
configPublishRequest.setGroup("test-group" + increment.getAndIncrement());
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
configPublishRequest.setRequestId(content);
Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(response.isSuccess());
connection.close();
}
@Test
public void test_f_ServerTlsTrustAll() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustAll(true);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
RpcClient clientTrustAll = RpcClientFactory.createClient("testServerTlsTrustAll", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustAll = clientTrustAll.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
String content = UUID.randomUUID().toString();
configPublishRequest.setContent(content);
configPublishRequest.setGroup("test-group" + increment.getAndIncrement());
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
Response response = connectionTrustAll.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(response.isSuccess());
connectionTrustAll.close();
}
@Test
@Ignore("TODO, Fix cert expired problem")
public void test_g_ServerTlsTrustCa() throws Exception {
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(EnvUtil.getPort());
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem");
RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequestCa = new ConfigPublishRequest();
String contentCa = UUID.randomUUID().toString();
configPublishRequestCa.setContent(contentCa);
configPublishRequestCa.setGroup("test-group" + increment.getAndIncrement());
configPublishRequestCa.setDataId("test-data" + increment.getAndIncrement());
Response responseCa = connectionTrustCa.request(configPublishRequestCa, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(responseCa.isSuccess());
connectionTrustCa.close();
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.config.server.enums.FileTypeEnum;
import org.junit.Assert;
import org.junit.Test;
/**
* @author by jiangmin.wu on 2020/12/30
*/
public class FileTypeEnum_ITCase {
@Test
public void fileTypeEnum_test1() {
for (FileTypeEnum value : FileTypeEnum.values()) {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.name());
Assert.assertEquals(fileTypeEnum, value);
}
}
@Test
public void fileTypeEnum_test2() {
for (FileTypeEnum value : FileTypeEnum.values()) {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.getFileType());
Assert.assertNotNull(fileTypeEnum);
}
}
@Test
public void fileTypeEnum_test3() {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("t");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(".");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("1");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(null);
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
}
}

View File

@ -0,0 +1,208 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpClientFactory;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.naming.misc.HttpClientManager.ProcessorHttpClientFactory;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
/**
* NacosAsyncRestTemplate_ITCase.
*
* @author mai.jh
*/
@SuppressWarnings("all")
@FixMethodOrder(MethodSorters.JVM)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NacosAsyncRestTemplate_ITCase {
@LocalServerPort
private int port;
private NacosAsyncRestTemplate nacosRestTemplate = HttpClientBeanHolder
.getNacosAsyncRestTemplate(LoggerFactory.getLogger(NacosAsyncRestTemplate_ITCase.class));
private static final HttpClientFactory PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY = new ProcessorHttpClientFactory();
private NacosAsyncRestTemplate processorRestTemplate = null;
private final String CONFIG_INSTANCE_PATH = "/nacos/v1/ns";
private String IP = null;
@Autowired
private Environment environment;
@Before
public void init() throws NacosException {
IP = String.format("http://localhost:%d", port);
EnvUtil.setEnvironment((ConfigurableEnvironment) environment);
processorRestTemplate = HttpClientBeanHolder
.getNacosAsyncRestTemplate(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY);
}
private class CallbackMap<T> implements Callback<T> {
private HttpRestResult<T> restResult;
private Throwable throwable;
@Override
public void onReceive(RestResult<T> result) {
restResult = (HttpRestResult<T>) result;
}
@Override
public void onError(Throwable throwable) {
this.throwable = throwable;
}
@Override
public void onCancel() {
}
public HttpRestResult<T> getRestResult() {
return restResult;
}
public Throwable getThrowable() {
return throwable;
}
}
@Test
public void test_url_post_form() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
CallbackMap<String> callbackMap = new CallbackMap<>();
nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
}
@Test
public void test_url_post_form_by_processor() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test2");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
CallbackMap<String> callbackMap = new CallbackMap<>();
processorRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
}
@Test
public void test_url_put_form() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test-change");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
CallbackMap<String> callbackMap = new CallbackMap<>();
nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
}
@Test
public void test_url_get() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance/list";
Query query = Query.newInstance().addParam("serviceName", "app-test");
CallbackMap<Map> callbackMap = new CallbackMap<>();
nacosRestTemplate.get(url, Header.newInstance(), query, Map.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<Map> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test");
}
@Test
public void test_url_by_map() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance/list";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
CallbackMap<Map> callbackMap = new CallbackMap<>();
nacosRestTemplate.get(url, Header.newInstance(), Query.newInstance().initParams(param), Map.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<Map> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test");
}
@Test
public void test_url_delete() throws Exception {
String url = IP + CONFIG_INSTANCE_PATH + "/instance";
Query query = Query.newInstance().addParam("ip", "11.11.11.11").addParam("port", "8080")
.addParam("serviceName", "app-test");
CallbackMap<String> callbackMap = new CallbackMap<>();
nacosRestTemplate.delete(url, Header.newInstance(), query, String.class, callbackMap);
Thread.sleep(2000);
HttpRestResult<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
Assert.assertTrue(restResult.ok());
}
}

View File

@ -0,0 +1,158 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
/**
* NacosRestTemplate_ITCase.
*
* @author mai.jh
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.JVM)
public class NacosRestTemplate_ITCase {
@LocalServerPort
private int port;
private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder
.getNacosRestTemplate(LoggerFactory.getLogger(NacosRestTemplate_ITCase.class));
private final String INSTANCE_PATH = "/nacos/v1/ns";
private final String CONFIG_PATH = "/nacos/v1/cs";
private String IP = null;
@Before
public void init() throws NacosException {
IP = String.format("http://localhost:%d", port);
}
@Test
public void test_url_post_config() throws Exception {
String url = IP + CONFIG_PATH + "/configs";
Map<String, String> param = new HashMap<>();
param.put("dataId", "test-1");
param.put("group", "DEFAULT_GROUP");
param.put("content", "aaa=b");
HttpRestResult<String> restResult = nacosRestTemplate
.postForm(url, Header.newInstance(), param, String.class);
Assert.assertTrue(restResult.ok());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
@Test
public void test_url_get_return_restResult() throws Exception {
String url = IP + CONFIG_PATH + "/configs";
Query query = Query.newInstance().addParam("beta", true).addParam("dataId", "test-1")
.addParam("group", "DEFAULT_GROUP");
HttpRestResult<ConfigInfo4Beta> restResult = nacosRestTemplate
.get(url, Header.newInstance(), query, new TypeReference<RestResult<ConfigInfo4Beta>>() {
}.getType());
Assert.assertTrue(restResult.ok());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
@Test
public void test_url_post_form() throws Exception {
String url = IP + INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
HttpRestResult<String> restResult = nacosRestTemplate
.postForm(url, Header.newInstance(), param, String.class);
Assert.assertTrue(restResult.ok());
System.out.println(restResult.getData());
}
@Test
@Ignore("new version can't update instance when service and instance is not exist")
public void test_url_put_from() throws Exception {
String url = IP + INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test-change");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
HttpRestResult<String> restResult = nacosRestTemplate
.putForm(url, Header.newInstance(), param, String.class);
Assert.assertTrue(restResult.ok());
System.out.println(restResult.getData());
}
@Test
public void test_url_get() throws Exception {
String url = IP + INSTANCE_PATH + "/instance/list";
Query query = Query.newInstance().addParam("serviceName", "app-test");
HttpRestResult<Map> restResult = nacosRestTemplate.get(url, Header.newInstance(), query, Map.class);
Assert.assertTrue(restResult.ok());
Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test");
System.out.println(restResult.getData());
}
@Test
public void test_url_get_by_map() throws Exception {
String url = IP + INSTANCE_PATH + "/instance/list";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
HttpRestResult<Map> restResult = nacosRestTemplate.get(url, Header.newInstance(), Query.newInstance().initParams(param), Map.class);
Assert.assertTrue(restResult.ok());
Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test");
System.out.println(restResult.getData());
}
@Test
public void test_url_delete() throws Exception {
String url = IP + INSTANCE_PATH + "/instance";
Query query = Query.newInstance().addParam("ip", "11.11.11.11").addParam("port", "8080")
.addParam("serviceName", "app-test");
HttpRestResult<String> restResult = nacosRestTemplate.delete(url, Header.newInstance(), query, String.class);
Assert.assertTrue(restResult.ok());
System.out.println(restResult);
}
}

View File

@ -0,0 +1,127 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.HttpClientRequestInterceptor;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.model.RequestHttpEntity;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* NacosRestTemplate_Interceptors_ITCase
*
* @author mai.jh
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.JVM)
public class NacosRestTemplate_Interceptors_ITCase {
@LocalServerPort
private int port;
private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder
.getNacosRestTemplate(LoggerFactory.getLogger(NacosRestTemplate_Interceptors_ITCase.class));
private final String CONFIG_PATH = "/nacos/v1/cs";
private String IP = null;
private class TerminationInterceptor implements HttpClientRequestInterceptor {
@Override
public HttpClientResponse intercept() {
return new HttpClientResponse() {
@Override
public Header getHeaders() {
return Header.EMPTY;
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("Stop request".getBytes());
}
@Override
public int getStatusCode() {
return NacosException.SERVER_ERROR;
}
@Override
public String getStatusText() {
return null;
}
@Override
public void close() {
}
};
}
@Override
public boolean isIntercept(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) {
return true;
}
}
@Before
public void init() throws NacosException {
nacosRestTemplate.setInterceptors(Arrays.asList(new TerminationInterceptor()));
IP = String.format("http://localhost:%d", port);
}
@Test
public void test_url_post_config() throws Exception {
String url = IP + CONFIG_PATH + "/configs";
Map<String, String> param = new HashMap<>();
param.put("dataId", "test-1");
param.put("group", "DEFAULT_GROUP");
param.put("content", "aaa=b");
HttpRestResult<String> restResult = nacosRestTemplate
.postForm(url, Header.newInstance(), param, String.class);
Assert.assertEquals(500, restResult.getCode());
Assert.assertEquals("Stop request", restResult.getMessage());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
}

View File

@ -0,0 +1,182 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.sys.file.FileChangeEvent;
import com.alibaba.nacos.sys.file.FileWatcher;
import com.alibaba.nacos.sys.file.WatchFileCenter;
import com.alibaba.nacos.common.utils.ByteUtils;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class WatchFileCenter_ITCase {
static final String path = Paths.get(System.getProperty("user.home"), "/watch_file_change_test").toString();
final Object monitor = new Object();
static final Executor executor = Executors.newFixedThreadPool(32);
@BeforeClass
public static void beforeCls() throws Exception {
DiskUtils.deleteDirThenMkdir(path);
}
@AfterClass
public static void afterCls() throws Exception {
DiskUtils.deleteDirectory(path);
}
// The last file change must be notified
@Test
public void test_high_concurrency_modify() throws Exception {
AtomicInteger count = new AtomicInteger(0);
Set<String> set = new ConcurrentHashSet<>();
final String fileName = "test2_file_change";
final File file = Paths.get(path, fileName).toFile();
func(fileName, file, content -> {
set.add(content);
count.incrementAndGet();
});
ThreadUtils.sleep(5_000L);
}
@Test
public void test_modify_file_much() throws Exception {
final String fileName = "modify_file_much";
final File file = Paths.get(path, fileName).toFile();
CountDownLatch latch = new CountDownLatch(3);
AtomicInteger count = new AtomicInteger(0);
WatchFileCenter.registerWatcher(path, new FileWatcher() {
@Override
public void onChange(FileChangeEvent event) {
try {
System.out.println(event);
System.out.println(DiskUtils.readFile(file));
count.incrementAndGet();
} finally {
latch.countDown();
}
}
@Override
public boolean interest(String context) {
return StringUtils.contains(context, fileName);
}
});
for (int i = 0; i < 3; i++) {
DiskUtils.writeFile(file, ByteUtils.toBytes(("test_modify_file_" + i)), false);
ThreadUtils.sleep(10_000L);
}
latch.await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(3, count.get());
}
@Test
public void test_multi_file_modify() throws Exception {
CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
AtomicInteger count = new AtomicInteger(0);
Set<String> set = new ConcurrentHashSet<>();
final String fileName = "test2_file_change_" + i;
final File file = Paths.get(path, fileName).toFile();
executor.execute(() -> {
try {
func(fileName, file, content -> {
set.add(content);
count.incrementAndGet();
});
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
latch.countDown();
}
});
}
latch.await(10_000L, TimeUnit.MILLISECONDS);
ThreadUtils.sleep(5_000L);
}
private void func(final String fileName, final File file, final Consumer<String> consumer) throws Exception {
CountDownLatch latch = new CountDownLatch(100);
DiskUtils.touch(file);
WatchFileCenter.registerWatcher(path, new FileWatcher() {
@Override
public void onChange(FileChangeEvent event) {
final File file = Paths.get(path, fileName).toFile();
final String content = DiskUtils.readFile(file);
consumer.accept(content);
}
@Override
public boolean interest(String context) {
return StringUtils.contains(context, fileName);
}
});
final AtomicInteger id = new AtomicInteger(0);
final AtomicReference<String> finalContent = new AtomicReference<>(null);
for (int i = 0; i < 100; i++) {
executor.execute(() -> {
final String j = fileName + "_" + id.incrementAndGet();
try {
final File file1 = Paths.get(path, fileName).toFile();
synchronized (monitor) {
finalContent.set(j);
DiskUtils.writeFile(file1, j.getBytes(StandardCharsets.UTF_8), false);
}
} finally {
latch.countDown();
}
});
}
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core;
import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class SnowFlowerIdGenerator_ITCase {
@Test
public void test_idGenerator() {
EnvUtil.setEnvironment(new StandardEnvironment());
SnowFlowerIdGenerator generator1 = new SnowFlowerIdGenerator();
SnowFlowerIdGenerator generator2 = new SnowFlowerIdGenerator();
SnowFlowerIdGenerator generator3 = new SnowFlowerIdGenerator();
generator1.initialize(1);
generator2.initialize(2);
generator3.initialize(3);
long id1 = generator1.nextId();
long id2 = generator2.nextId();
long id3 = generator3.nextId();
Assert.assertNotEquals(id1, id2);
Assert.assertNotEquals(id1, id3);
Assert.assertNotEquals(id2, id3);
}
}

View File

@ -0,0 +1,233 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.auth.config.AuthConfigs;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.test.base.HttpClient4Test;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Assert;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* @author nkorange
* @since 1.2.0
*/
public class AuthBase extends HttpClient4Test {
protected String accessToken;
protected String username1 = "username1";
protected String password1 = "password1";
protected String username2 = "username2";
protected String password2 = "password2";
protected String username3 = "username3";
protected String password3 = "password3";
protected String role1 = "role1";
protected String role2 = "role2";
protected String role3 = "role3";
protected Properties properties;
protected String namespace1 = "namespace1";
public String login(String username, String password) {
ResponseEntity<String> response = request("/nacos/v1/auth/users/login",
Params.newParams().appendParam("username", username).appendParam("password", password).done(),
String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
return json.get("accessToken").textValue();
}
public String login() {
return login("nacos", "nacos");
}
protected void init(int port) throws Exception {
AuthConfigs.setCachingEnabled(false);
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
System.setProperty("nacos.core.auth.enabled", "true");
this.base = new URL(url);
accessToken = login();
// Create a user:
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username1).appendParam("password", password1)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username2).appendParam("password", password2)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username3).appendParam("password", password3)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role1).appendParam("username", username1)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role2).appendParam("username", username2)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role3).appendParam("username", username3)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Add read permission of namespace1 to role1:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role1).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Add write permission of namespace1 to role2:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role2).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "w").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Add read/write permission of namespace1 to role3:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role3).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Init properties:
properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, namespace1);
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
}
protected void destroy() {
// Delete permission:
ResponseEntity<String> response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role1).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role2).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "w").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", role3).appendParam("resource", namespace1 + ":*:*")
.appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role1).appendParam("username", username1)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role2).appendParam("username", username2)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", role3).appendParam("username", username3)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username1).appendParam("password", password1)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username2).appendParam("password", password2)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", username3).appendParam("password", password3)
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
System.setProperty("nacos.core.auth.enabled", "false");
}
}

View File

@ -0,0 +1,234 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigChangeEvent;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import org.apache.http.HttpStatus;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigAuth_ITCase extends AuthBase {
@LocalServerPort
private int port;
public static final long TIME_OUT = 2000;
public ConfigService iconfig = null;
private String dataId = "yanlin";
private String group = "yanlin";
@Before
public void init() throws Exception {
super.init(port);
}
@After
public void destroy(){
super.destroy();
try {
iconfig.shutDown();
}catch (NacosException ex) {
}
}
@Test
public void writeWithReadPermission() throws Exception {
// Construct configService:
properties.put(PropertyKeyConst.USERNAME, username1);
properties.put(PropertyKeyConst.PASSWORD, password1);
properties.put(PropertyKeyConst.NAMESPACE, namespace1);
iconfig = NacosFactory.createConfigService(properties);
final String content = "test";
assertFalse(iconfig.publishConfig(dataId, group, content));
assertFalse(iconfig.removeConfig(dataId, group));
}
@Test
public void readWithReadPermission() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AtomicInteger ai = new AtomicInteger(0);
properties.put(PropertyKeyConst.USERNAME, username1);
properties.put(PropertyKeyConst.PASSWORD, password1);
iconfig = NacosFactory.createConfigService(properties);
final String content = "test" + System.currentTimeMillis();
System.out.println(content);
iconfig.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
ConfigChangeItem cci = event.getChangeItem("content");
System.out.println("content:" + cci);
if (!content.equals(cci.getNewValue())) {
return;
}
latch.countDown();
}
});
TimeUnit.SECONDS.sleep(3L);
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
ConfigService configService = NacosFactory.createConfigService(properties);
boolean result = configService.publishConfig(dataId, group, content);
Assert.assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
String res = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, res);
latch.await(5L, TimeUnit.SECONDS);
Assert.assertEquals(0, latch.getCount());
}
@Test
public void writeWithWritePermission() throws Exception {
// Construct configService:
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
iconfig = NacosFactory.createConfigService(properties);
final String content = "test";
boolean res = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(res);
res = iconfig.removeConfig(dataId, group);
Assert.assertTrue(res);
}
@Test
public void readWithWritePermission() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
properties.put(PropertyKeyConst.NAMESPACE, namespace1);
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
iconfig = NacosFactory.createConfigService(properties);
final String content = "test" + System.currentTimeMillis();
iconfig.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
ConfigChangeItem cci = event.getChangeItem("content");
System.out.println("content:" + cci);
if (!content.equals(cci.getNewValue())) {
return;
}
latch.countDown();
}
});
TimeUnit.SECONDS.sleep(3L);
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
try {
iconfig.getConfig(dataId, group, TIME_OUT);
fail();
} catch (NacosException ne) {
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ne.getErrCode());
}
latch.await(5L, TimeUnit.SECONDS);
Assert.assertTrue(latch.getCount() > 0);
}
@Test
public void ReadWriteWithFullPermission() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AtomicInteger ai = new AtomicInteger(0);
properties.put(PropertyKeyConst.USERNAME, username3);
properties.put(PropertyKeyConst.PASSWORD, password3);
iconfig = NacosFactory.createConfigService(properties);
final String content = "test" + System.currentTimeMillis();
iconfig.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
ConfigChangeItem cci = event.getChangeItem("content");
System.out.println("content:" + cci);
if (!content.equals(cci.getNewValue())) {
return;
}
latch.countDown();
}
});
TimeUnit.SECONDS.sleep(3L);
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
String res = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, res);
latch.await(5L, TimeUnit.SECONDS);
Assert.assertEquals(0, latch.getCount());
result = iconfig.removeConfig(dataId, group);
Assert.assertTrue(result);
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.auth.config.AuthConfigs;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.util.concurrent.TimeUnit;
@RunWith(Suite.class)
@Suite.SuiteClasses({ LdapAuth_ITCase.NonTlsTest.class,LdapAuth_ITCase.TlsTest.class})
public class LdapAuth_ITCase extends AuthBase {
@LocalServerPort
private int port;
private String filterPrefix = "uid";
@MockBean
private LdapTemplate ldapTemplate;
@Before
public void init() throws Exception {
Mockito.when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + "karson" + ")", "karson"))
.thenReturn(true);
AuthConfigs.setCachingEnabled(false);
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
System.setProperty("nacos.core.auth.enabled", "true");
this.base = new URL(url);
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
"nacos.core.auth.system.type=ldap"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public static class NonTlsTest extends LdapAuth_ITCase {
@Test
public void testLdapAuth() throws Exception {
super.login("karson", "karson");
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
"nacos.core.auth.system.type=ldap",
"nacos.core.auth.ldap.url=ldaps://localhost:636"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public static class TlsTest extends LdapAuth_ITCase {
@Test
public void testLdapAuth() throws Exception {
super.login("karson", "karson");
}
}
}

View File

@ -0,0 +1,159 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.http.HttpStatus;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NamingAuth_ITCase extends AuthBase {
@LocalServerPort
private int port;
private NamingService namingService;
@Before
public void init() throws Exception {
super.init(port);
}
@After
public void destroy() {
super.destroy();
}
@Test
public void writeWithReadPermission() throws Exception {
properties.put(PropertyKeyConst.USERNAME, username1);
properties.put(PropertyKeyConst.PASSWORD, password1);
namingService = NacosFactory.createNamingService(properties);
try {
namingService.registerInstance("test.1", "1.2.3.4", 80);
fail();
} catch (NacosException ne) {
NacosException cause = (NacosException) ne.getCause();
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode());
}
try {
namingService.deregisterInstance("test.1", "1.2.3.4", 80);
fail();
} catch (NacosException ne) {
NacosException cause = (NacosException) ne.getCause();
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode());
}
namingService.shutDown();
}
@Test
public void readWithReadPermission() throws Exception {
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
NamingService namingService1 = NacosFactory.createNamingService(properties);
namingService1.registerInstance("test.1", "1.2.3.4", 80);
TimeUnit.SECONDS.sleep(5L);
properties.put(PropertyKeyConst.USERNAME, username1);
properties.put(PropertyKeyConst.PASSWORD, password1);
namingService = NacosFactory.createNamingService(properties);
List<Instance> list = namingService.getAllInstances("test.1");
Assert.assertEquals(1, list.size());
namingService1.shutDown();
namingService.shutDown();
}
@Test
public void writeWithWritePermission() throws Exception {
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
namingService = NacosFactory.createNamingService(properties);
namingService.registerInstance("test.1", "1.2.3.4", 80);
TimeUnit.SECONDS.sleep(5L);
namingService.deregisterInstance("test.1", "1.2.3.4", 80);
namingService.shutDown();
}
@Test
public void readWithWritePermission() throws Exception {
properties.put(PropertyKeyConst.USERNAME, username2);
properties.put(PropertyKeyConst.PASSWORD, password2);
namingService = NacosFactory.createNamingService(properties);
namingService.registerInstance("test.1", "1.2.3.4", 80);
TimeUnit.SECONDS.sleep(5L);
try {
namingService.getAllInstances("test.1");
fail();
} catch (NacosException ne) {
NacosException cause = (NacosException) ne.getCause();
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode());
}
namingService.shutDown();
}
@Test
public void readWriteWithFullPermission() throws Exception {
properties.put(PropertyKeyConst.USERNAME, username3);
properties.put(PropertyKeyConst.PASSWORD, password3);
namingService = NacosFactory.createNamingService(properties);
namingService.registerInstance("test.1", "1.2.3.4", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> list = namingService.getAllInstances("test.1");
Assert.assertEquals(1, list.size());
namingService.shutDown();
}
}

View File

@ -0,0 +1,243 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.plugin.auth.api.Permission;
import com.alibaba.nacos.test.base.HttpClient4Test;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Permission_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
}
@After
public void destroy() {
// Delete permission:
ResponseEntity<String> response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*")
.appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*")
.appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", "role1").appendParam("username", "username3")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", "username3").appendParam("accessToken", accessToken).done(),
String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void login() {
ResponseEntity<String> response = request("/nacos/v1/auth/users/login",
Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(),
String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
accessToken = json.get("accessToken").textValue();
}
@Test
public void createDeleteQueryPermission() {
login();
// Create a user:
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", "username3").appendParam("password", "password1")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create role:
response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", "role1").appendParam("username", "username3")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*")
.appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create another permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*")
.appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Page<Permission> permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
boolean found1 = false, found2 = false;
for (Permission permission : permissionPage.getPageItems()) {
if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
found1 = true;
}
if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
found2 = true;
}
if (found1 && found2) {
break;
}
}
Assert.assertTrue(found1);
Assert.assertTrue(found2);
// Delete permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*")
.appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
found1 = false;
found2 = false;
for (Permission permission : permissionPage.getPageItems()) {
if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
found1 = true;
}
if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
found2 = true;
}
}
Assert.assertFalse(found1);
Assert.assertTrue(found2);
// Delete permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*")
.appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query permission:
response = request("/nacos/v1/auth/permissions",
Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
found1 = false;
found2 = false;
for (Permission permission : permissionPage.getPageItems()) {
if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) {
found1 = true;
}
if (permission.getResource().equals("test1:*:*") && permission.getAction().equals("r")) {
found2 = true;
}
}
Assert.assertFalse(found1);
Assert.assertFalse(found2);
}
}

View File

@ -0,0 +1,302 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.test.base.HttpClient4Test;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Role_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
}
@After
public void destroy() {
// Delete role:
ResponseEntity<String> response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role1")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete role:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role2")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void login() {
ResponseEntity<String> response = request("/nacos/v1/auth/users/login",
Params.newParams()
.appendParam("username", "nacos")
.appendParam("password", "nacos")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
accessToken = json.get("accessToken").textValue();
}
@Test
public void createDeleteQueryRole() {
login();
// Create a user:
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username2")
.appendParam("password", "password1")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Create a role:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role1")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query role of user:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("username", "username2")
.appendParam("pageNo", "1")
.appendParam("pageSize", "10")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Page<RoleInfo> roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {});
Assert.assertNotNull(roleInfoPage);
Assert.assertNotNull(roleInfoPage.getPageItems());
boolean found = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
if (roleInfo.getRole().equals("role1")) {
found = true;
break;
}
}
Assert.assertTrue(found);
// Add second role to user:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role2")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query roles of user:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("username", "username2")
.appendParam("pageNo", "1")
.appendParam("pageSize", "10")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {});
Assert.assertNotNull(roleInfoPage);
Assert.assertNotNull(roleInfoPage.getPageItems());
found = false;
boolean found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
if (roleInfo.getRole().equals("role1")) {
found = true;
}
if (roleInfo.getRole().equals("role2")) {
found2 = true;
}
if (found && found2) {
break;
}
}
Assert.assertTrue(found);
Assert.assertTrue(found2);
// Delete role:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role2")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query roles of user:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("username", "username2")
.appendParam("pageNo", "1")
.appendParam("pageSize", "10")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {});
Assert.assertNotNull(roleInfoPage);
Assert.assertNotNull(roleInfoPage.getPageItems());
found = false;
found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
if (roleInfo.getRole().equals("role1")) {
found = true;
}
if (roleInfo.getRole().equals("role2")) {
found2 = true;
}
}
Assert.assertFalse(found2);
Assert.assertTrue(found);
// Delete role:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("role", "role1")
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query roles of user:
response = request("/nacos/v1/auth/roles",
Params.newParams()
.appendParam("username", "username2")
.appendParam("pageNo", "1")
.appendParam("pageSize", "10")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.GET);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {});
Assert.assertNotNull(roleInfoPage);
Assert.assertNotNull(roleInfoPage.getPageItems());
found = false;
found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
if (roleInfo.getRole().equals("role1")) {
found = true;
}
if (roleInfo.getRole().equals("role2")) {
found2 = true;
}
}
Assert.assertFalse(found2);
Assert.assertFalse(found);
}
}

View File

@ -0,0 +1,302 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.auth;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil;
import com.alibaba.nacos.test.base.HttpClient4Test;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class User_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
TimeUnit.SECONDS.sleep(5L);
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
}
@After
public void destroy() {
// Delete a user:
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
System.setProperty("nacos.core.auth.enabled", "false");
}
@Test
public void login() {
ResponseEntity<String> response = login("nacos", "nacos");
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
accessToken = json.get("accessToken").textValue();
}
private ResponseEntity<String> login(String username,String password){
return request("/nacos/v1/auth/users/login",
Params.newParams()
.appendParam("username", username)
.appendParam("password", password)
.done(),
String.class,
HttpMethod.POST);
}
@Test
public void createUpdateDeleteUser() {
login();
// Create a user:
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("password", "password1")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("pageNo", "1")
.appendParam("pageSize", String.valueOf(Integer.MAX_VALUE))
.appendParam("accessToken", accessToken)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Page<User> userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {});
Assert.assertNotNull(userPage);
Assert.assertNotNull(userPage.getPageItems());
Assert.assertTrue(userPage.getPageItems().size() > 0);
boolean found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername()) &&
PasswordEncoderUtil.matches("password1", user.getPassword())) {
found = true;
break;
}
}
Assert.assertTrue(found);
// Update a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("newPassword", "password2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("pageNo", "1")
.appendParam("pageSize", String.valueOf(Integer.MAX_VALUE))
.appendParam("accessToken", accessToken)
.done(),
String.class);
userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {});
Assert.assertNotNull(userPage);
Assert.assertNotNull(userPage.getPageItems());
Assert.assertTrue(userPage.getPageItems().size() > 0);
found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername()) &&
PasswordEncoderUtil.matches("password2", user.getPassword())) {
found = true;
break;
}
}
Assert.assertTrue(found);
// Delete a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// Query a user:
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("pageNo", "1")
.appendParam("pageSize", String.valueOf(Integer.MAX_VALUE))
.appendParam("accessToken", accessToken)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {});
Assert.assertNotNull(userPage);
Assert.assertNotNull(userPage.getPageItems());
Assert.assertTrue(userPage.getPageItems().size() > 0);
found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername())) {
found = true;
break;
}
}
Assert.assertFalse(found);
}
@Test
public void updateUserWithPermission() {
System.setProperty("nacos.core.auth.enabled", "true");
// admin login
login();
// create username1
ResponseEntity<String> response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("password", "password1")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// create username2
response= request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username2")
.appendParam("password", "password2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// user login
response = login("username1", "password1");
String user1AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue();
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = login("username2", "password2");
String user2AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue();
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// update by admin
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("newPassword", "password3")
.appendParam("accessToken", accessToken)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// update by same user
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("newPassword", "password4")
.appendParam("accessToken", user1AccessToken)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
// update by another user
response = request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username1")
.appendParam("newPassword", "password5")
.appendParam("accessToken", user2AccessToken)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertEquals(response.getStatusCode(), HttpStatus.FORBIDDEN);
}
}

View File

@ -0,0 +1,156 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.cluster;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.cluster.lookup.AddressServerMemberLookup;
import com.alibaba.nacos.core.cluster.lookup.FileConfigMemberLookup;
import com.alibaba.nacos.core.cluster.lookup.LookupFactory;
import com.alibaba.nacos.core.cluster.MemberLookup;
import com.alibaba.nacos.core.cluster.lookup.StandaloneMemberLookup;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.web.MockServletContext;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class MemberLookup_ITCase {
static final String path = Paths.get(System.getProperty("user.home"), "/member_look")
.toString();
static final String name = "cluster.conf";
ServerMemberManager memberManager;
@Before
public void before() throws Exception {
System.setProperty("nacos.home", path);
EnvUtil.setEnvironment(new StandardEnvironment());
EnvUtil.setIsStandalone(false);
System.out.println(EnvUtil.getStandaloneMode());
System.out.println(Arrays.toString(LookupFactory.LookupType.values()));
DiskUtils.forceMkdir(path);
DiskUtils.forceMkdir(Paths.get(path, "conf").toString());
File file = Paths.get(path, "conf", name).toFile();
DiskUtils.touch(file);
String ip = InetUtils.getSelfIP();
DiskUtils.writeFile(file, (ip + ":8848," + ip + ":8847," + ip + ":8849").getBytes(
StandardCharsets.UTF_8), false);
try {
memberManager = new ServerMemberManager(
new MockServletContext());
}
catch (Exception e) {
e.printStackTrace();
}
}
@After
public void after() throws Exception {
try {
memberManager.shutdown();
} catch (Throwable ex) {
ex.printStackTrace();
}
DiskUtils.deleteDirectory(path);
}
@Test
public void test_a_lookup_file_config() throws Exception {
try {
LookupFactory.createLookUp(memberManager);
}
catch (Throwable ignore) {
}
MemberLookup lookup = LookupFactory.getLookUp();
System.out.println(lookup);
Assert.assertTrue(lookup instanceof FileConfigMemberLookup);
func(lookup);
}
@Test
public void test_b_lookup_standalone() throws Exception {
EnvUtil.setIsStandalone(true);
try {
LookupFactory.createLookUp(memberManager);
}
catch (Throwable ignore) {
} finally {
EnvUtil.setIsStandalone(false);
}
MemberLookup lookup = LookupFactory.getLookUp();
System.out.println(lookup);
Assert.assertTrue(lookup instanceof StandaloneMemberLookup);
}
@Test
public void test_c_lookup_address_server() throws Exception {
EnvUtil.setIsStandalone(false);
System.out.println(EnvUtil.getClusterConfFilePath());
DiskUtils.deleteFile(Paths.get(path, "conf").toString(), "cluster.conf");
System.out.println(new File(EnvUtil.getClusterConfFilePath()).exists());
try {
LookupFactory.createLookUp(memberManager);
}
catch (Throwable ignore) {
}
MemberLookup lookup = LookupFactory.getLookUp();
System.out.println(lookup);
Assert.assertTrue(lookup instanceof AddressServerMemberLookup);
try {
func(lookup);
} catch (NacosException e) {
System.out.println(e.getErrMsg());
Assert.assertTrue(StringUtils.containsIgnoreCase(e.getErrMsg(), "jmenv.tbsite.net"));
}
}
private void func(MemberLookup lookup) throws Exception {
func(lookup, 3);
}
private void func(MemberLookup lookup, int expectSize) throws Exception {
lookup.start();
Map<String, Member> tmp = memberManager.getServerList();
System.out.println(lookup + " : " + tmp);
Assert.assertEquals(expectSize, tmp.size());
}
}

View File

@ -0,0 +1,193 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.cluster;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MembersChangeEvent;
import com.alibaba.nacos.core.cluster.MemberUtil;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.env.Constants;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.web.MockServletContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* Cluster node manages unit tests.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ServerMemberManager_ITCase {
private ServerMemberManager memberManager;
@BeforeClass
public static void initClass() throws Exception {
System.setProperty(Constants.NACOS_SERVER_IP, "127.0.0.1");
System.setProperty("server.port", "8847");
EnvUtil.setIsStandalone(true);
EnvUtil.setEnvironment(new StandardEnvironment());
}
@AfterClass
public static void destroyClass() {
System.clearProperty(Constants.NACOS_SERVER_IP);
System.clearProperty("server.port");
}
@Before
public void before() throws Exception {
memberManager = new ServerMemberManager(new MockServletContext());
}
@After
public void after() throws Exception {
memberManager.shutdown();
}
@Test
public void testKisFirst() {
String firstIp = "127.0.0.1:8847";
String secondIp = "127.0.0.1:8848";
String thirdIp = "127.0.0.1:8849";
Map<String, Member> map = new HashMap<>(4);
map.put(firstIp, Member.builder().ip("127.0.0.1").port(8847).state(NodeState.UP).build());
map.put(secondIp, Member.builder().ip("127.0.0.1").port(8848).state(NodeState.UP).build());
map.put(thirdIp, Member.builder().ip("127.0.0.1").port(8849).state(NodeState.UP).build());
List<Member> members = new ArrayList<Member>(map.values());
Collections.sort(members);
List<String> ss = MemberUtil.simpleMembers(members);
Assert.assertEquals(ss.get(0), members.get(0).getAddress());
}
@Test
public void testMemberChange() throws Exception {
AtomicInteger integer = new AtomicInteger(0);
CountDownLatch latch = new CountDownLatch(1);
NotifyCenter.registerSubscriber(new Subscriber<MembersChangeEvent>() {
@Override
public void onEvent(MembersChangeEvent event) {
integer.incrementAndGet();
latch.countDown();
}
@Override
public Class<? extends Event> subscribeType() {
return MembersChangeEvent.class;
}
});
Collection<Member> members = memberManager.allMembers();
System.out.println(members);
memberManager.memberJoin(members);
members.add(Member.builder().ip("115.159.3.213").port(8848).build());
boolean changed = memberManager.memberJoin(members);
Assert.assertTrue(changed);
latch.await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(1, integer.get());
}
@Test
public void testMemberHealthCheck() throws Exception {
AtomicReference<Collection<Member>> healthMembers = new AtomicReference<>();
CountDownLatch first = new CountDownLatch(1);
CountDownLatch second = new CountDownLatch(1);
NotifyCenter.registerSubscriber(new Subscriber<MembersChangeEvent>() {
@Override
public void onEvent(MembersChangeEvent event) {
System.out.println(event);
healthMembers.set(MemberUtil.selectTargetMembers(event.getMembers(), member -> !NodeState.DOWN.equals(member.getState())));
if (first.getCount() == 1) {
first.countDown();
return;
}
if (second.getCount() == 1) {
second.countDown();
}
}
@Override
public Class<? extends Event> subscribeType() {
return MembersChangeEvent.class;
}
});
String firstIp = "127.0.0.1:8847";
String secondIp = "127.0.0.1:8848";
String thirdIp = "127.0.0.1:8849";
Map<String, Member> map = new HashMap<>(4);
map.put(firstIp, Member.builder().ip("127.0.0.1").port(8847).state(NodeState.UP).build());
map.put(secondIp, Member.builder().ip("127.0.0.1").port(8848).state(NodeState.UP).build());
map.put(thirdIp, Member.builder().ip("127.0.0.1").port(8849).state(NodeState.UP).build());
Set<Member> firstMemberList = new HashSet<>(map.values());
memberManager.memberJoin(map.values());
first.await();
Set<Member> copy = new HashSet<>(firstMemberList);
copy.removeAll(healthMembers.get());
Assert.assertEquals(2, copy.size());
Member member = map.get(firstIp);
member.setState(NodeState.DOWN);
Assert.assertTrue(memberManager.update(member));
second.await();
copy = new HashSet<>(firstMemberList);
copy.removeAll(healthMembers.get());
Assert.assertEquals(3, copy.size());
Assert.assertTrue(copy.contains(map.get(firstIp)));
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.core.code;
import static org.junit.Assert.assertEquals;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import com.alibaba.nacos.sys.env.EnvUtil;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.connector.Request;
import org.apache.tomcat.util.buf.MessageBytes;
import org.junit.Before;
import org.junit.Test;
/**
* @author horizonzy
* @since 1.3.2
*/
public class ControllerMethodsCache_ITCase {
private ControllerMethodsCache methodsCache;
@Before
public void setUp() throws Exception {
methodsCache = new ControllerMethodsCache();
EnvUtil.setContextPath("/nacos");
methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller");
}
@Test
public void testGetMethod() {
Request getConfigRequest = buildGetConfigRequest();
Method getConfigMethod = methodsCache.getMethod(getConfigRequest);
assertEquals("getConfig", getConfigMethod.getName());
Request searchConfigRequest = buildSearchConfigRequest();
Method searchConfigMethod = methodsCache.getMethod(searchConfigRequest);
assertEquals("searchConfig", searchConfigMethod.getName());
Request detailConfigInfoRequest = buildDetailConfigInfoRequest();
Method detailConfigInfoMethod = methodsCache.getMethod(detailConfigInfoRequest);
assertEquals("detailConfigInfo", detailConfigInfoMethod.getName());
}
private Request buildDetailConfigInfoRequest() {
Map<String, String> parameter = new HashMap<>();
parameter.put("show", "all");
return buildRequest("GET", "/nacos/v1/cs/configs", parameter);
}
private Request buildSearchConfigRequest() {
Map<String, String> parameter = new HashMap<>();
parameter.put("search", "accurate");
return buildRequest("GET", "/nacos/v1/cs/configs", parameter);
}
private Request buildGetConfigRequest() {
Map<String, String> parameter = new HashMap<>();
return buildRequest("GET", "/nacos/v1/cs/configs", parameter);
}
private Request buildRequest(String method, String path, Map<String, String> parameters) {
Connector connector = new Connector();
connector.setParseBodyMethods("GET,POST,PUT,DELETE,PATCH");
Request request = new Request(connector);
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
MessageBytes messageBytes = coyoteRequest.requestURI();
messageBytes.setString(path);
request.setCoyoteRequest(coyoteRequest);
coyoteRequest.method().setString(method);
if (parameters != null) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
coyoteRequest.getParameters().addParameter(entry.getKey(), entry.getValue());
}
}
return request;
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 1999-2018 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.
*/
package com.alibaba.nacos.test.smoke;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class nacosSmoke_ITCase {
private static Logger logger = Logger.getLogger(nacosSmoke_ITCase.class);
@Before
public void setUp() {
logger.info(String.format("nacosSmoke_ITCase: %s;", "setUp"));
}
@After
public void tearDown() {
logger.info(String.format("nacosSmoke_ITCase: %s;", "tearDown"));
}
@Test
public void testSmoke() {
}
}

View File

@ -0,0 +1,17 @@
#
# Copyright 1999-2018 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.
#
com.alibaba.nacos.test.base.TextChangeParser

View File

@ -0,0 +1,55 @@
#
# Copyright 1999-2018 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.
#
# spring
server.port=8848
nacos.standalone=true
management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200
# metrics for influx
management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D
# default current work dir
server.tomcat.basedir=file:.
### The ignore urls of auth, is deprecated in 1.2.0:
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
### The auth system to use, currently only 'nacos' is supported:
nacos.core.auth.system.type=nacos
### If turn on auth system:
nacos.core.auth.enabled=false
nacos.core.auth.caching.enabled=false
### The token expiration in seconds:
nacos.core.auth.default.token.expire.seconds=18000
### The default token:
#nacos.core.auth.default.token.secret.key=U2VjcmV0S2V5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5
nacos.core.auth.plugin.nacos.token.secret.key=U2VjcmV0S2V5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5
tldSkipPatterns=derbyLocale_*.jar,jaxb-api.jar,jsr173_1.0_api.jar,jaxb1-impl.jar,activation.jar

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 1999-2018 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.
-->
<configuration>
<!--<appender name="DefaultAppender" class="ch.qos.logback.core.ConsoleAppender">-->
<!--<append>true</append>-->
<!--<encoder>-->
<!--<pattern>%d{yyy-MM-dd HH\:mm\:ss,GMT+8} %p %t - %m%n</pattern>-->
<!--<charset class="java.nio.charset.Charset">UTF-8</charset>-->
<!--</encoder>-->
<!--</appender>-->
<!--<root>-->
<!--<level value="OFF"/>-->
<!--<appender-ref ref="DefaultAppender"/>-->
<!--</root>-->
</configuration>

View File

@ -0,0 +1,16 @@
-----BEGIN CERTIFICATE-----
MIICcDCCAdmgAwIBAgIJAO1XB4XkBYN3MA0GCSqGSIb3DQEB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