Add client module ut. (#11739)
* Add client module ut. * Fix naming ut possible failed.
This commit is contained in:
parent
3da1240f3a
commit
139f4f2377
@ -17,7 +17,7 @@
|
||||
package com.alibaba.nacos.client.config.impl;
|
||||
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import com.alibaba.nacos.client.config.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.config.utils.JvmUtil;
|
||||
import com.alibaba.nacos.client.config.utils.SnapShotSwitch;
|
||||
import com.alibaba.nacos.client.env.NacosClientProperties;
|
||||
|
@ -18,7 +18,7 @@ package com.alibaba.nacos.client.config.impl;
|
||||
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import com.alibaba.nacos.api.utils.StringUtils;
|
||||
import com.alibaba.nacos.client.config.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.config.utils.JvmUtil;
|
||||
import com.alibaba.nacos.client.config.utils.SnapShotSwitch;
|
||||
import com.alibaba.nacos.client.utils.LogUtils;
|
||||
|
@ -1,227 +0,0 @@
|
||||
/*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.client.config.utils;
|
||||
|
||||
import com.alibaba.nacos.common.utils.IoUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
|
||||
/**
|
||||
* concurrent disk util;op file with file lock.
|
||||
*
|
||||
* @author configCenter
|
||||
*/
|
||||
public class ConcurrentDiskUtil {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentDiskUtil.class);
|
||||
|
||||
static final int RETRY_COUNT = 10;
|
||||
|
||||
/**
|
||||
* ms.
|
||||
*/
|
||||
static final int SLEEP_BASETIME = 10;
|
||||
|
||||
private static final String READ_ONLY = "r";
|
||||
|
||||
private static final String READ_WRITE = "rw";
|
||||
|
||||
/**
|
||||
* get file content.
|
||||
*
|
||||
* @param path file path
|
||||
* @param charsetName charsetName
|
||||
* @return content
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static String getFileContent(String path, String charsetName) throws IOException {
|
||||
File file = new File(path);
|
||||
return getFileContent(file, charsetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* get file content.
|
||||
*
|
||||
* @param file file
|
||||
* @param charsetName charsetName
|
||||
* @return content
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static String getFileContent(File file, String charsetName) throws IOException {
|
||||
RandomAccessFile fis = null;
|
||||
FileLock rlock = null;
|
||||
try {
|
||||
fis = new RandomAccessFile(file, READ_ONLY);
|
||||
FileChannel fcin = fis.getChannel();
|
||||
int i = 0;
|
||||
do {
|
||||
try {
|
||||
rlock = fcin.tryLock(0L, Long.MAX_VALUE, true);
|
||||
} catch (Exception e) {
|
||||
++i;
|
||||
if (i > RETRY_COUNT) {
|
||||
LOGGER.error("read {} fail;retryed time:{}", file.getName(), i);
|
||||
throw new IOException("read " + file.getAbsolutePath() + " conflict");
|
||||
}
|
||||
sleep(SLEEP_BASETIME * i);
|
||||
LOGGER.warn("read {} conflict;retry time:{}", file.getName(), i);
|
||||
}
|
||||
} while (null == rlock);
|
||||
int fileSize = (int) fcin.size();
|
||||
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
|
||||
fcin.read(byteBuffer);
|
||||
byteBuffer.flip();
|
||||
return byteBufferToString(byteBuffer, charsetName);
|
||||
} finally {
|
||||
if (rlock != null) {
|
||||
rlock.release();
|
||||
rlock = null;
|
||||
}
|
||||
if (fis != null) {
|
||||
IoUtils.closeQuietly(fis);
|
||||
fis = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* write file content.
|
||||
*
|
||||
* @param path file path
|
||||
* @param content content
|
||||
* @param charsetName charsetName
|
||||
* @return whether write ok
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static Boolean writeFileContent(String path, String content, String charsetName) throws IOException {
|
||||
File file = new File(path);
|
||||
return writeFileContent(file, content, charsetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* write file content.
|
||||
*
|
||||
* @param file file
|
||||
* @param content content
|
||||
* @param charsetName charsetName
|
||||
* @return whether write ok
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static Boolean writeFileContent(File file, String content, String charsetName) throws IOException {
|
||||
if (!file.exists()) {
|
||||
boolean isCreateOk = file.createNewFile();
|
||||
if (!isCreateOk) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
FileChannel channel = null;
|
||||
FileLock lock = null;
|
||||
RandomAccessFile raf = null;
|
||||
try {
|
||||
raf = new RandomAccessFile(file, READ_WRITE);
|
||||
channel = raf.getChannel();
|
||||
int i = 0;
|
||||
do {
|
||||
try {
|
||||
lock = channel.tryLock();
|
||||
} catch (Exception e) {
|
||||
++i;
|
||||
if (i > RETRY_COUNT) {
|
||||
LOGGER.error("write {} fail;retryed time:{}", file.getName(), i);
|
||||
throw new IOException("write " + file.getAbsolutePath() + " conflict");
|
||||
}
|
||||
sleep(SLEEP_BASETIME * i);
|
||||
LOGGER.warn("write {} conflict;retry time:{}", file.getName(), i);
|
||||
}
|
||||
} while (null == lock);
|
||||
|
||||
ByteBuffer sendBuffer = ByteBuffer.wrap(content.getBytes(charsetName));
|
||||
while (sendBuffer.hasRemaining()) {
|
||||
channel.write(sendBuffer);
|
||||
}
|
||||
channel.truncate(content.length());
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new IOException("file not exist");
|
||||
} finally {
|
||||
if (lock != null) {
|
||||
try {
|
||||
lock.release();
|
||||
lock = null;
|
||||
} catch (IOException e) {
|
||||
LOGGER.warn("close wrong", e);
|
||||
}
|
||||
}
|
||||
if (channel != null) {
|
||||
try {
|
||||
channel.close();
|
||||
channel = null;
|
||||
} catch (IOException e) {
|
||||
LOGGER.warn("close wrong", e);
|
||||
}
|
||||
}
|
||||
if (raf != null) {
|
||||
try {
|
||||
raf.close();
|
||||
raf = null;
|
||||
} catch (IOException e) {
|
||||
LOGGER.warn("close wrong", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* transfer ByteBuffer to String.
|
||||
*
|
||||
* @param buffer buffer
|
||||
* @param charsetName charsetName
|
||||
* @return String
|
||||
* @throws IOException IOException
|
||||
*/
|
||||
public static String byteBufferToString(ByteBuffer buffer, String charsetName) throws IOException {
|
||||
Charset charset = null;
|
||||
CharsetDecoder decoder = null;
|
||||
CharBuffer charBuffer = null;
|
||||
charset = Charset.forName(charsetName);
|
||||
decoder = charset.newDecoder();
|
||||
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
|
||||
return charBuffer.toString();
|
||||
}
|
||||
|
||||
private static void sleep(int time) {
|
||||
try {
|
||||
Thread.sleep(time);
|
||||
} catch (InterruptedException e) {
|
||||
LOGGER.warn("sleep wrong", e);
|
||||
// set the interrupted flag
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
@ -47,7 +47,12 @@ public class JvmUtil {
|
||||
private static final String DEFAULT_IS_MULTI_INSTANCE = "false";
|
||||
|
||||
static {
|
||||
String multiDeploy = NacosClientProperties.PROTOTYPE.getProperty(IS_MULTI_INSTANCE_PROPERTY, DEFAULT_IS_MULTI_INSTANCE);
|
||||
init();
|
||||
}
|
||||
|
||||
private static void init() {
|
||||
String multiDeploy = NacosClientProperties.PROTOTYPE
|
||||
.getProperty(IS_MULTI_INSTANCE_PROPERTY, DEFAULT_IS_MULTI_INSTANCE);
|
||||
if (TRUE.equals(multiDeploy)) {
|
||||
isMultiInstance = true;
|
||||
}
|
||||
|
@ -21,7 +21,7 @@ import com.alibaba.nacos.client.naming.backups.FailoverData;
|
||||
import com.alibaba.nacos.client.naming.backups.FailoverDataSource;
|
||||
import com.alibaba.nacos.client.naming.backups.FailoverSwitch;
|
||||
import com.alibaba.nacos.client.naming.backups.NamingFailoverData;
|
||||
import com.alibaba.nacos.client.naming.cache.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.client.naming.cache.DiskCache;
|
||||
import com.alibaba.nacos.client.naming.utils.CacheDirUtil;
|
||||
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
|
||||
|
@ -20,6 +20,7 @@ import com.alibaba.nacos.api.common.Constants;
|
||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
|
||||
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
|
||||
import com.alibaba.nacos.client.utils.ConcurrentDiskUtil;
|
||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||
import com.alibaba.nacos.common.utils.StringUtils;
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@ -14,7 +14,10 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.client.naming.cache;
|
||||
package com.alibaba.nacos.client.utils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
@ -27,8 +30,6 @@ import java.nio.channels.FileLock;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
|
||||
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
|
||||
|
||||
/**
|
||||
* Concurrent Disk util.
|
||||
*
|
||||
@ -36,6 +37,8 @@ import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
|
||||
*/
|
||||
public class ConcurrentDiskUtil {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentDiskUtil.class);
|
||||
|
||||
private static final String READ_ONLY = "r";
|
||||
|
||||
private static final String READ_WRITE = "rw";
|
||||
@ -139,7 +142,7 @@ public class ConcurrentDiskUtil {
|
||||
try {
|
||||
Thread.sleep(time);
|
||||
} catch (InterruptedException e) {
|
||||
NAMING_LOGGER.warn("sleep wrong", e);
|
||||
LOGGER.warn("sleep wrong", e);
|
||||
// set the interrupted flag
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
@ -154,11 +157,11 @@ public class ConcurrentDiskUtil {
|
||||
} catch (Exception e) {
|
||||
++i;
|
||||
if (i > RETRY_COUNT) {
|
||||
NAMING_LOGGER.error("[NA] read " + file.getName() + " fail;retryed time: " + i, e);
|
||||
throw new IOException("read " + file.getAbsolutePath() + " conflict");
|
||||
LOGGER.error("[NA] lock " + file.getName() + " fail;retryed time: " + i, e);
|
||||
throw new IOException("lock " + file.getAbsolutePath() + " conflict");
|
||||
}
|
||||
sleep(SLEEP_BASETIME * i);
|
||||
NAMING_LOGGER.warn("read " + file.getName() + " conflict;retry time: " + i);
|
||||
LOGGER.warn("lock " + file.getName() + " conflict;retry time: " + i);
|
||||
}
|
||||
} while (null == result);
|
||||
return result;
|
@ -29,17 +29,19 @@ public class ConfigResponseTest {
|
||||
String group = "group";
|
||||
String tenant = "n";
|
||||
String content = "abc";
|
||||
String type = "yaml";
|
||||
|
||||
configResponse.setContent(content);
|
||||
configResponse.setDataId(dataId);
|
||||
configResponse.setGroup(group);
|
||||
configResponse.setTenant(tenant);
|
||||
configResponse.setConfigType(type);
|
||||
|
||||
Assert.assertEquals(dataId, configResponse.getDataId());
|
||||
Assert.assertEquals(group, configResponse.getGroup());
|
||||
Assert.assertEquals(tenant, configResponse.getTenant());
|
||||
Assert.assertEquals(content, configResponse.getContent());
|
||||
|
||||
Assert.assertEquals(type, configResponse.getConfigType());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -49,16 +51,19 @@ public class ConfigResponseTest {
|
||||
String group = "group";
|
||||
String tenant = "n";
|
||||
String content = "abc";
|
||||
String custom = "custom";
|
||||
|
||||
configResponse.setContent(content);
|
||||
configResponse.setDataId(dataId);
|
||||
configResponse.setGroup(group);
|
||||
configResponse.setTenant(tenant);
|
||||
configResponse.putParameter(custom, custom);
|
||||
|
||||
Assert.assertEquals(dataId, configResponse.getParameter("dataId"));
|
||||
Assert.assertEquals(group, configResponse.getParameter("group"));
|
||||
Assert.assertEquals(tenant, configResponse.getParameter("tenant"));
|
||||
Assert.assertEquals(content, configResponse.getParameter("content"));
|
||||
Assert.assertEquals(custom, configResponse.getParameter("custom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -18,8 +18,6 @@ package com.alibaba.nacos.client.config.http;
|
||||
|
||||
import com.alibaba.nacos.api.PropertyKeyConst;
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
|
||||
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
|
||||
import com.alibaba.nacos.client.config.impl.ServerListManager;
|
||||
import com.alibaba.nacos.common.http.HttpClientConfig;
|
||||
import com.alibaba.nacos.common.http.HttpRestResult;
|
||||
@ -32,44 +30,61 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.ConnectException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ServerHttpAgentTest {
|
||||
|
||||
NacosRestTemplate nacosRestTemplate;
|
||||
private static final String SERVER_ADDRESS_1 = "http://1.1.1.1:8848";
|
||||
|
||||
MockedStatic<ConfigHttpClientManager> configHttpClientManagerMockedStatic;
|
||||
private static final String SERVER_ADDRESS_2 = "http://2.2.2.2:8848";
|
||||
|
||||
@Mock
|
||||
ConfigHttpClientManager configHttpClientManager;
|
||||
ServerListManager serverListManager;
|
||||
|
||||
@Mock
|
||||
HttpRestResult<String> mockResult;
|
||||
|
||||
@Mock
|
||||
Iterator<String> mockIterator;
|
||||
|
||||
@Mock
|
||||
NacosRestTemplate nacosRestTemplate;
|
||||
|
||||
ServerHttpAgent serverHttpAgent;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
configHttpClientManagerMockedStatic = Mockito.mockStatic(ConfigHttpClientManager.class);
|
||||
configHttpClientManagerMockedStatic.when(() -> ConfigHttpClientManager.getInstance())
|
||||
.thenReturn(configHttpClientManager);
|
||||
nacosRestTemplate = Mockito.mock(NacosRestTemplate.class);
|
||||
Mockito.when(configHttpClientManager.getNacosRestTemplate()).thenReturn(nacosRestTemplate);
|
||||
public void setUp() throws NoSuchFieldException, IllegalAccessException {
|
||||
serverHttpAgent = new ServerHttpAgent(serverListManager, new Properties());
|
||||
injectRestTemplate();
|
||||
when(serverListManager.getCurrentServerAddr()).thenReturn(SERVER_ADDRESS_1);
|
||||
when(serverListManager.getIterator()).thenReturn(mockIterator);
|
||||
when(mockIterator.next()).thenReturn(SERVER_ADDRESS_2);
|
||||
}
|
||||
|
||||
private void injectRestTemplate() throws NoSuchFieldException, IllegalAccessException {
|
||||
Field restTemplateField = ServerHttpAgent.class.getDeclaredField("nacosRestTemplate");
|
||||
restTemplateField.setAccessible(true);
|
||||
restTemplateField.set(serverHttpAgent, nacosRestTemplate);
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
configHttpClientManagerMockedStatic.close();
|
||||
public void tearDown() throws NacosException {
|
||||
serverHttpAgent.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -88,154 +103,6 @@ public class ServerHttpAgentTest {
|
||||
|
||||
}
|
||||
|
||||
private void resetNacosHttpTemplate(ServerHttpAgent serverHttpAgent, NacosRestTemplate nacosRestTemplate)
|
||||
throws Exception {
|
||||
Field nacosRestTemplateFiled = ServerHttpAgent.class.getDeclaredField("nacosRestTemplate");
|
||||
nacosRestTemplateFiled.setAccessible(true);
|
||||
nacosRestTemplateFiled.set(serverHttpAgent, nacosRestTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpGetSuccess() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.get(anyString(), any(HttpClientConfig.class), any(Header.class), any(Query.class),
|
||||
eq(String.class))).thenReturn(new HttpRestResult(Header.newInstance(), 500, "", ""))
|
||||
.thenThrow(new ConnectException())
|
||||
.thenReturn(new HttpRestResult(Header.newInstance(), 200, "hello", "success"));
|
||||
ServerListManager server = new ServerListManager(
|
||||
Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
HttpRestResult<String> stringHttpRestResult = serverHttpAgent.httpGet(path, Header.newInstance().getHeader(),
|
||||
parmas, "UTF-8", 3000L);
|
||||
Assert.assertEquals("hello", stringHttpRestResult.getData());
|
||||
Assert.assertEquals(true, stringHttpRestResult.ok());
|
||||
Assert.assertEquals("success", stringHttpRestResult.getMessage());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpGetFail() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.get(anyString(), any(HttpClientConfig.class), any(Header.class), any(Query.class),
|
||||
eq(String.class))).thenThrow(new SocketTimeoutException()).thenThrow(new ConnectException())
|
||||
.thenThrow(new ConnectException()).thenThrow(new NacosRuntimeException(2048));
|
||||
ServerListManager server = new ServerListManager(Arrays.asList("127.0.0.1", "127.0.0.2"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
try {
|
||||
serverHttpAgent.httpGet(path, Header.newInstance().getHeader(), parmas, "UTF-8", 3000L);
|
||||
Assert.fail();
|
||||
} catch (NacosRuntimeException e) {
|
||||
Assert.assertEquals(e.getErrCode(), 2048);
|
||||
} catch (Exception e) {
|
||||
Assert.fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPostSuccess() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.postForm(anyString(), any(HttpClientConfig.class), any(Header.class), any(Map.class),
|
||||
eq(String.class))).thenReturn(new HttpRestResult(Header.newInstance(), 500, "", ""))
|
||||
.thenThrow(new ConnectException())
|
||||
.thenReturn(new HttpRestResult(Header.newInstance(), 200, "hello", "success"));
|
||||
ServerListManager server = new ServerListManager(
|
||||
Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
HttpRestResult<String> stringHttpRestResult = serverHttpAgent.httpPost(path, Header.newInstance().getHeader(),
|
||||
parmas, "UTF-8", 3000L);
|
||||
Assert.assertEquals("hello", stringHttpRestResult.getData());
|
||||
Assert.assertEquals(true, stringHttpRestResult.ok());
|
||||
Assert.assertEquals("success", stringHttpRestResult.getMessage());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPostFail() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.postForm(anyString(), any(HttpClientConfig.class), any(Header.class), any(Map.class),
|
||||
eq(String.class))).thenThrow(new SocketTimeoutException()).thenThrow(new ConnectException())
|
||||
.thenThrow(new ConnectException()).thenThrow(new NacosRuntimeException(2048));
|
||||
ServerListManager server = new ServerListManager(Arrays.asList("127.0.0.1", "127.0.0.2"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
try {
|
||||
serverHttpAgent.httpPost(path, Header.newInstance().getHeader(), parmas, "UTF-8", 3000L);
|
||||
Assert.fail();
|
||||
} catch (NacosRuntimeException e) {
|
||||
Assert.assertEquals(e.getErrCode(), 2048);
|
||||
} catch (Exception e) {
|
||||
Assert.fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpDeleteSuccess() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.delete(anyString(), any(HttpClientConfig.class), any(Header.class), any(Query.class),
|
||||
eq(String.class))).thenReturn(new HttpRestResult(Header.newInstance(), 500, "", ""))
|
||||
.thenThrow(new ConnectException())
|
||||
.thenReturn(new HttpRestResult(Header.newInstance(), 200, "hello", "success"));
|
||||
ServerListManager server = new ServerListManager(
|
||||
Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
HttpRestResult<String> stringHttpRestResult = serverHttpAgent.httpDelete(path, Header.newInstance().getHeader(),
|
||||
parmas, "UTF-8", 3000L);
|
||||
Assert.assertEquals("hello", stringHttpRestResult.getData());
|
||||
Assert.assertEquals(true, stringHttpRestResult.ok());
|
||||
Assert.assertEquals("success", stringHttpRestResult.getMessage());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpDeleteFail() throws Exception {
|
||||
|
||||
Mockito.when(
|
||||
nacosRestTemplate.delete(anyString(), any(HttpClientConfig.class), any(Header.class), any(Query.class),
|
||||
eq(String.class))).thenThrow(new SocketTimeoutException()).thenThrow(new ConnectException())
|
||||
.thenThrow(new ConnectException()).thenThrow(new NacosRuntimeException(2048));
|
||||
ServerListManager server = new ServerListManager(Arrays.asList("127.0.0.1", "127.0.0.2"));
|
||||
final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server);
|
||||
resetNacosHttpTemplate(serverHttpAgent, nacosRestTemplate);
|
||||
|
||||
String path = "config.do";
|
||||
Map<String, String> parmas = new HashMap<>();
|
||||
parmas.put("dataId", "12345");
|
||||
try {
|
||||
serverHttpAgent.httpDelete(path, Header.newInstance().getHeader(), parmas, "UTF-8", 3000L);
|
||||
Assert.fail();
|
||||
} catch (NacosRuntimeException e) {
|
||||
Assert.assertEquals(e.getErrCode(), 2048);
|
||||
} catch (Exception e) {
|
||||
Assert.fail();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetterAndSetter() throws NacosException {
|
||||
ServerListManager server = new ServerListManager("aaa", "namespace1");
|
||||
@ -273,4 +140,141 @@ public class ServerHttpAgentTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpGetSuccess() throws Exception {
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testHttpGetFailed() throws Exception {
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND);
|
||||
serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testHttpWithRequestException() throws Exception {
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class)))
|
||||
.thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException());
|
||||
serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetryWithNewServer() throws Exception {
|
||||
when(mockIterator.hasNext()).thenReturn(true);
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException());
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testRetryTimeout() throws Exception {
|
||||
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException());
|
||||
serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPostSuccess() throws Exception {
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testHttpPostFailed() throws Exception {
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND);
|
||||
serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testHttpPostWithRequestException() throws Exception {
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class)))
|
||||
.thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException());
|
||||
serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetryPostWithNewServer() throws Exception {
|
||||
when(mockIterator.hasNext()).thenReturn(true);
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectException());
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testRetryPostTimeout() throws Exception {
|
||||
when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), anyMap(), eq(String.class))).thenThrow(new SocketTimeoutException());
|
||||
serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpDeleteSuccess() throws Exception {
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testHttpDeleteFailed() throws Exception {
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND);
|
||||
serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testHttpDeleteWithRequestException() throws Exception {
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class)))
|
||||
.thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException());
|
||||
serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetryDeleteWithNewServer() throws Exception {
|
||||
when(mockIterator.hasNext()).thenReturn(true);
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException());
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
|
||||
when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK);
|
||||
HttpRestResult<String> actual = serverHttpAgent
|
||||
.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000);
|
||||
Assert.assertEquals(mockResult, actual);
|
||||
}
|
||||
|
||||
@Test(expected = ConnectException.class)
|
||||
public void testRetryDeleteTimeout() throws Exception {
|
||||
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
|
||||
any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException());
|
||||
serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0);
|
||||
}
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.client.config.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class ConcurrentDiskUtilTest {
|
||||
|
||||
@Test
|
||||
public void testReadAndWrite() throws IOException {
|
||||
File tempFile = File.createTempFile("aaa", "bbb");
|
||||
String fileName = tempFile.getAbsolutePath();
|
||||
String content = "hello";
|
||||
String charset = "UTF-8";
|
||||
ConcurrentDiskUtil.writeFileContent(fileName, content, charset);
|
||||
String actualContent = ConcurrentDiskUtil.getFileContent(fileName, charset);
|
||||
Assert.assertEquals(content, actualContent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testByteBufferToString() throws IOException {
|
||||
String msg = "test buff to string";
|
||||
ByteBuffer buff = ByteBuffer.wrap(msg.getBytes(Charset.forName("UTF-8")));
|
||||
String actual = ConcurrentDiskUtil.byteBufferToString(buff, "UTF-8");
|
||||
Assert.assertEquals(msg, actual);
|
||||
|
||||
}
|
||||
}
|
@ -18,14 +18,45 @@
|
||||
|
||||
package com.alibaba.nacos.client.config.utils;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JvmUtilTest {
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class JvmUtilTest {
|
||||
|
||||
Method initMethod;
|
||||
|
||||
@Before
|
||||
public void setUp() throws NoSuchMethodException {
|
||||
initMethod = JvmUtil.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
||||
System.clearProperty("isMultiInstance");
|
||||
Field field = JvmUtil.class.getDeclaredField("isMultiInstance");
|
||||
field.setAccessible(true);
|
||||
field.set(JvmUtil.class, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsMultiInstance() {
|
||||
public void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException {
|
||||
initMethod.invoke(JvmUtil.class);
|
||||
Boolean multiInstance = JvmUtil.isMultiInstance();
|
||||
Assert.assertFalse(multiInstance);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException {
|
||||
System.setProperty("isMultiInstance", "true");
|
||||
initMethod.invoke(JvmUtil.class);
|
||||
Boolean multiInstance = JvmUtil.isMultiInstance();
|
||||
Assert.assertTrue(multiInstance);
|
||||
}
|
||||
}
|
@ -1,6 +1,5 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
* Copyright 1999-2023 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@ -13,11 +12,11 @@
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.alibaba.nacos.client.naming.cache;
|
||||
package com.alibaba.nacos.client.naming.utils;
|
||||
|
||||
import com.alibaba.nacos.client.utils.ConcurrentDiskUtil;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
@ -21,8 +21,10 @@ import com.alibaba.nacos.naming.core.v2.metadata.InstanceMetadata;
|
||||
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
|
||||
import com.alibaba.nacos.naming.core.v2.pojo.Service;
|
||||
import com.alibaba.nacos.naming.pojo.instance.InstanceIdGeneratorManager;
|
||||
import com.alibaba.nacos.sys.env.EnvUtil;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@ -41,6 +43,7 @@ public class InstanceUtilTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
EnvUtil.setEnvironment(new MockEnvironment());
|
||||
service = Service.newService("namespace", "group", "serviceName");
|
||||
instancePublishInfo = new InstancePublishInfo("1.1.1.1", 8080);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user