[ISSUE #12227] upgrade module test from junit4 to junit5 (#12251)

* upgrade module naocs-test from junit4 to junit5

* fix test/core-test

* fix some test

* fix ci
This commit is contained in:
shalk(xiao kun) 2024-06-24 09:38:38 +08:00 committed by GitHub
parent 63dc87a30c
commit 3b2f787d61
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
69 changed files with 3697 additions and 3971 deletions

View File

@ -26,6 +26,7 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.utils.GenericType;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.env.Constants;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -33,6 +34,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.util.ReflectionTestUtils;
@ -48,6 +51,8 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class AddressServerMemberLookupTest {
private final GenericType<String> genericType = new GenericType<String>() {
@ -85,6 +90,7 @@ class AddressServerMemberLookupTest {
when(environment.getProperty("address.server.domain", "jmenv.tbsite.net")).thenReturn("jmenv.tbsite.net");
when(environment.getProperty("address.server.port", "8080")).thenReturn("8080");
when(environment.getProperty(eq("address.server.url"), any(String.class))).thenReturn("/nacos/serverlist");
when(environment.getProperty(Constants.WEB_CONTEXT_PATH)).thenReturn("/nacos");
initAddressSys();
when(restTemplate.<String>get(eq(addressServerUrl), any(Header.EMPTY.getClass()), any(Query.EMPTY.getClass()),
any(Type.class))).thenReturn(result);
@ -150,4 +156,4 @@ class AddressServerMemberLookupTest {
Loggers.CORE.info("ServerListService address-server port:" + addressPort);
Loggers.CORE.info("ADDRESS_SERVER_URL:" + addressServerUrl);
}
}
}

View File

@ -24,16 +24,16 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate;
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.persistence.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl;
import com.alibaba.nacos.consistency.ProtocolMetaData;
import com.alibaba.nacos.consistency.cp.CPProtocol;
import com.alibaba.nacos.consistency.cp.MetadataKey;
import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl;
import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
@ -57,9 +57,14 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class BaseClusterTest extends HttpClient4Test {
protected static final String CONFIG_INFO_ID = "config-info-id";
protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), new AtomicBoolean(false),
new AtomicBoolean(false)};
private static final Logger LOGGER = LoggerFactory.getLogger(BaseClusterTest.class);
protected static final String CONFIG_INFO_ID = "config-info-id";
protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER);
protected static ConfigService iconfig7;
@ -67,11 +72,6 @@ public class BaseClusterTest extends HttpClient4Test {
protected static ConfigService iconfig9;
protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER);
protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false),
new AtomicBoolean(false), new AtomicBoolean(false)};
protected static Map<String, ConfigurableApplicationContext> applications = new HashMap<>();
protected static String clusterInfo;
@ -95,8 +95,8 @@ public class BaseClusterTest extends HttpClient4Test {
});
}
@BeforeClass
public static void before() throws Exception {
@BeforeAll
static void before() throws Exception {
CountDownLatch latch = new CountDownLatch(3);
@ -144,8 +144,8 @@ public class BaseClusterTest extends HttpClient4Test {
TimeUnit.SECONDS.sleep(20L);
}
@AfterClass
public static void after() throws Exception {
@AfterAll
static void after() throws Exception {
CountDownLatch latch = new CountDownLatch(applications.size());
for (ConfigurableApplicationContext context : applications.values()) {
new Thread(() -> {
@ -179,15 +179,14 @@ public class BaseClusterTest extends HttpClient4Test {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", "884" + (7 + index));
properties.put("nacos.home", path);
properties.put("nacos.logs.path",
Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString());
properties.put("nacos.logs.path", Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString());
properties.put("spring.jmx.enabled", false);
properties.put("nacos.core.snowflake.worker-id", index + 1);
MapPropertySource propertySource = new MapPropertySource("nacos_cluster_test", properties);
ConfigurableEnvironment environment = new StandardServletEnvironment();
environment.getPropertySources().addFirst(propertySource);
SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET)
.environment(environment).properties(clusterInfo).properties("embeddedStorage=true").build();
SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET).environment(environment)
.properties(clusterInfo).properties("embeddedStorage=true").build();
ConfigurableApplicationContext context = cluster.run();

View File

@ -13,6 +13,7 @@
* 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;
@ -33,35 +34,31 @@ import java.net.URL;
* @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);
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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -13,6 +13,7 @@
* 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;
@ -22,20 +23,20 @@ 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

@ -32,29 +32,39 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager;
import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Base64;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class AbstractConfigAPI_CITCase {
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
abstract class AbstractConfigAPI_CITCase {
public static final long TIME_OUT = 5000;
@ -62,14 +72,14 @@ public abstract class AbstractConfigAPI_CITCase {
private static final String SPECIAL_CHARACTERS = "!@#$%^&*()_+-=_|/'?.";
private static String dataId = "yanlin";
private static String group = "yanlin";
static ConfigService iconfig = null;
static HttpAgent agent = null;
private static String dataId = "yanlin";
private static String group = "yanlin";
@Value("${server.servlet.context-path}")
private String contextPath;
@ -78,7 +88,7 @@ public abstract class AbstractConfigAPI_CITCase {
private EncryptionPluginService mockEncryptionPluginService;
@Before
@BeforeEach
public void initEncryptionPluginService() {
mockEncryptionPluginService = new EncryptionPluginService() {
@ -170,7 +180,7 @@ public abstract class AbstractConfigAPI_CITCase {
EncryptionPluginManager.join(mockEncryptionPluginService);
}
@Before
@BeforeEach
public void setUp() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
@ -182,7 +192,7 @@ public abstract class AbstractConfigAPI_CITCase {
agent.start();
}
@After
@AfterEach
public void cleanup() throws Exception {
HttpRestResult<String> result = null;
try {
@ -191,12 +201,12 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("group", group);
params.put("beta", "true");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
fail();
}
}
@ -205,20 +215,21 @@ public abstract class AbstractConfigAPI_CITCase {
* @TestStep :
* @ExpectResult :
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_getconfig_1() throws Exception {
final String content = "test";
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
result = iconfig.removeConfig(dataId, group);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
value = iconfig.getConfig(dataId, group, TIME_OUT);
System.out.println(value);
Assert.assertNull(value);
assertNull(value);
}
/**
@ -226,146 +237,155 @@ public abstract class AbstractConfigAPI_CITCase {
* @TestStep :
* @ExpectResult :
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacosPublishAndGetConfig() throws Exception {
String dataId = "cipher-aes-dataId";
final String content = "test";
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
result = iconfig.removeConfig(dataId, group);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertNull(value);
assertNull(value);
}
/**
* @throws Exception
* @TCDescription : nacos_服务端无配置时获取配置
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_getconfig_2() throws Exception {
String content = iconfig.getConfig(dataId, "nacos", TIME_OUT);
Assert.assertNull(content);
assertNull(content);
}
/**
* @throws Exception
* @TCDescription : nacos_获取配置时dataId为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_getconfig_3() throws Exception {
try {
String content = iconfig.getConfig(null, group, TIME_OUT);
} catch (Exception e) {
Assert.assertTrue(true);
assertTrue(true);
return;
}
Assert.fail();
fail();
}
/**
* @throws Exception
* @TCDescription : nacos_获取配置时group为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_getconfig_4() throws Exception {
final String dataId = "nacos_getconfig_4";
final String content = "test";
boolean result = iconfig.publishConfig(dataId, null, content);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(TIME_OUT);
String value = iconfig.getConfig(dataId, null, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
result = iconfig.removeConfig(dataId, null);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
}
/**
* @throws Exception
* @TCDescription : nacos_服务端无该配置项时正常创建配置
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_1() throws Exception {
final String content = "publishConfigTest";
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
result = iconfig.removeConfig(dataId, group);
Assert.assertTrue(result);
assertTrue(result);
}
/**
* @throws Exception
* @TCDescription : nacos_服务端有该配置项时正常修改配置
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_2() throws Exception {
final String content = "publishConfigTest";
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
final String content1 = "test.abc";
result = iconfig.publishConfig(dataId, group, content1);
Thread.sleep(TIME_OUT);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content1, value);
assertEquals(content1, value);
}
/**
* @throws Exception
* @TCDescription : nacos_发布配置时包含特殊字符
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_3() throws Exception {
String content = "test" + SPECIAL_CHARACTERS;
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
}
/**
* @throws Exception
* @TCDescription : nacos_发布配置时dataId为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_4() throws Exception {
try {
String content = "test";
boolean result = iconfig.publishConfig(null, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
} catch (Exception e) {
Assert.assertTrue(true);
assertTrue(true);
return;
}
Assert.fail();
fail();
}
/**
* @throws Exception
* @TCDescription : nacos_发布配置时group为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_5() throws Exception {
final String dataId = "nacos_publishConfig_5";
String content = "test";
boolean result = iconfig.publishConfig(dataId, null, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
String value = iconfig.getConfig(dataId, null, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
}
@ -373,31 +393,33 @@ public abstract class AbstractConfigAPI_CITCase {
* @throws Exception
* @TCDescription : nacos_发布配置时配置内容为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_6() throws Exception {
String content = null;
try {
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
} catch (Exception e) {
Assert.assertTrue(true);
assertTrue(true);
return;
}
Assert.fail();
fail();
}
/**
* @throws Exception
* @TCDescription : nacos_发布配置时配置内容包含中文字符
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_publishConfig_7() throws Exception {
String content = "阿里abc";
boolean result = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, value);
assertEquals(content, value);
}
/**
@ -409,70 +431,74 @@ public abstract class AbstractConfigAPI_CITCase {
String content = "test";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(TIME_OUT);
result = iconfig.removeConfig(dataId, group);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(TIME_OUT);
String value = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertNull(value);
assertNull(value);
}
/**
* @throws Exception
* @TCDescription : nacos_服务端无该配置项时配置删除失败
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeConfig_2() throws Exception {
group += "removeConfig2";
boolean result = iconfig.removeConfig(dataId, group);
Assert.assertTrue(result);
assertTrue(result);
}
/**
* @throws Exception
* @TCDescription : nacos_删除配置时dataId为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeConfig_3() throws Exception {
try {
boolean result = iconfig.removeConfig(null, group);
Assert.assertTrue(result);
assertTrue(result);
} catch (Exception e) {
Assert.assertTrue(true);
assertTrue(true);
return;
}
Assert.fail();
fail();
}
/**
* @throws Exception
* @TCDescription : nacos_删除配置时group为null
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeConfig_4() throws Exception {
boolean result = iconfig.removeConfig(dataId, null);
Assert.assertTrue(result);
assertTrue(result);
}
/**
* @throws Exception
* @TCDescription : nacos_添加对dataId的监听在服务端修改配置后获取监听后的修改的配置
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_addListener_1() throws Exception {
final AtomicInteger count = new AtomicInteger(0);
final String content = "test-abc";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
Listener ml = new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("receive23:" + configInfo);
count.incrementAndGet();
Assert.assertEquals(content, configInfo);
assertEquals(content, configInfo);
}
@Override
@ -484,7 +510,7 @@ public abstract class AbstractConfigAPI_CITCase {
while (count.get() == 0) {
Thread.sleep(2000);
}
Assert.assertTrue(count.get() >= 1);
assertTrue(count.get() >= 1);
iconfig.removeListener(dataId, group, ml);
}
@ -495,9 +521,12 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = TIME_OUT, expected = IllegalArgumentException.class)
@Test
@Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_addListener_2() throws Exception {
iconfig.addListener(dataId, group, null);
assertThrows(IllegalArgumentException.class, () -> {
iconfig.addListener(dataId, group, null);
});
}
@ -508,7 +537,8 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = Constants.CONFIG_LONG_POLL_TIMEOUT << 2)
@Test
@Timeout(value = Constants.CONFIG_LONG_POLL_TIMEOUT << 2, unit = TimeUnit.MILLISECONDS)
public void nacos_addListener_3() throws InterruptedException, NacosException {
final AtomicInteger count = new AtomicInteger(0);
final String dataId = "nacos_addListener_3";
@ -516,7 +546,7 @@ public abstract class AbstractConfigAPI_CITCase {
final String content = "test-abc-" + System.currentTimeMillis();
final String newContent = "nacos_addListener_3-" + System.currentTimeMillis();
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
// Maximum assurance level notification has been performed
ThreadUtils.sleep(5000);
@ -525,17 +555,17 @@ public abstract class AbstractConfigAPI_CITCase {
@Override
public void receiveConfigInfo(String configInfo) {
count.incrementAndGet();
Assert.assertEquals(newContent, configInfo);
assertEquals(newContent, configInfo);
}
};
String receive = iconfig.getConfigAndSignListener(dataId, group, 5000L, ml);
Assert.assertEquals(content, receive);
assertEquals(content, receive);
result = iconfig.publishConfig(dataId, group, newContent);
Assert.assertTrue(result);
assertTrue(result);
// Get enough sleep to ensure that the monitor is triggered only once
// during the two long training sessions
ThreadUtils.sleep(Constants.CONFIG_LONG_POLL_TIMEOUT << 1);
Assert.assertEquals(1, count.get());
assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
@ -546,7 +576,8 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_addListener_4() throws Exception {
final AtomicInteger count = new AtomicInteger(0);
@ -563,12 +594,12 @@ public abstract class AbstractConfigAPI_CITCase {
Thread.sleep(TIME_OUT);
String content = "test-abc";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
while (count.get() == 0) {
Thread.sleep(3000);
}
Assert.assertEquals(1, count.get());
assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
@ -587,7 +618,7 @@ public abstract class AbstractConfigAPI_CITCase {
final String content = "test-abc";
final String newContent = "new-test-def";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(2000);
@ -595,7 +626,7 @@ public abstract class AbstractConfigAPI_CITCase {
@Override
public void receiveConfigInfo(String configInfo) {
count.incrementAndGet();
Assert.assertEquals(newContent, configInfo);
assertEquals(newContent, configInfo);
}
};
@ -603,12 +634,12 @@ public abstract class AbstractConfigAPI_CITCase {
System.out.println(receiveContent);
result = iconfig.publishConfig(dataId, group, newContent);
Assert.assertTrue(result);
assertTrue(result);
Assert.assertEquals(content, receiveContent);
assertEquals(content, receiveContent);
Thread.sleep(2000);
Assert.assertEquals(1, count.get());
assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
@ -634,7 +665,7 @@ public abstract class AbstractConfigAPI_CITCase {
final String content = "test-abc";
final String newContent = "new-test-def";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(2000);
@ -643,7 +674,7 @@ public abstract class AbstractConfigAPI_CITCase {
public void receiveConfigInfo(String configInfo) {
count.incrementAndGet();
System.out.println("Listener receive : [" + configInfo + "]");
Assert.assertEquals(newContent, configInfo);
assertEquals(newContent, configInfo);
}
};
@ -654,15 +685,15 @@ public abstract class AbstractConfigAPI_CITCase {
System.out.println(receiveContent);
result = iconfig.publishConfig(dataId, group, newContent);
Assert.assertTrue(result);
assertTrue(result);
Thread.sleep(2000);
receiveContent = iconfig.getConfig(dataId, group, 1000);
Assert.assertEquals(newContent, receiveContent);
assertEquals(newContent, receiveContent);
Assert.assertEquals(1, count.get());
assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
@ -673,12 +704,13 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeListener_1() throws Exception {
iconfig.addListener(dataId, group, new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
Assert.fail();
fail();
}
});
Thread.sleep(TIME_OUT);
@ -701,19 +733,18 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = TIME_OUT)
@Test
@Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeListener_2() {
group += "test.nacos";
try {
Assertions.assertDoesNotThrow(() -> {
iconfig.removeListener(dataId, group, new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
}
});
} catch (Exception e) {
Assert.fail();
}
});
}
/**
@ -723,7 +754,8 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeListener_3() throws Exception {
final String contentRemove = "test-abc-two";
final AtomicInteger count = new AtomicInteger(0);
@ -739,7 +771,7 @@ public abstract class AbstractConfigAPI_CITCase {
public void receiveConfigInfo(String configInfo) {
//System.out.println("ml1 remove listener receive:" + configInfo);
count.incrementAndGet();
Assert.assertEquals(contentRemove, configInfo);
assertEquals(contentRemove, configInfo);
}
};
iconfig.addListener(dataId, group, ml);
@ -750,12 +782,12 @@ public abstract class AbstractConfigAPI_CITCase {
boolean result = iconfig.publishConfig(dataId, group, contentRemove);
Thread.sleep(TIME_OUT);
Assert.assertTrue(result);
assertTrue(result);
while (count.get() == 0) {
Thread.sleep(3000);
}
Assert.assertNotEquals(0, count.get());
assertNotEquals(0, count.get());
}
/**
@ -765,9 +797,12 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = TIME_OUT, expected = IllegalArgumentException.class)
@Test
@Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_removeListener_4() {
iconfig.removeListener(dataId, group, null);
assertThrows(IllegalArgumentException.class, () -> {
iconfig.removeListener(dataId, group, null);
});
}
/**
@ -777,26 +812,23 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_detailConfig_1() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
final String content = "test";
boolean ret = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(ret);
assertTrue(ret);
Map<String, String> params = new HashMap<>();
params.put("dataId", dataId);
params.put("group", group);
params.put("show", "all");
result = agent.httpGet(CONFIG_CONTROLLER_PATH, null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
HttpRestResult<String> result = agent.httpGet(CONFIG_CONTROLLER_PATH, null, params, agent.getEncode(), TIME_OUT);
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals(content, JacksonUtils.toObj(result.getData()).get("content").textValue());
} catch (Exception e) {
Assert.fail();
}
assertEquals(content, JacksonUtils.toObj(result.getData()).get("content").textValue());
});
}
/**
@ -806,27 +838,24 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_catalog() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
final String content = "test";
boolean ret = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(ret);
assertTrue(ret);
Map<String, String> params = new HashMap<>();
params.put("dataId", dataId);
params.put("group", group);
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/catalog", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
HttpRestResult<String> result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/catalog", null, params, agent.getEncode(), TIME_OUT);
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
System.out.println(result.getData());
Assert.assertFalse(JacksonUtils.toObj(result.getData()).get("data").isNull());
assertFalse(JacksonUtils.toObj(result.getData()).get("data").isNull());
} catch (Exception e) {
Assert.fail();
}
});
}
/**
@ -836,11 +865,11 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_queryBeta_1() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result = null;
final String content = "test-beta";
Map<String, String> headers = new HashMap<>();
headers.put("betaIps", "127.0.0.1");
@ -849,22 +878,19 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("group", group);
params.put("content", content);
result = agent.httpPost(CONFIG_CONTROLLER_PATH + "/", headers, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals("true", result.getData());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals("true", result.getData());
params.clear();
params.put("dataId", dataId);
params.put("group", group);
params.put("beta", "true");
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals(content, JacksonUtils.toObj(result.getData()).get("data").get("content").textValue());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(content, JacksonUtils.toObj(result.getData()).get("data").get("content").textValue());
// delete data
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
} catch (Exception e) {
Assert.fail();
}
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
});
}
/**
@ -874,7 +900,8 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 3 * TIME_OUT)
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_queryBeta_delete() {
HttpRestResult<String> result = null;
@ -887,8 +914,8 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("group", group);
params.put("content", content);
result = agent.httpPost(CONFIG_CONTROLLER_PATH + "/", headers, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals("true", result.getData());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals("true", result.getData());
params.clear();
params.put("dataId", dataId);
@ -896,11 +923,11 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("beta", "true");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue());
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
fail();
}
}
@ -911,15 +938,15 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_fuzzySearchConfig() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result;
final String content = "test123";
boolean ret = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(ret);
assertTrue(ret);
Map<String, String> params = new HashMap<>();
params.put("dataId", dataId);
params.put("group", group);
@ -927,14 +954,11 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("pageSize", "10");
params.put("search", "blur");
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1);
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue()
.startsWith(content));
} catch (Exception e) {
Assert.fail();
}
assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1);
assertTrue(JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue().startsWith(content));
});
}
/**
@ -944,15 +968,16 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_fuzzySearchConfig_1() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result;
final String content = "test123";
boolean ret = iconfig.publishConfig(dataId, group, content);
Thread.sleep(TIME_OUT);
Assert.assertTrue(ret);
assertTrue(ret);
Map<String, String> params = new HashMap<>();
params.put("dataId", dataId + "*");
params.put("group", group + "*");
@ -961,14 +986,11 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("search", "blur");
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1);
Assert.assertEquals(content,
JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1);
assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
} catch (Exception e) {
Assert.fail();
}
});
}
/**
@ -978,14 +1000,15 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_searchConfig() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result;
final String content = "test123";
boolean ret = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(ret);
assertTrue(ret);
Thread.sleep(TIME_OUT);
Map<String, String> params = new HashMap<>();
params.put("dataId", dataId);
@ -995,14 +1018,11 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("search", "accurate");
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue());
Assert.assertEquals(content,
JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue());
assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
} catch (Exception e) {
Assert.fail();
}
});
}
/**
@ -1012,14 +1032,15 @@ public abstract class AbstractConfigAPI_CITCase {
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test(timeout = 5 * TIME_OUT)
@Test
@Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
public void nacos_openAPI_searchConfig_2() {
HttpRestResult<String> result = null;
try {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result;
final String content = "test测试";
boolean ret = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(ret);
assertTrue(ret);
Thread.sleep(TIME_OUT);
Map<String, String> params = new HashMap<>();
@ -1029,13 +1050,10 @@ public abstract class AbstractConfigAPI_CITCase {
params.put("pageSize", "10");
params.put("search", "accurate");
result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
Assert.assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue());
Assert.assertEquals(content,
JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
} catch (Exception e) {
Assert.fail();
}
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue());
assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue());
});
}

View File

@ -18,29 +18,28 @@ package com.alibaba.nacos.test.config;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/**
* @author xiaochun.xxc
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigAPI_CITCase extends AbstractConfigAPI_CITCase {
class ConfigAPI_CITCase extends AbstractConfigAPI_CITCase {
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeClass() {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
}

View File

@ -19,37 +19,37 @@ package com.alibaba.nacos.test.config;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import com.alibaba.nacos.test.base.HttpClient4Test;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.databind.JsonNode;
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.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.net.URL;
import java.util.Random;
import static com.alibaba.nacos.test.config.ConfigAPI_V2_CITCase.CONTEXT_PATH;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author karsonto
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=" + CONTEXT_PATH}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.JVM)
@TestMethodOrder(MethodName.class)
public class ConfigAPI_V2_CITCase extends HttpClient4Test {
public static final long TIME_OUT = 5000;
@ -69,80 +69,18 @@ public class ConfigAPI_V2_CITCase extends HttpClient4Test {
@LocalServerPort
private int port;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeClass() {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_V2_CITCase.class.getSimpleName());
}
@AfterClass
@BeforeClass
public static void cleanClientCache() throws Exception {
@AfterAll
@BeforeAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Before
public void setUp() throws Exception {
String url = String.format("http://127.0.0.1:%d/", port);
this.base = new URL(url);
}
@Test
public void test() throws Exception {
publishConfig();
Thread.sleep(TIME_OUT);
String config = getConfig(true);
Assert.assertEquals(config, CONTENT);
Thread.sleep(TIME_OUT);
deleteConfig();
Thread.sleep(TIME_OUT);
boolean thrown = false;
try {
getConfig(false);
} catch (Exception e) {
thrown = true;
}
Assert.assertTrue(thrown);
}
public void publishConfig() throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP)
.appendParam("namespaceId", NAME_SPACE_ID).appendParam("content", CONTENT).done(), String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(true, json.get("data").asBoolean());
}
public String getConfig(boolean ignoreStatusCode) throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP)
.appendParam("namespaceId", NAME_SPACE_ID).done(), String.class, HttpMethod.GET);
if (!ignoreStatusCode) {
if (!response.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("Fail to get config");
}
} else {
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
}
JsonNode json = JacksonUtils.toObj(response.getBody());
return json.get("data").asText();
}
public void deleteConfig() throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP)
.appendParam("namespaceId", NAME_SPACE_ID).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(true, json.get("data").asBoolean());
}
public static String randomContent() {
StringBuilder sb = new StringBuilder();
Random rand = new Random();
@ -153,4 +91,63 @@ public class ConfigAPI_V2_CITCase extends HttpClient4Test {
}
return sb.toString();
}
@BeforeEach
void setUp() throws Exception {
String url = String.format("http://127.0.0.1:%d/", port);
this.base = new URL(url);
}
@Test
void test() throws Exception {
publishConfig();
Thread.sleep(TIME_OUT);
String config = getConfig(true);
assertEquals(CONTENT, config);
Thread.sleep(TIME_OUT);
deleteConfig();
Thread.sleep(TIME_OUT);
boolean thrown = false;
try {
getConfig(false);
} catch (Exception e) {
thrown = true;
}
assertTrue(thrown);
}
public void publishConfig() throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP).appendParam("namespaceId", NAME_SPACE_ID)
.appendParam("content", CONTENT).done(), String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
assertTrue(json.get("data").asBoolean());
}
public String getConfig(boolean ignoreStatusCode) throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP).appendParam("namespaceId", NAME_SPACE_ID)
.done(), String.class, HttpMethod.GET);
if (!ignoreStatusCode) {
if (!response.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("Fail to get config");
}
} else {
assertTrue(response.getStatusCode().is2xxSuccessful());
}
JsonNode json = JacksonUtils.toObj(response.getBody());
return json.get("data").asText();
}
public void deleteConfig() throws Exception {
ResponseEntity<String> response = request(CONFIG_V2_CONTROLLER_PATH,
Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP).appendParam("namespaceId", NAME_SPACE_ID)
.done(), String.class, HttpMethod.DELETE);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
assertTrue(json.get("data").asBoolean());
}
}

View File

@ -19,35 +19,34 @@ package com.alibaba.nacos.test.config;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
/**
* Test context path is '/'.
*
* @see <a href="https://github.com/alibaba/nacos/issues/4181">#4171</a>
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/",
"server.port=7001"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigAPI_With_RootContextPath_CITCase extends AbstractConfigAPI_CITCase {
class ConfigAPI_With_RootContextPath_CITCase extends AbstractConfigAPI_CITCase {
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_With_RootContextPath_CITCase.class.getSimpleName());
ConfigCleanUtils.cleanClientCache();
EnvUtil.setPort(7001);
}
@AfterClass
public static void cleanClientCache() throws Exception {
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
EnvUtil.setPort(8848);
}

View File

@ -22,12 +22,11 @@ import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import com.alibaba.nacos.test.base.Params;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
@ -36,365 +35,276 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author xiaochun.xxc
* @date 2019-07-03
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigBeta_CITCase {
@LocalServerPort
private int port;
private String url;
@Autowired
private TestRestTemplate restTemplate;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ConfigBeta_CITCase {
static final String CONFIG_CONTROLLER_PATH = "/nacos/v1/cs";
String dataId = "com.dungu.test";
String group = "default";
String tenant = "dungu";
String content = "test";
String appName = "nacos";
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@LocalServerPort
private int port;
private String url;
@Autowired
private TestRestTemplate restTemplate;
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(ConfigBeta_CITCase.class.getSimpleName());
}
@Before
public void init() throws NacosException {
@BeforeEach
void init() throws NacosException {
url = String.format("http://localhost:%d", port);
}
/**
* @TCDescription : 正常发布Beta配置
* @TestStep :
* @ExpectResult :
*/
@Test
public void publishBetaConfig() throws Exception {
void publishBetaConfig() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("betaIps", "127.0.0.1,127.0.0.2");
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("publishBetaConfig : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
}
/**
* @TCDescription : 必选content未设置的发布Beta配置
* @TestStep :
* @ExpectResult :
*/
@Test
public void publishBetaConfig_no_content() throws Exception {
void publishBetaConfig_no_content() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("betaIps", "127.0.0.1,127.0.0.2");
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("config_tags", "").appendParam("appName", appName).done(), String.class, HttpMethod.POST);
System.out.println("publishBetaConfig_no_content : " + response);
Assert.assertFalse(response.getStatusCode().is2xxSuccessful());
assertFalse(response.getStatusCode().is2xxSuccessful());
}
/**
* @TCDescription : 可选参数betaIps不存在时发布Beta配置应该不成功
* @TestStep :
* @ExpectResult :
*/
@Test
public void publishBetaConfig_noBetaIps_beta() throws Exception {
void publishBetaConfig_noBetaIps_beta() throws Exception {
HttpHeaders headers = new HttpHeaders(); //不存在betaIps
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("publishBetaConfig_noBetaIps_beta post : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
ResponseEntity<String> response1 = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("publishBetaConfig_noBetaIps_beta get : " + response);
Assert.assertTrue(response1.getStatusCode().is2xxSuccessful());
Assert.assertTrue(JacksonUtils.toObj(response1.getBody()).get("data").isNull());
assertTrue(response1.getStatusCode().is2xxSuccessful());
assertTrue(JacksonUtils.toObj(response1.getBody()).get("data").isNull());
}
/**
* @TCDescription : 可选参数betaIps不存在时发布Beta配置应该不成功
* @TestStep :
* @ExpectResult :
*/
@Test
public void publishBetaConfig_noBetaIps() throws Exception {
void publishBetaConfig_noBetaIps() throws Exception {
HttpHeaders headers = new HttpHeaders(); //不存在betaIps
final String dataId = "publishBetaConfig_noBetaIps";
final String groupId = "publishBetaConfig_noBetaIps";
final String content = "publishBetaConfig_noBetaIps";
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", groupId)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", groupId).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("publishBetaConfig_noBetaIps post : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
ThreadUtils.sleep(10_000L);
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", groupId)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", groupId).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("publishBetaConfig_noBetaIps get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals(content, response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals(content, response.getBody());
}
/**
* @TCDescription : 正常获取Beta配置
* @TestStep :
* @ExpectResult :
*/
@Test
public void getBetaConfig() throws Exception {
void getBetaConfig() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("betaIps", "127.0.0.1,127.0.0.2");
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("getBetaConfig post : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("getBetaConfig get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
}
/**
* @TCDescription : 正常删除Beta配置
* @TestStep :
* @ExpectResult :
*/
@Test
public void deleteBetaConfig() throws Exception {
void deleteBetaConfig() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("betaIps", "127.0.0.1,127.0.0.2");
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("deleteBetaConfig post : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("deleteBetaConfig get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.DELETE);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.DELETE);
System.out.println("deleteBetaConfig delete : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", JacksonUtils.toObj(response.getBody()).get("data").asText());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", JacksonUtils.toObj(response.getBody()).get("data").asText());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("deleteBetaConfig after delete then get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertTrue(JacksonUtils.toObj(response.getBody()).get("data").isNull());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(JacksonUtils.toObj(response.getBody()).get("data").isNull());
}
/**
* @TCDescription : beta=false时删除Beta配置
* @TestStep :
* @ExpectResult :
*/
@Test
public void deleteBetaConfig_delete_beta_false() throws Exception {
void deleteBetaConfig_delete_beta_false() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("betaIps", "127.0.0.1,127.0.0.2");
ResponseEntity<String> response = request(CONFIG_CONTROLLER_PATH + "/configs", headers,
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.appendParam("content", content)
.appendParam("config_tags", "")
.appendParam("appName", appName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant)
.appendParam("content", content).appendParam("config_tags", "").appendParam("appName", appName).done(),
String.class, HttpMethod.POST);
System.out.println("deleteBetaConfig_delete_beta_false post : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("deleteBetaConfig_delete_beta_false get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.DELETE);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.DELETE);
System.out.println("deleteBetaConfig_delete_beta_false delete : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("true", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("true", response.getBody());
response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true",
Params.newParams()
.appendParam("dataId", dataId)
.appendParam("group", group)
.appendParam("tenant", tenant)
.done(),
String.class,
HttpMethod.GET);
Params.newParams().appendParam("dataId", dataId).appendParam("group", group).appendParam("tenant", tenant).done(),
String.class, HttpMethod.GET);
System.out.println("deleteBetaConfig_delete_beta_false after delete then get : " + response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText());
}
<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.url.toString() + path)
.queryParams(params);
return this.restTemplate.exchange(
builder.toUriString(), httpMethod, entity, clazz);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
<T> ResponseEntity<T> request(String path, HttpHeaders headers, MultiValueMap<String, String> params, Class<T> clazz, HttpMethod httpMethod) {
<T> ResponseEntity<T> request(String path, HttpHeaders headers, MultiValueMap<String, String> params, Class<T> clazz,
HttpMethod httpMethod) {
HttpEntity<?> entity = new HttpEntity<T>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path)
.queryParams(params);
return this.restTemplate.exchange(
builder.toUriString(), httpMethod, entity, clazz);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -26,74 +26,32 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.File;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Data import integration tests.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigDerbyImport_CITCase {
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyImport_CITCase.class.getSimpleName());
}
@Before
public void setUp() {
DynamicDataSource.getInstance().getDataSource().getJdbcTemplate().execute("TRUNCATE TABLE config_info");
}
@Test()
public void testDerbyImport() throws Throwable {
DatabaseOperate operate = context.getBean(DatabaseOperate.class);
File file = DiskUtils.createTmpFile("derby_import" + System.currentTimeMillis(), ".tmp");
DiskUtils.writeFile(file, ByteUtils.toBytes(SQL_SCRIPT_CONTEXT), false);
try {
List<Integer> ids = operate.queryMany("SELECT id FROM config_info", new Object[]{}, Integer.class);
for (Integer each : ids) {
System.out.println("current id in table config_info contain: " + each);
}
CompletableFuture<RestResult<String>> future = operate.dataImport(file);
RestResult<String> result = future.join();
System.out.println(result);
Assert.assertTrue(result.ok());
final String queryDataId = "people";
final String queryGroup = "DEFAULT_GROUP";
final String expectContent = "people.enable=true";
ConfigInfoPersistService persistService = context.getBean(ConfigInfoPersistService.class);
ConfigInfo configInfo = persistService.findConfigInfo(queryDataId, queryGroup, "");
System.out.println(configInfo);
Assert.assertNotNull(configInfo);
Assert.assertEquals(queryDataId, configInfo.getDataId());
Assert.assertEquals(queryGroup, configInfo.getGroup());
Assert.assertEquals("", configInfo.getTenant());
Assert.assertEquals(expectContent, configInfo.getContent());
} finally {
DiskUtils.deleteQuietly(file);
}
}
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ConfigDerbyImport_CITCase {
private static String SQL_SCRIPT_CONTEXT =
"INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n"
@ -115,4 +73,49 @@ public class ConfigDerbyImport_CITCase {
+ "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (33,'application.properties','DEFAULT_GROUP','name=liaochuntao is man','17581188a1cdc684721dde500c693c07','2020-04-30 10:45:21','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n"
+ "\n";
@Autowired
private ApplicationContext context;
@BeforeAll
static void beforeClass() {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyImport_CITCase.class.getSimpleName());
}
@BeforeEach
void setUp() {
DynamicDataSource.getInstance().getDataSource().getJdbcTemplate().execute("TRUNCATE TABLE config_info");
}
@Test
void testDerbyImport() throws Throwable {
DatabaseOperate operate = context.getBean(DatabaseOperate.class);
File file = DiskUtils.createTmpFile("derby_import" + System.currentTimeMillis(), ".tmp");
DiskUtils.writeFile(file, ByteUtils.toBytes(SQL_SCRIPT_CONTEXT), false);
try {
List<Integer> ids = operate.queryMany("SELECT id FROM config_info", new Object[] {}, Integer.class);
for (Integer each : ids) {
System.out.println("current id in table config_info contain: " + each);
}
CompletableFuture<RestResult<String>> future = operate.dataImport(file);
RestResult<String> result = future.join();
System.out.println(result);
assertTrue(result.ok());
final String queryDataId = "people";
final String queryGroup = "DEFAULT_GROUP";
final String expectContent = "people.enable=true";
ConfigInfoPersistService persistService = context.getBean(ConfigInfoPersistService.class);
ConfigInfo configInfo = persistService.findConfigInfo(queryDataId, queryGroup, "");
System.out.println(configInfo);
assertNotNull(configInfo);
assertEquals(queryDataId, configInfo.getDataId());
assertEquals(queryGroup, configInfo.getGroup());
assertEquals("", configInfo.getTenant());
assertEquals(expectContent, configInfo.getContent());
} finally {
DiskUtils.deleteQuietly(file);
}
}
}

View File

@ -36,12 +36,11 @@ import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.sys.utils.InetUtils;
import com.alibaba.nacos.test.base.BaseClusterTest;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.HashMap;
@ -52,30 +51,37 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("all")
@Ignore
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
@TestMethodOrder(MethodName.class)
// todo the suffix is _DITCase, the case will be skipped by default
class ConfigDerbyRaft_DITCase extends BaseClusterTest {
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeClass() {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyRaft_DITCase.class.getSimpleName());
}
@Test
public void test_a_publish_config() throws Exception {
void test_a_publish_config() throws Exception {
boolean result = iconfig7.publishConfig("raft_test", "cluster_test_1", "this.is.raft_cluster=lessspring_7");
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
ConfigurableApplicationContext context7 = applications.get("8847");
ConfigurableApplicationContext context8 = applications.get("8848");
ConfigurableApplicationContext context9 = applications.get("8849");
ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
@ -84,24 +90,23 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
String s8 = operate8.findConfigInfo("raft_test", "cluster_test_1", "").getContent();
String s9 = operate9.findConfigInfo("raft_test", "cluster_test_1", "").getContent();
Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9},
new String[] {"this.is.raft_cluster=lessspring_7", "this.is.raft_cluster=lessspring_7",
"this.is.raft_cluster=lessspring_7"});
assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_7", "this.is.raft_cluster=lessspring_7",
"this.is.raft_cluster=lessspring_7"}, "The three nodes must have consistent data");
}
@Test
public void test_b_publish_config() throws Exception {
void test_b_publish_config() throws Exception {
ThreadUtils.sleep(5000);
boolean result = iconfig8.publishConfig("raft_test", "cluster_test_2", "this.is.raft_cluster=lessspring_8");
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
ConfigurableApplicationContext context7 = applications.get("8847");
ConfigurableApplicationContext context8 = applications.get("8848");
ConfigurableApplicationContext context9 = applications.get("8849");
ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
@ -110,23 +115,22 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
String s8 = operate8.findConfigInfo("raft_test", "cluster_test_2", "").getContent();
String s9 = operate9.findConfigInfo("raft_test", "cluster_test_2", "").getContent();
Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9},
new String[] {"this.is.raft_cluster=lessspring_8", "this.is.raft_cluster=lessspring_8",
"this.is.raft_cluster=lessspring_8"});
assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_8", "this.is.raft_cluster=lessspring_8",
"this.is.raft_cluster=lessspring_8"}, "The three nodes must have consistent data");
}
@Test
public void test_c_publish_config() throws Exception {
void test_c_publish_config() throws Exception {
ThreadUtils.sleep(5000);
boolean result = iconfig9.publishConfig("raft_test", "cluster_test_2", "this.is.raft_cluster=lessspring_9");
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
ConfigurableApplicationContext context7 = applications.get("8847");
ConfigurableApplicationContext context8 = applications.get("8848");
ConfigurableApplicationContext context9 = applications.get("8849");
ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
@ -135,23 +139,21 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
String s8 = operate8.findConfigInfo("raft_test", "cluster_test_2", "").getContent();
String s9 = operate9.findConfigInfo("raft_test", "cluster_test_2", "").getContent();
Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9},
new String[] {"this.is.raft_cluster=lessspring_9", "this.is.raft_cluster=lessspring_9",
"this.is.raft_cluster=lessspring_9"});
assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_9", "this.is.raft_cluster=lessspring_9",
"this.is.raft_cluster=lessspring_9"}, "The three nodes must have consistent data");
}
@Test
public void test_d_modify_config() throws Exception {
boolean result = iconfig7
.publishConfig("raft_test", "cluster_test_1", "this.is.raft_cluster=lessspring_7_it_is_for_modify");
Assert.assertTrue(result);
void test_d_modify_config() throws Exception {
boolean result = iconfig7.publishConfig("raft_test", "cluster_test_1", "this.is.raft_cluster=lessspring_7_it_is_for_modify");
assertTrue(result);
ThreadUtils.sleep(5000);
ConfigurableApplicationContext context7 = applications.get("8847");
ConfigurableApplicationContext context8 = applications.get("8848");
ConfigurableApplicationContext context9 = applications.get("8849");
ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class);
@ -160,75 +162,74 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
String s8 = operate8.findConfigInfo("raft_test", "cluster_test_1", "").getContent();
String s9 = operate9.findConfigInfo("raft_test", "cluster_test_1", "").getContent();
Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9},
new String[] {"this.is.raft_cluster=lessspring_7_it_is_for_modify",
"this.is.raft_cluster=lessspring_7_it_is_for_modify",
"this.is.raft_cluster=lessspring_7_it_is_for_modify"});
assertArrayEquals(new String[] {s7, s8, s9},
new String[] {"this.is.raft_cluster=lessspring_7_it_is_for_modify", "this.is.raft_cluster=lessspring_7_it_is_for_modify",
"this.is.raft_cluster=lessspring_7_it_is_for_modify"}, "The three nodes must have consistent data");
}
@Test
public void test_l_client_operation() throws Exception {
void test_l_client_operation() throws Exception {
final String dataId = "test_l_client_operation";
final String groupId = "test_l_client_operation";
String content = "test_l_client_operation" + System.currentTimeMillis();
// publish by 8847
boolean result = iconfig7.publishConfig(dataId, groupId, content);
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
String v1_7 = iconfig7.getConfig(dataId, groupId, 5000L);
String v1_8 = iconfig8.getConfig(dataId, groupId, 5000L);
String v1_9 = iconfig9.getConfig(dataId, groupId, 5000L);
Assert.assertEquals(content, v1_7);
Assert.assertEquals(content, v1_8);
Assert.assertEquals(content, v1_9);
assertEquals(content, v1_7);
assertEquals(content, v1_8);
assertEquals(content, v1_9);
// publish by 8848
content = "test_l_client_operation" + System.currentTimeMillis();
result = iconfig8.publishConfig(dataId, groupId, content);
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
String v2_7 = iconfig7.getConfig(dataId, groupId, 5000L);
String v2_8 = iconfig8.getConfig(dataId, groupId, 5000L);
String v2_9 = iconfig9.getConfig(dataId, groupId, 5000L);
Assert.assertEquals(content, v2_7);
Assert.assertEquals(content, v2_8);
Assert.assertEquals(content, v2_9);
assertEquals(content, v2_7);
assertEquals(content, v2_8);
assertEquals(content, v2_9);
// publish by 8849
content = "test_l_client_operation" + System.currentTimeMillis();
result = iconfig9.publishConfig(dataId, groupId, content);
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
String v3_7 = iconfig7.getConfig(dataId, groupId, 5000L);
String v3_8 = iconfig8.getConfig(dataId, groupId, 5000L);
String v3_9 = iconfig9.getConfig(dataId, groupId, 5000L);
Assert.assertEquals(content, v3_7);
Assert.assertEquals(content, v3_8);
Assert.assertEquals(content, v3_9);
assertEquals(content, v3_7);
assertEquals(content, v3_8);
assertEquals(content, v3_9);
// delete by 8849
result = iconfig9.removeConfig(dataId, groupId);
Assert.assertTrue(result);
assertTrue(result);
ThreadUtils.sleep(5000);
String v4_7 = iconfig7.getConfig(dataId, groupId, 5000L);
String v4_8 = iconfig8.getConfig(dataId, groupId, 5000L);
String v4_9 = iconfig9.getConfig(dataId, groupId, 5000L);
Assert.assertNull(v4_7);
Assert.assertNull(v4_8);
Assert.assertNull(v4_9);
assertNull(v4_7);
assertNull(v4_8);
assertNull(v4_9);
}
@Test
public void test_k_config_listener() throws Exception {
void test_k_config_listener() throws Exception {
String dataId = "test_h_config_listener";
String group = "test_h_config_listener";
String content = "test_h_config_listener";
@ -248,51 +249,50 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
ThreadUtils.sleep(10_000L);
latch[0].await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(content, r.get());
Assert.assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L));
assertEquals(content, r.get());
assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L));
content = content + System.currentTimeMillis();
iconfig7.publishConfig(dataId, group, content);
ThreadUtils.sleep(10_000L);
latch[1].await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(content, r.get());
Assert.assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L));
assertEquals(content, r.get());
assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L));
}
@Test
public void test_e_derby_ops() throws Exception {
void test_e_derby_ops() throws Exception {
String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby";
Query query = Query.newInstance().addParam("sql", "select * from users");
RestResult<List<Map<String, Object>>> result = NACOS_REST_TEMPLATE
.get(url, Header.EMPTY, query, new GenericType<RestResult<List<Map<String, Object>>>>() {
RestResult<List<Map<String, Object>>> result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query,
new GenericType<RestResult<List<Map<String, Object>>>>() {
}.getType());
System.out.println(result.getData());
Assert.assertTrue(result.ok());
assertTrue(result.ok());
List<Map<String, Object>> list = result.getData();
Assert.assertEquals(1, list.size());
Assert.assertEquals("nacos", list.get(0).get("USERNAME"));
assertEquals(1, list.size());
assertEquals("nacos", list.get(0).get("USERNAME"));
}
@Test
public void test_g_derby_ops_no_select() throws Exception {
void test_g_derby_ops_no_select() throws Exception {
String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby";
Query query = Query.newInstance().addParam("sql", "update users set username='nacos'");
RestResult<Object> result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, new GenericType<RestResult<Object>>() {
}.getType());
System.out.println(result);
Assert.assertFalse(result.ok());
Assert.assertEquals("Only query statements are allowed to be executed", result.getMessage());
assertFalse(result.ok());
assertEquals("Only query statements are allowed to be executed", result.getMessage());
}
@Test
public void test_h_derby_has_error() throws Exception {
void test_h_derby_has_error() throws Exception {
ThreadUtils.sleep(5000);
boolean result = iconfig7
.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7");
Assert.assertTrue(result);
boolean result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7");
assertTrue(result);
NotifyCenter.registerToPublisher(RaftDbErrorRecoverEvent.class, 8);
@ -312,7 +312,7 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
latch1.await(10_000L, TimeUnit.MILLISECONDS);
result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7");
Assert.assertFalse(result);
assertFalse(result);
CountDownLatch latch2 = new CountDownLatch(1);
NotifyCenter.registerSubscriber(new Subscriber<RaftDbErrorRecoverEvent>() {
@ -331,11 +331,11 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
latch2.await(10_000L, TimeUnit.MILLISECONDS);
result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7");
Assert.assertTrue(result);
assertTrue(result);
}
@Test
public void test_f_id_generator_leader_transfer() throws Exception {
void test_f_id_generator_leader_transfer() throws Exception {
ConfigurableApplicationContext context7 = applications.get("8847");
ConfigurableApplicationContext context8 = applications.get("8848");
ConfigurableApplicationContext context9 = applications.get("8849");
@ -367,13 +367,13 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9847");
RestResult<String> result = protocol7.execute(transfer);
System.out.println(result);
Assert.assertTrue(result.ok());
assertTrue(result.ok());
TimeUnit.SECONDS.sleep(2);
Assert.assertTrue(protocol7.isLeader(configGroup));
assertTrue(protocol7.isLeader(configGroup));
currentId = manager7.nextId(CONFIG_INFO_ID);
Assert.assertNotEquals(preId, currentId);
assertNotEquals(preId, currentId);
preId = currentId;
// transfer leader to ip:8808
@ -382,13 +382,13 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9848");
result = protocol8.execute(transfer);
System.out.println(result);
Assert.assertTrue(result.ok());
assertTrue(result.ok());
TimeUnit.SECONDS.sleep(2);
Assert.assertTrue(protocol8.isLeader(configGroup));
assertTrue(protocol8.isLeader(configGroup));
currentId = manager8.nextId(CONFIG_INFO_ID);
Assert.assertNotEquals(preId, currentId);
assertNotEquals(preId, currentId);
preId = currentId;
// transfer leader to ip:8809
@ -397,13 +397,13 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest {
transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9849");
result = protocol9.execute(transfer);
System.out.println(result);
Assert.assertTrue(result.ok());
assertTrue(result.ok());
TimeUnit.SECONDS.sleep(2);
Assert.assertTrue(protocol9.isLeader(configGroup));
assertTrue(protocol9.isLeader(configGroup));
currentId = manager9.nextId(CONFIG_INFO_ID);
Assert.assertNotEquals(preId, currentId);
assertNotEquals(preId, currentId);
}

View File

@ -48,16 +48,17 @@ import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.lang.reflect.Type;
@ -67,6 +68,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
/**
* CITCase for ConfigExportAndImportAPI.
@ -74,11 +80,11 @@ import java.util.Properties;
* @author klw
* @date 2019/5/23 15:26
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@SuppressWarnings({"checkstyle:TypeName", "checkstyle:AbbreviationAsWordInName"})
public class ConfigExportAndImportAPI_CITCase {
class ConfigExportAndImportAPI_CITCase {
private static final long TIME_OUT = 2000;
@ -93,23 +99,21 @@ public class ConfigExportAndImportAPI_CITCase {
private NacosRestTemplate nacosRestTemplate;
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(ConfigExportAndImportAPI_CITCase.class.getSimpleName());
}
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
nacosRestTemplate = ConfigHttpClientManager.getInstance().getNacosRestTemplate();
// register a handler to process byte[] result
nacosRestTemplate.registerResponseHandler(byte[].class.getName(), new AbstractResponseHandler() {
@Override
public HttpRestResult<byte[]> convertResult(HttpClientResponse response, Type responseType)
throws Exception {
return new HttpRestResult(response.getHeaders(), response.getStatusCode(),
IOUtils.toByteArray(response.getBody()), null);
public HttpRestResult<byte[]> convertResult(HttpClientResponse response, Type responseType) throws Exception {
return new HttpRestResult(response.getHeaders(), response.getStatusCode(), IOUtils.toByteArray(response.getBody()), null);
}
});
@ -126,88 +130,86 @@ public class ConfigExportAndImportAPI_CITCase {
prarm.put("content", "test: test");
prarm.put("desc", "testNoAppname1");
prarm.put("type", "yaml");
Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
prarm.put("dataId", "testNoAppname2.txt");
prarm.put("group", "TEST1_GROUP");
prarm.put("content", "test: test");
prarm.put("desc", "testNoAppname2");
prarm.put("type", "text");
Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
prarm.put("dataId", "testHasAppname1.properties");
prarm.put("group", "EXPORT_IMPORT_TEST_GROUP");
prarm.put("content", "test.test1.value=test");
prarm.put("desc", "testHasAppname1");
prarm.put("type", "properties");
prarm.put("appName", "testApp1");
Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm));
}
@After
public void cleanup() throws Exception {
HttpRestResult<String> result;
try {
@AfterEach
void cleanup() throws Exception {
Assertions.assertDoesNotThrow(() -> {
HttpRestResult<String> result;
Map<String, String> params = new HashMap<>();
params.put("dataId", "testNoAppname1.yml");
params.put("group", "EXPORT_IMPORT_TEST_GROUP");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "testNoAppname2.txt");
params.put("group", "TEST1_GROUP");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "testHasAppname1.properties");
params.put("group", "EXPORT_IMPORT_TEST_GROUP");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test1.yml");
params.put("group", "TEST_IMPORT");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test2.txt");
params.put("group", "TEST_IMPORT");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test3.properties");
params.put("group", "TEST_IMPORT");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test1");
params.put("group", "TEST_IMPORT2");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test3");
params.put("group", "TEST_IMPORT2");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
params.put("dataId", "test4");
params.put("group", "TEST_IMPORT2");
params.put("beta", "false");
result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT);
Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
} catch (Exception e) {
Assert.fail();
}
assertEquals(HttpURLConnection.HTTP_OK, result.getCode());
});
agent.shutdown();
}
@Test()
public void testExportByIds() {
@Test
void testExportByIds() {
String getDataUrl = "?search=accurate&dataId=&group=&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId=";
String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
JsonNode resultObj = JacksonUtils.toObj(queryResult);
@ -221,76 +223,79 @@ public class ConfigExportAndImportAPI_CITCase {
byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null);
ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData);
List<ZipUtils.ZipItem> zipItemList = unZiped.getZipItemList();
Assert.assertEquals(2, zipItemList.size());
assertEquals(2, zipItemList.size());
String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue();
String config2Name = config2.get("group").textValue() + "/" + config2.get("dataId").textValue();
for (ZipUtils.ZipItem zipItem : zipItemList) {
if (!(config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName()))) {
Assert.fail();
fail();
}
}
}
@Test(timeout = 3 * TIME_OUT)
public void testExportByGroup() {
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void testExportByGroup() {
String getDataUrl = "?search=accurate&dataId=&group=EXPORT_IMPORT_TEST_GROUP&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId=";
String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
JsonNode resultObj = JacksonUtils.toObj(queryResult);
JsonNode resultConfigs = resultObj.get("pageItems");
Assert.assertEquals(2, resultConfigs.size());
assertEquals(2, resultConfigs.size());
JsonNode config1 = resultConfigs.get(0);
JsonNode config2 = resultConfigs.get(1);
String exportByIdsUrl = "?export=true&tenant=&group=EXPORT_IMPORT_TEST_GROUP&appName=&ids=";
byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null);
ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData);
List<ZipUtils.ZipItem> zipItemList = unZiped.getZipItemList();
Assert.assertEquals(2, zipItemList.size());
assertEquals(2, zipItemList.size());
String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue();
String config2Name = config2.get("group").textValue() + "/" + config2.get("dataId").textValue();
for (ZipUtils.ZipItem zipItem : zipItemList) {
if (!(config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName()))) {
Assert.fail();
fail();
}
}
// verification metadata
Map<String, String> metaData = processMetaData(unZiped.getMetaDataItem());
String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties");
String appName = metaData.get(metaDataName);
Assert.assertNotNull(appName);
Assert.assertEquals("testApp1", appName);
assertNotNull(appName);
assertEquals("testApp1", appName);
}
@Test(timeout = 3 * TIME_OUT)
public void testExportByGroupAndApp() {
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void testExportByGroupAndApp() {
String getDataUrl = "?search=accurate&dataId=&group=EXPORT_IMPORT_TEST_GROUP&appName=testApp1&config_tags="
+ "&pageNo=1&pageSize=10&tenant=&namespaceId=";
String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
JsonNode resultObj = JacksonUtils.toObj(queryResult);
JsonNode resultConfigs = resultObj.get("pageItems");
Assert.assertEquals(1, resultConfigs.size());
assertEquals(1, resultConfigs.size());
JsonNode config1 = resultConfigs.get(0);
String exportByIdsUrl = "?export=true&tenant=&group=EXPORT_IMPORT_TEST_GROUP&appName=testApp1&ids=";
byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null);
ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData);
List<ZipUtils.ZipItem> zipItemList = unZiped.getZipItemList();
Assert.assertEquals(1, zipItemList.size());
assertEquals(1, zipItemList.size());
String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue();
for (ZipUtils.ZipItem zipItem : zipItemList) {
if (!config1Name.equals(zipItem.getItemName())) {
Assert.fail();
fail();
}
}
// verification metadata
Map<String, String> metaData = processMetaData(unZiped.getMetaDataItem());
String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties");
String appName = metaData.get(metaDataName);
Assert.assertNotNull(appName);
Assert.assertEquals("testApp1", appName);
assertNotNull(appName);
assertEquals("testApp1", appName);
}
@Test(timeout = 3 * TIME_OUT)
public void testExportAll() {
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void testExportAll() {
String exportByIdsUrl = "?export=true&tenant=&group=&appName=&ids=";
byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null);
ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData);
@ -300,22 +305,23 @@ public class ConfigExportAndImportAPI_CITCase {
String config3Name = "EXPORT_IMPORT_TEST_GROUP/testHasAppname1.properties";
int successCount = 0;
for (ZipUtils.ZipItem zipItem : zipItemList) {
if (config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName())
|| config3Name.equals(zipItem.getItemName())) {
if (config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName()) || config3Name.equals(
zipItem.getItemName())) {
successCount++;
}
}
Assert.assertEquals(3, successCount);
assertEquals(3, successCount);
// verification metadata
Map<String, String> metaData = processMetaData(unZiped.getMetaDataItem());
String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties");
String appName = metaData.get(metaDataName);
Assert.assertNotNull(appName);
Assert.assertEquals("testApp1", appName);
assertNotNull(appName);
assertEquals("testApp1", appName);
}
@Test(timeout = 3 * TIME_OUT)
public void testImport() {
@Test
@Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void testImport() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT/test1.yml", "test: test1"));
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT/test2.txt", "test: test1"));
@ -328,39 +334,39 @@ public class ConfigExportAndImportAPI_CITCase {
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm,
"testImport.zip", ZipUtils.zip(zipItemList));
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm, "testImport.zip",
ZipUtils.zip(zipItemList));
System.out.println("importResult: " + importResult);
// test unrecognizedData
JsonNode importResObj = JacksonUtils.toObj(importResult);
int unrecognizedCount = importResObj.get("data").get("unrecognizedCount").intValue();
Assert.assertEquals(1, unrecognizedCount);
assertEquals(1, unrecognizedCount);
JsonNode unrecognizedData = importResObj.get("data").get("unrecognizedData").get(0);
Assert.assertEquals("TEST_IMPORT/SUB_GROUP/test5.properties", unrecognizedData.get("itemName").textValue());
assertEquals("TEST_IMPORT/SUB_GROUP/test5.properties", unrecognizedData.get("itemName").textValue());
String getDataUrl = "?search=accurate&dataId=&group=TEST_IMPORT&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId=";
String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
JsonNode resultObj = JacksonUtils.toObj(queryResult);
JsonNode resultConfigs = resultObj.get("pageItems");
Assert.assertEquals(3, resultConfigs.size());
assertEquals(3, resultConfigs.size());
for (int i = 0; i < resultConfigs.size(); i++) {
JsonNode config = resultConfigs.get(i);
if (!"TEST_IMPORT".equals(config.get("group").textValue())) {
Assert.fail();
fail();
}
switch (config.get("dataId").textValue()) {
case "test1.yml":
Assert.assertEquals(config.get("appName").textValue(), "testApp1");
assertEquals("testApp1", config.get("appName").textValue());
break;
case "test2.txt":
Assert.assertEquals(config.get("appName").textValue(), "testApp2");
assertEquals("testApp2", config.get("appName").textValue());
break;
case "test3.properties":
Assert.assertEquals(config.get("appName").textValue(), "testApp3");
assertEquals("testApp3", config.get("appName").textValue());
break;
default:
Assert.fail();
fail();
}
}
@ -368,9 +374,9 @@ public class ConfigExportAndImportAPI_CITCase {
queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
resultObj = JacksonUtils.toObj(queryResult);
resultConfigs = resultObj.get("pageItems");
Assert.assertEquals(1, resultConfigs.size());
assertEquals(1, resultConfigs.size());
JsonNode jsonNode = resultConfigs.get(0);
Assert.assertEquals(jsonNode.get("appName").textValue(), "testApp4");
assertEquals("testApp4", jsonNode.get("appName").textValue());
}
private Map<String, String> processMetaData(ZipUtils.ZipItem metaDataZipItem) {
@ -380,7 +386,7 @@ public class ConfigExportAndImportAPI_CITCase {
String[] metaDataArr = metaDataStr.split("\r\n");
for (String metaDataItem : metaDataArr) {
String[] metaDataItemArr = metaDataItem.split("=");
Assert.assertEquals(2, metaDataItemArr.length);
assertEquals(2, metaDataItemArr.length);
metaDataMap.put(metaDataItemArr[0], metaDataItemArr[1]);
}
}
@ -390,17 +396,15 @@ public class ConfigExportAndImportAPI_CITCase {
private String packageMetaName(String group, String dataId) {
String tempDataId = dataId;
if (tempDataId.contains(".")) {
tempDataId = tempDataId.substring(0, tempDataId.lastIndexOf(".")) + "~" + tempDataId.substring(
tempDataId.lastIndexOf(".") + 1);
tempDataId = tempDataId.substring(0, tempDataId.lastIndexOf(".")) + "~" + tempDataId.substring(tempDataId.lastIndexOf(".") + 1);
}
return group + "." + tempDataId + ".app";
}
@Test
public void testExportV2() {
void testExportV2() {
String dataId = "testNoAppname2.txt";
String getDataUrl =
"?search=accurate&group=TEST1_GROUP&pageNo=1&pageSize=10&tenant=&namespaceId=&dataId=" + dataId;
String getDataUrl = "?search=accurate&group=TEST1_GROUP&pageNo=1&pageSize=10&tenant=&namespaceId=&dataId=" + dataId;
String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null);
JsonNode resultObj = JacksonUtils.toObj(queryResult);
JsonNode resultConfigs = resultObj.get("pageItems");
@ -410,139 +414,137 @@ public class ConfigExportAndImportAPI_CITCase {
byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null);
ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData);
List<ZipUtils.ZipItem> zipItemList = unZiped.getZipItemList();
Assert.assertEquals(1, zipItemList.size());
assertEquals(1, zipItemList.size());
String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue();
for (ZipUtils.ZipItem zipItem : zipItemList) {
if (!(config1Name.equals(zipItem.getItemName()))) {
Assert.fail();
fail();
}
}
Assert.assertEquals(dataId, config1.get("dataId").asText());
assertEquals(dataId, config1.get("dataId").asText());
String group = config1.get("group").asText();
String queryConfigDetailResult = httpGetString(
serverAddr + CONFIG_CONTROLLER_PATH + "?show=all&dataId=" + dataId + "&group=" + group, null);
JsonNode configDetailResult = JacksonUtils.toObj(queryConfigDetailResult);
Assert.assertNotNull(configDetailResult);
assertNotNull(configDetailResult);
// verification metadata
ZipUtils.ZipItem metaDataItem = unZiped.getMetaDataItem();
Assert.assertNotNull(metaDataItem);
assertNotNull(metaDataItem);
String metaDataItemItemData = metaDataItem.getItemData();
ConfigMetadata configMetadata = YamlParserUtil.loadObject(metaDataItemItemData, ConfigMetadata.class);
Assert.assertNotNull(configMetadata);
Assert.assertEquals(configMetadata.getMetadata().size(), 1);
assertNotNull(configMetadata);
assertEquals(1, configMetadata.getMetadata().size());
ConfigMetadata.ConfigExportItem config1Metadata = new ConfigMetadata.ConfigExportItem();
config1Metadata.setDataId(dataId);
config1Metadata.setGroup(group);
config1Metadata.setType(configDetailResult.get("type").asText());
config1Metadata.setAppName(
configDetailResult.get("appName") == null ? null : configDetailResult.get("appName").asText());
config1Metadata.setDesc(
configDetailResult.get("desc") == null ? null : configDetailResult.get("desc").asText());
config1Metadata.setAppName(configDetailResult.get("appName") == null ? null : configDetailResult.get("appName").asText());
config1Metadata.setDesc(configDetailResult.get("desc") == null ? null : configDetailResult.get("desc").asText());
ConfigMetadata.ConfigExportItem configExportItem1 = configMetadata.getMetadata().get(0);
Assert.assertEquals(configExportItem1, config1Metadata);
assertEquals(configExportItem1, config1Metadata);
}
@Test
public void testImportV2() {
void testImportV2() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test1", "test: test1"));
String metaDataStr = "metadata:\n" + "- appName: testAppName\n" + " dataId: test1\n" + " desc: testDesc\n"
+ " group: TEST_IMPORT2\n" + " type: yaml";
zipItemList.add(new ZipUtils.ZipItem(Constants.CONFIG_EXPORT_METADATA_NEW, metaDataStr));
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm,
"testImport.zip", ZipUtils.zip(zipItemList));
JsonNode importResObj = JacksonUtils.toObj(importResult);
Assert.assertEquals(importResObj.get("data").get("succCount").asInt(), 1);
String queryConfigDetailResult = httpGetString(
serverAddr + CONFIG_CONTROLLER_PATH + "?show=all&dataId=test1&group=TEST_IMPORT2", null);
JsonNode configDetailResult = JacksonUtils.toObj(queryConfigDetailResult);
Assert.assertNotNull(configDetailResult);
Assert.assertEquals(configDetailResult.get("dataId").asText(), "test1");
Assert.assertEquals(configDetailResult.get("group").asText(), "TEST_IMPORT2");
Assert.assertEquals(configDetailResult.get("type").asText(), "yaml");
Assert.assertEquals(configDetailResult.get("appName").asText(), "testAppName");
Assert.assertEquals(configDetailResult.get("desc").asText(), "testDesc");
}
@Test
public void testImportV2MetadataError() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test2", "test: test2"));
String metaDataStr =
"metadata:\n" + "- appName: testAppName\n" + " desc: test desc\n" + " group: TEST_IMPORT\n"
"metadata:\n" + "- appName: testAppName\n" + " dataId: test1\n" + " desc: testDesc\n" + " group: TEST_IMPORT2\n"
+ " type: yaml";
zipItemList.add(new ZipUtils.ZipItem(Constants.CONFIG_EXPORT_METADATA_NEW, metaDataStr));
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm,
"testImport.zip", ZipUtils.zip(zipItemList));
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm, "testImport.zip",
ZipUtils.zip(zipItemList));
JsonNode importResObj = JacksonUtils.toObj(importResult);
Assert.assertEquals(importResObj.get("code").intValue(), ResultCodeEnum.METADATA_ILLEGAL.getCode());
Assert.assertEquals(importResObj.get("message").textValue(), ResultCodeEnum.METADATA_ILLEGAL.getCodeMsg());
assertEquals(1, importResObj.get("data").get("succCount").asInt());
String queryConfigDetailResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + "?show=all&dataId=test1&group=TEST_IMPORT2",
null);
JsonNode configDetailResult = JacksonUtils.toObj(queryConfigDetailResult);
assertNotNull(configDetailResult);
assertEquals("test1", configDetailResult.get("dataId").asText());
assertEquals("TEST_IMPORT2", configDetailResult.get("group").asText());
assertEquals("yaml", configDetailResult.get("type").asText());
assertEquals("testAppName", configDetailResult.get("appName").asText());
assertEquals("testDesc", configDetailResult.get("desc").asText());
}
@Test
public void testImportV2MetadataNotFind() {
void testImportV2MetadataError() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test3.yml", "test: test3"));
String metaDataStr = "metadata:\n" + "- dataId: notExist\n" + " group: TEST_IMPORT2\n" + " type: yaml\n"
+ "- dataId: test3.yml\n" + " group: TEST_IMPORT2\n" + " type: yaml";
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test2", "test: test2"));
String metaDataStr = "metadata:\n" + "- appName: testAppName\n" + " desc: test desc\n" + " group: TEST_IMPORT\n" + " type: yaml";
zipItemList.add(new ZipUtils.ZipItem(Constants.CONFIG_EXPORT_METADATA_NEW, metaDataStr));
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm,
"testImport.zip", ZipUtils.zip(zipItemList));
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm, "testImport.zip",
ZipUtils.zip(zipItemList));
JsonNode importResObj = JacksonUtils.toObj(importResult);
JsonNode data = importResObj.get("data");
Assert.assertEquals(1, data.get("succCount").intValue());
// test unrecognizedData
int unrecognizedCount = data.get("unrecognizedCount").intValue();
Assert.assertEquals(1, unrecognizedCount);
JsonNode unrecognizedData = data.get("unrecognizedData").get(0);
Assert.assertEquals("未在文件中找到: TEST_IMPORT2/notExist", unrecognizedData.get("itemName").textValue());
assertEquals(importResObj.get("code").intValue(), ResultCodeEnum.METADATA_ILLEGAL.getCode());
assertEquals(importResObj.get("message").textValue(), ResultCodeEnum.METADATA_ILLEGAL.getCodeMsg());
}
@Test
public void testImportV2ConfigIgnore() {
void testImportV2MetadataNotFind() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test4", "test: test4"));
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/ignore.yml", "test: test4"));
String metaDataStr = "metadata:\n" + "- appName: testAppName\n" + " dataId: test4\n" + " desc: testDesc\n"
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test3.yml", "test: test3"));
String metaDataStr = "metadata:\n" + "- dataId: notExist\n" + " group: TEST_IMPORT2\n" + " type: yaml\n" + "- dataId: test3.yml\n"
+ " group: TEST_IMPORT2\n" + " type: yaml";
zipItemList.add(new ZipUtils.ZipItem(Constants.CONFIG_EXPORT_METADATA_NEW, metaDataStr));
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm,
"testImport.zip", ZipUtils.zip(zipItemList));
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm, "testImport.zip",
ZipUtils.zip(zipItemList));
JsonNode importResObj = JacksonUtils.toObj(importResult);
JsonNode data = importResObj.get("data");
Assert.assertEquals(1, data.get("succCount").intValue());
assertEquals(1, data.get("succCount").intValue());
// test unrecognizedData
int unrecognizedCount = data.get("unrecognizedCount").intValue();
Assert.assertEquals(1, unrecognizedCount);
assertEquals(1, unrecognizedCount);
JsonNode unrecognizedData = data.get("unrecognizedData").get(0);
Assert.assertEquals("未在元数据中找到: TEST_IMPORT2/ignore.yml", unrecognizedData.get("itemName").textValue());
assertEquals("未在文件中找到: TEST_IMPORT2/notExist", unrecognizedData.get("itemName").textValue());
}
@Test
void testImportV2ConfigIgnore() {
List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(3);
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test4", "test: test4"));
zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/ignore.yml", "test: test4"));
String metaDataStr =
"metadata:\n" + "- appName: testAppName\n" + " dataId: test4\n" + " desc: testDesc\n" + " group: TEST_IMPORT2\n"
+ " type: yaml";
zipItemList.add(new ZipUtils.ZipItem(Constants.CONFIG_EXPORT_METADATA_NEW, metaDataStr));
final String importUrl = "?import=true&namespace=";
Map<String, String> importPrarm = new HashMap<>(1);
importPrarm.put("policy", "OVERWRITE");
String importResult = uploadZipFile(serverAddr + CONFIG_CONTROLLER_PATH + importUrl, importPrarm, "testImport.zip",
ZipUtils.zip(zipItemList));
JsonNode importResObj = JacksonUtils.toObj(importResult);
JsonNode data = importResObj.get("data");
assertEquals(1, data.get("succCount").intValue());
// test unrecognizedData
int unrecognizedCount = data.get("unrecognizedCount").intValue();
assertEquals(1, unrecognizedCount);
JsonNode unrecognizedData = data.get("unrecognizedData").get(0);
assertEquals("未在元数据中找到: TEST_IMPORT2/ignore.yml", unrecognizedData.get("itemName").textValue());
}
private String httpGetString(String url, Map<String, String> param) {
@ -585,8 +587,7 @@ public class ConfigExportAndImportAPI_CITCase {
int connectTimeout = 10000;
int socketTimeout = 10000;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.config;
import com.alibaba.nacos.Nacos;
@ -25,40 +26,43 @@ import com.alibaba.nacos.api.config.PropertyChangeType;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigLongPollReturnChanges_CITCase {
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ConfigLongPollReturnChanges_CITCase {
@LocalServerPort
private int port;
private ConfigService configService;
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPollReturnChanges_CITCase.class.getSimpleName());
}
@Before
public void init() throws NacosException {
@BeforeEach
void init() throws NacosException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "20000");
@ -66,31 +70,31 @@ public class ConfigLongPollReturnChanges_CITCase {
properties.put(PropertyKeyConst.MAX_RETRY, "5");
configService = NacosFactory.createConfigService(properties);
}
@After
public void destroy(){
@AfterEach
void destroy() {
try {
configService.shutDown();
}catch (NacosException ex) {
} catch (NacosException ex) {
}
}
@Test
public void testAdd() throws InterruptedException, NacosException {
void testAdd() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String content = "config data";
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
Assert.assertNull(cci.getOldValue());
Assert.assertEquals(content, cci.getNewValue());
Assert.assertEquals(PropertyChangeType.ADDED, cci.getType());
assertNull(cci.getOldValue());
assertEquals(content, cci.getNewValue());
assertEquals(PropertyChangeType.ADDED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
@ -98,75 +102,75 @@ public class ConfigLongPollReturnChanges_CITCase {
}
});
boolean result = configService.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
configService.getConfig(dataId, group, 50);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
@Test
public void testModify() throws InterruptedException, NacosException {
void testModify() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String oldData = "old data";
final String newData = "new data";
boolean result = configService.publishConfig(dataId, group, oldData);
Assert.assertTrue(result);
assertTrue(result);
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
Assert.assertEquals(oldData, cci.getOldValue());
Assert.assertEquals(newData, cci.getNewValue());
Assert.assertEquals(PropertyChangeType.MODIFIED, cci.getType());
assertEquals(oldData, cci.getOldValue());
assertEquals(newData, cci.getNewValue());
assertEquals(PropertyChangeType.MODIFIED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
}
}
});
configService.publishConfig(dataId, group, newData);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
@Test
public void testDelete() throws InterruptedException, NacosException {
void testDelete() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String oldData = "old data";
boolean result = configService.publishConfig(dataId, group, oldData);
Assert.assertTrue(result);
assertTrue(result);
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
Assert.assertEquals(oldData, cci.getOldValue());
Assert.assertNull(cci.getNewValue());
Assert.assertEquals(PropertyChangeType.DELETED, cci.getType());
assertEquals(oldData, cci.getOldValue());
assertNull(cci.getNewValue());
assertEquals(PropertyChangeType.DELETED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
}
}
});
configService.removeConfig(dataId, group);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
}

View File

@ -23,15 +23,15 @@ import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.Properties;
import java.util.concurrent.Executor;
@ -41,26 +41,26 @@ import java.util.concurrent.TimeUnit;
* @author liaochuntao
* @date 2019-06-07 22:24
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigLongPoll_CITCase {
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ConfigLongPoll_CITCase {
@LocalServerPort
private int port;
private ConfigService configService;
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPoll_CITCase.class.getSimpleName());
}
@Before
public void init() throws NacosException {
@BeforeEach
void init() throws NacosException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "20000");
@ -68,44 +68,44 @@ public class ConfigLongPoll_CITCase {
properties.put(PropertyKeyConst.MAX_RETRY, "5");
configService = NacosFactory.createConfigService(properties);
}
@After
public void destroy(){
@AfterEach
void destroy() {
try {
configService.shutDown();
}catch (NacosException ex) {
} catch (NacosException ex) {
}
}
@Test
public void test() throws InterruptedException, NacosException {
void test() throws InterruptedException, NacosException {
configService.addListener("test", "DEFAULT_GROUP", new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println(configInfo);
}
});
configService.addListener("test-1", "DEFAULT_GROUP", new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println(configInfo);
}
});
TimeUnit.SECONDS.sleep(10);
}
}

View File

@ -19,30 +19,31 @@ package com.alibaba.nacos.test.config;
import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder;
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class EmbeddedStorageContextUtils_CITCase {
class EmbeddedStorageContextUtils_CITCase {
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(EmbeddedStorageContextUtils_CITCase.class.getSimpleName());
}
@Test
public void test_multi_thread_sql_contexts() throws Exception {
void test_multi_thread_sql_contexts() throws Exception {
CountDownLatch latch = new CountDownLatch(3);
ExecutorService service = Executors.newFixedThreadPool(3);
@ -55,8 +56,8 @@ public class EmbeddedStorageContextUtils_CITCase {
List<ModifyRequest> list = EmbeddedStorageContextHolder.getCurrentSqlContext();
System.out.println(list);
Assert.assertEquals("test_" + j, list.get(0).getSql());
Assert.assertEquals("test_" + j * 10, list.get(0).getSql());
assertEquals("test_" + j, list.get(0).getSql());
assertEquals("test_" + j * 10, list.get(0).getSql());
} finally {
latch.countDown();
}

View File

@ -24,15 +24,15 @@ import com.alibaba.nacos.client.config.NacosConfigService;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.util.Properties;
@ -41,34 +41,35 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* use configPublishRequest for communication verification between client and server.
*
* @author githubcheng2978.
*/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC
+ ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ExtendWith(SpringExtension.class)
@TestMethodOrder(MethodName.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=true", RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NacosConfigServiceComTlsGrpcClient_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceComTlsGrpcClient_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
public void test_e_TlsServerAndPlainClient() throws Exception {
void test_e_TlsServerAndPlainClient() throws Exception {
Properties propertiesfalse = new Properties();
propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "false");
propertiesfalse.put("serverAddr", "127.0.0.1");
@ -90,6 +91,6 @@ public class NacosConfigServiceComTlsGrpcClient_CITCase {
}
});
latch2.await(5, TimeUnit.SECONDS);
Assert.assertTrue(res);
assertTrue(res);
}
}

View File

@ -24,14 +24,13 @@ import com.alibaba.nacos.client.config.NacosConfigService;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import com.alibaba.nacos.test.base.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.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.util.Properties;
@ -40,34 +39,36 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* use configPublishRequest for communication verification between client and server.
*
* @author githubcheng2978.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC
+ ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NacosConfigServiceNoComTlsGrpcClient_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceNoComTlsGrpcClient_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
@Ignore("TODO, Fix cert expired problem")
public void test_e_TlsServerAndTlsClient() throws Exception {
@Disabled("TODO, Fix cert expired problem")
void test_e_TlsServerAndTlsClient() throws Exception {
Properties properties = new Properties();
properties.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
properties.put(RpcConstants.RPC_CLIENT_TLS_PROVIDER, "openssl");
@ -77,8 +78,8 @@ public class NacosConfigServiceNoComTlsGrpcClient_CITCase {
String content = UUID.randomUUID().toString();
String dataId = "test-group" + increment.getAndIncrement();
String groupId = "test-data" + increment.getAndIncrement();
boolean b = configService.publishConfig("test-group" + increment.getAndIncrement(),
"test-data" + increment.getAndIncrement(), content);
boolean b = configService.publishConfig("test-group" + increment.getAndIncrement(), "test-data" + increment.getAndIncrement(),
content);
CountDownLatch latch = new CountDownLatch(1);
configService.addListener(dataId, groupId, new AbstractConfigChangeListener() {
@Override
@ -92,11 +93,11 @@ public class NacosConfigServiceNoComTlsGrpcClient_CITCase {
}
});
latch.await(5, TimeUnit.SECONDS);
Assert.assertTrue(b);
assertTrue(b);
}
@Test
public void test_e_TlsServerAndPlainClient() throws Exception {
void test_e_TlsServerAndPlainClient() throws Exception {
Properties propertiesfalse = new Properties();
propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "false");
propertiesfalse.put("serverAddr", "127.0.0.1");
@ -118,6 +119,6 @@ public class NacosConfigServiceNoComTlsGrpcClient_CITCase {
}
});
latch2.await(5, TimeUnit.SECONDS);
Assert.assertFalse(res);
assertFalse(res);
}
}

View File

@ -24,14 +24,13 @@ import com.alibaba.nacos.client.config.NacosConfigService;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import com.alibaba.nacos.test.base.ConfigCleanUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.util.Properties;
@ -40,15 +39,17 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* use configPublishRequest for communication verification between client and server.
*
* @author githubcheng2978.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC
+ ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ -57,20 +58,20 @@ public class NacosConfigV2MutualAuth_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigV2MutualAuth_CITCase.class.getSimpleName());
}
@After
public void cleanClientCache() throws Exception {
@AfterEach
void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
@Ignore("TODO, Fix cert expired problem")
public void test_d_MutualAuth() throws Exception {
@Disabled("TODO, Fix cert expired problem")
void test_d_MutualAuth() throws Exception {
Properties propertiesfalse = new Properties();
propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
propertiesfalse.put(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
@ -96,11 +97,11 @@ public class NacosConfigV2MutualAuth_CITCase {
}
});
latch2.await(5, TimeUnit.SECONDS);
Assert.assertTrue(res);
assertTrue(res);
}
@Test
public void test_d_MutualAuthButClientNot() throws Exception {
void test_d_MutualAuthButClientNot() throws Exception {
Properties propertiesfalse = new Properties();
propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
@ -125,6 +126,6 @@ public class NacosConfigV2MutualAuth_CITCase {
}
});
latch2.await(5, TimeUnit.SECONDS);
Assert.assertFalse(res);
assertFalse(res);
}
}

View File

@ -25,16 +25,17 @@ 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);
@ -44,7 +45,7 @@ public class TextChangeParser implements ConfigChangeParser {
cci.setType(PropertyChangeType.DELETED);
}
map.put(key, cci);
return map;
}
}

View File

@ -29,6 +29,13 @@
<artifactId>core-test</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>

View File

@ -28,7 +28,6 @@ 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;
@ -44,14 +43,13 @@ 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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.annotation.Resource;
import java.lang.reflect.Field;
@ -62,11 +60,15 @@ import java.util.Map;
import java.util.Properties;
import java.util.UUID;
@RunWith(SpringRunner.class)
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@SuppressWarnings("all")
public class AbilityDiscovery {
class AbilityDiscovery {
@LocalServerPort
private int port;
@ -81,9 +83,9 @@ public class AbilityDiscovery {
private ConnectionManager connectionManager;
private RpcClient client;
private RpcClient clusterClient;
private ConfigService configService;
private AbstractAbilityControlManager oldInstance;
@ -94,27 +96,26 @@ public class AbilityDiscovery {
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 {
@BeforeEach
void setup() throws NoSuchFieldException, IllegalAccessException, NacosException {
// load class
oldInstance = NacosAbilityManagerHolder.getInstance();
// replace
abstractAbilityControlManager = NacosAbilityManagerHolder.class
.getDeclaredField("abstractAbilityControlManager");
abstractAbilityControlManager = NacosAbilityManagerHolder.class.getDeclaredField("abstractAbilityControlManager");
abstractAbilityControlManager.setAccessible(true);
abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, new TestServerAbilityControlManager());
@ -130,15 +131,15 @@ public class AbilityDiscovery {
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() {
@ -146,12 +147,12 @@ public class AbilityDiscovery {
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);
@ -159,19 +160,19 @@ public class AbilityDiscovery {
});
// 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);
@ -182,16 +183,15 @@ public class AbilityDiscovery {
}
@Test
public void testClientDiscovery() throws NacosException {
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);
assertEquals(AbilityStatus.SUPPORTED, client.getConnectionAbility(AbilityKey.SERVER_TEST_1));
assertEquals(AbilityStatus.NOT_SUPPORTED, client.getConnectionAbility(AbilityKey.SERVER_TEST_2));
}
@Test
public void testServerDiscoveryAndJudge() throws Exception {
Map<String, RequestHandler> handlers = (Map<String, RequestHandler>) registryHandlerFields
.get(requestHandlerRegistry);
void testServerDiscoveryAndJudge() throws Exception {
Map<String, RequestHandler> handlers = (Map<String, RequestHandler>) registryHandlerFields.get(requestHandlerRegistry);
// set handler
RequestHandler oldRequestHandler = handlers.remove(ConfigQueryRequest.class.getSimpleName());
@ -199,28 +199,29 @@ public class AbilityDiscovery {
configService.getConfig("test", "DEFAULT_GROUP", 2000);
// wait server invoke
Thread.sleep(3000);
Assert.assertTrue(serverSuccess);
assertTrue(serverSuccess);
// recover
handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler);
}
@Test
public void testClientJudge() throws Exception {
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)) {
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(){};
return new Response() {
};
}
});
// get id
Connection conn = (Connection) currentConnField.get(client);
@ -233,40 +234,39 @@ public class AbilityDiscovery {
// wait client react
Thread.sleep(4000);
Assert.assertTrue(clientSuccess);
assertTrue(clientSuccess);
}
@Test
public void testClusterClient() throws IllegalAccessException, NacosException, InterruptedException, NoSuchFieldException {
Map<String, RequestHandler> handlers = (Map<String, RequestHandler>) registryHandlerFields
.get(requestHandlerRegistry);
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);
assertTrue(clusterSuccess);
// recover
handlers.remove(ConfigQueryRequest.class.getSimpleName());
handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler);
}
@Test
public void testNegotiationTimeout() throws Exception {
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);
assertNull(connection);
// recovery
setupRequestHandlerField.set(client, origin);
}
@After
public void recover() throws IllegalAccessException, NacosException {
@AfterEach
void recover() throws IllegalAccessException, NacosException {
abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, oldInstance);
client.shutdown();
}
@ -290,18 +290,18 @@ public class AbilityDiscovery {
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)) {

View File

@ -24,7 +24,7 @@ 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<>();
@ -32,11 +32,11 @@ public class TestServerAbilityControlManager extends ServerAbilityControlManager
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);

View File

@ -13,6 +13,7 @@
* 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;
@ -33,35 +34,31 @@ import java.net.URL;
* @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);
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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -13,6 +13,7 @@
* 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;
@ -22,20 +23,20 @@ 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

@ -25,16 +25,17 @@ 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);
@ -44,7 +45,7 @@ public class TextChangeParser implements ConfigChangeParser {
cci.setType(PropertyChangeType.DELETED);
}
map.put(key, cci);
return map;
}
}

View File

@ -26,16 +26,13 @@ import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.common.remote.client.RpcConstants;
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.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
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;
@ -43,19 +40,20 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 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",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC
+ ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Ignore("TODO, Fix cert expired problem")
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Disabled("TODO, Fix cert expired problem")
public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@ -63,20 +61,19 @@ public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
@LocalServerPort
private int port;
@BeforeClass
public static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(
ConfigIntegrationV1ServerNonCompatibility_CITCase.class.getSimpleName());
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV1ServerNonCompatibility_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
public void test_a_TlsServer() throws Exception {
void test_a_TlsServer() throws Exception {
RpcClient client = RpcClientFactory.createClient("testTlsServer", ConnectionType.GRPC,
Collections.singletonMap("labelKey", "labelValue"), null);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
@ -84,11 +81,11 @@ public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
Assert.assertNull(connection);
assertNull(connection);
}
@Test
public void test_b_ServerTlsTrustAll() throws Exception {
void test_b_ServerTlsTrustAll() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustAll(true);
@ -106,12 +103,12 @@ public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
Response response = connectionTrustCa.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(response.isSuccess());
assertTrue(response.isSuccess());
connectionTrustCa.close();
}
@Test
public void test_c_ServerTlsTrustCa() throws Exception {
void test_c_ServerTlsTrustCa() throws Exception {
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
@ -130,7 +127,7 @@ public class ConfigIntegrationV1ServerNonCompatibility_CITCase {
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());
assertTrue(responseCa.isSuccess());
connectionTrustCa.close();
}
}

View File

@ -27,15 +27,12 @@ import com.alibaba.nacos.common.remote.client.RpcClientFactory;
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import com.alibaba.nacos.test.ConfigCleanUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
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;
@ -43,40 +40,40 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* use configPublishRequest for communication verification between client and server.
*
* @author githubcheng2978
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true",
RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem",
RpcConstants.NACOS_SERVER_RPC + ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC
+ ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigIntegrationV2MutualAuth_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@LocalServerPort
private int port;
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV2MutualAuth_CITCase.class.getSimpleName());
}
@After
public void cleanClientCache() throws Exception {
@AfterEach
void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
@Ignore("TODO, fix the cert expired problem")
public void test_d_MutualAuth() throws Exception {
@Disabled("TODO, fix the cert expired problem")
void test_d_MutualAuth() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
@ -101,12 +98,12 @@ public class ConfigIntegrationV2MutualAuth_CITCase {
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
configPublishRequest.setRequestId(content);
Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(5));
Assert.assertTrue(response.isSuccess());
assertTrue(response.isSuccess());
connection.close();
}
@Test
public void test_e_ServerMutualAuthOnly() throws Exception {
void test_e_ServerMutualAuthOnly() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
@ -118,7 +115,7 @@ public class ConfigIntegrationV2MutualAuth_CITCase {
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
Assert.assertNull(connection);
assertNull(connection);
TimeUnit.SECONDS.sleep(3);
}
}

View File

@ -28,15 +28,12 @@ import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import com.alibaba.nacos.sys.env.EnvUtil;
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.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
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;
@ -44,36 +41,38 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* use configPublishRequest for communication verification between client and server
*
* @author githubcheng2978
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
//todo fix this test case
//ConfigIntegrationV3_CITCase and ConfigIntegrationV2MutualAuth_CITCase will fail when run together
@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigIntegrationV3_CITCase {
public static AtomicInteger increment = new AtomicInteger(100);
@LocalServerPort
private int port;
public static AtomicInteger increment = new AtomicInteger(100);
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV3_CITCase.class.getSimpleName());
}
@BeforeClass
@AfterClass
public static void cleanClientCache() throws Exception {
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
public void test_e_TlsServerAndPlainClient() throws Exception {
void test_e_TlsServerAndPlainClient() throws Exception {
RpcClient client = RpcClientFactory.createClient("testTlsServerAndPlainClient", ConnectionType.GRPC,
Collections.singletonMap("labelKey", "labelValue"), null);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
@ -89,12 +88,12 @@ public class ConfigIntegrationV3_CITCase {
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
configPublishRequest.setRequestId(content);
Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
Assert.assertTrue(response.isSuccess());
assertTrue(response.isSuccess());
connection.close();
}
@Test
public void test_f_ServerTlsTrustAll() throws Exception {
void test_f_ServerTlsTrustAll() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustAll(true);
@ -110,14 +109,14 @@ public class ConfigIntegrationV3_CITCase {
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());
assertTrue(response.isSuccess());
connectionTrustAll.close();
}
@Disabled("TODO, Fix cert expired problem")
@Test
@Ignore("TODO, Fix cert expired problem")
public void test_g_ServerTlsTrustCa() throws Exception {
void test_g_ServerTlsTrustCa() throws Exception {
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
@ -136,7 +135,7 @@ public class ConfigIntegrationV3_CITCase {
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());
assertTrue(responseCa.isSuccess());
connectionTrustCa.close();
}
}

View File

@ -17,46 +17,48 @@
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.config.server.enums.FileTypeEnum;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author by jiangmin.wu on 2020/12/30
*/
public class FileTypeEnum_ITCase {
class FileTypeEnum_ITCase {
@Test
public void fileTypeEnum_test1() {
void fileTypeEnum_test1() {
for (FileTypeEnum value : FileTypeEnum.values()) {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.name());
Assert.assertEquals(fileTypeEnum, value);
assertEquals(fileTypeEnum, value);
}
}
@Test
public void fileTypeEnum_test2() {
void fileTypeEnum_test2() {
for (FileTypeEnum value : FileTypeEnum.values()) {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.getFileType());
Assert.assertNotNull(fileTypeEnum);
assertNotNull(fileTypeEnum);
}
}
@Test
public void fileTypeEnum_test3() {
void fileTypeEnum_test3() {
FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("t");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
assertEquals(FileTypeEnum.TEXT, fileTypeEnum);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
assertEquals(FileTypeEnum.TEXT, fileTypeEnum);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(".");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
assertEquals(FileTypeEnum.TEXT, fileTypeEnum);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("1");
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
assertEquals(FileTypeEnum.TEXT, fileTypeEnum);
fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(null);
Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT);
assertEquals(FileTypeEnum.TEXT, fileTypeEnum);
}
}

View File

@ -28,59 +28,149 @@ 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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* NacosAsyncRestTemplate_ITCase.
*
* @author mai.jh
*/
@SuppressWarnings("all")
@FixMethodOrder(MethodSorters.JVM)
@RunWith(SpringRunner.class)
@TestMethodOrder(MethodName.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NacosAsyncRestTemplate_ITCase {
class NacosAsyncRestTemplate_ITCase {
private static final HttpClientFactory PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY = new ProcessorHttpClientFactory();
private final String CONFIG_INSTANCE_PATH = "/nacos/v1/ns";
@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 nacosRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(
LoggerFactory.getLogger(NacosAsyncRestTemplate_ITCase.class));
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 {
@BeforeEach
void init() throws NacosException {
IP = String.format("http://localhost:%d", port);
EnvUtil.setEnvironment((ConfigurableEnvironment) environment);
processorRestTemplate = HttpClientBeanHolder
.getNacosAsyncRestTemplate(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY);
processorRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY);
}
@Test
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());
assertTrue(restResult.ok());
}
@Test
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());
assertTrue(restResult.ok());
}
@Test
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());
assertTrue(restResult.ok());
}
@Test
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());
assertTrue(restResult.ok());
assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name"));
}
@Test
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());
assertTrue(restResult.ok());
assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name"));
}
@Test
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());
assertTrue(restResult.ok());
}
private class CallbackMap<T> implements Callback<T> {
@ -98,7 +188,7 @@ public class NacosAsyncRestTemplate_ITCase {
public void onError(Throwable throwable) {
this.throwable = throwable;
}
@Override
public void onCancel() {
@ -113,96 +203,4 @@ public class NacosAsyncRestTemplate_ITCase {
}
}
@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

@ -26,132 +26,129 @@ 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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* NacosRestTemplate_ITCase.
*
* @author mai.jh
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.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));
@TestMethodOrder(MethodName.class)
class NacosRestTemplate_ITCase {
private final String INSTANCE_PATH = "/nacos/v1/ns";
private final String CONFIG_PATH = "/nacos/v1/cs";
@LocalServerPort
private int port;
private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder.getNacosRestTemplate(
LoggerFactory.getLogger(NacosRestTemplate_ITCase.class));
private String IP = null;
@Before
public void init() throws NacosException {
@BeforeEach
void init() throws NacosException {
IP = String.format("http://localhost:%d", port);
}
@Test
public void test_url_post_config() throws Exception {
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());
HttpRestResult<String> restResult = nacosRestTemplate.postForm(url, Header.newInstance(), param, String.class);
assertTrue(restResult.ok());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
@Test
public void test_url_get_return_restResult() throws Exception {
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>>() {
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());
assertTrue(restResult.ok());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
@Test
public void test_url_post_form() throws Exception {
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());
HttpRestResult<String> restResult = nacosRestTemplate.postForm(url, Header.newInstance(), param, String.class);
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 {
@Disabled("new version can't update instance when service and instance is not exist")
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());
HttpRestResult<String> restResult = nacosRestTemplate.putForm(url, Header.newInstance(), param, String.class);
assertTrue(restResult.ok());
System.out.println(restResult.getData());
}
@Test
public void test_url_get() throws Exception {
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");
assertTrue(restResult.ok());
assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name"));
System.out.println(restResult.getData());
}
@Test
public void test_url_get_by_map() throws Exception {
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");
assertTrue(restResult.ok());
assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name"));
System.out.println(restResult.getData());
}
@Test
public void test_url_delete() throws Exception {
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");
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());
assertTrue(restResult.ok());
System.out.println(restResult);
}

View File

@ -25,16 +25,15 @@ 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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ -44,27 +43,49 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* NacosRestTemplate_Interceptors_ITCase
*
* @author mai.jh
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.JVM)
public class NacosRestTemplate_Interceptors_ITCase {
@TestMethodOrder(MethodName.class)
class NacosRestTemplate_Interceptors_ITCase {
private final String CONFIG_PATH = "/nacos/v1/cs";
@LocalServerPort
private int port;
private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder
.getNacosRestTemplate(LoggerFactory.getLogger(NacosRestTemplate_Interceptors_ITCase.class));
private final String CONFIG_PATH = "/nacos/v1/cs";
private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder.getNacosRestTemplate(
LoggerFactory.getLogger(NacosRestTemplate_Interceptors_ITCase.class));
private String IP = null;
@BeforeEach
void init() throws NacosException {
nacosRestTemplate.setInterceptors(Arrays.asList(new TerminationInterceptor()));
IP = String.format("http://localhost:%d", port);
}
@Test
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);
assertEquals(500, restResult.getCode());
assertEquals("Stop request", restResult.getMessage());
System.out.println(restResult.getData());
System.out.println(restResult.getHeader());
}
private class TerminationInterceptor implements HttpClientRequestInterceptor {
@Override
@ -103,25 +124,4 @@ public class NacosRestTemplate_Interceptors_ITCase {
}
}
@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

@ -16,18 +16,17 @@
package com.alibaba.nacos.test.common;
import com.alibaba.nacos.common.utils.ByteUtils;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
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 org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.charset.StandardCharsets;
@ -41,31 +40,33 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class WatchFileCenter_ITCase {
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 {
final Object monitor = new Object();
@BeforeAll
static void beforeCls() throws Exception {
DiskUtils.deleteDirThenMkdir(path);
}
@AfterClass
public static void afterCls() throws Exception {
@AfterAll
static void afterCls() throws Exception {
DiskUtils.deleteDirectory(path);
}
// The last file change must be notified
@Test
public void test_high_concurrency_modify() throws Exception {
void test_high_concurrency_modify() throws Exception {
AtomicInteger count = new AtomicInteger(0);
Set<String> set = new ConcurrentHashSet<>();
@ -81,7 +82,7 @@ public class WatchFileCenter_ITCase {
}
@Test
public void test_modify_file_much() throws Exception {
void test_modify_file_much() throws Exception {
final String fileName = "modify_file_much";
final File file = Paths.get(path, fileName).toFile();
@ -113,11 +114,11 @@ public class WatchFileCenter_ITCase {
latch.await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(3, count.get());
assertEquals(3, count.get());
}
@Test
public void test_multi_file_modify() throws Exception {
void test_multi_file_modify() throws Exception {
CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
AtomicInteger count = new AtomicInteger(0);

View File

@ -18,34 +18,35 @@ 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.junit.jupiter.api.Test;
import org.springframework.core.env.StandardEnvironment;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @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);
}
class SnowFlowerIdGenerator_ITCase {
@Test
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();
assertNotEquals(id1, id2);
assertNotEquals(id1, id3);
assertNotEquals(id2, id3);
}
}

View File

@ -22,8 +22,6 @@ 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;
@ -31,6 +29,8 @@ import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
@ -64,12 +64,12 @@ public class AuthBase extends HttpClient4Test {
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);
Params.newParams().appendParam("username", username).appendParam("password", password).done(), String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
assertTrue(json.has("accessToken"));
return json.get("accessToken").textValue();
}
@ -90,69 +90,64 @@ public class AuthBase extends HttpClient4Test {
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());
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);
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());
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);
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());
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);
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());
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);
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());
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);
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());
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);
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());
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);
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());
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);
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());
assertTrue(response.getStatusCode().is2xxSuccessful());
// Init properties:
properties = new Properties();
@ -164,69 +159,63 @@ public class AuthBase extends HttpClient4Test {
// 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);
Params.newParams().appendParam("role", role1).appendParam("resource", namespace1 + ":*:*").appendParam("action", "r")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", role2).appendParam("resource", namespace1 + ":*:*").appendParam("action", "w")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", role3).appendParam("resource", namespace1 + ":*:*").appendParam("action", "rw")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", role1).appendParam("username", username1).appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", role2).appendParam("username", username2).appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", role3).appendParam("username", username3).appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
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());
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);
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());
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);
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());
assertTrue(response.getStatusCode().is2xxSuccessful());
System.setProperty("nacos.core.auth.enabled", "false");
}

View File

@ -13,6 +13,7 @@
* 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;
@ -24,84 +25,85 @@ 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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.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)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.contextPath=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ConfigAuth_ITCase extends AuthBase {
public static final long TIME_OUT = 2000;
public ConfigService iconfig = null;
@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 {
@BeforeEach
void init() throws Exception {
super.init(port);
}
@After
public void destroy(){
@AfterEach
public void destroy() {
super.destroy();
try {
iconfig.shutDown();
}catch (NacosException ex) {
if (iconfig != null) {
iconfig.shutDown();
}
} catch (NacosException ex) {
}
}
@Test
public void writeWithReadPermission() throws Exception {
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 {
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) {
@ -113,52 +115,52 @@ public class ConfigAuth_ITCase extends AuthBase {
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);
assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
String res = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, res);
assertEquals(content, res);
latch.await(5L, TimeUnit.SECONDS);
Assert.assertEquals(0, latch.getCount());
assertEquals(0, latch.getCount());
}
@Test
public void writeWithWritePermission() throws Exception {
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);
assertTrue(res);
res = iconfig.removeConfig(dataId, group);
Assert.assertTrue(res);
assertTrue(res);
}
@Test
public void readWithWritePermission() throws Exception {
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) {
@ -170,38 +172,38 @@ public class ConfigAuth_ITCase extends AuthBase {
latch.countDown();
}
});
TimeUnit.SECONDS.sleep(3L);
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
try {
iconfig.getConfig(dataId, group, TIME_OUT);
fail();
} catch (NacosException ne) {
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ne.getErrCode());
assertEquals(HttpStatus.SC_FORBIDDEN, ne.getErrCode());
}
latch.await(5L, TimeUnit.SECONDS);
Assert.assertTrue(latch.getCount() > 0);
assertTrue(latch.getCount() > 0);
}
@Test
public void ReadWriteWithFullPermission() throws Exception {
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) {
@ -213,22 +215,22 @@ public class ConfigAuth_ITCase extends AuthBase {
latch.countDown();
}
});
TimeUnit.SECONDS.sleep(3L);
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
assertTrue(result);
TimeUnit.SECONDS.sleep(5L);
String res = iconfig.getConfig(dataId, group, TIME_OUT);
Assert.assertEquals(content, res);
assertEquals(content, res);
latch.await(5L, TimeUnit.SECONDS);
Assert.assertEquals(0, latch.getCount());
assertEquals(0, latch.getCount());
result = iconfig.removeConfig(dataId, group);
Assert.assertTrue(result);
assertTrue(result);
}
}

View File

@ -18,62 +18,72 @@ 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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.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 org.springframework.test.annotation.DirtiesContext;
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 {
@Suite
@SelectClasses({LdapAuth_ITCase.NonTlsTest.class, LdapAuth_ITCase.TlsTest.class})
class LdapAuth_ITCase {
@LocalServerPort
private int port;
@Test
void empty() {
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)
abstract class LdapBase extends AuthBase {
@LocalServerPort
private int port;
private String filterPrefix = "uid";
@MockBean
private LdapTemplate ldapTemplate;
@BeforeEach
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);
}
}
@Nested
@DirtiesContext
@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 {
class NonTlsTest extends LdapBase {
@Test
public void testLdapAuth() throws Exception {
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",
@Nested
@DirtiesContext
@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 {
class TlsTest extends LdapBase {
@Test
public void testLdapAuth() throws Exception {
void testLdapAuth() throws Exception {
super.login("karson", "karson");
}
}

View File

@ -13,6 +13,7 @@
* 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;
@ -21,139 +22,138 @@ 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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.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 {
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class NamingAuth_ITCase extends AuthBase {
@LocalServerPort
private int port;
private NamingService namingService;
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
super.init(port);
}
@After
@AfterEach
public void destroy() {
super.destroy();
}
@Test
public void writeWithReadPermission() throws Exception {
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());
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());
assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode());
}
namingService.shutDown();
}
@Test
public void readWithReadPermission() throws Exception {
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());
assertEquals(1, list.size());
namingService1.shutDown();
namingService.shutDown();
}
@Test
public void writeWithWritePermission() throws Exception {
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 {
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());
assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode());
}
namingService.shutDown();
}
@Test
public void readWriteWithFullPermission() throws Exception {
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());
assertEquals(1, list.size());
namingService.shutDown();
}
}

View File

@ -24,90 +24,91 @@ 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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
* @since 1.2.0
*/
@RunWith(SpringRunner.class)
//todo fix this test case
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Permission_ITCase extends HttpClient4Test {
class Permission_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
@BeforeEach
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() {
@AfterEach
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*").appendParam("action", "rw")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*").appendParam("action", "r")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", "role1").appendParam("username", "username3").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("username", "username3").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void login() {
void login() {
ResponseEntity<String> response = request("/nacos/v1/auth/users/login",
Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(),
String.class, HttpMethod.POST);
Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
assertTrue(json.has("accessToken"));
accessToken = json.get("accessToken").textValue();
}
@Test
public void createDeleteQueryPermission() {
void createDeleteQueryPermission() {
login();
@ -116,30 +117,28 @@ public class Permission_ITCase extends HttpClient4Test {
Params.newParams().appendParam("username", "username3").appendParam("password", "password1")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", "role1").appendParam("username", "username3").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*").appendParam("action", "rw")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*").appendParam("action", "r")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
// Query permission:
response = request("/nacos/v1/auth/permissions",
@ -147,13 +146,13 @@ public class Permission_ITCase extends HttpClient4Test {
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
Page<Permission> permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
assertNotNull(permissionPage);
assertNotNull(permissionPage.getPageItems());
boolean found1 = false, found2 = false;
for (Permission permission : permissionPage.getPageItems()) {
@ -167,29 +166,28 @@ public class Permission_ITCase extends HttpClient4Test {
break;
}
}
Assert.assertTrue(found1);
Assert.assertTrue(found2);
assertTrue(found1);
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "public:*:*").appendParam("action", "rw")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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());
assertTrue(response.getStatusCode().is2xxSuccessful());
permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
assertNotNull(permissionPage);
assertNotNull(permissionPage.getPageItems());
found1 = false;
found2 = false;
@ -202,29 +200,28 @@ public class Permission_ITCase extends HttpClient4Test {
found2 = true;
}
}
Assert.assertFalse(found1);
Assert.assertTrue(found2);
assertFalse(found1);
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);
Params.newParams().appendParam("role", "role1").appendParam("resource", "test1:*:*").appendParam("action", "r")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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());
assertTrue(response.getStatusCode().is2xxSuccessful());
permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<Permission>>() {
});
Assert.assertNotNull(permissionPage);
Assert.assertNotNull(permissionPage.getPageItems());
assertNotNull(permissionPage);
assertNotNull(permissionPage.getPageItems());
found1 = false;
found2 = false;
@ -237,7 +234,7 @@ public class Permission_ITCase extends HttpClient4Test {
found2 = true;
}
}
Assert.assertFalse(found1);
Assert.assertFalse(found2);
assertFalse(found1);
assertFalse(found2);
}
}

View File

@ -13,154 +13,122 @@
* 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.plugin.auth.impl.persistence.RoleInfo;
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
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;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @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 {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Disabled("todo fix this test case")
class Role_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
@BeforeEach
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() {
@AfterEach
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());
ResponseEntity<String> response = request("/nacos/v1/auth/roles",
Params.newParams().appendParam("role", "role1").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
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());
Params.newParams().appendParam("role", "role2").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
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());
Params.newParams().appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
public void login() {
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());
Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(), String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
assertTrue(json.has("accessToken"));
accessToken = json.get("accessToken").textValue();
}
@Test
public void createDeleteQueryRole() {
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());
Params.newParams().appendParam("username", "username2").appendParam("password", "password1")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
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());
Params.newParams().appendParam("role", "role1").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.POST);
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());
Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
Page<RoleInfo> roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
});
assertNotNull(roleInfoPage);
assertNotNull(roleInfoPage.getPageItems());
boolean found = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
if (roleInfo.getRole().equals("role1")) {
@ -168,37 +136,27 @@ public class Role_ITCase extends HttpClient4Test {
break;
}
}
Assert.assertTrue(found);
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());
Params.newParams().appendParam("role", "role2").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.POST);
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());
Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
});
assertNotNull(roleInfoPage);
assertNotNull(roleInfoPage.getPageItems());
found = false;
boolean found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
@ -212,38 +170,28 @@ public class Role_ITCase extends HttpClient4Test {
break;
}
}
Assert.assertTrue(found);
Assert.assertTrue(found2);
assertTrue(found);
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());
Params.newParams().appendParam("role", "role2").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
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());
Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
});
assertNotNull(roleInfoPage);
assertNotNull(roleInfoPage.getPageItems());
found = false;
found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
@ -254,38 +202,28 @@ public class Role_ITCase extends HttpClient4Test {
found2 = true;
}
}
Assert.assertFalse(found2);
Assert.assertTrue(found);
assertFalse(found2);
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());
Params.newParams().appendParam("role", "role1").appendParam("username", "username2").appendParam("accessToken", accessToken)
.done(), String.class, HttpMethod.DELETE);
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());
Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
});
assertNotNull(roleInfoPage);
assertNotNull(roleInfoPage.getPageItems());
found = false;
found2 = false;
for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
@ -296,7 +234,7 @@ public class Role_ITCase extends HttpClient4Test {
found2 = true;
}
}
Assert.assertFalse(found2);
Assert.assertFalse(found);
assertFalse(found2);
assertFalse(found);
}
}

View File

@ -13,6 +13,7 @@
* 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;
@ -24,201 +25,167 @@ 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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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 org.springframework.test.context.junit.jupiter.SpringExtension;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @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 {
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class User_ITCase extends HttpClient4Test {
@LocalServerPort
private int port;
private String accessToken;
@Before
public void init() throws Exception {
@BeforeEach
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() {
@AfterEach
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());
Params.newParams().appendParam("username", "username1").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
assertTrue(response.getStatusCode().is2xxSuccessful());
// Delete a user:
request("/nacos/v1/auth/users",
Params.newParams()
.appendParam("username", "username2")
.appendParam("accessToken", accessToken)
.done(),
String.class,
Params.newParams().appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
System.setProperty("nacos.core.auth.enabled", "false");
}
@Test
public void login() {
void login() {
ResponseEntity<String> response = login("nacos", "nacos");
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertTrue(json.has("accessToken"));
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,
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() {
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());
Params.newParams().appendParam("username", "username1").appendParam("password", "password1")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
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);
Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE))
.appendParam("accessToken", accessToken).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
Page<User> userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {
});
assertNotNull(userPage);
assertNotNull(userPage.getPageItems());
assertTrue(userPage.getPageItems().size() > 0);
boolean found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername()) &&
PasswordEncoderUtil.matches("password1", user.getPassword())) {
if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password1", user.getPassword())) {
found = true;
break;
}
}
Assert.assertTrue(found);
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());
Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password2")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.PUT);
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);
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>>() {
});
assertNotNull(userPage);
assertNotNull(userPage.getPageItems());
assertTrue(userPage.getPageItems().size() > 0);
found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername()) &&
PasswordEncoderUtil.matches("password2", user.getPassword())) {
if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password2", user.getPassword())) {
found = true;
break;
}
}
Assert.assertTrue(found);
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());
Params.newParams().appendParam("username", "username1").appendParam("accessToken", accessToken).done(), String.class,
HttpMethod.DELETE);
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);
Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE))
.appendParam("accessToken", accessToken).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {
});
assertNotNull(userPage);
assertNotNull(userPage.getPageItems());
assertTrue(userPage.getPageItems().size() > 0);
found = false;
for (User user : userPage.getPageItems()) {
if ("username1".equals(user.getUsername())) {
@ -226,77 +193,52 @@ public class User_ITCase extends HttpClient4Test {
break;
}
}
Assert.assertFalse(found);
assertFalse(found);
}
@Test
public void updateUserWithPermission() {
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());
Params.newParams().appendParam("username", "username1").appendParam("password", "password1")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
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());
response = request("/nacos/v1/auth/users",
Params.newParams().appendParam("username", "username2").appendParam("password", "password2")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
// user login
response = login("username1", "password1");
String user1AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue();
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
response = login("username2", "password2");
String user2AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue();
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
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());
Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password3")
.appendParam("accessToken", accessToken).done(), String.class, HttpMethod.PUT);
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());
Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password4")
.appendParam("accessToken", user1AccessToken).done(), String.class, HttpMethod.PUT);
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);
Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password5")
.appendParam("accessToken", user2AccessToken).done(), String.class, HttpMethod.PUT);
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
}

View File

@ -17,23 +17,22 @@
package com.alibaba.nacos.test.core.cluster;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberLookup;
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.web.MockServletContext;
@ -43,114 +42,110 @@ import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @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());
}
@TestMethodOrder(MethodName.class)
class MemberLookup_ITCase {
static final String path = Paths.get(System.getProperty("user.home"), "/member_look").toString();
static final String name = "cluster.conf";
ServerMemberManager memberManager;
@BeforeEach
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();
}
}
@AfterEach
void after() throws Exception {
try {
memberManager.shutdown();
} catch (Throwable ex) {
ex.printStackTrace();
}
DiskUtils.deleteDirectory(path);
}
@Test
void test_a_lookup_file_config() throws Exception {
try {
LookupFactory.createLookUp(memberManager);
} catch (Throwable ignore) {
}
MemberLookup lookup = LookupFactory.getLookUp();
System.out.println(lookup);
assertTrue(lookup instanceof FileConfigMemberLookup);
func(lookup);
}
@Test
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);
assertTrue(lookup instanceof StandaloneMemberLookup);
}
@Test
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);
assertTrue(lookup instanceof AddressServerMemberLookup);
try {
func(lookup);
} catch (NacosException e) {
System.out.println(e.getErrMsg());
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);
assertEquals(expectSize, tmp.size());
}
}

View File

@ -20,20 +20,19 @@ 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.MembersChangeEvent;
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 com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.web.MockServletContext;
@ -50,42 +49,46 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Cluster node manages unit tests.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ServerMemberManager_ITCase {
@TestMethodOrder(MethodName.class)
// todo fix
class ServerMemberManager_ITCase {
private ServerMemberManager memberManager;
@BeforeClass
public static void initClass() throws Exception {
@BeforeAll
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() {
@AfterAll
static void destroyClass() {
System.clearProperty(Constants.NACOS_SERVER_IP);
System.clearProperty("server.port");
}
@Before
public void before() throws Exception {
@BeforeEach
void before() throws Exception {
memberManager = new ServerMemberManager(new MockServletContext());
}
@After
public void after() throws Exception {
@AfterEach
void after() throws Exception {
memberManager.shutdown();
}
@Test
public void testKisFirst() {
void testKisFirst() {
String firstIp = "127.0.0.1:8847";
String secondIp = "127.0.0.1:8848";
String thirdIp = "127.0.0.1:8849";
@ -99,11 +102,11 @@ public class ServerMemberManager_ITCase {
Collections.sort(members);
List<String> ss = MemberUtil.simpleMembers(members);
Assert.assertEquals(ss.get(0), members.get(0).getAddress());
assertEquals(ss.get(0), members.get(0).getAddress());
}
@Test
public void testMemberChange() throws Exception {
void testMemberChange() throws Exception {
AtomicInteger integer = new AtomicInteger(0);
CountDownLatch latch = new CountDownLatch(1);
@ -129,15 +132,15 @@ public class ServerMemberManager_ITCase {
members.add(Member.builder().ip("115.159.3.213").port(8848).build());
boolean changed = memberManager.memberJoin(members);
Assert.assertTrue(changed);
assertTrue(changed);
latch.await(10_000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(1, integer.get());
assertEquals(1, integer.get());
}
@Test
public void testMemberHealthCheck() throws Exception {
void testMemberHealthCheck() throws Exception {
AtomicReference<Collection<Member>> healthMembers = new AtomicReference<>();
CountDownLatch first = new CountDownLatch(1);
CountDownLatch second = new CountDownLatch(1);
@ -174,20 +177,20 @@ public class ServerMemberManager_ITCase {
memberManager.memberJoin(map.values());
first.await();
first.await(); //fix blocking
Set<Member> copy = new HashSet<>(firstMemberList);
copy.removeAll(healthMembers.get());
Assert.assertEquals(2, copy.size());
assertEquals(2, copy.size());
Member member = map.get(firstIp);
member.setState(NodeState.DOWN);
Assert.assertTrue(memberManager.update(member));
assertTrue(memberManager.update(member));
second.await();
second.await();//fix blocking
copy = new HashSet<>(firstMemberList);
copy.removeAll(healthMembers.get());
Assert.assertEquals(3, copy.size());
Assert.assertTrue(copy.contains(map.get(firstIp)));
assertEquals(3, copy.size());
assertTrue(copy.contains(map.get(firstIp)));
}
}

View File

@ -16,66 +16,67 @@
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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author horizonzy
* @since 1.3.2
*/
public class ControllerMethodsCache_ITCase {
class ControllerMethodsCache_ITCase {
private ControllerMethodsCache methodsCache;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
methodsCache = new ControllerMethodsCache();
EnvUtil.setContextPath("/nacos");
methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller");
}
@Test
public void testGetMethod() {
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");
@ -92,5 +93,5 @@ public class ControllerMethodsCache_ITCase {
}
return request;
}
}

View File

@ -17,25 +17,25 @@
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 {
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class nacosSmoke_ITCase {
private static Logger logger = Logger.getLogger(nacosSmoke_ITCase.class);
@Before
public void setUp() {
@BeforeEach
void setUp() {
logger.info(String.format("nacosSmoke_ITCase: %s;", "setUp"));
}
@After
public void tearDown() {
@AfterEach
void tearDown() {
logger.info(String.format("nacosSmoke_ITCase: %s;", "tearDown"));
}
@Test
public void testSmoke() {
void testSmoke() {
}
}

View File

@ -24,16 +24,16 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate;
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.persistence.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl;
import com.alibaba.nacos.consistency.ProtocolMetaData;
import com.alibaba.nacos.consistency.cp.CPProtocol;
import com.alibaba.nacos.consistency.cp.MetadataKey;
import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl;
import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
@ -57,19 +57,19 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class BaseClusterTest extends HttpClient4Test {
protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), new AtomicBoolean(false),
new AtomicBoolean(false)};
private static final Logger LOGGER = LoggerFactory.getLogger(BaseClusterTest.class);
protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER);
protected static NamingService inaming7;
protected static NamingService inaming8;
protected static NamingService inaming9;
protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER);
protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false),
new AtomicBoolean(false), new AtomicBoolean(false)};
protected static Map<String, ConfigurableApplicationContext> applications = new HashMap<>();
protected static String clusterInfo;
@ -93,8 +93,8 @@ public class BaseClusterTest extends HttpClient4Test {
});
}
@BeforeClass
public static void before() throws Exception {
@BeforeAll
static void before() throws Exception {
CountDownLatch latch = new CountDownLatch(3);
@ -142,8 +142,8 @@ public class BaseClusterTest extends HttpClient4Test {
TimeUnit.SECONDS.sleep(20L);
}
@AfterClass
public static void after() throws Exception {
@AfterAll
static void after() throws Exception {
CountDownLatch latch = new CountDownLatch(applications.size());
for (ConfigurableApplicationContext context : applications.values()) {
new Thread(() -> {
@ -177,15 +177,14 @@ public class BaseClusterTest extends HttpClient4Test {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", "884" + (7 + index));
properties.put("nacos.home", path);
properties.put("nacos.logs.path",
Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString());
properties.put("nacos.logs.path", Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString());
properties.put("spring.jmx.enabled", false);
properties.put("nacos.core.snowflake.worker-id", index + 1);
MapPropertySource propertySource = new MapPropertySource("nacos_cluster_test", properties);
ConfigurableEnvironment environment = new StandardServletEnvironment();
environment.getPropertySources().addFirst(propertySource);
SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET)
.environment(environment).properties(clusterInfo).properties("embeddedStorage=true").build();
SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET).environment(environment)
.properties(clusterInfo).properties("embeddedStorage=true").build();
ConfigurableApplicationContext context = cluster.run();

View File

@ -13,6 +13,7 @@
* 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;
@ -33,35 +34,31 @@ import java.net.URL;
* @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);
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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -25,11 +25,8 @@ import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.remote.NamingClientProxy;
import com.alibaba.nacos.common.utils.ReflectUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
@ -42,12 +39,12 @@ import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public abstract class AbstractInstanceOperate_ITCase {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private NamingService naming;
@LocalServerPort
@ -56,7 +53,7 @@ public abstract class AbstractInstanceOperate_ITCase {
@Value("${server.servlet.context-path}")
private String contextPath;
@Before
@BeforeEach
public void init() throws Exception {
NamingBase.prepareServer(port, contextPath);
@ -93,7 +90,7 @@ public abstract class AbstractInstanceOperate_ITCase {
verifyInstanceList(instances, 1, serviceName);
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT);
@ -101,7 +98,7 @@ public abstract class AbstractInstanceOperate_ITCase {
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 0);
assertEquals(0, instances.size());
}
/**
@ -122,7 +119,7 @@ public abstract class AbstractInstanceOperate_ITCase {
verifyInstanceList(instances, 1, serviceName);
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
@ -130,7 +127,7 @@ public abstract class AbstractInstanceOperate_ITCase {
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
/**
@ -149,7 +146,7 @@ public abstract class AbstractInstanceOperate_ITCase {
instances = naming.getAllInstances(serviceName);
verifyInstanceList(instances, 1, serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
@ -157,7 +154,7 @@ public abstract class AbstractInstanceOperate_ITCase {
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
private void verifyInstanceList(List<Instance> instances, int size, String serviceName) throws Exception {
@ -189,7 +186,7 @@ public abstract class AbstractInstanceOperate_ITCase {
naming.registerInstance(serviceName, "127.0.0.2", 80, "c2");
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
}
/**
@ -207,9 +204,9 @@ public abstract class AbstractInstanceOperate_ITCase {
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT);
assertEquals(1, instances.size());
assertEquals(NamingBase.TEST_IP_4_DOM_1, instances.get(0).getIp());
assertEquals(NamingBase.TEST_PORT, instances.get(0).getPort());
}
/**
@ -224,23 +221,21 @@ public abstract class AbstractInstanceOperate_ITCase {
System.out.println(serviceName);
naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT,
NamingBase.TEST_NEW_CLUSTER_4_DOM_1);
naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT, NamingBase.TEST_NEW_CLUSTER_4_DOM_1);
TimeUnit.SECONDS.sleep(3);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT);
assertEquals(1, instances.size());
assertEquals(NamingBase.TEST_IP_4_DOM_1, instances.get(0).getIp());
assertEquals(NamingBase.TEST_PORT, instances.get(0).getPort());
List<Instance> instances2 = naming
.getAllInstances(serviceName, Arrays.asList(NamingBase.TEST_NEW_CLUSTER_4_DOM_1));
List<Instance> instances2 = naming.getAllInstances(serviceName, Arrays.asList(NamingBase.TEST_NEW_CLUSTER_4_DOM_1));
Assert.assertEquals(instances2.size(), 1);
Assert.assertEquals(instances2.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
Assert.assertEquals(instances2.get(0).getPort(), NamingBase.TEST_PORT);
assertEquals(1, instances2.size());
assertEquals(NamingBase.TEST_IP_4_DOM_1, instances2.get(0).getIp());
assertEquals(NamingBase.TEST_PORT, instances2.get(0).getPort());
}
/**
@ -259,9 +254,9 @@ public abstract class AbstractInstanceOperate_ITCase {
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 1);
assertEquals(1, instances.size());
Assert.assertTrue(NamingBase.verifyInstance(i1, instances.get(0)));
assertTrue(NamingBase.verifyInstance(i1, instances.get(0)));
}
@ -282,7 +277,7 @@ public abstract class AbstractInstanceOperate_ITCase {
List<Instance> instances = naming.selectInstances(serviceName, false);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
@Test
@ -305,9 +300,9 @@ public abstract class AbstractInstanceOperate_ITCase {
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("1.0", instances.get(0).getMetadata().get("version"));
Assert.assertEquals("prod", instances.get(0).getMetadata().get("env"));
assertEquals(1, instances.size());
assertEquals("1.0", instances.get(0).getMetadata().get("version"));
assertEquals("prod", instances.get(0).getMetadata().get("env"));
}
@Test
@ -331,7 +326,7 @@ public abstract class AbstractInstanceOperate_ITCase {
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
naming.deregisterInstance(serviceName, instance);
@ -339,7 +334,7 @@ public abstract class AbstractInstanceOperate_ITCase {
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
/**
@ -349,22 +344,22 @@ public abstract class AbstractInstanceOperate_ITCase {
*/
@Test
public void registerEphemeralInstanceWithInvalidClusterName() throws Exception {
expectedException.expect(Exception.class);
expectedException.expectMessage(
"Param 'cluster' is illegal, illegal characters should not appear in the param.");
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setIp(NamingBase.TEST_IP_4_DOM_1);
instance.setPort(NamingBase.TEST_PORT);
instance.setWeight(1.0);
instance.setEphemeral(true);
instance.setClusterName("cluster1,cluster2");
// Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking
// in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not.
NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy");
clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance);
Throwable exception = assertThrows(Exception.class, () -> {
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setIp(NamingBase.TEST_IP_4_DOM_1);
instance.setPort(NamingBase.TEST_PORT);
instance.setWeight(1.0);
instance.setEphemeral(true);
instance.setClusterName("cluster1,cluster2");
// Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking
// in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not.
NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy");
clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance);
});
assertTrue(exception.getMessage().contains("Param 'cluster' is illegal, illegal characters should not appear in the param."));
}
/**
@ -374,21 +369,21 @@ public abstract class AbstractInstanceOperate_ITCase {
*/
@Test
public void registerPersistentInstanceWithInvalidClusterName() throws Exception {
expectedException.expect(NacosException.class);
expectedException.expectMessage(
"Param 'cluster' is illegal, illegal characters should not appear in the param.");
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setIp(NamingBase.TEST_IP_4_DOM_1);
instance.setPort(NamingBase.TEST_PORT);
instance.setWeight(1.0);
instance.setEphemeral(false);
instance.setClusterName("cluster1,cluster2");
// Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking
// in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not.
NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy");
clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance);
Throwable exception = assertThrows(NacosException.class, () -> {
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setIp(NamingBase.TEST_IP_4_DOM_1);
instance.setPort(NamingBase.TEST_PORT);
instance.setWeight(1.0);
instance.setEphemeral(false);
instance.setClusterName("cluster1,cluster2");
// Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking
// in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not.
NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy");
clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance);
});
assertTrue(exception.getMessage().contains("Param 'cluster' is illegal, illegal characters should not appear in the param."));
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
@ -25,12 +26,9 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.test.base.Params;
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
@ -39,7 +37,6 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
@ -48,60 +45,66 @@ import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.NAMING_CONTROLLER_PATH;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_1;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_NAMESPACE_1;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_NAMESPACE_2;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT2_4_DOM_1;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class CPInstancesAPI_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class CPInstancesAPI_ITCase {
private NamingService naming;
private NamingService naming1;
private NamingService naming2;
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate restTemplate;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Properties properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE_1);
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming1 = NamingFactory.createNamingService(properties);
properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE_2);
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming2 = NamingFactory.createNamingService(properties);
}
@After
public void cleanup() throws Exception {
@AfterEach
void cleanup() throws Exception {
}
/**
* @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为true
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_ephemeral_true() throws Exception {
void registerInstance_ephemeral_true() throws Exception {
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setEphemeral(true); //是否临时实例
instance.setClusterName("c1");
@ -112,17 +115,17 @@ public class CPInstancesAPI_ITCase {
naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance);
namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1);
}
/**
* @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为false
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_ephemeral_false() throws Exception {
void registerInstance_ephemeral_false() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1);
Instance instance = new Instance();
instance.setEphemeral(false); //是否临时实例
instance.setClusterName("c1");
@ -133,17 +136,17 @@ public class CPInstancesAPI_ITCase {
naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance);
namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1);
}
/**
* @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为false
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_ephemeral_false_deregisterInstance() throws Exception {
void registerInstance_ephemeral_false_deregisterInstance() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1);
Instance instance = new Instance();
instance.setEphemeral(false); //是否临时实例
instance.setClusterName("c1");
@ -152,320 +155,264 @@ public class CPInstancesAPI_ITCase {
naming1.registerInstance(serviceName, TEST_GROUP_1, instance);
naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance);
TimeUnit.SECONDS.sleep(3L);
namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1);
}
/**
* @TCDescription : 根据serviceName创建服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void createService() throws Exception {
void createService() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, TEST_NAMESPACE_1);
namingServiceDelete(serviceName, TEST_NAMESPACE_1);
}
/**
* @TCDescription : 根据serviceName创建服务, 存在实例不能被删除, 抛异常
* @TestStep :
* @ExpectResult :
*/
@Test
public void deleteService_hasInstace() {
void deleteService_hasInstace() {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> registerResponse = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("ip", "11.11.11.11")
.appendParam("port", "80")
.appendParam("namespaceId", TEST_NAMESPACE_1)
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(registerResponse.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11").appendParam("port", "80")
.appendParam("namespaceId", TEST_NAMESPACE_1).done(), String.class, HttpMethod.POST);
assertTrue(registerResponse.getStatusCode().is2xxSuccessful());
ResponseEntity<String> deleteServiceResponse = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("namespaceId", TEST_NAMESPACE_1)
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(deleteServiceResponse.getStatusCode().is4xxClientError());
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1).done(),
String.class, HttpMethod.DELETE);
assertTrue(deleteServiceResponse.getStatusCode().is4xxClientError());
}
/**
* @TCDescription : 根据serviceName修改服务并通过HTTP接口获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void getService() throws Exception {
void getService() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, TEST_NAMESPACE_1);
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("namespaceId", TEST_NAMESPACE_1)
.appendParam("protectThreshold", "0.5")
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1)
.appendParam("protectThreshold", "0.5").done(), String.class, HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
//get service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("namespaceId", TEST_NAMESPACE_1)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1).done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(serviceName, json.get("name").textValue());
Assert.assertEquals("0.5", json.get("protectThreshold").asText());
assertEquals(serviceName, json.get("name").textValue());
assertEquals("0.5", json.get("protectThreshold").asText());
namingServiceDelete(serviceName, TEST_NAMESPACE_1);
}
/**
* @TCDescription : 根据serviceName修改服务并通过接口获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void getService_1() throws Exception {
void getService_1() throws Exception {
String serviceName = NamingBase.randomDomainName();
ListView<String> listView = naming1.getServicesOfServer(1, 50);
namingServiceCreate(serviceName, TEST_NAMESPACE_1);
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView1 = naming1.getServicesOfServer(1, 50);
Assert.assertEquals(listView.getCount()+1, listView1.getCount());
assertEquals(listView.getCount() + 1, listView1.getCount());
namingServiceDelete(serviceName, TEST_NAMESPACE_1);
}
/**
* @TCDescription : 获取服务list信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void listService() throws Exception {
void listService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ListView<String> listView = naming.getServicesOfServer(1, 50);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID);
//get service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("pageNo", "1")
.appendParam("pageSize", "150")
.done(),
String.class);
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "150").done(),
String.class);
System.out.println("json = " + response.getBody());
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
int count = json.get("count").intValue();
Assert.assertEquals(listView.getCount() + 1, count);
assertEquals(listView.getCount() + 1, count);
namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID);
}
/**
* @TCDescription : 根据serviceName创建服务注册持久化实例, 注销实例删除服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_api() throws Exception {
void registerInstance_api() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
ResponseEntity<String> response = request(NAMING_CONTROLLER_PATH + "/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID);
}
/**
* @TCDescription : 根据serviceName创建服务注册持久化实例, 查询实例注销实例删除服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_query() throws Exception {
void registerInstance_query() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("33.33.33.33", instances.get(0).getIp());
assertEquals(1, instances.size());
assertEquals("33.33.33.33", instances.get(0).getIp());
instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
TimeUnit.SECONDS.sleep(3L);
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID);
}
/**
* @TCDescription : 根据serviceName创建服务注册不同group的2个非持久化实例, 注销实例删除服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void registerInstance_2() throws Exception {
void registerInstance_2() throws Exception {
String serviceName = NamingBase.randomDomainName();
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID);
namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1, "22.22.22.22", TEST_PORT2_4_DOM_1);
ResponseEntity<String> response = request(NAMING_CONTROLLER_PATH + "/instance/list",
Params.newParams()
.appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1);
instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1, "22.22.22.22", TEST_PORT2_4_DOM_1);
namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID);
namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1);
}
private void instanceDeregister(String serviceName, String namespace, String ip, String port) {
instanceDeregister(serviceName, namespace, Constants.DEFAULT_GROUP, ip, port);
}
private void instanceDeregister(String serviceName, String namespace, String groupName, String ip, String port) {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("ip", ip)
.appendParam("port", port)
.appendParam("namespaceId", namespace)
.appendParam("groupName", groupName)
.appendParam("ephemeral", "false")
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", ip).appendParam("port", port)
.appendParam("namespaceId", namespace).appendParam("groupName", groupName).appendParam("ephemeral", "false").done(),
String.class, HttpMethod.DELETE);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
private void instanceRegister(String serviceName, String namespace, String groupName, String ip, String port) {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("ip", ip)
.appendParam("port", port)
.appendParam("namespaceId", namespace)
.appendParam("groupName", groupName)
.appendParam("ephemeral", "false")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", ip).appendParam("port", port)
.appendParam("namespaceId", namespace).appendParam("groupName", groupName).appendParam("ephemeral", "false").done(),
String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
private void instanceRegister(String serviceName, String namespace, String ip, String port) {
instanceRegister(serviceName, namespace, Constants.DEFAULT_GROUP, ip, port);
}
private void namingServiceCreate(String serviceName, String namespace) {
namingServiceCreate(serviceName, namespace, Constants.DEFAULT_GROUP);
}
private void namingServiceCreate(String serviceName, String namespace, String groupName) {
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.appendParam("namespaceId", namespace)
.appendParam("groupName", groupName)
.done(),
String.class,
HttpMethod.POST);
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3")
.appendParam("namespaceId", namespace).appendParam("groupName", groupName).done(), String.class, HttpMethod.POST);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
}
private void namingServiceDelete(String serviceName, String namespace) {
namingServiceDelete(serviceName, namespace, Constants.DEFAULT_GROUP);
}
private void namingServiceDelete(String serviceName, String namespace, String groupName) {
//delete service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("namespaceId", namespace)
.appendParam("groupName", groupName)
.done(),
String.class,
HttpMethod.DELETE);
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", namespace)
.appendParam("groupName", groupName).done(), String.class, HttpMethod.DELETE);
System.out.println(response);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
}
private <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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, clazz);
}
private <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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}
}

View File

@ -21,33 +21,33 @@ import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.test.base.Params;
import com.alibaba.nacos.common.utils.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.alibaba.nacos.test.base.Params;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.List;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ClientBeat_ITCase extends NamingBase {
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ClientBeat_ITCase extends NamingBase {
private NamingService naming;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
NamingBase.prepareServer(port);
if (naming == null) {
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
@ -62,82 +62,74 @@ public class ClientBeat_ITCase extends NamingBase {
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
}
@Test
public void testLightBeat() throws Exception {
void testLightBeat() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.2.3.4", 81);
Instance instance = new Instance();
instance.setIp("1.2.3.4");
instance.setPort(80);
instance.addMetadata("k1", "v1");
instance.addMetadata("k2", "v2");
naming.registerInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(2L);
List<Instance> list = naming.getAllInstances(serviceName);
Assert.assertEquals(1, list.size());
assertEquals(1, list.size());
for (Instance instance1 : list) {
Assert.assertEquals("1.2.3.4", instance1.getIp());
Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
assertEquals("1.2.3.4", instance1.getIp());
assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
if (instance1.getPort() == 80) {
Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
}
}
// Sleep 35 seconds and see if instance list not changed:
TimeUnit.SECONDS.sleep(35L);
list = naming.getAllInstances(serviceName);
Assert.assertEquals(1, list.size());
assertEquals(1, list.size());
for (Instance instance1 : list) {
Assert.assertEquals("1.2.3.4", instance1.getIp());
Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
assertEquals("1.2.3.4", instance1.getIp());
assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
if (instance1.getPort() == 80) {
Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
}
}
// Change the light beat switch of server:
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/operator/switches",
Params.newParams()
.appendParam("entry", "lightBeatEnabled")
.appendParam("value", "false")
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("entry", "lightBeatEnabled").appendParam("value", "false").done(), String.class,
HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
// Sleep 35 seconds and see if instance list not changed:
TimeUnit.SECONDS.sleep(35L);
list = naming.getAllInstances(serviceName);
Assert.assertEquals(1, list.size());
assertEquals(1, list.size());
for (Instance instance1 : list) {
Assert.assertEquals("1.2.3.4", instance1.getIp());
Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
assertEquals("1.2.3.4", instance1.getIp());
assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81);
if (instance1.getPort() == 80) {
Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY));
assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY));
}
}
// Reset the light beat switch of server:
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/operator/switches",
Params.newParams()
.appendParam("entry", "lightBeatEnabled")
.appendParam("value", "true")
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("entry", "lightBeatEnabled").appendParam("value", "true").done(), String.class,
HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
}

View File

@ -17,9 +17,7 @@
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by wangtong.wt on 2018/6/20.
@ -27,9 +25,8 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class InstanceOperate_ITCase extends AbstractInstanceOperate_ITCase {
}

View File

@ -26,15 +26,11 @@ import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.Collections;
@ -42,31 +38,44 @@ import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_1;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_2;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_IP_4_DOM_1;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_SERVER_STATUS;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class MultiTenant_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class MultiTenant_ITCase {
private NamingService naming;
private NamingService naming1;
private NamingService naming2;
@LocalServerPort
private int port;
private volatile List<Instance> instances = Collections.emptyList();
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
Thread.sleep(6000L);
NamingBase.prepareServer(port);
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
while (true) {
if (!"UP".equals(naming.getServerStatus())) {
Thread.sleep(1000L);
@ -74,587 +83,588 @@ public class MultiTenant_ITCase {
}
break;
}
Properties properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, "namespace-1");
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming1 = NamingFactory.createNamingService(properties);
properties = new Properties();
properties.put(PropertyKeyConst.NAMESPACE, "namespace-2");
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
naming2 = NamingFactory.createNamingService(properties);
}
/**
* @TCDescription : 多租户注册IPport不相同实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_registerInstance() throws Exception {
void multipleTenant_registerInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
naming2.registerInstance(serviceName, "22.22.22.22", 80);
naming.registerInstance(serviceName, "33.33.33.33", 8888);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("11.11.11.11", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming2.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("22.22.22.22", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("22.22.22.22", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
}
/**
* @TCDescription : 多Group注册实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_multiGroup_registerInstance() throws Exception {
void multipleTenant_multiGroup_registerInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80);
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", 80);
naming.registerInstance(serviceName, "33.33.33.33", 8888);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
instances = naming2.getAllInstances(serviceName, TEST_GROUP_2);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("22.22.22.22", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("22.22.22.22", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80);
assertEquals(1, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2, "22.22.22.22", 80);
}
/**
* @TCDescription : 多租户注册IPport相同的实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_equalIP() throws Exception {
void multipleTenant_equalIP() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
naming2.registerInstance(serviceName, "11.11.11.11", 80);
naming.registerInstance(serviceName, "11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("11.11.11.11", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming2.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("11.11.11.11", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
}
/**
* @TCDescription : 多租户注册IPport相同的实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_selectInstances() throws Exception {
void multipleTenant_selectInstances() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
naming2.registerInstance(serviceName, "22.22.22.22", 80);
naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
Assert.assertEquals(TEST_IP_4_DOM_1, instances.get(0).getIp());
Assert.assertEquals(TEST_PORT, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals(TEST_IP_4_DOM_1, instances.get(0).getIp());
assertEquals(TEST_PORT, instances.get(0).getPort());
instances = naming2.selectInstances(serviceName, false);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
}
/**
* @TCDescription : 多租户,多Group注册IPport相同的实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_equalIP() throws Exception {
void multipleTenant_group_equalIP() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80);
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
naming2.registerInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP, "11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
instances = naming2.getAllInstances(serviceName, TEST_GROUP_2);
Assert.assertEquals(1, instances.size());
Assert.assertEquals("11.11.11.11", instances.get(0).getIp());
Assert.assertEquals(80, instances.get(0).getPort());
assertEquals(1, instances.size());
assertEquals("11.11.11.11", instances.get(0).getIp());
assertEquals(80, instances.get(0).getPort());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
}
/**
* @TCDescription : 多租户,多Group注册IPport相同的实例, 通过group获取实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_getInstances() throws Exception {
void multipleTenant_group_getInstances() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
// will cover the instance before
naming1.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80);
naming1.registerInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80);
naming.registerInstance(serviceName, Constants.DEFAULT_GROUP, "11.11.11.11", 80);
TimeUnit.SECONDS.sleep(5L);
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
instances = naming.getAllInstances(serviceName);
Assert.assertEquals(1, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80);
assertEquals(1, instances.size());
naming1.deregisterInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
naming1.deregisterInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80);
}
/**
* @TCDescription : 多租户同服务获取实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_getServicesOfServer() throws Exception {
void multipleTenant_getServicesOfServer() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView = naming1.getServicesOfServer(1, 200);
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView1 = naming1.getServicesOfServer(1, 200);
Assert.assertEquals(listView.getCount(), listView1.getCount());
assertEquals(listView.getCount(), listView1.getCount());
}
/**
* @TCDescription : 多租户, 多group同服务获取实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_getServicesOfServer() throws Exception {
void multipleTenant_group_getServicesOfServer() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", TEST_PORT, "c1");
// will cover the instance before
naming1.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
//服务不会删除实例会注销
ListView<String> listView = naming1.getServicesOfServer(1, 20, TEST_GROUP_1);
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(5L);
ListView<String> listView1 = naming1.getServicesOfServer(1, 20, TEST_GROUP_1);
Assert.assertEquals(listView.getCount(), listView1.getCount());
Assert.assertNotEquals(0, listView1.getCount());
assertEquals(listView.getCount(), listView1.getCount());
assertNotEquals(0, listView1.getCount());
}
/**
* @TCDescription : 多租户订阅服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_subscribe() throws Exception {
void multipleTenant_subscribe() throws Exception {
String serviceName = randomDomainName();
naming1.subscribe(serviceName, new EventListener() {
@Override
public void onEvent(Event event) {
instances = ((NamingEvent) event).getInstances();
}
});
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
TimeUnit.SECONDS.sleep(2L);
Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName)));
}
/**
* @TCDescription : 多租户多group订阅服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_subscribe() throws Exception {
void multipleTenant_group_subscribe() throws Exception {
String serviceName = randomDomainName();
naming1.subscribe(serviceName, TEST_GROUP_1, new EventListener() {
@Override
public void onEvent(Event event) {
instances = ((NamingEvent) event).getInstances();
}
});
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
TimeUnit.SECONDS.sleep(2L);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
TimeUnit.SECONDS.sleep(2L);
Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName, TEST_GROUP_1)));
assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName, TEST_GROUP_1)));
naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1, "33.33.33.33", TEST_PORT, "c1");
}
/**
* @TCDescription : 多租户取消订阅服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_unSubscribe() throws Exception {
void multipleTenant_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
System.out.println(((NamingEvent) event).getServiceName());
instances = ((NamingEvent) event).getInstances();
}
};
naming1.subscribe(serviceName, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
assertEquals(0, naming2.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener);
TimeUnit.SECONDS.sleep(5L);
Assert.assertEquals(0, naming1.getSubscribeServices().size());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
assertEquals(0, naming1.getSubscribeServices().size());
assertEquals(0, naming2.getSubscribeServices().size());
}
/**
* @TCDescription : 多租户,多group下, 没有对应的group订阅取消订阅服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_nosubscribe_unSubscribe() throws Exception {
void multipleTenant_group_nosubscribe_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
System.out.println(((NamingEvent) event).getServiceName());
instances = ((NamingEvent) event).getInstances();
}
};
naming1.subscribe(serviceName, TEST_GROUP_1, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
assertEquals(0, naming2.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener); //取消订阅服务没有订阅group
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(1, naming1.getSubscribeServices().size());
assertEquals(1, naming1.getSubscribeServices().size());
naming1.unsubscribe(serviceName, TEST_GROUP_1, listener); //取消订阅服务有订阅group
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(0, naming1.getSubscribeServices().size());
Assert.assertEquals(0, naming2.getSubscribeServices().size());
assertEquals(0, naming1.getSubscribeServices().size());
assertEquals(0, naming2.getSubscribeServices().size());
}
/**
* @TCDescription : 多租户,多group下, 多个group订阅查看服务的个数
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_unSubscribe() throws Exception {
void multipleTenant_group_unSubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent)event).getServiceName());
instances = ((NamingEvent)event).getInstances();
System.out.println(((NamingEvent) event).getServiceName());
instances = ((NamingEvent) event).getInstances();
}
};
naming1.subscribe(serviceName, Constants.DEFAULT_GROUP, listener);
naming1.subscribe(serviceName, TEST_GROUP_2, listener);
naming1.subscribe(serviceName, TEST_GROUP_1, listener);
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c1");
while (instances.size() == 0) {
TimeUnit.SECONDS.sleep(1L);
}
TimeUnit.SECONDS.sleep(2L);
Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
Assert.assertEquals(3, naming1.getSubscribeServices().size());
assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName());
assertEquals(3, naming1.getSubscribeServices().size());
naming1.unsubscribe(serviceName, listener);
naming1.unsubscribe(serviceName, TEST_GROUP_2, listener);
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(1, naming1.getSubscribeServices().size());
Assert.assertEquals(TEST_GROUP_1, naming1.getSubscribeServices().get(0).getGroupName());
assertEquals(1, naming1.getSubscribeServices().size());
assertEquals(TEST_GROUP_1, naming1.getSubscribeServices().get(0).getGroupName());
naming1.unsubscribe(serviceName, TEST_GROUP_1, listener);
}
/**
* @TCDescription : 多租户获取server状态
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_serverStatus() throws Exception {
Assert.assertEquals(TEST_SERVER_STATUS, naming1.getServerStatus());
Assert.assertEquals(TEST_SERVER_STATUS, naming2.getServerStatus());
void multipleTenant_serverStatus() throws Exception {
assertEquals(TEST_SERVER_STATUS, naming1.getServerStatus());
assertEquals(TEST_SERVER_STATUS, naming2.getServerStatus());
}
/**
* @TCDescription : 多租户删除实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_deregisterInstance() throws Exception {
void multipleTenant_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 1, serviceName);
Assert.assertEquals(1, naming1.getAllInstances(serviceName).size());
assertEquals(1, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(12);
Assert.assertEquals(0, naming1.getAllInstances(serviceName).size());
Assert.assertEquals(1, naming2.getAllInstances(serviceName).size());
assertEquals(0, naming1.getAllInstances(serviceName).size());
assertEquals(1, naming2.getAllInstances(serviceName).size());
}
/**
* @TCDescription : 多租户, 多group删除group不存在的实例
* @TestStep :
* @ExpectResult :
*/
@Test
@Ignore("nacos 2.0 deregister only judged by client and service")
public void multipleTenant_group_deregisterInstance() throws Exception {
@Disabled("nacos 2.0 deregister only judged by client and service")
void multipleTenant_group_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", TEST_PORT, "c1");
assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(12);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
assertEquals(2, naming1.getAllInstances(serviceName).size());
}
/**
* @TCDescription : 多租户, 多group删除clusterName不存在的实例
* @TestStep :
* @ExpectResult :
*/
@Test
@Ignore("nacos 2.0 deregister only judged by client and service")
public void multipleTenant_group_cluster_deregisterInstance() throws Exception {
@Disabled("nacos 2.0 deregister only judged by client and service")
void multipleTenant_group_cluster_deregisterInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 2, serviceName);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT);
TimeUnit.SECONDS.sleep(3L);
Assert.assertEquals(2, naming1.getAllInstances(serviceName).size());
assertEquals(2, naming1.getAllInstances(serviceName).size());
naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
}
/**
* @TCDescription : 多租户下选择一个健康的实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_selectOneHealthyInstance() throws Exception {
void multipleTenant_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2");
naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c3");
List<Instance> instances = naming1.getAllInstances(serviceName);
verifyInstanceListForNaming(naming1, 1, serviceName);
Assert.assertEquals(1, naming1.getAllInstances(serviceName).size());
assertEquals(1, naming1.getAllInstances(serviceName).size());
Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c2"));
Assert.assertEquals("22.22.22.22", instance.getIp());
assertEquals("22.22.22.22", instance.getIp());
naming2.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c3");
TimeUnit.SECONDS.sleep(5);
instance = naming1.selectOneHealthyInstance(serviceName);
Assert.assertEquals("22.22.22.22", instance.getIp());
assertEquals("22.22.22.22", instance.getIp());
}
/**
* @TCDescription : 多租户下多group下选择一个健康的实例
* @TestStep :
* @ExpectResult :
*/
@Test
public void multipleTenant_group_selectOneHealthyInstance() throws Exception {
void multipleTenant_group_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3");
naming1.registerInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2");
naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c3");
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
verifyInstanceListForNaming(naming1, 0, serviceName);
Assert.assertEquals(0, naming1.getAllInstances(serviceName).size()); //defalut group
assertEquals(0, naming1.getAllInstances(serviceName).size()); //defalut group
Instance instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP, Arrays.asList("c1"));
Assert.assertEquals("11.11.11.11", instance.getIp());
assertEquals("11.11.11.11", instance.getIp());
instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP_1);
Assert.assertEquals("22.22.22.22", instance.getIp());
assertEquals("22.22.22.22", instance.getIp());
naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
naming1.deregisterInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3");
naming1.deregisterInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2");
naming1.deregisterInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c3");
}
/**
* @TCDescription : 多租户下多group下选择group不存在一个健康的实例
* @TestStep :
* @ExpectResult :
*/
@Test(expected = IllegalStateException.class)
public void multipleTenant_noGroup_selectOneHealthyInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
verifyInstanceListForNaming(naming1, 0, serviceName);
Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1"));
naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2");
@Test
void multipleTenant_noGroup_selectOneHealthyInstance() throws Exception {
assertThrows(IllegalStateException.class, () -> {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.registerInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2");
List<Instance> instances = naming1.getAllInstances(serviceName, TEST_GROUP);
verifyInstanceListForNaming(naming1, 0, serviceName);
Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1"));
naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1");
naming1.deregisterInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2");
});
}
private void verifyInstanceListForNaming(NamingService naming, int size, String serviceName) throws Exception {
int i = 0;
while ( i < 20 ) {
while (i < 20) {
List<Instance> instances = naming.getAllInstances(serviceName);
if (instances.size() == size) {
break;

View File

@ -24,10 +24,8 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
@ -37,7 +35,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
@ -50,14 +47,17 @@ import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_1;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_2;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class MultiTenant_InstanceAPI_ITCase {
class MultiTenant_InstanceAPI_ITCase {
private final List<Instance> instances = Collections.emptyList();
private NamingService naming;
@ -73,10 +73,8 @@ public class MultiTenant_InstanceAPI_ITCase {
private URL base;
private final List<Instance> instances = Collections.emptyList();
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
NamingBase.prepareServer(port);
@ -110,7 +108,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_listInstance() throws Exception {
void multipleTenant_listInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -123,18 +121,17 @@ public class MultiTenant_InstanceAPI_ITCase {
String url = "/nacos/v1/ns/instance/list";
ResponseEntity<String> response = request(url,
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1")
.done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText());
assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText());
response = request(url, Params.newParams().appendParam("serviceName", serviceName).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
}
/**
@ -143,7 +140,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_group_listInstance() throws Exception {
void multipleTenant_group_listInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80);
@ -159,19 +156,18 @@ public class MultiTenant_InstanceAPI_ITCase {
ResponseEntity<String> response = request(url,
Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1")
.appendParam("groupName", TEST_GROUP_1).done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText());
assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText());
response = request(url,
Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1)
.done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request(url, Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1).done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
assertEquals(1, json.get("hosts").size());
assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
}
/**
@ -180,7 +176,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_getInstance() throws Exception {
void multipleTenant_getInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -192,18 +188,17 @@ public class MultiTenant_InstanceAPI_ITCase {
TimeUnit.SECONDS.sleep(5L);
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName)
.appendParam("ip", "33.33.33.33") //错误的IP隔离验证
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33") //错误的IP隔离验证
.appendParam("port", "8888").appendParam("namespaceId", "namespace-2").done(), String.class);
Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c1")
.appendParam("healthyOnly", "true").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c1").appendParam("healthyOnly", "true")
.done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
assertEquals(1, json.get("hosts").size());
assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
}
/**
@ -212,7 +207,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_group_getInstance() throws Exception {
void multipleTenant_group_getInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -228,15 +223,15 @@ public class MultiTenant_InstanceAPI_ITCase {
Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1)
.appendParam("ip", "33.33.33.33") //不存在的IP隔离验证
.appendParam("port", "8888").appendParam("namespaceId", "namespace-2").done(), String.class);
Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c2")
.appendParam("healthyOnly", "true").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c2").appendParam("healthyOnly", "true")
.done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
Assert.assertEquals("44.44.44.44", json.get("hosts").get(0).get("ip").asText());
assertEquals(1, json.get("hosts").size());
assertEquals("44.44.44.44", json.get("hosts").get(0).get("ip").asText());
}
/**
@ -245,7 +240,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_putInstance() throws Exception {
void multipleTenant_putInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -258,25 +253,23 @@ public class MultiTenant_InstanceAPI_ITCase {
TimeUnit.SECONDS.sleep(5L);
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33")
.appendParam("port", "8888").done(), String.class, HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888")
.done(), String.class, HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
//namespace-2个数
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
System.out.println(json);
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
}
/**
@ -285,7 +278,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_group_putInstance() throws Exception {
void multipleTenant_group_putInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -293,20 +286,17 @@ public class MultiTenant_InstanceAPI_ITCase {
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2)
.appendParam("ip", "22.22.22.22").appendParam("port", "80")
.appendParam("namespaceId", "namespace-2").appendParam("weight", "8.0").done(), String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
.appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2")
.appendParam("weight", "8.0").done(), String.class, HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
TimeUnit.SECONDS.sleep(5L);
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
Assert.assertEquals("8.0", json.get("hosts").get(0).get("weight").asText());
assertEquals(1, json.get("hosts").size());
assertEquals("8.0", json.get("hosts").get(0).get("weight").asText());
}
/**
@ -315,7 +305,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_group_patchInstance() throws Exception {
void multipleTenant_group_patchInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -325,27 +315,24 @@ public class MultiTenant_InstanceAPI_ITCase {
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2)
.appendParam("ip", "22.22.22.22").appendParam("port", "80")
.appendParam("namespaceId", "namespace-2").appendParam("weight", "8.0").done(), String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
.appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2")
.appendParam("weight", "8.0").done(), String.class, HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2)
.appendParam("ip", "22.22.22.22").appendParam("port", "80")
.appendParam("namespaceId", "namespace-2").done(), String.class, HttpMethod.PATCH);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
.appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2").done(),
String.class, HttpMethod.PATCH);
assertTrue(response.getStatusCode().is2xxSuccessful());
TimeUnit.SECONDS.sleep(3L);
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
Assert.assertEquals("8.0", json.get("hosts").get(0).get("weight").asText());
assertEquals(1, json.get("hosts").size());
assertEquals("8.0", json.get("hosts").get(0).get("weight").asText());
}
/**
@ -354,7 +341,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_updateInstance_notExsitInstance() throws Exception {
void multipleTenant_updateInstance_notExsitInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -365,26 +352,24 @@ public class MultiTenant_InstanceAPI_ITCase {
naming.registerInstance(serviceName, "44.44.44.44", 8888);
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33")
.appendParam("port", "8888").appendParam("namespaceId", "namespace-1") //新增
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888")
.appendParam("namespaceId", "namespace-1") //新增
.done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
TimeUnit.SECONDS.sleep(5L);
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(2, json.get("hosts").size());
assertEquals(2, json.get("hosts").size());
//namespace-2个数
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
}
/**
@ -393,7 +378,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_group_updateInstance_notExsitInstance() throws Exception {
void multipleTenant_group_updateInstance_notExsitInstance() throws Exception {
String serviceName = randomDomainName();
naming1.registerInstance(serviceName, "11.11.11.11", 80);
@ -401,20 +386,18 @@ public class MultiTenant_InstanceAPI_ITCase {
TimeUnit.SECONDS.sleep(5L);
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33")
.appendParam("port", "8888").appendParam("namespaceId", "namespace-1") //新增
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888")
.appendParam("namespaceId", "namespace-1") //新增
.appendParam("groupName", TEST_GROUP_1).done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").appendParam("groupName", TEST_GROUP_1).done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").appendParam("groupName", TEST_GROUP_1).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
String body = response.getBody();
System.out.println("multipleTenant_group_updateInstance_notExsitInstance received body: " + body);
JsonNode json = JacksonUtils.toObj(body);
Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText());
}
/**
@ -423,7 +406,7 @@ public class MultiTenant_InstanceAPI_ITCase {
* @ExpectResult :
*/
@Test
public void multipleTenant_updateInstance() throws Exception {
void multipleTenant_updateInstance() throws Exception {
String serviceName = randomDomainName();
naming2.registerInstance(serviceName, "22.22.22.22", 80);
@ -434,25 +417,23 @@ public class MultiTenant_InstanceAPI_ITCase {
TimeUnit.SECONDS.sleep(5L);
ResponseEntity<String> response = request("/nacos/v1/ns/instance",
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11")
.appendParam("port", "80").appendParam("namespaceId", "namespace-1") //新增
Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11").appendParam("port", "80")
.appendParam("namespaceId", "namespace-1") //新增
.done(), String.class, HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-1").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
//namespace-2个数
response = request("/nacos/v1/ns/instance/list",
Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例
.appendParam("namespaceId", "namespace-2").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, json.get("hosts").size());
assertEquals(1, json.get("hosts").size());
}
private void verifyInstanceListForNaming(NamingService naming, int size, String serviceName) throws Exception {
@ -472,15 +453,13 @@ public class MultiTenant_InstanceAPI_ITCase {
return request(path, params, clazz, HttpMethod.GET);
}
private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz,
HttpMethod httpMethod) {
private <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);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params);
return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz);
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.api.naming.pojo.Instance;
@ -24,46 +25,60 @@ import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.test.base.HttpClient4Test;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author nkorange
*/
public class NamingBase extends HttpClient4Test {
private static final NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getInstance().getNacosRestTemplate();
public static final String TEST_DOM_1 = "nacos.test.1";
public static final String TEST_IP_4_DOM_1 = "127.0.0.1";
public static final String TEST_PORT_4_DOM_1 = "8080";
public static final String TEST_PORT2_4_DOM_1 = "8888";
public static final String TEST_PORT3_4_DOM_1 = "80";
public static final String TEST_TOKEN_4_DOM_1 = "abc";
public static final String TEST_NEW_CLUSTER_4_DOM_1 = "TEST1";
public static final String TEST_DOM_2 = "nacos.test.2";
public static final String TEST_IP_4_DOM_2 = "127.0.0.2";
public static final String TEST_PORT_4_DOM_2 = "7070";
public static final String TETS_TOKEN_4_DOM_2 = "xyz";
public static final String TEST_SERVER_STATUS = "UP";
public static final String TEST_GROUP = "group";
public static final String TEST_GROUP_1 = "group1";
public static final String TEST_GROUP_2 = "group2";
public static final String TEST_NAMESPACE_1 = "namespace-1";
public static final String TEST_NAMESPACE_2 = "namespace-2";
static final String NAMING_CONTROLLER_PATH = "/nacos/v1/ns";
public static final int TEST_PORT = 8080;
public static final int TIME_OUT = 3000;
static final String NAMING_CONTROLLER_PATH = "/nacos/v1/ns";
private static final NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getInstance().getNacosRestTemplate();
public static String randomDomainName() {
StringBuilder sb = new StringBuilder();
sb.append("jinhan");
@ -79,7 +94,7 @@ public class NamingBase extends HttpClient4Test {
}
return sb.toString();
}
public static Instance getInstance(String serviceName) {
Instance instance = new Instance();
instance.setIp("127.0.0.1");
@ -89,21 +104,20 @@ public class NamingBase extends HttpClient4Test {
Map<String, String> instanceMeta = new HashMap<String, String>();
instanceMeta.put("site", "et2");
instance.setMetadata(instanceMeta);
instance.setServiceName(serviceName);
instance.setClusterName("c1");
return instance;
}
public static boolean verifyInstance(Instance i1, Instance i2) {
if (!i1.getIp().equals(i2.getIp()) || i1.getPort() != i2.getPort() ||
i1.getWeight() != i2.getWeight() || i1.isHealthy() != i2.isHealthy() ||
!i1.getMetadata().equals(i2.getMetadata())) {
if (!i1.getIp().equals(i2.getIp()) || i1.getPort() != i2.getPort() || i1.getWeight() != i2.getWeight()
|| i1.isHealthy() != i2.isHealthy() || !i1.getMetadata().equals(i2.getMetadata())) {
return false;
}
//Service service1 = i1.getService();
//Service service2 = i2.getService();
//
@ -114,7 +128,7 @@ public class NamingBase extends HttpClient4Test {
// service1.isEnableHealthCheck() != service2.isEnableHealthCheck()) {
// return false;
//}
//Cluster cluster1 = i1.getCluster();
//Cluster cluster2 = i2.getCluster();
//
@ -145,22 +159,22 @@ public class NamingBase extends HttpClient4Test {
// return false;
// }
//}
return true;
}
public static boolean verifyInstanceList(List<Instance> instanceList1, List<Instance> instanceList2) {
Map<String, Instance> instanceMap = new HashMap<String, Instance>();
for (Instance instance : instanceList1) {
instanceMap.put(instance.getIp(), instance);
}
Map<String, Instance> instanceGetMap = new HashMap<String, Instance>();
for (Instance instance : instanceList2) {
instanceGetMap.put(instance.getIp(), instance);
}
for (String ip : instanceMap.keySet()) {
if (!instanceGetMap.containsKey(ip)) {
return false;
@ -171,42 +185,45 @@ public class NamingBase extends HttpClient4Test {
}
return true;
}
public static void prepareServer(int localPort) throws Exception{
public static void prepareServer(int localPort) throws Exception {
prepareServer(localPort, "UP", "/nacos");
}
public static void prepareServer(int localPort,String contextPath) throws Exception{
public static void prepareServer(int localPort, String contextPath) throws Exception {
prepareServer(localPort, "UP", contextPath);
}
public static void prepareServer(int localPort, String status,String contextPath) throws Exception {
String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=overriddenServerStatus&value=" + status;
public static void prepareServer(int localPort, String status, String contextPath) throws Exception {
String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath)
+ "/v1/ns/operator/switches?entry=overriddenServerStatus&value=" + status;
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
HttpRestResult<String> result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class);
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false;
assertEquals(HttpStatus.SC_OK, result.getCode());
url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath)
+ "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false;
result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class);
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
assertEquals(HttpStatus.SC_OK, result.getCode());
}
public static void destoryServer(int localPort) throws Exception{
public static void destoryServer(int localPort) throws Exception {
destoryServer(localPort, "/nacos");
}
public static void destoryServer(int localPort, String contextPath) throws Exception{
String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true;
public static void destoryServer(int localPort, String contextPath) throws Exception {
String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath)
+ "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true;
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
HttpRestResult<String> result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class);
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
assertEquals(HttpStatus.SC_OK, result.getCode());
}
public static String normalizeContextPath(String contextPath) {

View File

@ -28,14 +28,11 @@ import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.List;
@ -43,6 +40,8 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* NamingCompatibilityServiceTls_ITCase.
@ -50,13 +49,11 @@ import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
* @author githucheng2978.
* @date .
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=true",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=true",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NamingCompatibilityServiceTls_ITCase {
class NamingCompatibilityServiceTls_ITCase {
private NamingMaintainService namingMaintainService;
@ -69,8 +66,8 @@ public class NamingCompatibilityServiceTls_ITCase {
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
NamingBase.prepareServer(port);
@ -99,7 +96,7 @@ public class NamingCompatibilityServiceTls_ITCase {
}
@Test
public void updateInstance() throws NacosException, InterruptedException {
void updateInstance() throws NacosException, InterruptedException {
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
@ -108,13 +105,13 @@ public class NamingCompatibilityServiceTls_ITCase {
namingMaintainService.updateInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(3L);
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version"));
assertEquals(1, instances.size());
assertEquals("2.0", instances.get(0).getMetadata().get("version"));
System.out.println(instances.get(0));
}
@Test
public void updateInstanceWithDisable() throws NacosException, InterruptedException {
void updateInstanceWithDisable() throws NacosException, InterruptedException {
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
@ -124,11 +121,11 @@ public class NamingCompatibilityServiceTls_ITCase {
namingMaintainService.updateInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(3L);
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
@Test
public void createAndUpdateService() throws NacosException {
void createAndUpdateService() throws NacosException {
String serviceName = randomDomainName();
// register service
Service preService = new Service();
@ -145,7 +142,7 @@ public class NamingCompatibilityServiceTls_ITCase {
namingMaintainService.createService(preService, selector);
Service remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(preService.toString(), remoteService.toString());
assertEquals(preService.toString(), remoteService.toString());
// update service
Service nowService = new Service();
@ -159,22 +156,22 @@ public class NamingCompatibilityServiceTls_ITCase {
namingMaintainService.updateService(nowService, new NoneSelector());
remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(nowService.toString(), remoteService.toString());
assertEquals(nowService.toString(), remoteService.toString());
}
@Test
public void deleteService() throws NacosException {
void deleteService() throws NacosException {
String serviceName = randomDomainName();
Service preService = new Service();
preService.setName(serviceName);
System.out.println("service info : " + preService);
namingMaintainService.createService(preService, new NoneSelector());
Assert.assertTrue(namingMaintainService.deleteService(serviceName));
assertTrue(namingMaintainService.deleteService(serviceName));
}
@After
public void tearDown() throws NacosException {
@AfterEach
void tearDown() throws NacosException {
namingMaintainService.shutDown();
namingService.shutDown();
}

View File

@ -27,14 +27,11 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.List;
@ -42,39 +39,43 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author liaochuntao
* @date 2019-05-07 10:13
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class NamingMaintainService_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class NamingMaintainService_ITCase {
private NamingMaintainService namingMaintainService;
private NamingService namingService;
private Instance instance;
private String serviceName;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
NamingBase.prepareServer(port);
if (namingMaintainService == null) {
TimeUnit.SECONDS.sleep(10);
namingMaintainService = NamingMaintainFactory.createMaintainService("127.0.0.1" + ":" + port);
}
if (namingService == null) {
TimeUnit.SECONDS.sleep(10);
namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
@ -84,13 +85,13 @@ public class NamingMaintainService_ITCase {
map.put("netType", "external");
map.put("version", "1.0");
instance.setMetadata(map);
serviceName = randomDomainName();
}
@Test
public void updateInstance() throws NacosException, InterruptedException {
void updateInstance() throws NacosException, InterruptedException {
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
@ -99,13 +100,13 @@ public class NamingMaintainService_ITCase {
namingMaintainService.updateInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(3L);
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version"));
assertEquals(1, instances.size());
assertEquals("2.0", instances.get(0).getMetadata().get("version"));
System.out.println(instances.get(0));
}
@Test
public void updateInstanceWithDisable() throws NacosException, InterruptedException {
void updateInstanceWithDisable() throws NacosException, InterruptedException {
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
@ -115,11 +116,11 @@ public class NamingMaintainService_ITCase {
namingMaintainService.updateInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(3L);
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
}
@Test
public void createAndUpdateService() throws NacosException {
void createAndUpdateService() throws NacosException {
String serviceName = randomDomainName();
// register service
Service preService = new Service();
@ -131,13 +132,13 @@ public class NamingMaintainService_ITCase {
preService.setMetadata(metadata);
ExpressionSelector selector = new ExpressionSelector();
selector.setExpression("CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B");
System.out.println("service info : " + preService);
namingMaintainService.createService(preService, selector);
Service remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(preService.toString(), remoteService.toString());
assertEquals(preService.toString(), remoteService.toString());
// update service
Service nowService = new Service();
nowService.setName(serviceName);
@ -146,26 +147,26 @@ public class NamingMaintainService_ITCase {
metadata.clear();
metadata.put(serviceName, "this is a update metadata");
nowService.setMetadata(metadata);
namingMaintainService.updateService(nowService, new NoneSelector());
remoteService = namingMaintainService.queryService(serviceName);
System.out.println("remote service info : " + remoteService);
Assert.assertEquals(nowService.toString(), remoteService.toString());
assertEquals(nowService.toString(), remoteService.toString());
}
@Test
public void deleteService() throws NacosException {
void deleteService() throws NacosException {
String serviceName = randomDomainName();
Service preService = new Service();
preService.setName(serviceName);
System.out.println("service info : " + preService);
namingMaintainService.createService(preService, new NoneSelector());
Assert.assertTrue(namingMaintainService.deleteService(serviceName));
assertTrue(namingMaintainService.deleteService(serviceName));
}
@After
public void tearDown() throws NacosException {
@AfterEach
void tearDown() throws NacosException {
namingMaintainService.shutDown();
namingService.shutDown();
}

View File

@ -19,47 +19,49 @@ package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.test.base.BaseClusterTest;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@Ignore
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class NamingRaft_DITCase extends BaseClusterTest {
@Test
public void test_register_instance() throws Exception {
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setEphemeral(true); //是否临时实例
instance.setServiceName(serviceName);
instance.setClusterName("c1");
instance.setIp("11.11.11.11");
instance.setPort(80);
try {
inaming7.registerInstance(serviceName, instance);
} catch (Throwable ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
return;
}
List<Instance> list = inaming8.getAllInstances(serviceName);
Assert.assertEquals(1, list.size());
Instance host = list.get(0);
Assert.assertEquals(host.getIp(), instance.getIp());
Assert.assertEquals(host.getPort(), instance.getPort());
Assert.assertEquals(host.getServiceName(), NamingUtils.getGroupedName(instance.getServiceName(), "DEFAULT_GROUP"));
Assert.assertEquals(host.getClusterName(), instance.getClusterName());
}
@Disabled
@TestMethodOrder(MethodName.class)
class NamingRaft_DITCase extends BaseClusterTest {
@Test
void test_register_instance() throws Exception {
String serviceName = NamingBase.randomDomainName();
Instance instance = new Instance();
instance.setEphemeral(true); //是否临时实例
instance.setServiceName(serviceName);
instance.setClusterName("c1");
instance.setIp("11.11.11.11");
instance.setPort(80);
try {
inaming7.registerInstance(serviceName, instance);
} catch (Throwable ex) {
ex.printStackTrace();
fail(ex.getMessage());
return;
}
List<Instance> list = inaming8.getAllInstances(serviceName);
assertEquals(1, list.size());
Instance host = list.get(0);
assertEquals(host.getIp(), instance.getIp());
assertEquals(host.getPort(), instance.getPort());
assertEquals(host.getServiceName(), NamingUtils.getGroupedName(instance.getServiceName(), "DEFAULT_GROUP"));
assertEquals(host.getClusterName(), instance.getClusterName());
}
}

View File

@ -23,16 +23,13 @@ import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import org.junit.After;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
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.List;
@ -40,6 +37,8 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* NamingTlsServiceAndMutualAuth_ITCase.
@ -47,24 +46,21 @@ import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
* @author githucheng2978.
* @date .
**/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@TestMethodOrder(MethodName.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC
+ ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Ignore("TODO, Fix cert expired problem")
public class NamingTlsServiceAndMutualAuth_ITCase {
@Disabled("TODO, Fix cert expired problem")
class NamingTlsServiceAndMutualAuth_ITCase {
@LocalServerPort
private int port;
@Test
public void test_a_MutualAuth() throws NacosException {
void test_a_MutualAuth() throws NacosException {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem");
@ -88,60 +84,65 @@ public class NamingTlsServiceAndMutualAuth_ITCase {
throw new RuntimeException(e);
}
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version"));
assertEquals(1, instances.size());
assertEquals("2.0", instances.get(0).getMetadata().get("version"));
namingService.shutDown();
}
@Test(expected = NacosException.class)
public void test_b_MutualAuthClientTrustCa() throws NacosException {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem");
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
instance.setMetadata(map);
namingService.registerInstance(serviceName, instance);
namingService.shutDown();
@Test
void test_b_MutualAuthClientTrustCa() throws NacosException {
assertThrows(NacosException.class, () -> {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem");
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
instance.setMetadata(map);
namingService.registerInstance(serviceName, instance);
namingService.shutDown();
});
}
@Test(expected = NacosException.class)
public void test_c_MutualAuthClientTrustALl() throws NacosException {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true");
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
instance.setMetadata(map);
namingService.registerInstance(serviceName, instance);
namingService.shutDown();
@Test
void test_c_MutualAuthClientTrustALl() throws NacosException {
assertThrows(NacosException.class, () -> {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true");
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
instance.setMetadata(map);
namingService.registerInstance(serviceName, instance);
namingService.shutDown();
});
}
@After
public void after() {
@AfterEach
void after() {
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "");
}
}

View File

@ -23,15 +23,12 @@ import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.remote.client.RpcConstants;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer.MethodName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
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.List;
@ -39,6 +36,8 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* NamingTlsServiceTls_ITCase.
@ -46,39 +45,40 @@ import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
* @author githucheng2978.
* @date .
**/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@TestMethodOrder(MethodName.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos",
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true",
RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC
+ ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Ignore("TODO, Fix cert expired problem")
public class NamingTlsServiceTls_ITCase {
RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=false",
RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem",
RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Disabled("TODO, Fix cert expired problem")
class NamingTlsServiceTls_ITCase {
@LocalServerPort
private int port;
@Test(expected = NacosException.class)
public void Tls_a_ServerAndPlainClient() throws NacosException {
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
namingService.registerInstance(randomDomainName(), instance);
namingService.shutDown();
@Test
void Tls_a_ServerAndPlainClient() throws NacosException {
assertThrows(NacosException.class, () -> {
Instance instance = new Instance();
instance.setIp("127.0.0.1");
instance.setPort(8081);
instance.setWeight(2);
instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME);
NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
Map<String, String> map = new HashMap<String, String>();
map.put("netType", "external-update");
map.put("version", "2.0");
namingService.registerInstance(randomDomainName(), instance);
namingService.shutDown();
});
}
@Test
public void Tls_b_ServerAndTlsClientTrustCa() throws NacosException {
void Tls_b_ServerAndTlsClientTrustCa() throws NacosException {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem");
@ -100,14 +100,14 @@ public class NamingTlsServiceTls_ITCase {
throw new RuntimeException(e);
}
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version"));
assertEquals(1, instances.size());
assertEquals("2.0", instances.get(0).getMetadata().get("version"));
namingService.shutDown();
}
@Test
public void Tls_c_ServerAndTlsClientAll() throws NacosException {
void Tls_c_ServerAndTlsClientAll() throws NacosException {
String serviceName = randomDomainName();
System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true");
@ -128,8 +128,8 @@ public class NamingTlsServiceTls_ITCase {
throw new RuntimeException(e);
}
List<Instance> instances = namingService.getAllInstances(serviceName, false);
Assert.assertEquals(instances.size(), 1);
Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version"));
assertEquals(1, instances.size());
assertEquals("2.0", instances.get(0).getMetadata().get("version"));
System.out.println(instances.get(0));
namingService.shutDown();
}

View File

@ -13,9 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import java.util.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
/**
* Created by wangtong.wt on 2018/6/20.
@ -24,39 +29,43 @@ import java.util.*;
* @date 2018/6/20
*/
public class RandomUtils {
private static final String STRING_POOL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random rd = new Random();
private static int UNICODE_START = 19968;
private static int UNICODE_END = 40864;
private static final String STRING_POOL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private RandomUtils() {
}
public static long getLong() {
return rd.nextLong();
}
public static long getLongMoreThanZero() {
long res;
for(res = rd.nextLong(); res <= 0L; res = rd.nextLong()) {
for (res = rd.nextLong(); res <= 0L; res = rd.nextLong()) {
}
return res;
}
public static long getLongLessThan(long n) {
long res = rd.nextLong();
return res % n;
}
public static long getLongMoreThanZeroLessThan(long n) {
long res;
for(res = getLongLessThan(n); res <= 0L; res = getLongLessThan(n)) {
for (res = getLongLessThan(n); res <= 0L; res = getLongLessThan(n)) {
}
return res;
}
public static long getLongBetween(long n, long m) {
if (m <= n) {
return n;
@ -65,32 +74,32 @@ public class RandomUtils {
return n + res % (m - n);
}
}
public static int getInteger() {
return rd.nextInt();
}
public static int getIntegerMoreThanZero() {
int res;
for(res = rd.nextInt(); res <= 0; res = rd.nextInt()) {
for (res = rd.nextInt(); res <= 0; res = rd.nextInt()) {
}
return res;
}
public static int getIntegerLessThan(int n) {
int res = rd.nextInt();
return res % n;
}
public static int getIntegerMoreThanZeroLessThan(int n) {
int res;
for(res = rd.nextInt(n); res == 0; res = rd.nextInt(n)) {
for (res = rd.nextInt(n); res == 0; res = rd.nextInt(n)) {
}
return res;
}
public static int getIntegerBetween(int n, int m) {
if (m == n) {
return n;
@ -99,71 +108,71 @@ public class RandomUtils {
return n + res % (m - n);
}
}
private static char getChar(int[] arg) {
int size = arg.length;
int c = rd.nextInt(size / 2);
c *= 2;
return (char)getIntegerBetween(arg[c], arg[c + 1]);
return (char) getIntegerBetween(arg[c], arg[c + 1]);
}
private static String getString(int n, int[] arg) {
StringBuilder res = new StringBuilder();
for(int i = 0; i < n; ++i) {
for (int i = 0; i < n; ++i) {
res.append(getChar(arg));
}
return res.toString();
}
public static String getStringWithCharacter(int n) {
int[] arg = new int[]{97, 123, 65, 91};
int[] arg = new int[] {97, 123, 65, 91};
return getString(n, arg);
}
public static String getStringWithNumber(int n) {
int[] arg = new int[]{48, 58};
int[] arg = new int[] {48, 58};
return getString(n, arg);
}
public static String getStringWithNumAndCha(int n) {
int[] arg = new int[]{97, 123, 65, 91, 48, 58};
int[] arg = new int[] {97, 123, 65, 91, 48, 58};
return getString(n, arg);
}
public static String getRandomString(int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
int range = STRING_POOL.length();
for(int i = 0; i < length; ++i) {
for (int i = 0; i < length; ++i) {
sb.append(STRING_POOL.charAt(random.nextInt(range)));
}
return sb.toString();
}
public static String getStringShortenThan(int n) {
int len = getIntegerMoreThanZeroLessThan(n);
return getStringWithCharacter(len);
}
public static String getStringWithNumAndChaShortenThan(int n) {
int len = getIntegerMoreThanZeroLessThan(n);
return getStringWithNumAndCha(len);
}
public static String getStringBetween(int n, int m) {
int len = getIntegerBetween(n, m);
return getStringWithCharacter(len);
}
public static String getStringWithNumAndChaBetween(int n, int m) {
int len = getIntegerBetween(n, m);
return getStringWithNumAndCha(len);
}
public static String getStringWithPrefix(int n, String prefix) {
int len = prefix.length();
if (n <= len) {
@ -175,7 +184,7 @@ public class RandomUtils {
return res.toString();
}
}
public static String getStringWithSuffix(int n, String suffix) {
int len = suffix.length();
if (n <= len) {
@ -188,7 +197,7 @@ public class RandomUtils {
return res.toString();
}
}
public static String getStringWithBoth(int n, String prefix, String suffix) {
int len = prefix.length() + suffix.length();
StringBuilder res = new StringBuilder(prefix);
@ -201,7 +210,7 @@ public class RandomUtils {
return res.toString();
}
}
public static String getCheseWordWithPrifix(int n, String prefix) {
int len = prefix.length();
if (n <= len) {
@ -213,7 +222,7 @@ public class RandomUtils {
return res.toString();
}
}
public static String getCheseWordWithSuffix(int n, String suffix) {
int len = suffix.length();
if (n <= len) {
@ -226,7 +235,7 @@ public class RandomUtils {
return res.toString();
}
}
public static String getCheseWordWithBoth(int n, String prefix, String suffix) {
int len = prefix.length() + suffix.length();
StringBuilder res = new StringBuilder(prefix);
@ -239,89 +248,89 @@ public class RandomUtils {
return res.toString();
}
}
public static String getCheseWord(int len) {
StringBuilder res = new StringBuilder();
for(int i = 0; i < len; ++i) {
for (int i = 0; i < len; ++i) {
char str = getCheseChar();
res.append(str);
}
return res.toString();
}
private static char getCheseChar() {
return (char)(UNICODE_START + rd.nextInt(UNICODE_END - UNICODE_START));
return (char) (UNICODE_START + rd.nextInt(UNICODE_END - UNICODE_START));
}
public static boolean getBoolean() {
return getIntegerMoreThanZeroLessThan(3) == 1;
}
public static String getStringByUUID() {
return UUID.randomUUID().toString();
}
public static int[] getRandomArray(int min, int max, int n) {
int len = max - min + 1;
if (max >= min && n <= len) {
int[] source = new int[len];
for(int i = min; i < min + len; source[i - min] = i++) {
for (int i = min; i < min + len; source[i - min] = i++) {
}
int[] result = new int[n];
Random rd = new Random();
for(int i = 0; i < result.length; ++i) {
for (int i = 0; i < result.length; ++i) {
int index = Math.abs(rd.nextInt() % len--);
result[i] = source[index];
source[index] = source[len];
}
return result;
} else {
return null;
}
}
public static Collection<Integer> getRandomCollection(int min, int max, int n) {
Set<Integer> res = new HashSet();
int mx = max;
int mn = min;
int i;
if (n == max + 1 - min) {
for(i = 1; i <= n; ++i) {
for (i = 1; i <= n; ++i) {
res.add(i);
}
return res;
} else {
for(i = 0; i < n; ++i) {
for (i = 0; i < n; ++i) {
int v = getIntegerBetween(mn, mx);
if (v == mx) {
--mx;
}
if (v == mn) {
++mn;
}
while(res.contains(v)) {
while (res.contains(v)) {
v = getIntegerBetween(mn, mx);
if (v == mx) {
mx = v;
}
if (v == mn) {
mn = v;
}
}
res.add(v);
}
return res;
}
}

View File

@ -13,253 +13,206 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class RestAPI_ITCase extends NamingBase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class RestAPI_ITCase extends NamingBase {
@LocalServerPort
private int port;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
String url = String.format("http://localhost:%d/", port);
this.base = new URL(url);
//prepareData();
}
@After
public void cleanup() throws Exception {
@AfterEach
void cleanup() throws Exception {
//removeData();
}
@Test
public void metrics() throws Exception {
void metrics() throws Exception {
ResponseEntity<String> response = request("/nacos/v1/ns/operator/metrics",
Params.newParams().appendParam("onlyStatus", "false").done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("onlyStatus", "false").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertNotNull(json.get("serviceCount"));
Assert.assertNotNull(json.get("instanceCount"));
Assert.assertNotNull(json.get("responsibleInstanceCount"));
Assert.assertNotNull(json.get("clientCount"));
Assert.assertNotNull(json.get("connectionBasedClientCount"));
Assert.assertNotNull(json.get("ephemeralIpPortClientCount"));
Assert.assertNotNull(json.get("persistentIpPortClientCount"));
Assert.assertNotNull(json.get("responsibleClientCount"));
assertNotNull(json.get("serviceCount"));
assertNotNull(json.get("instanceCount"));
assertNotNull(json.get("responsibleInstanceCount"));
assertNotNull(json.get("clientCount"));
assertNotNull(json.get("connectionBasedClientCount"));
assertNotNull(json.get("ephemeralIpPortClientCount"));
assertNotNull(json.get("persistentIpPortClientCount"));
assertNotNull(json.get("responsibleClientCount"));
}
/**
* @TCDescription : 根据serviceName创建服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void createService() throws Exception {
void createService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3").done(), String.class,
HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
namingServiceDelete(serviceName);
}
/**
* @TCDescription : 根据serviceName获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void getService() throws Exception {
void getService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3").done(), String.class,
HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
//get service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3").done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(serviceName, json.get("name").asText());
assertEquals(serviceName, json.get("name").asText());
namingServiceDelete(serviceName);
}
/**
* @TCDescription : 获取服务list信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void listService() throws Exception {
void listService() throws Exception {
String serviceName = NamingBase.randomDomainName();
//get service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("pageNo", "1")
.appendParam("pageSize", "150")
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "150").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
int count = json.get("count").asInt();
Assert.assertTrue(count >= 0);
assertTrue(count >= 0);
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3").done(), String.class,
HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("pageNo", "1")
.appendParam("pageSize", "150")
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "150").done(),
String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
json = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(count + 1, json.get("count").asInt());
assertEquals(count + 1, json.get("count").asInt());
namingServiceDelete(serviceName);
}
/**
* @TCDescription : 更新serviceName获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void updateService() throws Exception {
void updateService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6").done(), String.class,
HttpMethod.POST);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
//update service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("healthCheckMode", "server")
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("healthCheckMode", "server")
.appendParam("protectThreshold", "0.3").done(), String.class, HttpMethod.PUT);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
//get service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Params.newParams().appendParam("serviceName", serviceName).done(), String.class);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode json = JacksonUtils.toObj(response.getBody());
System.out.println(json);
Assert.assertEquals(0.3f, json.get("protectThreshold").floatValue(), 0.0f);
assertEquals(0.3f, json.get("protectThreshold").floatValue(), 0.0f);
namingServiceDelete(serviceName);
}
@Test
@Ignore
public void testInvalidNamespace() {
@Disabled
void testInvalidNamespace() {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "..invalid-namespace")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is4xxClientError());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "..invalid-namespace").done(), String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is4xxClientError());
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "/invalid-namespace")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is4xxClientError());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "/invalid-namespace").done(), String.class, HttpMethod.POST);
assertTrue(response.getStatusCode().is4xxClientError());
}
private void namingServiceDelete(String serviceName) {
//delete service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.3")
.done(),
String.class,
HttpMethod.DELETE);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3").done(), String.class,
HttpMethod.DELETE);
assertTrue(response.getStatusCode().is2xxSuccessful());
assertEquals("ok", response.getBody());
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
@ -22,15 +23,12 @@ import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
@ -38,7 +36,11 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Created by wangtong.wt on 2018/6/20.
@ -46,19 +48,29 @@ import static com.alibaba.nacos.test.naming.NamingBase.*;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SelectInstances_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class SelectInstances_ITCase {
private static NamingService naming;
private static NamingService naming1;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
@AfterAll
static void tearDown() throws NacosException {
if (null != naming) {
naming.shutDown();
}
if (null != naming1) {
naming1.shutDown();
}
}
@BeforeEach
void init() throws Exception {
NamingBase.prepareServer(port);
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
@ -67,7 +79,7 @@ public class SelectInstances_ITCase {
}
int i = 5;
while (i >= 0) {
i --;
i--;
if (!"UP".equals(naming.getServerStatus())) {
Thread.sleep(1000L);
continue;
@ -76,33 +88,23 @@ public class SelectInstances_ITCase {
}
}
@AfterClass
public static void tearDown() throws NacosException {
if (null != naming) {
naming.shutDown();
}
if (null != naming1) {
naming1.shutDown();
}
}
/**
* 获取所有健康的Instance
*
* @throws Exception
*/
@Test
public void selectHealthyInstances() throws Exception {
void selectHealthyInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT);
naming1.registerInstance(serviceName, "1.1.1.1", 9090);
TimeUnit.SECONDS.sleep(10);
List<Instance> instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(2, instances.size());
assertEquals(2, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance : instancesGet) {
@ -110,316 +112,316 @@ public class SelectInstances_ITCase {
instanceNotH = instance;
}
}
instancesGet.remove(instanceNotH);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取所有不健康的Instance
*
* @throws Exception
*/
@Test
public void selectUnhealthyInstances() throws Exception {
void selectUnhealthyInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT);
naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT);
TimeUnit.SECONDS.sleep(8);
List<Instance> instances = naming.selectInstances(serviceName, false);
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
List<Instance> instancesGet = naming.getAllInstances(serviceName);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取指定cluster中单个多个所有健康的Instance
*
* @throws Exception
*/
@Test
public void selectHealthyInstancesClusters() throws Exception {
void selectHealthyInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "127.0.0.2", 9090, "c2");
TimeUnit.SECONDS.sleep(8);
List<Instance> instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true);
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(instances.size(), 2);
assertEquals(2, instances.size());
List<Instance> instancesGet = naming.getAllInstances(serviceName);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取指定cluster中单个多个不所有健康的Instance
*
* @throws Exception
*/
@Test
public void selectUnhealthyInstancesClusters() throws Exception {
void selectUnhealthyInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT, "c2");
TimeUnit.SECONDS.sleep(8);
List<Instance> instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), false);
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(0, instances.size());
assertEquals(0, instances.size());
List<Instance> instancesGet = naming.getAllInstances(serviceName);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
@Test
public void selectInstancesCheckClusterName() throws Exception {
void selectInstancesCheckClusterName() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT, "c2");
TimeUnit.SECONDS.sleep(8);
List<Instance> instancesGet = naming.getAllInstances(serviceName);
Assert.assertEquals(2, instancesGet.size());
assertEquals(2, instancesGet.size());
for (Instance instance : instancesGet) {
if (instance.getIp().equals("1.1.1.1")) {
Assert.assertEquals(instance.getClusterName(), "c1");
assertEquals("c1", instance.getClusterName());
}
if (instance.getIp().equals("2.2.2.2")) {
Assert.assertEquals(instance.getClusterName(), "c2");
assertEquals("c2", instance.getClusterName());
}
}
}
/**
* 获取权重不为0的Instance
*
* @throws Exception
*/
@Test
public void selectAllWeightedInstances() throws Exception {
void selectAllWeightedInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT);
naming1.registerInstance(serviceName, "1.1.1.1", 9090);
TimeUnit.SECONDS.sleep(10);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 2);
assertEquals(2, instances.size());
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(2, instances.size());
assertEquals(2, instances.size());
instances.get(0).setWeight(0);
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance : instancesGet) {
if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) {
instanceNotH = instance;
}
}
instancesGet.remove(instanceNotH);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取指定cluster中单个多个所有权重不为0的Instance
*
* @throws Exception
*/
@Test
public void selectAllWeightedInstancesClusters() throws Exception {
void selectAllWeightedInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "1.1.1.1", 9090, "c2");
TimeUnit.SECONDS.sleep(10);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 2);
assertEquals(2, instances.size());
instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true);
Assert.assertEquals(2, instances.size());
assertEquals(2, instances.size());
instances.get(0).setWeight(0);
instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance : instancesGet) {
if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) {
instanceNotH = instance;
}
}
instancesGet.remove(instanceNotH);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取所有Enable的Instance
*
* @throws Exception
*/
@Test
public void selectAllEnabledInstances() throws Exception {
void selectAllEnabledInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT);
naming1.registerInstance(serviceName, "1.1.1.1", 9090);
TimeUnit.SECONDS.sleep(10);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 2);
assertEquals(2, instances.size());
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(2, instances.size());
assertEquals(2, instances.size());
instances.get(0).setEnabled(false);
instances = naming.selectInstances(serviceName, true);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance : instancesGet) {
if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) {
instanceNotH = instance;
}
}
instancesGet.remove(instanceNotH);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
/**
* 获取指定cluster中单个多个所有Enabled的Instance
*
* @throws Exception
*/
@Test
public void selectAllEnabledInstancesClusters() throws Exception {
void selectAllEnabledInstancesClusters() throws Exception {
String serviceName = randomDomainName();
System.out.println(serviceName);
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "1.1.1.1", 9090, "c2");
TimeUnit.SECONDS.sleep(5);
List<Instance> instances = naming.getAllInstances(serviceName);
Assert.assertEquals(instances.size(), 2);
assertEquals(2, instances.size());
instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true);
Assert.assertEquals(2, instances.size());
assertEquals(2, instances.size());
instances.get(0).setEnabled(false);
instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true);
TimeUnit.SECONDS.sleep(5);
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
Instance instanceNotH = null;
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance : instancesGet) {
if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) {
instanceNotH = instance;
}
}
instancesGet.remove(instanceNotH);
Assert.assertTrue(verifyInstanceList(instances, instancesGet));
assertTrue(verifyInstanceList(instances, instancesGet));
}
@Test
@Ignore("TODO nacos 2.0 can't support selector for now")
public void getServiceListWithSelector() throws NacosException, InterruptedException {
@Disabled("TODO nacos 2.0 can't support selector for now")
void getServiceListWithSelector() throws NacosException, InterruptedException {
String serviceName = randomDomainName();
Instance instance = new Instance();
instance.setIp("128.0.0.1");
instance.setPort(999);
instance.setServiceName(serviceName);
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("registerSource", "dubbo");
instance.setMetadata(metadata);
naming.registerInstance(serviceName, instance);
naming.registerInstance(serviceName, "127.0.0.1", 80, "c1");
naming.registerInstance(serviceName, "127.0.0.2", 80, "c2");
TimeUnit.SECONDS.sleep(10);
ExpressionSelector expressionSelector = new ExpressionSelector();
expressionSelector.setExpression("INSTANCE.label.registerSource = 'dubbo'");
ListView<String> serviceList = naming.getServicesOfServer(1, 10, expressionSelector);
Assert.assertTrue(serviceList.getData().contains(serviceName));
assertTrue(serviceList.getData().contains(serviceName));
serviceName = randomDomainName();
instance.setServiceName(serviceName);
metadata.put("registerSource", "spring");
instance.setMetadata(metadata);
naming.registerInstance(serviceName, instance);
TimeUnit.SECONDS.sleep(10);
expressionSelector.setExpression("INSTANCE.label.registerSource = 'spring'");
serviceList = naming.getServicesOfServer(1, 10, expressionSelector);
Assert.assertTrue(serviceList.getData().contains(serviceName));
assertTrue(serviceList.getData().contains(serviceName));
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
@ -20,20 +21,22 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static com.alibaba.nacos.test.naming.NamingBase.verifyInstance;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Created by wangtong.wt on 2018/6/20.
@ -41,32 +44,25 @@ import static com.alibaba.nacos.test.naming.NamingBase.*;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SelectOneHealthyInstance_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class SelectOneHealthyInstance_ITCase {
private static NamingService naming;
private static NamingService naming1;
private static NamingService naming2;
private static NamingService naming3;
private static NamingService naming4;
@LocalServerPort
private int port;
@Before
public void init() throws Exception{
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
naming = NamingFactory.createNamingService("127.0.0.1"+":"+port);
naming1 = NamingFactory.createNamingService("127.0.0.1"+":"+port);
naming2 = NamingFactory.createNamingService("127.0.0.1"+":"+port);
naming3 = NamingFactory.createNamingService("127.0.0.1"+":"+port);
naming4 = NamingFactory.createNamingService("127.0.0.1"+":"+port);
}
}
@AfterClass
public static void tearDown() throws NacosException {
@AfterAll
static void tearDown() throws NacosException {
if (null != naming) {
naming.shutDown();
}
@ -83,94 +79,106 @@ public class SelectOneHealthyInstance_ITCase {
naming4.shutDown();
}
}
@BeforeEach
void init() throws Exception {
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
naming1 = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
naming2 = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
naming3 = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
naming4 = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
}
/**
* 获取一个健康的Instance
*
* @throws Exception
*/
@Test
public void selectOneHealthyInstances() throws Exception {
void selectOneHealthyInstances() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT);
naming1.registerInstance(serviceName, "127.0.0.1", 60000);
TimeUnit.SECONDS.sleep(2);
Instance instance = naming.selectOneHealthyInstance(serviceName);
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance1 : instancesGet) {
if (instance1.getIp().equals(instance.getIp())&&
instance1.getPort() == instance.getPort()) {
Assert.assertTrue(instance.isHealthy());
Assert.assertTrue(verifyInstance(instance1, instance));
if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) {
assertTrue(instance.isHealthy());
assertTrue(verifyInstance(instance1, instance));
return;
}
}
Assert.fail();
fail();
}
/**
* 获取指定单个cluster中一个健康的Instance
*
* @throws Exception
*/
@Test
public void selectOneHealthyInstancesCluster() throws Exception {
void selectOneHealthyInstancesCluster() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "127.0.0.1", 60000, "c1");
naming2.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
naming3.registerInstance(serviceName, "127.0.0.1", 60001, "c1");
naming4.registerInstance(serviceName, "127.0.0.1", 60002, "c2");
TimeUnit.SECONDS.sleep(2);
Instance instance = naming.selectOneHealthyInstance(serviceName, Arrays.asList("c1"));
Assert.assertNotSame("1.1.1.1", instance.getIp());
Assert.assertTrue(instance.getPort() != 60002);
assertNotSame("1.1.1.1", instance.getIp());
assertTrue(instance.getPort() != 60002);
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance1 : instancesGet) {
if (instance1.getIp().equals(instance.getIp())&&
instance1.getPort() == instance.getPort()) {
Assert.assertTrue(instance.isHealthy());
Assert.assertTrue(verifyInstance(instance1, instance));
if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) {
assertTrue(instance.isHealthy());
assertTrue(verifyInstance(instance1, instance));
return;
}
}
Assert.fail();
fail();
}
/**
* 获取指定多个cluster中一个健康的Instance
*
* @throws Exception
*/
@Test
public void selectOneHealthyInstancesClusters() throws Exception {
void selectOneHealthyInstancesClusters() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
naming1.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming2.registerInstance(serviceName, "127.0.0.1", 60000, "c1");
naming3.registerInstance(serviceName, "127.0.0.1", 60001, "c2");
TimeUnit.SECONDS.sleep(2);
Instance instance = naming.selectOneHealthyInstance(serviceName, Arrays.asList("c1", "c2"));
Assert.assertNotSame("1.1.1.1", instance.getIp());
assertNotSame("1.1.1.1", instance.getIp());
List<Instance> instancesGet = naming.getAllInstances(serviceName);
for (Instance instance1 : instancesGet) {
if (instance1.getIp().equals(instance.getIp()) &&
instance1.getPort() == instance.getPort()) {
Assert.assertTrue(instance.isHealthy());
Assert.assertTrue(verifyInstance(instance1, instance));
if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) {
assertTrue(instance.isHealthy());
assertTrue(verifyInstance(instance1, instance));
return;
}
}
Assert.fail();
fail();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
@ -25,84 +26,80 @@ import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import java.util.List;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author nkorange
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ServiceListTest_ITCase {
private NamingService naming;
private volatile List<Instance> instances = Collections.emptyList();
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ServiceListTest_ITCase {
private static int listenseCount = 0;
private NamingService naming;
private volatile List<Instance> instances = Collections.emptyList();
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
@BeforeEach
void init() throws Exception {
if (naming == null) {
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
}
@Test
public void serviceList() throws NacosException {
void serviceList() throws NacosException {
naming.getServicesOfServer(1, 10);
}
/**
* @throws NacosException
* @description 获取当前订阅的所有服务
*/
@Test
public void getSubscribeServices() throws NacosException, InterruptedException {
void getSubscribeServices() throws NacosException, InterruptedException {
ListView<String> listView = naming.getServicesOfServer(1, 10);
if (listView != null && listView.getCount() > 0) {
naming.getAllInstances(listView.getData().get(0));
}
List<ServiceInfo> serviceInfoList = naming.getSubscribeServices();
int count = serviceInfoList.size();
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming.subscribe(serviceName, new EventListener() {
@Override
public void onEvent(Event event) {
}
});
serviceInfoList = naming.getSubscribeServices();
Assert.assertEquals(count + 1, serviceInfoList.size());
assertEquals(count + 1, serviceInfoList.size());
}
/**
* @throws NacosException
* @description 删除注册获取当前订阅的所有服务
*/
@Test
public void getSubscribeServices_deregisterInstance() throws NacosException, InterruptedException {
void getSubscribeServices_deregisterInstance() throws NacosException, InterruptedException {
listenseCount = 0;
EventListener listener = new EventListener() {
@Override
@ -112,21 +109,21 @@ public class ServiceListTest_ITCase {
listenseCount++;
}
};
List<ServiceInfo> serviceInfoList = naming.getSubscribeServices();
int count = serviceInfoList.size();
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming.subscribe(serviceName, listener);
serviceInfoList = naming.getSubscribeServices();
Assert.assertEquals(count + 1, serviceInfoList.size());
assertEquals(count + 1, serviceInfoList.size());
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
Assert.assertEquals(count + 1, serviceInfoList.size());
assertEquals(count + 1, serviceInfoList.size());
}
}

View File

@ -13,10 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
/**
* @author nkorange
*/
public class Starter_ITCase {
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
@ -22,21 +23,22 @@ import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Created by wangtong.wt on 2018/6/20.
@ -44,35 +46,36 @@ import static com.alibaba.nacos.test.naming.NamingBase.*;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SubscribeCluster_ITCase {
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class SubscribeCluster_ITCase {
private NamingService naming;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
private volatile List<Instance> instances = Collections.emptyList();
@BeforeEach
void init() throws Exception {
instances.clear();
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
}
private volatile List<Instance> instances = Collections.emptyList();
/**
* 添加IP收到通知
*
* @throws Exception
*/
@Test(timeout = 10000L)
public void subscribeAdd() throws Exception {
@Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
void subscribeAdd() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() {
@Override
public void onEvent(Event event) {
@ -81,31 +84,32 @@ public class SubscribeCluster_ITCase {
instances = ((NamingEvent) event).getInstances();
}
});
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
while (instances.isEmpty()) {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
}
/**
* 删除IP收到通知
*
* @throws Exception
*/
@Test(timeout = 10000L)
public void subscribeDelete() throws Exception {
@Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
void subscribeDelete() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
TimeUnit.SECONDS.sleep(3);
naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() {
int index = 0;
@Override
public void onEvent(Event event) {
if (index == 0) {
@ -117,27 +121,28 @@ public class SubscribeCluster_ITCase {
instances = ((NamingEvent) event).getInstances();
}
});
TimeUnit.SECONDS.sleep(1);
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
while (!instances.isEmpty()) {
Thread.sleep(1000L);
}
Assert.assertTrue(instances.isEmpty());
assertTrue(instances.isEmpty());
}
/**
* 添加不可用IP收到通知
*
* @throws Exception
*/
@Test(timeout = 10000L)
public void subscribeUnhealthy() throws Exception {
@Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
void subscribeUnhealthy() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() {
@Override
public void onEvent(Event event) {
@ -146,28 +151,28 @@ public class SubscribeCluster_ITCase {
instances = ((NamingEvent) event).getInstances();
}
});
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
while (instances.isEmpty()) {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
}
/**
* 新增其他cluster IP不会收到通知
*
* @throws Exception
*/
@Test
public void subscribeOtherCluster() throws Exception {
void subscribeOtherCluster() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, Arrays.asList("c2"), new EventListener() {
int index = 0;
@Override
public void onEvent(Event event) {
if (index == 0) {
@ -179,9 +184,9 @@ public class SubscribeCluster_ITCase {
instances = ((NamingEvent) event).getInstances();
}
});
naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1");
int i = 0;
while (instances.isEmpty()) {
Thread.sleep(1000L);
@ -189,7 +194,7 @@ public class SubscribeCluster_ITCase {
return;
}
}
Assert.fail();
fail();
}
}

View File

@ -25,26 +25,25 @@ import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.selector.NamingSelector;
import com.alibaba.nacos.client.naming.selector.DefaultNamingSelector;
import com.alibaba.nacos.client.naming.selector.NamingSelectorFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author lideyou
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SubscribeSelector_ITCase extends NamingBase {
class SubscribeSelector_ITCase extends NamingBase {
private NamingService naming;
@ -53,23 +52,24 @@ public class SubscribeSelector_ITCase extends NamingBase {
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
private volatile List<Instance> instances = Collections.emptyList();
@BeforeEach
void init() throws Exception {
instances.clear();
if (naming == null) {
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
}
private volatile List<Instance> instances = Collections.emptyList();
/**
* Add IP and receive notification.
*
* @throws Exception
*/
@Test(timeout = 10000L)
public void subscribeAdd() throws Exception {
@Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
void subscribeAdd() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, selector, new EventListener() {
@ -87,7 +87,7 @@ public class SubscribeSelector_ITCase extends NamingBase {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
}
/**
@ -95,8 +95,9 @@ public class SubscribeSelector_ITCase extends NamingBase {
*
* @throws Exception
*/
@Test(timeout = 10000L)
public void subscribeDelete() throws Exception {
@Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
void subscribeDelete() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "172.18.137.1", TEST_PORT, "c1");
@ -125,7 +126,7 @@ public class SubscribeSelector_ITCase extends NamingBase {
Thread.sleep(1000L);
}
Assert.assertTrue(instances.isEmpty());
assertTrue(instances.isEmpty());
}
/**
@ -134,7 +135,7 @@ public class SubscribeSelector_ITCase extends NamingBase {
* @throws Exception
*/
@Test
public void subscribeOtherIp() throws Exception {
void subscribeOtherIp() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, selector, new EventListener() {
@ -162,6 +163,6 @@ public class SubscribeSelector_ITCase extends NamingBase {
}
}
Assert.fail();
fail();
}
}

View File

@ -29,15 +29,13 @@ import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.test.base.Params;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
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.Collections;
@ -46,7 +44,9 @@ import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Created by wangtong.wt on 2018/6/20.
@ -54,18 +54,19 @@ import static org.junit.Assert.assertTrue;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Subscribe_ITCase extends NamingBase {
class Subscribe_ITCase extends NamingBase {
private NamingService naming;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
private volatile List<Instance> instances = Collections.emptyList();
@BeforeEach
void init() throws Exception {
instances.clear();
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
@ -78,15 +79,14 @@ public class Subscribe_ITCase extends NamingBase {
this.base = new URL(url);
}
private volatile List<Instance> instances = Collections.emptyList();
/**
* 添加IP收到通知
*
* @throws Exception
*/
@Test(timeout = 4 * TIME_OUT)
public void subscribeAdd() throws Exception {
@Test
@Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void subscribeAdd() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, new EventListener() {
@ -112,8 +112,9 @@ public class Subscribe_ITCase extends NamingBase {
*
* @throws Exception
*/
@Test(timeout = 4 * TIME_OUT)
public void subscribeDelete() throws Exception {
@Test
@Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void subscribeDelete() throws Exception {
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
@ -150,8 +151,9 @@ public class Subscribe_ITCase extends NamingBase {
*
* @throws Exception
*/
@Test(timeout = 4 * TIME_OUT)
public void subscribeUnhealthy() throws Exception {
@Test
@Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void subscribeUnhealthy() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, new EventListener() {
@ -172,8 +174,9 @@ public class Subscribe_ITCase extends NamingBase {
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
}
@Test(timeout = 4 * TIME_OUT)
public void subscribeEmpty() throws Exception {
@Test
@Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS)
void subscribeEmpty() throws Exception {
String serviceName = randomDomainName();
@ -200,12 +203,12 @@ public class Subscribe_ITCase extends NamingBase {
Thread.sleep(1000L);
}
Assert.assertEquals(0, instances.size());
Assert.assertEquals(0, naming.getAllInstances(serviceName).size());
assertEquals(0, instances.size());
assertEquals(0, naming.getAllInstances(serviceName).size());
}
@Test
public void querySubscribers() throws Exception {
void querySubscribers() throws Exception {
String serviceName = randomDomainName();
@ -225,13 +228,13 @@ public class Subscribe_ITCase extends NamingBase {
TimeUnit.SECONDS.sleep(3);
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/subscribers",
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1")
.appendParam("pageSize", "10").done(), String.class, HttpMethod.GET);
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "10").done(),
String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
JsonNode body = JacksonUtils.toObj(response.getBody());
Assert.assertEquals(1, body.get("subscribers").size());
assertEquals(1, body.get("subscribers").size());
Properties properties = new Properties();
properties.setProperty("namingRequestTimeout", "300000");
@ -250,18 +253,18 @@ public class Subscribe_ITCase extends NamingBase {
TimeUnit.SECONDS.sleep(3);
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/subscribers",
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1")
.appendParam("pageSize", "10").done(), String.class, HttpMethod.GET);
Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "10").done(),
String.class, HttpMethod.GET);
assertTrue(response.getStatusCode().is2xxSuccessful());
body = JacksonUtils.toObj(response.getBody());
// server will remove duplicate subscriber by ip port service app and so on
Assert.assertEquals(1, body.get("subscribers").size());
assertEquals(1, body.get("subscribers").size());
}
@Test
public void subscribeSameServiceForTwoNamingService() throws Exception {
void subscribeSameServiceForTwoNamingService() throws Exception {
Properties properties1 = new Properties();
properties1.setProperty("serverAddr", "127.0.0.1" + ":" + port);
properties1.setProperty("namespace", "ns-001");
@ -299,7 +302,7 @@ public class Subscribe_ITCase extends NamingBase {
try {
assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName)));
Assert.assertEquals(0, concurrentHashSet1.size());
assertEquals(0, concurrentHashSet1.size());
} finally {
naming1.shutDown();
naming2.shutDown();
@ -307,7 +310,7 @@ public class Subscribe_ITCase extends NamingBase {
}
@Test
public void subscribeUsingAbstractNamingChangeListener() throws Exception {
void subscribeUsingAbstractNamingChangeListener() throws Exception {
String serviceName = randomDomainName();
naming.subscribe(serviceName, new AbstractNamingChangeListener() {
@ -330,7 +333,7 @@ public class Subscribe_ITCase extends NamingBase {
}
@Test
public void testListenerFirstCallback() throws Exception {
void testListenerFirstCallback() throws Exception {
String serviceName = randomDomainName();
AtomicInteger count = new AtomicInteger(0);
naming.subscribe(serviceName, new EventListener() {
@ -363,7 +366,7 @@ public class Subscribe_ITCase extends NamingBase {
while (count.get() < 2) {
Thread.sleep(1000L);
if (i++ > 10) {
Assert.fail();
fail();
}
}
}

View File

@ -25,13 +25,10 @@ import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.selector.NamingSelector;
import com.alibaba.nacos.client.naming.selector.DefaultNamingSelector;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.Collections;
@ -40,6 +37,8 @@ import java.util.List;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName;
import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Created by wangtong.wt on 2018/6/20.
@ -47,18 +46,19 @@ import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList;
* @author wangtong.wt
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Nacos.class, properties = {
"server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Unsubscribe_ITCase {
class Unsubscribe_ITCase {
private NamingService naming;
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
private volatile List<Instance> instances = Collections.emptyList();
@BeforeEach
void init() throws Exception {
instances = Collections.emptyList();
if (naming == null) {
//TimeUnit.SECONDS.sleep(10);
@ -66,15 +66,13 @@ public class Unsubscribe_ITCase {
}
}
private volatile List<Instance> instances = Collections.emptyList();
/**
* 取消订阅添加IP不会收到通知
*
* @throws Exception
*/
@Test
public void unsubscribe() throws Exception {
void unsubscribe() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@ -94,7 +92,7 @@ public class Unsubscribe_ITCase {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
naming.unsubscribe(serviceName, listener);
@ -109,7 +107,7 @@ public class Unsubscribe_ITCase {
}
}
Assert.fail();
fail();
}
/**
@ -118,7 +116,7 @@ public class Unsubscribe_ITCase {
* @throws Exception
*/
@Test
public void unsubscribeCluster() throws Exception {
void unsubscribeCluster() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@ -138,7 +136,7 @@ public class Unsubscribe_ITCase {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
naming.unsubscribe(serviceName, Arrays.asList("c1"), listener);
@ -153,7 +151,7 @@ public class Unsubscribe_ITCase {
}
}
Assert.fail();
fail();
}
/**
@ -162,7 +160,7 @@ public class Unsubscribe_ITCase {
* @throws Exception
*/
@Test
public void unsubscribeSelector() throws Exception {
void unsubscribeSelector() throws Exception {
String serviceName = randomDomainName();
EventListener listener = new EventListener() {
@ -184,7 +182,7 @@ public class Unsubscribe_ITCase {
Thread.sleep(1000L);
}
Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName)));
naming.unsubscribe(serviceName, selector, listener);
@ -199,7 +197,7 @@ public class Unsubscribe_ITCase {
}
}
Assert.fail();
fail();
}
}