Develop client ut (#11557)

* Add UT for client module logging package.

* Add UT for client module utils package.

* Add UT for client module naming package.

* For checkstyle.

* For PMD.
This commit is contained in:
杨翊 SionYang 2023-12-26 11:53:26 +08:00 committed by GitHub
parent 41222ee99a
commit 9e48e8cb3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
63 changed files with 2359 additions and 965 deletions

View File

@ -60,11 +60,8 @@ public class NacosLogging {
try {
nacosLogging.loadConfiguration();
} catch (Throwable t) {
if (isLogback) {
LOGGER.warn("Load Logback Configuration of Nacos fail, message: {}", t.getMessage());
} else {
LOGGER.warn("Load Log4j Configuration of Nacos fail, message: {}", t.getMessage());
}
String loggerName = isLogback ? "Logback" : "Log4j";
LOGGER.warn("Load {} Configuration of Nacos fail, message: {}", loggerName, t.getMessage());
}
}
}

View File

@ -42,10 +42,6 @@ public class MetricsMonitor {
return NACOS_MONITOR.labels("naming", "serviceInfoMapSize");
}
public static Gauge.Child getDom2BeatSizeMonitor() {
return NACOS_MONITOR.labels("naming", "dom2BeatSize");
}
public static Gauge.Child getListenConfigCountMonitor() {
return NACOS_MONITOR.labels("config", "listenConfigCount");
}

View File

@ -69,6 +69,7 @@ public class NacosNamingService implements NamingService {
*/
private String namespace;
@Deprecated
private String logName;
private ServiceInfoHolder serviceInfoHolder;
@ -107,6 +108,7 @@ public class NacosNamingService implements NamingService {
changeNotifier);
}
@Deprecated
private void initLogName(NacosClientProperties properties) {
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME, DEFAULT_NAMING_LOG_FILE_PATH);
}

View File

@ -26,12 +26,12 @@ public class FailoverData {
/**
* failover type,naming or config.
*/
private DataType dataType;
private final DataType dataType;
/**
* failover data.
*/
private Object data;
private final Object data;
public FailoverData(DataType dataType, Object data) {
this.data = data;
@ -53,15 +53,7 @@ public class FailoverData {
return dataType;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}

View File

@ -29,9 +29,7 @@ import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Metrics;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -60,7 +58,7 @@ public class FailoverReactor implements Closeable {
private String notifierEventScope;
private HashMap<String, Meter> meterMap = new HashMap<>(10);
private Map<String, Meter> meterMap = new HashMap<>(10);
public FailoverReactor(ServiceInfoHolder serviceInfoHolder, String notifierEventScope) {
this.serviceInfoHolder = serviceInfoHolder;
@ -85,9 +83,7 @@ public class FailoverReactor implements Closeable {
* Init.
*/
public void init() {
executorService.scheduleWithFixedDelay(new FailoverSwitchRefresher(), 0L, 5000L, TimeUnit.MILLISECONDS);
}
class FailoverSwitchRefresher implements Runnable {
@ -146,7 +142,6 @@ public class FailoverReactor implements Closeable {
serviceMap.clear();
failoverSwitchEnable = false;
failoverServiceCntMetricsClear();
return;
}
} catch (Exception e) {
NAMING_LOGGER.error("FailoverSwitchRefresher run err", e);
@ -169,20 +164,6 @@ public class FailoverReactor implements Closeable {
return serviceInfo;
}
/**
* Add day.
*
* @param date start time
* @param num add day number
* @return new date
*/
public Date addDay(Date date, int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
/**
* shutdown ThreadPool.
*
@ -200,10 +181,10 @@ public class FailoverReactor implements Closeable {
try {
for (Map.Entry<String, ServiceInfo> entry : failoverMap.entrySet()) {
String serviceName = entry.getKey();
Gauge register = Gauge.builder("nacos_naming_client_failover_instances",
((ServiceInfo) failoverMap.get(serviceName)).ipCount(), Integer::intValue)
.tag("service_name", serviceName).description("Nacos failover data service count")
.register(Metrics.globalRegistry);
Gauge register = Gauge
.builder("nacos_naming_client_failover_instances", failoverMap.get(serviceName).ipCount(),
Integer::intValue).tag("service_name", serviceName)
.description("Nacos failover data service count").register(Metrics.globalRegistry);
meterMap.put(serviceName, register);
}
} catch (Exception e) {

View File

@ -26,16 +26,12 @@ public class FailoverSwitch {
/**
* Failover switch enable.
*/
private boolean enabled;
private final boolean enabled;
public boolean getEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public FailoverSwitch(boolean enabled) {
this.enabled = enabled;
}

View File

@ -24,17 +24,11 @@ import com.alibaba.nacos.client.naming.backups.NamingFailoverData;
import com.alibaba.nacos.client.naming.cache.ConcurrentDiskUtil;
import com.alibaba.nacos.client.naming.cache.DiskCache;
import com.alibaba.nacos.client.naming.utils.CacheDirUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
@ -66,7 +60,7 @@ public class DiskFailoverDataSource implements FailoverDataSource {
private long lastModifiedMillis = 0L;
public DiskFailoverDataSource() {
failoverDir = CacheDirUtil.gettCacheDir() + FAILOVER_DIR;
failoverDir = CacheDirUtil.getCacheDir() + FAILOVER_DIR;
}
class FailoverFileReader implements Runnable {
@ -75,13 +69,9 @@ public class DiskFailoverDataSource implements FailoverDataSource {
public void run() {
Map<String, FailoverData> domMap = new HashMap<>(200);
BufferedReader reader = null;
try {
File cacheDir = new File(failoverDir);
if (!cacheDir.exists() && !cacheDir.mkdirs()) {
throw new IllegalStateException("failed to create cache dir: " + failoverDir);
}
DiskCache.createFileIfAbsent(cacheDir, true);
File[] files = cacheDir.listFiles();
if (files == null) {
@ -97,36 +87,8 @@ public class DiskFailoverDataSource implements FailoverDataSource {
continue;
}
ServiceInfo dom = null;
try {
dom = new ServiceInfo(URLDecoder.decode(file.getName(), StandardCharsets.UTF_8.name()));
String dataString = ConcurrentDiskUtil.getFileContent(file,
Charset.defaultCharset().toString());
reader = new BufferedReader(new StringReader(dataString));
String json;
if ((json = reader.readLine()) != null) {
try {
dom = JacksonUtils.toObj(json, ServiceInfo.class);
} catch (Exception e) {
NAMING_LOGGER.error("[NA] error while parsing cached dom : {}", json, e);
}
}
} catch (Exception e) {
NAMING_LOGGER.error("[NA] failed to read cache for dom: {}", file.getName(), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
//ignore
}
}
if (dom != null && !CollectionUtils.isEmpty(dom.getHosts())) {
domMap.put(dom.getKey(), NamingFailoverData.newNamingFailoverData(dom));
for (Map.Entry<String, ServiceInfo> entry : DiskCache.parseServiceInfoFromCache(file).entrySet()) {
domMap.put(entry.getKey(), NamingFailoverData.newNamingFailoverData(entry.getValue()));
}
}
} catch (Exception e) {
@ -152,8 +114,8 @@ public class DiskFailoverDataSource implements FailoverDataSource {
if (lastModifiedMillis < modified) {
lastModifiedMillis = modified;
String failover = ConcurrentDiskUtil.getFileContent(switchFile.getPath(),
Charset.defaultCharset().toString());
String failover = ConcurrentDiskUtil
.getFileContent(switchFile.getPath(), Charset.defaultCharset().toString());
if (!StringUtils.isEmpty(failover)) {
String[] lines = failover.split(DiskCache.getLineSeparator());

View File

@ -16,8 +16,6 @@
package com.alibaba.nacos.client.naming.cache;
import com.alibaba.nacos.common.utils.IoUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -68,39 +66,14 @@ public class ConcurrentDiskUtil {
* @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) {
NAMING_LOGGER.error("[NA] read " + file.getName() + " fail;retryed time: " + i, e);
throw new IOException("read " + file.getAbsolutePath() + " conflict");
}
sleep(SLEEP_BASETIME * i);
NAMING_LOGGER.warn("read " + file.getName() + " conflict;retry time: " + i);
}
} while (null == rlock);
try (RandomAccessFile fis = new RandomAccessFile(file, READ_ONLY);
FileChannel fcin = fis.getChannel();
FileLock rlock = tryLock(file, fcin, true)) {
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;
}
}
}
@ -132,27 +105,9 @@ public class ConcurrentDiskUtil {
if (!file.exists() && !file.createNewFile()) {
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) {
NAMING_LOGGER.error("[NA] write {} fail;retryed time:{}", file.getName(), i);
throw new IOException("write " + file.getAbsolutePath() + " conflict", e);
}
sleep(SLEEP_BASETIME * i);
NAMING_LOGGER.warn("write " + file.getName() + " conflict;retry time: " + i);
}
} while (null == lock);
try (RandomAccessFile raf = new RandomAccessFile(file, READ_WRITE);
FileChannel channel = raf.getChannel();
FileLock lock = tryLock(file, channel, false)) {
byte[] contentBytes = content.getBytes(charsetName);
ByteBuffer sendBuffer = ByteBuffer.wrap(contentBytes);
while (sendBuffer.hasRemaining()) {
@ -161,32 +116,6 @@ public class ConcurrentDiskUtil {
channel.truncate(contentBytes.length);
} catch (FileNotFoundException e) {
throw new IOException("file not exist");
} finally {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException e) {
NAMING_LOGGER.warn("close wrong", e);
}
}
if (channel != null) {
try {
channel.close();
channel = null;
} catch (IOException e) {
NAMING_LOGGER.warn("close wrong", e);
}
}
if (raf != null) {
try {
raf.close();
raf = null;
} catch (IOException e) {
NAMING_LOGGER.warn("close wrong", e);
}
}
}
return true;
}
@ -216,4 +145,23 @@ public class ConcurrentDiskUtil {
}
}
private static FileLock tryLock(File file, FileChannel channel, boolean shared) throws IOException {
FileLock result = null;
int i = 0;
do {
try {
result = channel.tryLock(0L, Long.MAX_VALUE, shared);
} 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");
}
sleep(SLEEP_BASETIME * i);
NAMING_LOGGER.warn("read " + file.getName() + " conflict;retry time: " + i);
}
} while (null == result);
return result;
}
}

View File

@ -25,7 +25,9 @@ import com.alibaba.nacos.common.utils.StringUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
@ -54,12 +56,7 @@ public class DiskCache {
makeSureCacheDirExists(dir);
File file = new File(dir, dom.getKeyEncoded());
if (!file.exists()) {
// add another !file.exists() to avoid conflicted creating-new-file from multi-instances
if (!file.createNewFile() && !file.exists()) {
throw new IllegalStateException("failed to create cache file");
}
}
createFileIfAbsent(file, false);
StringBuilder keyContentBuffer = new StringBuilder();
@ -91,8 +88,6 @@ public class DiskCache {
*/
public static Map<String, ServiceInfo> read(String cacheDir) {
Map<String, ServiceInfo> domMap = new HashMap<>(16);
BufferedReader reader = null;
try {
File[] files = makeSureCacheDirExists(cacheDir).listFiles();
if (files == null || files.length == 0) {
@ -103,57 +98,7 @@ public class DiskCache {
if (!file.isFile()) {
continue;
}
String fileName = URLDecoder.decode(file.getName(), "UTF-8");
if (!(fileName.endsWith(Constants.SERVICE_INFO_SPLITER + "meta") || fileName
.endsWith(Constants.SERVICE_INFO_SPLITER + "special-url"))) {
ServiceInfo dom = new ServiceInfo(fileName);
List<Instance> ips = new ArrayList<>();
dom.setHosts(ips);
ServiceInfo newFormat = null;
try {
String dataString = ConcurrentDiskUtil
.getFileContent(file, Charset.defaultCharset().toString());
reader = new BufferedReader(new StringReader(dataString));
String json;
while ((json = reader.readLine()) != null) {
try {
if (!json.startsWith("{")) {
continue;
}
newFormat = JacksonUtils.toObj(json, ServiceInfo.class);
if (StringUtils.isEmpty(newFormat.getName())) {
ips.add(JacksonUtils.toObj(json, Instance.class));
}
} catch (Throwable e) {
NAMING_LOGGER.error("[NA] error while parsing cache file: " + json, e);
}
}
} catch (Exception e) {
NAMING_LOGGER.error("[NA] failed to read cache for dom: " + file.getName(), e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
//ignore
}
}
if (newFormat != null && !StringUtils.isEmpty(newFormat.getName()) && !CollectionUtils
.isEmpty(newFormat.getHosts())) {
domMap.put(dom.getKey(), newFormat);
} else if (!CollectionUtils.isEmpty(dom.getHosts())) {
domMap.put(dom.getKey(), dom);
}
}
domMap.putAll(parseServiceInfoFromCache(file));
}
} catch (Throwable e) {
NAMING_LOGGER.error("[NA] failed to read cache file", e);
@ -162,14 +107,75 @@ public class DiskCache {
return domMap;
}
private static File makeSureCacheDirExists(String dir) {
File cacheDir = new File(dir);
if (!cacheDir.exists()) {
if (!cacheDir.mkdirs() && !cacheDir.exists()) {
throw new IllegalStateException("failed to create cache dir: " + dir);
/**
* Parse Service info from cache file or failover file.
*
* @param file cache file or failover file
* @return Service info
* @throws UnsupportedEncodingException if the file is not encoded in UTF-8
*/
@SuppressWarnings("PMD.UndefineMagicConstantRule")
public static Map<String, ServiceInfo> parseServiceInfoFromCache(File file) throws UnsupportedEncodingException {
Map<String, ServiceInfo> result = new HashMap<>(1);
String fileName = URLDecoder.decode(file.getName(), "UTF-8");
if (!(fileName.endsWith(Constants.SERVICE_INFO_SPLITER + "meta") || fileName
.endsWith(Constants.SERVICE_INFO_SPLITER + "special-url"))) {
ServiceInfo dom = new ServiceInfo(fileName);
List<Instance> ips = new ArrayList<>();
dom.setHosts(ips);
ServiceInfo newFormat = null;
try (BufferedReader reader = new BufferedReader(
new StringReader(ConcurrentDiskUtil.getFileContent(file, Charset.defaultCharset().toString())))) {
String json;
while ((json = reader.readLine()) != null) {
try {
if (!json.startsWith("{")) {
continue;
}
newFormat = JacksonUtils.toObj(json, ServiceInfo.class);
if (StringUtils.isEmpty(newFormat.getName())) {
ips.add(JacksonUtils.toObj(json, Instance.class));
}
} catch (Throwable e) {
NAMING_LOGGER.error("[NA] error while parsing cache file: " + json, e);
}
}
} catch (Exception e) {
NAMING_LOGGER.error("[NA] failed to read cache for dom: " + file.getName(), e);
}
if (newFormat != null && !StringUtils.isEmpty(newFormat.getName()) && !CollectionUtils
.isEmpty(newFormat.getHosts())) {
result.put(dom.getKey(), newFormat);
} else if (!CollectionUtils.isEmpty(dom.getHosts())) {
result.put(dom.getKey(), dom);
}
}
return result;
}
/**
* Create file if absent.
*
* @param file file
* @param isDir is dir
* @throws IOException if any io exception during create.
*/
public static void createFileIfAbsent(File file, boolean isDir) throws IOException {
if (file.exists()) {
return;
}
boolean createResult = isDir ? file.mkdirs() : file.createNewFile();
if (!createResult && !file.exists()) {
throw new IllegalStateException("failed to create cache : " + (isDir ? "dir" : file) + file.getPath());
}
}
private static File makeSureCacheDirExists(String dir) throws IOException {
File cacheDir = new File(dir);
createFileIfAbsent(cacheDir, true);
return cacheDir;
}
}

View File

@ -44,11 +44,9 @@ public class Balancer {
*/
public static List<Instance> selectAll(ServiceInfo serviceInfo) {
List<Instance> hosts = serviceInfo.getHosts();
if (CollectionUtils.isEmpty(hosts)) {
throw new IllegalStateException("no host to srv for serviceInfo: " + serviceInfo.getName());
}
return hosts;
}
@ -59,14 +57,7 @@ public class Balancer {
* @return random instance
*/
public static Instance selectHost(ServiceInfo dom) {
List<Instance> hosts = selectAll(dom);
if (CollectionUtils.isEmpty(hosts)) {
throw new IllegalStateException("no host to srv for service: " + dom.getName());
}
return getHostByRandomWeight(hosts);
return getHostByRandomWeight(selectAll(dom));
}
}

View File

@ -75,9 +75,9 @@ public class ServerListManager implements ServerListFactory, Closeable {
private ScheduledExecutorService refreshServerListExecutor;
private String endpoint;
private String contentPath = ParamUtil.getDefaultContextPath();
private String serverListName = ParamUtil.getDefaultNodesPath();
private String nacosDomain;
@ -91,7 +91,7 @@ public class ServerListManager implements ServerListFactory, Closeable {
public ServerListManager(NacosClientProperties properties, String namespace) {
this.namespace = namespace;
initServerAddr(properties);
if (getServerList().isEmpty() && StringUtils.isEmpty(endpoint)) {
if (getServerList().isEmpty()) {
throw new NacosLoadException("serverList is empty,please check configuration");
} else {
currentIndex.set(new Random().nextInt(getServerList().size()));
@ -101,7 +101,7 @@ public class ServerListManager implements ServerListFactory, Closeable {
private void initServerAddr(NacosClientProperties properties) {
this.endpoint = InitUtils.initEndpoint(properties);
if (StringUtils.isNotEmpty(endpoint)) {
String contentPathTmp = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
if (!StringUtils.isBlank(contentPathTmp)) {
this.contentPath = contentPathTmp;
@ -110,7 +110,7 @@ public class ServerListManager implements ServerListFactory, Closeable {
if (!StringUtils.isBlank(serverListNameTmp)) {
this.serverListName = serverListNameTmp;
}
this.serversFromEndpoint = getServerListFromEndpoint();
refreshServerListExecutor = new ScheduledThreadPoolExecutor(1,
new NameThreadFactory("com.alibaba.nacos.client.naming.server.list.refresher"));
@ -130,13 +130,11 @@ public class ServerListManager implements ServerListFactory, Closeable {
private List<String> getServerListFromEndpoint() {
try {
StringBuilder addressServerUrlTem = new StringBuilder(
String.format("http://%s%s/%s", this.endpoint,
ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName));
StringBuilder addressServerUrlTem = new StringBuilder(String.format("http://%s%s/%s", this.endpoint,
ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName));
String urlString = addressServerUrlTem.toString();
Header header = NamingHttpUtil.builderHeader();
Query query = StringUtils.isNotBlank(namespace)
? Query.newInstance().addParam("namespace", namespace)
Query query = StringUtils.isNotBlank(namespace) ? Query.newInstance().addParam("namespace", namespace)
: Query.EMPTY;
HttpRestResult<String> restResult = nacosRestTemplate.get(urlString, header, query, String.class);
if (!restResult.ok()) {
@ -154,7 +152,7 @@ public class ServerListManager implements ServerListFactory, Closeable {
} catch (Exception e) {
NAMING_LOGGER.error("[SERVER-LIST] failed to update server list.", e);
}
return null;
return new ArrayList<>();
}
private void refreshServerListIfNeed() {

View File

@ -138,8 +138,9 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
doRegisterServiceForPersistent(serviceName, groupName, instance);
}
}
private void registerServiceForEphemeral(String serviceName, String groupName, Instance instance) throws NacosException {
private void registerServiceForEphemeral(String serviceName, String groupName, Instance instance)
throws NacosException {
redoService.cacheInstanceForRedo(serviceName, groupName, instance);
doRegisterService(serviceName, groupName, instance);
}
@ -163,9 +164,9 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
/**
* Get instance list that need to be Retained.
*
* @param serviceName service name
* @param groupName group name
* @param deRegisterInstances deregister instance list
* @param serviceName service name
* @param groupName group name
* @param deRegisterInstances deregister instance list
* @return instance list that need to be retained.
*/
private List<Instance> getRetainInstance(String serviceName, String groupName, List<Instance> deRegisterInstances)
@ -215,8 +216,8 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
}
private boolean compareIpAndPort(Instance deRegisterInstance, Instance redoInstance) {
return ((deRegisterInstance.getIp().equals(redoInstance.getIp()))
&& (deRegisterInstance.getPort() == redoInstance.getPort()));
return ((deRegisterInstance.getIp().equals(redoInstance.getIp())) && (deRegisterInstance.getPort()
== redoInstance.getPort()));
}
/**
@ -258,24 +259,27 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
* @param instance instance to register
* @throws NacosException nacos exception
*/
public void doRegisterServiceForPersistent(String serviceName, String groupName, Instance instance) throws NacosException {
public void doRegisterServiceForPersistent(String serviceName, String groupName, Instance instance)
throws NacosException {
PersistentInstanceRequest request = new PersistentInstanceRequest(namespaceId, serviceName, groupName,
NamingRemoteConstants.REGISTER_INSTANCE, instance);
requestToServer(request, Response.class);
}
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId,
serviceName, instance);
NAMING_LOGGER
.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId, serviceName,
instance);
if (instance.isEphemeral()) {
deregisterServiceForEphemeral(serviceName, groupName, instance);
} else {
doDeregisterServiceForPersistent(serviceName, groupName, instance);
}
}
private void deregisterServiceForEphemeral(String serviceName, String groupName, Instance instance) throws NacosException {
private void deregisterServiceForEphemeral(String serviceName, String groupName, Instance instance)
throws NacosException {
String key = NamingUtils.getGroupedName(serviceName, groupName);
InstanceRedoData instanceRedoData = redoService.getRegisteredInstancesByKey(key);
if (instanceRedoData instanceof BatchInstanceRedoData) {
@ -304,7 +308,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
requestToServer(request, Response.class);
redoService.instanceDeregistered(serviceName, groupName);
}
/**
* Execute deregister operation for persistent instance.
*
@ -313,7 +317,8 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
* @param instance instance
* @throws NacosException nacos exception
*/
public void doDeregisterServiceForPersistent(String serviceName, String groupName, Instance instance) throws NacosException {
public void doDeregisterServiceForPersistent(String serviceName, String groupName, Instance instance)
throws NacosException {
PersistentInstanceRequest request = new PersistentInstanceRequest(namespaceId, serviceName, groupName,
NamingRemoteConstants.DE_REGISTER_INSTANCE, instance);
requestToServer(request, Response.class);
@ -321,7 +326,6 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException {
}
@Override
@ -341,7 +345,6 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public void createService(Service service, AbstractSelector selector) throws NacosException {
}
@Override
@ -351,7 +354,6 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public void updateService(Service service, AbstractSelector selector) throws NacosException {
}
@Override
@ -372,9 +374,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException {
if (NAMING_LOGGER.isDebugEnabled()) {
NAMING_LOGGER.debug("[GRPC-SUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
}
NAMING_LOGGER.info("[GRPC-SUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
redoService.cacheSubscriberForRedo(serviceName, groupName, clusters);
return doSubscribe(serviceName, groupName, clusters);
}
@ -398,10 +398,7 @@ public class NamingGrpcClientProxy extends AbstractNamingClientProxy {
@Override
public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException {
if (NAMING_LOGGER.isDebugEnabled()) {
NAMING_LOGGER.debug("[GRPC-UNSUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName,
clusters);
}
NAMING_LOGGER.info("[GRPC-UNSUBSCRIBE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters);
redoService.subscriberDeregister(serviceName, groupName, clusters);
doUnsubscribe(serviceName, groupName, clusters);
}

View File

@ -59,10 +59,7 @@ public class NamingHttpClientManager implements Closeable {
}
public String getPrefix() {
if (ENABLE_HTTPS) {
return HTTPS_PREFIX;
}
return HTTP_PREFIX;
return ENABLE_HTTPS ? HTTPS_PREFIX : HTTP_PREFIX;
}
public NacosRestTemplate getNacosRestTemplate() {

View File

@ -69,7 +69,7 @@ public class CacheDirUtil {
return cacheDir;
}
public static String gettCacheDir() {
public static String getCacheDir() {
return cacheDir;
}
}

View File

@ -32,6 +32,17 @@ public class Chooser<K, T> {
private volatile Ref<T> ref;
public Chooser(K uniqueKey) {
this(uniqueKey, new ArrayList<>());
}
public Chooser(K uniqueKey, List<Pair<T>> pairs) {
Ref<T> ref = new Ref<>(pairs);
ref.refresh();
this.uniqueKey = uniqueKey;
this.ref = ref;
}
/**
* Random get one item.
*
@ -79,17 +90,6 @@ public class Chooser<K, T> {
return ref.items.get(ref.items.size() - 1);
}
public Chooser(K uniqueKey) {
this(uniqueKey, new ArrayList<Pair<T>>());
}
public Chooser(K uniqueKey, List<Pair<T>> pairs) {
Ref<T> ref = new Ref<>(pairs);
ref.refresh();
this.uniqueKey = uniqueKey;
this.ref = ref;
}
public K getUniqueKey() {
return uniqueKey;
}
@ -193,19 +193,8 @@ public class Chooser<K, T> {
if (getClass() != other.getClass()) {
return false;
}
if (!(other.getClass().getGenericInterfaces()[0].equals(this.getClass().getGenericInterfaces()[0]))) {
return false;
}
Ref<T> otherRef = (Ref<T>) other;
if (itemsWithWeight == null) {
return otherRef.itemsWithWeight == null;
} else {
if (otherRef.itemsWithWeight == null) {
return false;
} else {
return this.itemsWithWeight.equals(otherRef.itemsWithWeight);
}
}
return this.itemsWithWeight.equals(otherRef.itemsWithWeight);
}
}
@ -239,15 +228,6 @@ public class Chooser<K, T> {
}
}
if (this.ref == null) {
return otherChooser.getRef() == null;
} else {
if (otherChooser.getRef() == null) {
return false;
} else {
return this.ref.equals(otherChooser.getRef());
}
}
return this.ref.equals(otherChooser.getRef());
}
}

View File

@ -48,12 +48,6 @@ public class CollectionUtils {
*/
private static final Integer INTEGER_ONE = 1;
/**
* <code>CollectionUtils</code> should not normally be instantiated.
*/
public CollectionUtils() {
}
/**
* Returns a new {@link Collection} containing <tt><i>a</i> - <i>b</i></tt>. The cardinality of each element
* <i>e</i> in the returned {@link Collection} will be the cardinality of <i>e</i> in <i>a</i> minus the

View File

@ -43,8 +43,10 @@ public class UtilAndComs {
public static final int REQUEST_DOMAIN_RETRY_COUNT = 3;
@Deprecated
public static final String NACOS_NAMING_LOG_NAME = "com.alibaba.nacos.naming.log.filename";
@Deprecated
public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level";
public static final int DEFAULT_POLLING_THREAD_COUNT =

View File

@ -21,6 +21,7 @@ import org.slf4j.Logger;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* env util.
@ -47,7 +48,7 @@ public class EnvUtil {
}
} else {
String amoryTagTmpStr = listToString(amoryTagTmp);
if (!amoryTagTmpStr.equals(selfAmoryTag)) {
if (!Objects.equals(amoryTagTmpStr, selfAmoryTag)) {
selfAmoryTag = amoryTagTmpStr;
LOGGER.warn("selfAmoryTag:{}", selfAmoryTag);
}
@ -61,7 +62,7 @@ public class EnvUtil {
}
} else {
String vipserverTagTmpStr = listToString(vipserverTagTmp);
if (!vipserverTagTmpStr.equals(selfVipserverTag)) {
if (!Objects.equals(vipserverTagTmpStr, selfVipserverTag)) {
selfVipserverTag = vipserverTagTmpStr;
LOGGER.warn("selfVipserverTag:{}", selfVipserverTag);
}
@ -74,7 +75,7 @@ public class EnvUtil {
}
} else {
String locationTagTmpStr = listToString(locationTagTmp);
if (!locationTagTmpStr.equals(selfLocationTag)) {
if (!Objects.equals(locationTagTmpStr, selfLocationTag)) {
selfLocationTag = locationTagTmpStr;
LOGGER.warn("selfLocationTag:{}", selfLocationTag);
}

View File

@ -80,33 +80,42 @@ public class ParamUtil {
// Client identity information
appKey = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_APP_KEY, BLANK_STR);
defaultContextPath = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_CONTEXTPATH_KEY,
DEFAULT_NACOS_CLIENT_CONTEXTPATH);
defaultContextPath = NacosClientProperties.PROTOTYPE
.getProperty(NACOS_CLIENT_CONTEXTPATH_KEY, DEFAULT_NACOS_CLIENT_CONTEXTPATH);
appName = AppNameUtils.getAppName();
serverPort = NacosClientProperties.PROTOTYPE.getProperty(NACOS_SERVER_PORT_KEY, DEFAULT_SERVER_PORT);
LOGGER.info("[settings] [req-serv] nacos-server port:{}", serverPort);
String tmp = "1000";
connectTimeout = initConnectionTimeout();
LOGGER.info("[settings] [http-client] connect timeout:{}", connectTimeout);
clientVersion = VersionUtils.version;
perTaskConfigSize = initPerTaskConfigSize();
LOGGER.info("PER_TASK_CONFIG_SIZE: {}", perTaskConfigSize);
}
private static int initConnectionTimeout() {
String tmp = DEFAULT_NACOS_CONNECT_TIMEOUT;
try {
tmp = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CONNECT_TIMEOUT_KEY, DEFAULT_NACOS_CONNECT_TIMEOUT);
connectTimeout = Integer.parseInt(tmp);
return Integer.parseInt(tmp);
} catch (NumberFormatException e) {
final String msg = "[http-client] invalid connect timeout:" + tmp;
LOGGER.error("[settings] " + msg, e);
throw new IllegalArgumentException(msg, e);
}
LOGGER.info("[settings] [http-client] connect timeout:{}", connectTimeout);
clientVersion = VersionUtils.version;
}
private static double initPerTaskConfigSize() {
try {
perTaskConfigSize = Double.parseDouble(NacosClientProperties.PROTOTYPE.getProperty(PER_TASK_CONFIG_SIZE_KEY,
DEFAULT_PER_TASK_CONFIG_SIZE_KEY));
LOGGER.info("PER_TASK_CONFIG_SIZE: {}", perTaskConfigSize);
} catch (Throwable t) {
LOGGER.error("[PER_TASK_CONFIG_SIZE] PER_TASK_CONFIG_SIZE invalid", t);
return Double.parseDouble(NacosClientProperties.PROTOTYPE
.getProperty(PER_TASK_CONFIG_SIZE_KEY, DEFAULT_PER_TASK_CONFIG_SIZE_KEY));
} catch (NumberFormatException e) {
LOGGER.error("[PER_TASK_CONFIG_SIZE] PER_TASK_CONFIG_SIZE invalid", e);
throw new IllegalArgumentException("invalid PER_TASK_CONFIG_SIZE, expected value type double", e);
}
}
@ -208,8 +217,8 @@ public class ParamUtil {
// If entered in the configuration file, the priority in ENV will be given priority.
if (endpointUrl == null || !PATTERN.matcher(endpointUrl).find()) {
// skip retrieve from system property and retrieve directly from system env
String endpointUrlSource = NacosClientProperties.PROTOTYPE.getProperty(
PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL);
String endpointUrlSource = NacosClientProperties.PROTOTYPE
.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL);
if (StringUtils.isNotBlank(endpointUrlSource)) {
endpointUrl = endpointUrlSource;
}
@ -225,10 +234,10 @@ public class ParamUtil {
endpointUrl = endpointUrl.substring(0, defStartOf);
}
String endpointUrlSource = TemplateUtils.stringBlankAndThenExecute(
NacosClientProperties.PROTOTYPE.getProperty(endpointUrl),
() -> NacosClientProperties.PROTOTYPE.getProperty(
PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL));
String endpointUrlSource = TemplateUtils
.stringBlankAndThenExecute(NacosClientProperties.PROTOTYPE.getProperty(endpointUrl),
() -> NacosClientProperties.PROTOTYPE
.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL));
if (StringUtils.isBlank(endpointUrlSource)) {
if (StringUtils.isNotBlank(defaultEndpointUrl)) {

View File

@ -24,6 +24,8 @@ import org.mockito.Mockito;
import java.lang.reflect.Field;
import static org.mockito.Mockito.doThrow;
public class NacosLoggingTest {
@Test
@ -42,4 +44,21 @@ public class NacosLoggingTest {
instance.loadConfiguration();
Mockito.verify(mockLogging, Mockito.times(1)).loadConfiguration();
}
@Test
public void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException {
NacosLogging instance = NacosLogging.getInstance();
Field nacosLoggingField = NacosLogging.class.getDeclaredField("nacosLogging");
nacosLoggingField.setAccessible(true);
AbstractNacosLogging cachedLogging = (AbstractNacosLogging) nacosLoggingField.get(instance);
try {
AbstractNacosLogging mockLogging = Mockito.mock(AbstractNacosLogging.class);
doThrow(new RuntimeException()).when(mockLogging).loadConfiguration();
nacosLoggingField.set(instance, mockLogging);
instance.loadConfiguration();
// without exception thrown
} finally {
nacosLoggingField.set(instance, cachedLogging);
}
}
}

View File

@ -21,33 +21,102 @@ package com.alibaba.nacos.client.logging.log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class Log4J2NacosLoggingTest {
private static final String NACOS_LOGGER_PREFIX = "com.alibaba.nacos";
@Mock
PropertyChangeListener propertyChangeListener;
Log4J2NacosLogging log4J2NacosLogging;
@Before
public void setUp() throws Exception {
log4J2NacosLogging = new Log4J2NacosLogging();
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
loggerContext.addPropertyChangeListener(propertyChangeListener);
}
@After
public void tearDown() throws Exception {
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
loggerContext.removePropertyChangeListener(propertyChangeListener);
System.clearProperty("nacos.logging.default.config.enabled");
System.clearProperty("nacos.logging.config");
}
@Test
public void testLoadConfiguration() {
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
Configuration contextConfiguration = loggerContext.getConfiguration();
Assert.assertEquals(0, contextConfiguration.getLoggers().size());
Log4J2NacosLogging log4J2NacosLogging = new Log4J2NacosLogging();
//when
assertEquals(0, contextConfiguration.getLoggers().size());
log4J2NacosLogging.loadConfiguration();
//then
verify(propertyChangeListener).propertyChange(any());
loggerContext = (LoggerContext) LogManager.getContext(false);
contextConfiguration = loggerContext.getConfiguration();
Map<String, LoggerConfig> nacosClientLoggers = contextConfiguration.getLoggers();
Assert.assertEquals(4, nacosClientLoggers.size());
assertEquals(4, nacosClientLoggers.size());
for (Map.Entry<String, LoggerConfig> loggerEntry : nacosClientLoggers.entrySet()) {
String loggerName = loggerEntry.getKey();
Assert.assertTrue(loggerName.startsWith(NACOS_LOGGER_PREFIX));
}
}
@Test
public void testLoadConfigurationWithoutLocation() {
System.setProperty("nacos.logging.default.config.enabled", "false");
log4J2NacosLogging = new Log4J2NacosLogging();
log4J2NacosLogging.loadConfiguration();
verify(propertyChangeListener, never()).propertyChange(any());
}
@Test(expected = IllegalStateException.class)
public void testLoadConfigurationWithWrongLocation() {
System.setProperty("nacos.logging.config", "http://localhost");
log4J2NacosLogging = new Log4J2NacosLogging();
log4J2NacosLogging.loadConfiguration();
verify(propertyChangeListener, never()).propertyChange(any());
}
@Test
public void testGetConfigurationSourceForNonFileProtocol()
throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException {
Method getConfigurationSourceMethod = Log4J2NacosLogging.class
.getDeclaredMethod("getConfigurationSource", URL.class);
getConfigurationSourceMethod.setAccessible(true);
URL url = mock(URL.class);
InputStream inputStream = mock(InputStream.class);
when(url.openStream()).thenReturn(inputStream);
when(url.getProtocol()).thenReturn("http");
ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod.invoke(log4J2NacosLogging, url);
assertEquals(inputStream, actual.getInputStream());
assertEquals(url, actual.getURL());
}
}

View File

@ -18,28 +18,155 @@
package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.junit.Rule;
import ch.qos.logback.classic.joran.ReconfigureOnChangeTask;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.CoreConstants;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;
import static org.hamcrest.CoreMatchers.isA;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class LogbackNacosLoggingTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
LogbackNacosLogging logbackNacosLogging;
@Test
public void testLoadConfiguration() {
ILoggerFactory loggerFactory;
if ((loggerFactory = LoggerFactory.getILoggerFactory()) != null && loggerFactory instanceof LoggerContext) {
exceptionRule.expectCause(isA(ClassCastException.class));
exceptionRule.expectMessage("Could not initialize Logback Nacos logging from classpath:nacos-logback.xml");
LogbackNacosLogging logbackNacosLogging = new LogbackNacosLogging();
logbackNacosLogging.loadConfiguration();
@Mock
LoggerContextListener loggerContextListener;
ILoggerFactory cachedLoggerFactory;
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
logbackNacosLogging = new LogbackNacosLogging();
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (loggerFactory instanceof LoggerContext) {
LoggerContext loggerContext = (LoggerContext) loggerFactory;
loggerContext.addListener(loggerContextListener);
} else {
cachedLoggerFactory = loggerFactory;
LoggerContext loggerContext = new LoggerContext();
loggerContext.addListener(loggerContextListener);
setLoggerFactory(loggerContext);
}
}
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.removeListener(loggerContextListener);
if (null != cachedLoggerFactory) {
setLoggerFactory(cachedLoggerFactory);
assertEquals(cachedLoggerFactory, LoggerFactory.getILoggerFactory());
}
System.clearProperty("nacos.logging.default.config.enabled");
System.clearProperty("nacos.logging.config");
}
public void setLoggerFactory(ILoggerFactory loggerFactory) throws NoSuchFieldException, IllegalAccessException {
Field loggerFactoryField = StaticLoggerBinder.getSingleton().getClass().getDeclaredField("loggerFactory");
loggerFactoryField.setAccessible(true);
loggerFactoryField.set(StaticLoggerBinder.getSingleton(), loggerFactory);
}
@Test
public void testLoadConfigurationSuccess() {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask());
logbackNacosLogging.loadConfiguration();
for (Logger each : loggerContext.getLoggerList()) {
if (!"com.alibaba.nacos.client.naming".equals(each.getName())) {
continue;
}
assertNotNull(each.getAppender("ASYNC-NAMING"));
}
boolean containListener = false;
LoggerContextListener listener = null;
for (LoggerContextListener each : loggerContext.getCopyOfListenerList()) {
if (each instanceof LogbackNacosLogging.NacosLoggerContextListener) {
containListener = true;
listener = each;
break;
}
}
assertTrue(containListener);
// reload duplicate, without exception, listener not add again
logbackNacosLogging.loadConfiguration();
containListener = false;
for (LoggerContextListener each : loggerContext.getCopyOfListenerList()) {
if (each instanceof LogbackNacosLogging.NacosLoggerContextListener) {
assertEquals(listener, each);
containListener = true;
}
}
assertTrue(containListener);
}
@Test(expected = IllegalStateException.class)
public void testLoadConfigurationFailure() {
System.setProperty("nacos.logging.config", "http://localhost");
logbackNacosLogging.loadConfiguration();
}
@Test
public void testLoadConfigurationReload() {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask());
logbackNacosLogging.loadConfiguration();
loggerContext.reset();
verify(loggerContextListener).onReset(loggerContext);
for (Logger each : loggerContext.getLoggerList()) {
if (!"com.alibaba.nacos.client.naming".equals(each.getName())) {
continue;
}
assertNotNull(each.getAppender("ASYNC-NAMING"));
}
}
@Test
public void testLoadConfigurationStart() {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask());
logbackNacosLogging.loadConfiguration();
loggerContext.start();
verify(loggerContextListener).onStart(loggerContext);
for (Logger each : loggerContext.getLoggerList()) {
if (!"com.alibaba.nacos.client.naming".equals(each.getName())) {
continue;
}
assertNotNull(each.getAppender("ASYNC-NAMING"));
}
}
@Test
public void testLoadConfigurationStop() {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask());
logbackNacosLogging.loadConfiguration();
loggerContext.stop();
verify(loggerContextListener).onReset(loggerContext);
verify(loggerContextListener, never()).onStop(loggerContext);
for (Logger each : loggerContext.getLoggerList()) {
if (!"com.alibaba.nacos.client.naming".equals(each.getName())) {
continue;
}
assertNotNull(each.getAppender("ASYNC-NAMING"));
}
assertTrue(loggerContext.getCopyOfListenerList().isEmpty());
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logging.logback;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NacosClientLogbackPropertiesTest {
NacosClientLogbackProperties nacosClientLogbackProperties;
@Before
public void setUp() throws Exception {
System.setProperty("nacos.logging.logback.test", "test");
nacosClientLogbackProperties = new NacosClientLogbackProperties();
}
@After
public void tearDown() throws Exception {
System.clearProperty("nacos.logging.logback.test");
}
@Test
public void testGetValue() {
assertEquals("test", nacosClientLogbackProperties.getValue("nacos.logging.logback.test", ""));
assertEquals("", nacosClientLogbackProperties.getValue("nacos.logging.logback.non.exist", ""));
}
}

View File

@ -16,24 +16,42 @@
package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.status.ErrorStatus;
import ch.qos.logback.core.status.Status;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.xml.sax.Attributes;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class NacosClientPropertyActionTest {
ContextBase context;
@Before
public void setUp() throws Exception {
context = new ContextBase();
}
@After
public void tearDown() throws Exception {
context.stop();
}
@Test
public void testLookUpVar() throws ActionException {
NacosClientProperties.PROTOTYPE.setProperty("test.nacos.logging.action.lookup", "true");
Context context = new ContextBase();
final InterpretationContext interpretationContext = new InterpretationContext(context, null);
final Attributes mockAttr = Mockito.mock(AttributesForTest.class);
@ -41,15 +59,33 @@ public class NacosClientPropertyActionTest {
Mockito.when(mockAttr.getValue(Mockito.eq("source"))).thenReturn("test.nacos.logging.action.lookup");
Mockito.when(mockAttr.getValue(Mockito.eq("scope"))).thenReturn("context");
Mockito.when(mockAttr.getValue(Mockito.eq("defaultValue"))).thenReturn("/root");
NacosClientPropertyAction nacosClientPropertyAction = new NacosClientPropertyAction();
nacosClientPropertyAction.setContext(context);
nacosClientPropertyAction.begin(interpretationContext, "nacosClientProperty", mockAttr);
final String actual = context.getProperty("logPath");
Assert.assertEquals("true", actual);
assertEquals("true", actual);
}
@Test
public void testBeginWithoutName() throws ActionException {
final InterpretationContext interpretationContext = new InterpretationContext(context, null);
final Attributes mockAttr = Mockito.mock(AttributesForTest.class);
Mockito.when(mockAttr.getValue(Mockito.eq("name"))).thenReturn("");
Mockito.when(mockAttr.getValue(Mockito.eq("source"))).thenReturn("test.nacos.logging.action.lookup");
Mockito.when(mockAttr.getValue(Mockito.eq("scope"))).thenReturn("context");
Mockito.when(mockAttr.getValue(Mockito.eq("defaultValue"))).thenReturn("/root");
NacosClientPropertyAction nacosClientPropertyAction = new NacosClientPropertyAction();
nacosClientPropertyAction.setContext(context);
nacosClientPropertyAction.begin(interpretationContext, "nacosClientProperty", mockAttr);
List<Status> statusList = context.getStatusManager().getCopyOfStatusList();
assertEquals(1, statusList.size());
assertTrue(statusList.get(0) instanceof ErrorStatus);
assertEquals("The \"name\" and \"source\" attributes of <nacosClientProperty> must be set",
statusList.get(0).getMessage());
}
static class AttributesForTest implements Attributes {
@ -98,7 +134,7 @@ public class NacosClientPropertyActionTest {
public String getType(String qName) {
return null;
}
@Override
public String getValue(int index) {
return null;

View File

@ -0,0 +1,84 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.status.ErrorStatus;
import ch.qos.logback.core.status.Status;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class NacosLogbackConfiguratorAdapterV1Test {
@Mock
private URL url;
@Mock
private URLConnection urlConnection;
@Mock
private InputStream inputStream;
ContextBase context;
NacosLogbackConfiguratorAdapterV1 nacosLogbackConfiguratorAdapter;
@Before
public void setUp() throws Exception {
nacosLogbackConfiguratorAdapter = new NacosLogbackConfiguratorAdapterV1();
context = new ContextBase();
nacosLogbackConfiguratorAdapter.setContext(context);
when(url.openConnection()).thenReturn(urlConnection);
when(urlConnection.getInputStream()).thenReturn(inputStream);
}
@After
public void tearDown() throws Exception {
context.stop();
}
@Test
public void testConfigureWithError() throws Exception {
doThrow(new IOException("test")).when(inputStream).close();
try {
nacosLogbackConfiguratorAdapter.configure(url);
} catch (JoranException e) {
List<Status> statusList = context.getStatusManager().getCopyOfStatusList();
assertFalse(statusList.isEmpty());
assertTrue(statusList.get(statusList.size() - 1) instanceof ErrorStatus);
assertEquals("Could not close input stream", statusList.get(statusList.size() - 1).getMessage());
}
}
}

View File

@ -25,65 +25,96 @@ import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.NamingClientProxy;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class NacosNamingServiceTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private NacosNamingService client;
@Mock
private NamingClientProxy proxy;
private String uuid;
@Mock
private InstancesChangeNotifier changeNotifier;
@Mock
private ServiceInfoHolder serviceInfoHolder;
private NacosNamingService client;
@Before
public void before() throws NoSuchFieldException, NacosException, IllegalAccessException {
Properties prop = new Properties();
prop.setProperty("serverAddr", "localhost");
prop.put(PropertyKeyConst.NAMESPACE, "test");
client = new NacosNamingService(prop);
injectMocks(client);
}
@After
public void tearDown() throws NacosException {
client.shutDown();
}
private void injectMocks(NacosNamingService client) throws NoSuchFieldException, IllegalAccessException {
// inject proxy
proxy = mock(NamingHttpClientProxy.class);
Field serverProxyField = NacosNamingService.class.getDeclaredField("clientProxy");
serverProxyField.setAccessible(true);
try {
((NamingHttpClientProxy) serverProxyField.get(client)).shutdown();
} catch (Throwable ignored) {
}
serverProxyField.set(client, proxy);
// inject notifier
changeNotifier = mock(InstancesChangeNotifier.class);
doReturn(InstancesChangeEvent.class).when(changeNotifier).subscribeType();
Field changeNotifierField = NacosNamingService.class.getDeclaredField("changeNotifier");
changeNotifierField.setAccessible(true);
changeNotifierField.set(client, changeNotifier);
// inject service info holder
Field serviceInfoHolderField = NacosNamingService.class.getDeclaredField("serviceInfoHolder");
serviceInfoHolderField.setAccessible(true);
try {
((ServiceInfoHolder) serviceInfoHolderField.get(client)).shutdown();
} catch (Throwable ignored) {
}
serviceInfoHolderField.set(client, serviceInfoHolder);
}
@Test
@ -138,7 +169,7 @@ public class NacosNamingServiceTest {
verify(proxy, times(1)).batchRegisterService(eq(serviceName), eq(Constants.DEFAULT_GROUP),
argThat(instances -> CollectionUtils.isEqualCollection(instanceList, instances)));
}
@Test
public void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException {
Instance instance = new Instance();
@ -430,8 +461,8 @@ public class NacosNamingServiceTest {
//when
client.getAllInstances(serviceName, clusterList, false);
//then
verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2",
false);
verify(proxy, times(1))
.queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false);
}
@Test
@ -446,6 +477,28 @@ public class NacosNamingServiceTest {
verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false);
}
@Test
public void testGetAllInstanceFromFailover() throws NacosException {
when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true);
ServiceInfo serviceInfo = new ServiceInfo("group1@@service1");
serviceInfo.setHosts(Collections.singletonList(new Instance()));
when(serviceInfoHolder.getFailoverServiceInfo(anyString(), anyString(), anyString())).thenReturn(serviceInfo);
List<Instance> actual = client.getAllInstances("service1", "group1", false);
verify(proxy, never()).queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean());
assertEquals(1, actual.size());
assertEquals(new Instance(), actual.get(0));
}
@Test
public void testGetAllInstanceFromFailoverEmpty() throws NacosException {
when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true);
ServiceInfo serviceInfo = new ServiceInfo("group1@@service1");
when(serviceInfoHolder.getFailoverServiceInfo(anyString(), anyString(), anyString())).thenReturn(serviceInfo);
List<Instance> actual = client.getAllInstances("service1", "group1", false);
verify(proxy).queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean());
assertEquals(0, actual.size());
}
@Test
public void testSelectInstances1() throws NacosException {
//given
@ -521,8 +574,8 @@ public class NacosNamingServiceTest {
//when
client.selectInstances(serviceName, clusterList, true, false);
//then
verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2",
false);
verify(proxy, times(1))
.queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false);
}
@Test
@ -569,7 +622,7 @@ public class NacosNamingServiceTest {
//when
List<Instance> instances = client.selectInstances(serviceName, groupName, clusterList, true, false);
//then
Assert.assertEquals(1, instances.size());
assertEquals(1, instances.size());
Assert.assertSame(healthyInstance, instances.get(0));
}
@ -622,8 +675,8 @@ public class NacosNamingServiceTest {
hosts.add(healthyInstance);
ServiceInfo infoWithHealthyInstance = new ServiceInfo();
infoWithHealthyInstance.setHosts(hosts);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(
infoWithHealthyInstance);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()))
.thenReturn(infoWithHealthyInstance);
String serviceName = "service1";
//when
@ -642,8 +695,8 @@ public class NacosNamingServiceTest {
hosts.add(healthyInstance);
ServiceInfo infoWithHealthyInstance = new ServiceInfo();
infoWithHealthyInstance.setHosts(hosts);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(
infoWithHealthyInstance);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()))
.thenReturn(infoWithHealthyInstance);
String serviceName = "service1";
String groupName = "group1";
@ -706,16 +759,16 @@ public class NacosNamingServiceTest {
hosts.add(healthyInstance);
ServiceInfo infoWithHealthyInstance = new ServiceInfo();
infoWithHealthyInstance.setHosts(hosts);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(
infoWithHealthyInstance);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()))
.thenReturn(infoWithHealthyInstance);
String serviceName = "service1";
List<String> clusterList = Arrays.asList("cluster1", "cluster2");
//when
client.selectOneHealthyInstance(serviceName, clusterList, false);
//then
verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2",
false);
verify(proxy, times(1))
.queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false);
}
@Test
@ -728,8 +781,8 @@ public class NacosNamingServiceTest {
hosts.add(healthyInstance);
ServiceInfo infoWithHealthyInstance = new ServiceInfo();
infoWithHealthyInstance.setHosts(hosts);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(
infoWithHealthyInstance);
when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()))
.thenReturn(infoWithHealthyInstance);
String serviceName = "service1";
String groupName = "group1";
@ -780,8 +833,8 @@ public class NacosNamingServiceTest {
//when
client.subscribe(serviceName, clusterList, listener);
//then
verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2",
listener);
verify(changeNotifier, times(1))
.registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener);
verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2");
}
@ -801,6 +854,18 @@ public class NacosNamingServiceTest {
verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2");
}
@Test
public void testSubscribeWithNullListener() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
//when
client.subscribe(serviceName, groupName, null);
//then
verify(changeNotifier, never()).registerListener(groupName, serviceName, "", null);
verify(proxy, never()).subscribe(serviceName, groupName, "");
}
@Test
public void testUnSubscribe1() throws NacosException {
//given
@ -808,8 +873,6 @@ public class NacosNamingServiceTest {
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(serviceName, Constants.DEFAULT_GROUP, "")).thenReturn(false);
//when
client.unsubscribe(serviceName, listener);
//then
verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "", listener);
@ -824,9 +887,6 @@ public class NacosNamingServiceTest {
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(serviceName, groupName, "")).thenReturn(false);
//when
client.unsubscribe(serviceName, groupName, listener);
//then
verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "", listener);
@ -841,13 +901,10 @@ public class NacosNamingServiceTest {
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2")).thenReturn(false);
//when
client.unsubscribe(serviceName, clusterList, listener);
//then
verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2",
listener);
verify(changeNotifier, times(1))
.deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener);
verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2");
}
@ -860,9 +917,6 @@ public class NacosNamingServiceTest {
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(serviceName, groupName, "cluster1,cluster2")).thenReturn(false);
//when
client.unsubscribe(serviceName, groupName, clusterList, listener);
//then
verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "cluster1,cluster2", listener);
@ -943,7 +997,7 @@ public class NacosNamingServiceTest {
//when
String serverStatus = client.getServerStatus();
//then
Assert.assertEquals("UP", serverStatus);
assertEquals("UP", serverStatus);
}
@Test
@ -953,7 +1007,7 @@ public class NacosNamingServiceTest {
//when
String serverStatus = client.getServerStatus();
//then
Assert.assertEquals("DOWN", serverStatus);
assertEquals("DOWN", serverStatus);
}
@Test
@ -963,4 +1017,17 @@ public class NacosNamingServiceTest {
//then
verify(proxy, times(1)).shutdown();
}
@Test
public void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException {
NacosNamingService namingService = new NacosNamingService("localhost");
try {
Field namespaceField = NacosNamingService.class.getDeclaredField("namespace");
namespaceField.setAccessible(true);
String namespace = (String) namespaceField.get(namingService);
assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, namespace);
} finally {
namingService.shutDown();
}
}
}

View File

@ -19,59 +19,137 @@ package com.alibaba.nacos.client.naming.backups;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.common.utils.ReflectUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.Date;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class FailoverReactorTest {
@Test
public void testInit() throws NacosException, NoSuchFieldException, IllegalAccessException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
FailoverReactor failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString());
Field executorService = FailoverReactor.class.getDeclaredField("executorService");
executorService.setAccessible(true);
ScheduledExecutorService o = (ScheduledExecutorService) executorService.get(failoverReactor);
Assert.assertFalse(o.isShutdown());
failoverReactor.shutdown();
Assert.assertTrue(o.isShutdown());
@Mock
ServiceInfoHolder holder;
@Mock
FailoverDataSource failoverDataSource;
FailoverReactor failoverReactor;
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString());
Field failoverDataSourceField = FailoverReactor.class.getDeclaredField("failoverDataSource");
failoverDataSourceField.setAccessible(true);
failoverDataSourceField.set(failoverReactor, failoverDataSource);
}
@Test
public void testAddDay() throws NacosException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
FailoverReactor failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString());
Date date = new Date();
Date actual = failoverReactor.addDay(date, 1);
Assert.assertEquals(date.getTime() + 24 * 60 * 60 * 1000, actual.getTime());
@After
public void tearDown() throws NacosException {
failoverReactor.shutdown();
}
@Test
public void testIsFailoverSwitch() throws NacosException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
FailoverReactor failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString());
Assert.assertFalse(failoverReactor.isFailoverSwitch());
failoverReactor.shutdown();
}
@Test
public void testGetService() throws NacosException {
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
FailoverReactor failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString());
ServiceInfo info = failoverReactor.getService("aa@@bb");
Assert.assertEquals(new ServiceInfo("aa@@bb").toString(), info.toString());
failoverReactor.shutdown();
assertEquals(new ServiceInfo("aa@@bb").toString(), info.toString());
}
@Test
public void testRefreshFromDisabledToEnabled() throws InterruptedException {
// make sure the first no delay refresh thread finished.
TimeUnit.MILLISECONDS.sleep(500);
FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true);
when(failoverDataSource.getSwitch()).thenReturn(mockFailoverSwitch);
Map<String, FailoverData> map = new HashMap<>();
ServiceInfo serviceInfo = new ServiceInfo("a@@b");
map.put("a@@b", NamingFailoverData.newNamingFailoverData(serviceInfo));
when(failoverDataSource.getFailoverData()).thenReturn(map);
when(holder.isChangedServiceInfo(any(), any())).thenReturn(true);
// waiting refresh thread work
TimeUnit.MILLISECONDS.sleep(5500);
ServiceInfo actual = failoverReactor.getService("a@@b");
assertEquals(serviceInfo, actual);
}
@Test
public void testRefreshFromDisabledToEnabledWithException() throws InterruptedException {
// make sure the first no delay refresh thread finished.
TimeUnit.MILLISECONDS.sleep(500);
FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true);
when(failoverDataSource.getSwitch()).thenReturn(mockFailoverSwitch);
when(failoverDataSource.getFailoverData()).thenReturn(null);
// waiting refresh thread work
TimeUnit.MILLISECONDS.sleep(5500);
assertTrue(((Map) ReflectUtils.getFieldValue(failoverDataSource, "serviceMap", new HashMap<>())).isEmpty());
}
@Test
public void testRefreshFromEnabledToDisabled()
throws InterruptedException, NoSuchFieldException, IllegalAccessException {
// make sure the first no delay refresh thread finished.
TimeUnit.MILLISECONDS.sleep(500);
FailoverSwitch mockFailoverSwitch = new FailoverSwitch(false);
when(failoverDataSource.getSwitch()).thenReturn(mockFailoverSwitch);
Field failoverSwitchEnableField = FailoverReactor.class.getDeclaredField("failoverSwitchEnable");
failoverSwitchEnableField.setAccessible(true);
failoverSwitchEnableField.set(failoverReactor, true);
Map<String, ServiceInfo> map = new HashMap<>();
ServiceInfo serviceInfo = new ServiceInfo("a@@b");
map.put("a@@b", serviceInfo);
when(holder.getServiceInfoMap()).thenReturn(map);
Field serviceMapField = FailoverReactor.class.getDeclaredField("serviceMap");
serviceMapField.setAccessible(true);
serviceMapField.set(failoverReactor, map);
when(holder.isChangedServiceInfo(any(), any())).thenReturn(true);
// waiting refresh thread work
TimeUnit.MILLISECONDS.sleep(5500);
ServiceInfo actual = failoverReactor.getService("a@@b");
assertNotEquals(serviceInfo, actual);
}
@Test
public void testFailoverServiceCntMetrics()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetrics", Map.class);
method.setAccessible(true);
method.invoke(failoverReactor, new Object[1]);
// No exception
}
@Test
public void testFailoverServiceCntMetricsClear()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Field field = FailoverReactor.class.getDeclaredField("meterMap");
field.setAccessible(true);
field.set(failoverReactor, Collections.singletonMap("a", null));
Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetricsClear");
method.setAccessible(true);
method.invoke(failoverReactor);
// No exception
}
}

View File

@ -16,38 +16,66 @@
package com.alibaba.nacos.client.naming.backups.datasource;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.utils.CacheDirUtil;
import junit.framework.TestCase;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.backups.FailoverData;
import com.alibaba.nacos.client.naming.backups.FailoverSwitch;
import com.alibaba.nacos.client.naming.cache.DiskCacheTest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import java.util.Properties;
import java.lang.reflect.Field;
import java.util.Map;
public class DiskFailoverDataSourceTest extends TestCase {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class DiskFailoverDataSourceTest {
@Test
public void testGetSwitch() {
Properties prop = new Properties();
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(prop);
String cacheDir = CacheDirUtil.initCacheDir("public", properties);
DiskFailoverDataSource diskFailoverDataSource = new DiskFailoverDataSource();
diskFailoverDataSource.getSwitch();
DiskFailoverDataSource dataSource;
@Before
public void setUp() {
dataSource = new DiskFailoverDataSource();
}
@Test
public void testGetFailoverData() {
Properties prop = new Properties();
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Mockito.when(holder.getServiceInfoMap()).thenReturn(new HashMap<>());
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(prop);
String cacheDir = CacheDirUtil.initCacheDir("public", properties);
DiskFailoverDataSource diskFailoverDataSource = new DiskFailoverDataSource();
diskFailoverDataSource.getFailoverData();
public void testGetSwitchWithNonExistFailoverSwitchFile() {
FailoverSwitch actual = dataSource.getSwitch();
assertFalse(actual.getEnabled());
}
@Test
public void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException {
String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/disabled";
injectFailOverDir(dir);
assertFalse(dataSource.getSwitch().getEnabled());
Map<String, FailoverData> actual = dataSource.getFailoverData();
assertTrue(actual.isEmpty());
}
@Test
public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException {
String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/enabled";
injectFailOverDir(dir);
assertTrue(dataSource.getSwitch().getEnabled());
Map<String, FailoverData> actual = dataSource.getFailoverData();
assertEquals(1, actual.size());
assertTrue(actual.containsKey("legal@@with_name@@file"));
assertEquals(FailoverData.DataType.naming, actual.get("legal@@with_name@@file").getDataType());
assertEquals("1.1.1.1",
((ServiceInfo) actual.get("legal@@with_name@@file").getData()).getHosts().get(0).getIp());
}
@Test
public void testGetFailoverDataForFailoverDisabled() {
Map<String, FailoverData> actual = dataSource.getFailoverData();
assertTrue(actual.isEmpty());
}
private void injectFailOverDir(String failoverDir) throws NoSuchFieldException, IllegalAccessException {
Field failoverDirField = DiskFailoverDataSource.class.getDeclaredField("failoverDir");
failoverDirField.setAccessible(true);
failoverDirField.set(dataSource, failoverDir);
}
}

View File

@ -23,9 +23,17 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConcurrentDiskUtilTest {
@Test
@ -55,6 +63,42 @@ public class ConcurrentDiskUtilTest {
ByteBuffer buff = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
String actual = ConcurrentDiskUtil.byteBufferToString(buff, "UTF-8");
Assert.assertEquals(msg, actual);
}
@Test
public void testWriteFileContent() throws IOException {
File file = mock(File.class);
Assert.assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8"));
}
@Test(expected = IOException.class)
public void testTryLockFailure() throws Throwable {
Method method = ConcurrentDiskUtil.class
.getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class);
method.setAccessible(true);
File file = new File("non-exist");
FileChannel channel = mock(FileChannel.class);
when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException());
try {
method.invoke(null, file, channel, true);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
@Test(expected = IOException.class)
public void testTryLockFailureForIntercept() throws Throwable {
Method method = ConcurrentDiskUtil.class
.getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class);
method.setAccessible(true);
File file = new File("non-exist");
FileChannel channel = mock(FileChannel.class);
Thread.currentThread().interrupt();
when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException());
try {
method.invoke(null, file, channel, true);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
}

View File

@ -24,12 +24,14 @@ import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class DiskCacheTest {
@ -59,6 +61,7 @@ public class DiskCacheTest {
for (File each : file.listFiles()) {
each.delete();
}
file.delete();
}
}
@ -71,6 +74,54 @@ public class DiskCacheTest {
assertServiceInfo(actual.get(serviceInfo.getKey()), serviceInfo);
}
@Test
public void testWriteCacheWithErrorPath() {
File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded());
try {
file.mkdirs();
DiskCache.write(serviceInfo, CACHE_DIR);
assertTrue(file.isDirectory());
} finally {
file.delete();
}
}
@Test
public void testReadCacheForAllSituation() {
String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test";
Map<String, ServiceInfo> actual = DiskCache.read(dir);
assertEquals(2, actual.size());
assertTrue(actual.containsKey("legal@@no_name@@file"));
assertEquals("1.1.1.1", actual.get("legal@@no_name@@file").getHosts().get(0).getIp());
assertTrue(actual.containsKey("legal@@with_name@@file"));
assertEquals("1.1.1.1", actual.get("legal@@with_name@@file").getHosts().get(0).getIp());
}
@Test
public void testReadCacheForNullFile() {
Map<String, ServiceInfo> actual = DiskCache.read(null);
assertTrue(actual.isEmpty());
}
@Test
public void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException {
File file = new File("non%40%40exist%40%40file");
Map<String, ServiceInfo> actual = DiskCache.parseServiceInfoFromCache(file);
assertTrue(actual.isEmpty());
}
@Test(expected = IllegalStateException.class)
public void testCreateFileIfAbsentForDir() throws Throwable {
File file = mock(File.class);
DiskCache.createFileIfAbsent(file, true);
}
@Test(expected = IllegalStateException.class)
public void testCreateFileIfAbsentForFile() throws Throwable {
File file = mock(File.class);
DiskCache.createFileIfAbsent(file, false);
}
private void assertServiceInfo(ServiceInfo actual, ServiceInfo expected) {
assertEquals(actual.getName(), expected.getName());
assertEquals(actual.getGroupName(), expected.getGroupName());

View File

@ -24,23 +24,38 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.backups.FailoverReactor;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServiceInfoHolderTest {
NacosClientProperties nacosClientProperties;
ServiceInfoHolder holder;
@Before
public void setUp() throws Exception {
nacosClientProperties = NacosClientProperties.PROTOTYPE.derive();
holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException {
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
Assert.assertEquals(0, holder.getServiceInfoMap().size());
Field fieldNotifierEventScope = ServiceInfoHolder.class.getDeclaredField("notifierEventScope");
fieldNotifierEventScope.setAccessible(true);
@ -57,10 +72,6 @@ public class ServiceInfoHolderTest {
hosts.add(instance2);
info.setHosts(hosts);
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
ServiceInfo actual1 = holder.processServiceInfo(info);
Assert.assertEquals(info, actual1);
@ -86,9 +97,6 @@ public class ServiceInfoHolderTest {
@Test
public void testProcessServiceInfo2() {
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}";
ServiceInfo actual = holder.processServiceInfo(json);
@ -98,7 +106,7 @@ public class ServiceInfoHolderTest {
}
@Test
public void testProcessServiceInfoWithPushEmpty() {
public void testProcessServiceInfoWithPushEmpty() throws NacosException {
ServiceInfo oldInfo = new ServiceInfo("a@@b@@c");
Instance instance1 = createInstance("1.1.1.1", 1);
Instance instance2 = createInstance("1.1.1.2", 2);
@ -107,10 +115,9 @@ public class ServiceInfoHolderTest {
hosts.add(instance2);
oldInfo.setHosts(hosts);
Properties prop = new Properties();
prop.setProperty(PropertyKeyConst.NAMING_PUSH_EMPTY_PROTECTION, "true");
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_PUSH_EMPTY_PROTECTION, "true");
holder.shutdown();
holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
holder.processServiceInfo(oldInfo);
ServiceInfo newInfo = new ServiceInfo("a@@b@@c");
@ -121,6 +128,28 @@ public class ServiceInfoHolderTest {
Assert.assertEquals(2, actual.getHosts().size());
}
@Test
public void testProcessNullServiceInfo() {
Assert.assertNull(holder.processServiceInfo(new ServiceInfo()));
}
@Test
public void testProcessServiceInfoForOlder() {
ServiceInfo info = new ServiceInfo("a@@b@@c");
Instance instance1 = createInstance("1.1.1.1", 1);
Instance instance2 = createInstance("1.1.1.2", 2);
List<Instance> hosts = new ArrayList<>();
hosts.add(instance1);
hosts.add(instance2);
info.setHosts(hosts);
info.setLastRefTime(System.currentTimeMillis());
holder.processServiceInfo(info);
ServiceInfo olderInfo = new ServiceInfo("a@@b@@c");
olderInfo.setLastRefTime(0L);
final ServiceInfo actual = holder.processServiceInfo(olderInfo);
Assert.assertEquals(olderInfo, actual);
}
@Test
public void testGetServiceInfo() {
ServiceInfo info = new ServiceInfo("a@@b@@c");
@ -129,10 +158,6 @@ public class ServiceInfoHolderTest {
hosts.add(instance1);
info.setHosts(hosts);
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
ServiceInfo expect = holder.processServiceInfo(info);
String serviceName = "b";
String groupName = "a";
@ -145,9 +170,6 @@ public class ServiceInfoHolderTest {
@Test
public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException {
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
ServiceInfoHolder holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor");
field.setAccessible(true);
FailoverReactor reactor = (FailoverReactor) field.get(holder);
@ -158,4 +180,40 @@ public class ServiceInfoHolderTest {
holder.shutdown();
Assert.assertTrue(pool.isShutdown());
}
@Test
public void testConstructWithCacheLoad() throws NacosException {
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "true");
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "non-exist");
holder.shutdown();
holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties);
Assert.assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir());
Assert.assertTrue(holder.getServiceInfoMap().isEmpty());
}
@Test
public void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException {
FailoverReactor mock = injectMockFailoverReactor();
when(mock.isFailoverSwitch()).thenReturn(true);
Assert.assertTrue(holder.isFailoverSwitch());
}
@Test
public void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException {
FailoverReactor mock = injectMockFailoverReactor();
ServiceInfo serviceInfo = new ServiceInfo("a@@b@@c");
when(mock.getService("a@@b@@c")).thenReturn(serviceInfo);
Assert.assertEquals(serviceInfo, holder.getFailoverServiceInfo("b", "a", "c"));
}
private FailoverReactor injectMockFailoverReactor()
throws NoSuchFieldException, IllegalAccessException, NacosException {
Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor");
field.setAccessible(true);
FailoverReactor old = (FailoverReactor) field.get(holder);
old.shutdown();
FailoverReactor mock = mock(FailoverReactor.class);
field.set(holder, mock);
return mock;
}
}

View File

@ -17,52 +17,186 @@
package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.runtime.NacosLoadException;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import org.junit.After;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@RunWith(MockitoJUnitRunner.class)
public class ServerListManagerTest {
private static final String NS = "ns";
@Mock
NacosRestTemplate nacosRestTemplate;
NacosRestTemplate cachedNacosRestTemplate;
NacosClientProperties clientProperties;
HttpRestResult httpRestResult;
ServerListManager serverListManager;
@Before
public void setUp() throws Exception {
clientProperties = NacosClientProperties.PROTOTYPE.derive();
Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST");
restMapField.setAccessible(true);
Map<String, NacosRestTemplate> restMap = (Map<String, NacosRestTemplate>) restMapField.get(null);
cachedNacosRestTemplate = restMap
.get("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory");
restMap.put("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory",
nacosRestTemplate);
httpRestResult = new HttpRestResult<>();
httpRestResult.setData("127.0.0.1:8848");
httpRestResult.setCode(200);
Mockito.when(nacosRestTemplate.get(any(), any(), any(), any())).thenReturn(httpRestResult);
}
@After
public void tearDown() throws Exception {
if (null != cachedNacosRestTemplate) {
Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST");
restMapField.setAccessible(true);
Map<String, NacosRestTemplate> restMap = (Map<String, NacosRestTemplate>) restMapField.get(null);
restMap.put("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory",
cachedNacosRestTemplate);
}
if (null != serverListManager) {
serverListManager.shutdown();
}
}
@Test(expected = NacosLoadException.class)
public void testConstructError() {
serverListManager = new ServerListManager(new Properties());
}
@Test
public void testConstructWithAddr() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849");
final ServerListManager serverListManager = new ServerListManager(properties);
serverListManager = new ServerListManager(properties);
final List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(2, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
Assert.assertEquals("127.0.0.1:8849", serverList.get(1));
}
@Ignore
@Test
public void testConstructWithEndpoint() throws Exception {
public void testConstructWithAddrTryToRefresh()
throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849");
serverListManager = new ServerListManager(properties);
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(2, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
Assert.assertEquals("127.0.0.1:8849", serverList.get(1));
mockThreadInvoke(serverListManager, false);
serverList = serverListManager.getServerList();
Assert.assertEquals(2, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
Assert.assertEquals("127.0.0.1:8849", serverList.get(1));
}
@Test
public void testConstructWithEndpointAndRefresh() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1");
final ServerListManager serverListManager = new ServerListManager(properties);
NacosRestTemplate mock = Mockito.mock(NacosRestTemplate.class);
serverListManager = new ServerListManager(properties);
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("127.0.0.1:8848");
a.setCode(200);
Mockito.when(mock.get(any(), any(), any(), any())).thenReturn(a);
httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948");
mockThreadInvoke(serverListManager, true);
serverList = serverListManager.getServerList();
Assert.assertEquals(2, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
Assert.assertEquals("127.0.0.1:8948", serverList.get(1));
}
@Test
public void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1");
serverListManager = new ServerListManager(properties);
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
final Field nacosRestTemplate = ServerListManager.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplate.setAccessible(true);
nacosRestTemplate.set(serverListManager, mock);
TimeUnit.SECONDS.sleep(31);
final List<String> serverList = serverListManager.getServerList();
httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948");
mockThreadInvoke(serverListManager, false);
serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
}
@Test
public void testConstructWithEndpointAndRefreshEmpty() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1");
serverListManager = new ServerListManager(properties);
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
httpRestResult.setData("");
mockThreadInvoke(serverListManager, true);
serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
}
@Test
public void testConstructWithEndpointAndRefreshException()
throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1");
serverListManager = new ServerListManager(properties);
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
httpRestResult.setCode(500);
mockThreadInvoke(serverListManager, true);
serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
}
@Test
public void testConstructWithEndpointWithCustomPathAndName() throws Exception {
clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "aaa");
clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "bbb");
clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1");
Mockito.reset(nacosRestTemplate);
Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/aaa/bbb"), any(), any(), any()))
.thenReturn(httpRestResult);
serverListManager = new ServerListManager(clientProperties, "test");
List<String> serverList = serverListManager.getServerList();
Assert.assertEquals(1, serverList.size());
Assert.assertEquals("127.0.0.1:8848", serverList.get(0));
}
@ -71,7 +205,7 @@ public class ServerListManagerTest {
public void testIsDomain() throws IOException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
final ServerListManager serverListManager = new ServerListManager(properties);
serverListManager = new ServerListManager(properties);
Assert.assertTrue(serverListManager.isDomain());
Assert.assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain());
}
@ -97,4 +231,13 @@ public class ServerListManagerTest {
}
}
private void mockThreadInvoke(ServerListManager serverListManager, boolean expectedInvoked)
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Field field = ServerListManager.class.getDeclaredField("lastServerListRefreshTime");
field.setAccessible(true);
field.set(serverListManager, expectedInvoked ? 0 : System.currentTimeMillis());
Method method = ServerListManager.class.getDeclaredMethod("refreshServerListIfNeed");
method.setAccessible(true);
method.invoke(serverListManager);
}
}

View File

@ -16,71 +16,193 @@
package com.alibaba.nacos.client.naming.core;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.NamingClientProxy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Properties;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ServiceInfoUpdateServiceTest {
@Test
public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException {
String serviceName = "aa";
String group = "bb";
String clusters = "cc";
ServiceInfo info = new ServiceInfo();
String serviceName = "aa";
String group = "bb";
String clusters = "cc";
@Mock
ServiceInfoHolder holder;
@Mock
NamingClientProxy proxy;
@Mock
InstancesChangeNotifier notifier;
NacosClientProperties nacosClientProperties;
ServiceInfo info;
ServiceInfoUpdateService serviceInfoUpdateService;
@Before
public void setUp() throws Exception {
nacosClientProperties = NacosClientProperties.PROTOTYPE.derive();
info = new ServiceInfo();
info.setName(serviceName);
info.setGroupName(group);
info.setClusters(clusters);
info.setLastRefTime(System.currentTimeMillis());
when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info);
}
@After
public void tearDown() throws Exception {
if (null != serviceInfoUpdateService) {
serviceInfoUpdateService.shutdown();
}
}
@Test
public void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException {
serviceInfoUpdateService = new ServiceInfoUpdateService(null, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException {
info.setCacheMillis(10000L);
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
NamingClientProxy proxy = Mockito.mock(NamingClientProxy.class);
Mockito.when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info);
InstancesChangeNotifier notifyer = Mockito.mock(InstancesChangeNotifier.class);
Properties prop = new Properties();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
nacosClientProperties.setProperty("namingAsyncQuerySubscribeService", "true");
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties,
holder, proxy, notifyer);
serviceInfoUpdateService.scheduleUpdateIfAbsent("aa", "bb", "cc");
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testStopUpdateIfContain() throws NacosException {
String serviceName = "aa";
String group = "bb";
String clusters = "cc";
ServiceInfo info = new ServiceInfo();
info.setName(serviceName);
info.setGroupName(group);
info.setClusters(clusters);
info.setLastRefTime(System.currentTimeMillis());
NamingClientProxy proxy = Mockito.mock(NamingClientProxy.class);
Mockito.when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info);
InstancesChangeNotifier notifyer = Mockito.mock(InstancesChangeNotifier.class);
Properties prop = new Properties();
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop);
final ServiceInfoUpdateService serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties,
holder, proxy, notifyer);
public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException {
info.setCacheMillis(10000L);
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
TimeUnit.MILLISECONDS.sleep(1500);
// Only once called
Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException {
info.setCacheMillis(10000L);
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
Map<String, ServiceInfo> map = new HashMap<>();
map.put(ServiceInfo.getKey(group + "@@" + serviceName, clusters), info);
when(holder.getServiceInfoMap()).thenReturn(map);
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException {
info.setCacheMillis(10000L);
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
Map<String, ServiceInfo> map = new HashMap<>();
map.put(ServiceInfo.getKey(group + "@@" + serviceName, clusters), info);
when(holder.getServiceInfoMap()).thenReturn(map);
info.setHosts(Collections.singletonList(new Instance()));
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testScheduleUpdateIfAbsentWith403Exception()
throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException {
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
when(proxy.queryInstancesOfService(serviceName, group, clusters, false))
.thenThrow(new NacosException(403, "test"));
TimeUnit.MILLISECONDS.sleep(1500);
assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000);
}
@Test
public void testScheduleUpdateIfAbsentWith500Exception()
throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException {
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
when(proxy.queryInstancesOfService(serviceName, group, clusters, false))
.thenThrow(new NacosException(500, "test"));
TimeUnit.MILLISECONDS.sleep(1500);
assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 2000);
}
@Test
public void testScheduleUpdateIfAbsentWithOtherException()
throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException {
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
when(proxy.queryInstancesOfService(serviceName, group, clusters, false))
.thenThrow(new RuntimeException("test"));
TimeUnit.MILLISECONDS.sleep(1500);
assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000);
}
@Test
public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException {
info.setCacheMillis(10000L);
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
serviceInfoUpdateService.stopUpdateIfContain(serviceName, group, clusters);
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false);
}
@Test
public void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException {
serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier);
serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters);
TimeUnit.MILLISECONDS.sleep(1500);
Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false);
serviceInfoUpdateService.stopUpdateIfContain(serviceName, group, clusters);
serviceInfoUpdateService.shutdown();
}
private ScheduledFuture getScheduleFuture() throws NoSuchFieldException, IllegalAccessException {
Field field = serviceInfoUpdateService.getClass().getDeclaredField("executor");
field.setAccessible(true);
ScheduledThreadPoolExecutor executorService = (ScheduledThreadPoolExecutor) field.get(serviceInfoUpdateService);
return (ScheduledFuture) executorService.getQueue().peek();
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.client.naming.event;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
@ -25,9 +26,13 @@ import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
public class InstancesChangeNotifierTest {
@ -45,7 +50,7 @@ public class InstancesChangeNotifierTest {
Assert.assertEquals(group, subscribeServices.get(0).getGroupName());
Assert.assertEquals(name, subscribeServices.get(0).getName());
Assert.assertEquals(clusters, subscribeServices.get(0).getClusters());
List<Instance> hosts = new ArrayList<>();
Instance ins = new Instance();
hosts.add(ins);
@ -69,6 +74,9 @@ public class InstancesChangeNotifierTest {
List<ServiceInfo> subscribeServices2 = instancesChangeNotifier.getSubscribeServices();
Assert.assertEquals(0, subscribeServices2.size());
instancesChangeNotifier.deregisterListener(group, name, clusters, listener);
Assert.assertEquals(0, subscribeServices2.size());
}
@Test
@ -96,14 +104,52 @@ public class InstancesChangeNotifierTest {
instancesChangeNotifier.registerListener(group, name, clusters, listener);
InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class);
Mockito.when(event1.getClusters()).thenReturn(clusters);
Mockito.when(event1.getGroupName()).thenReturn(group);
Mockito.when(event1.getServiceName()).thenReturn(name);
when(event1.getClusters()).thenReturn(clusters);
when(event1.getGroupName()).thenReturn(group);
when(event1.getServiceName()).thenReturn(name);
instancesChangeNotifier.onEvent(event1);
Mockito.verify(listener, times(1)).onEvent(any());
}
@Test
public void testOnEventWithoutListener() {
String eventScope = "scope-001";
String group = "a";
String name = "b";
String clusters = "c";
InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class);
when(event1.getClusters()).thenReturn(clusters);
when(event1.getGroupName()).thenReturn(group);
when(event1.getServiceName()).thenReturn(name);
EventListener listener = Mockito.mock(EventListener.class);
InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope);
instancesChangeNotifier.registerListener(group, name + "c", clusters, listener);
instancesChangeNotifier.onEvent(event1);
Mockito.verify(listener, never()).onEvent(any());
}
@Test
public void testOnEventByExecutor() {
String eventScope = "scope-001";
String group = "a";
String name = "b";
String clusters = "c";
InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope);
AbstractEventListener listener = Mockito.mock(AbstractEventListener.class);
Executor executor = mock(Executor.class);
when(listener.getExecutor()).thenReturn(executor);
instancesChangeNotifier.registerListener(group, name, clusters, listener);
InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class);
when(event1.getClusters()).thenReturn(clusters);
when(event1.getGroupName()).thenReturn(group);
when(event1.getServiceName()).thenReturn(name);
instancesChangeNotifier.onEvent(event1);
Mockito.verify(executor).execute(any());
}
@Test
public void testSubscribeType() {
String eventScope = "scope-001";

View File

@ -31,35 +31,61 @@ import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier;
import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy;
import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class NamingClientProxyDelegateTest {
@Test
public void testRegisterEphemeralServiceByGrpc() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
private static final String TEST_NAMESPACE = "ns1";
@Mock
ServiceInfoHolder holder;
@Mock
NamingGrpcClientProxy mockGrpcClient;
NamingClientProxyDelegate delegate;
InstancesChangeNotifier notifier;
NacosClientProperties nacosClientProperties;
@Before
public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException {
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
notifier = new InstancesChangeNotifier();
delegate = new NamingClientProxyDelegate(TEST_NAMESPACE, holder, nacosClientProperties, notifier);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
}
@After
public void tearDown() throws NacosException {
delegate.shutdown();
}
@Test
public void testRegisterEphemeralServiceByGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -73,20 +99,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testBatchRegisterServiceByGrpc() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testBatchRegisterServiceByGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -101,19 +114,20 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testRegisterPersistentServiceByGrpc() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testBatchDeregisterServiceByGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
List<Instance> instanceList = new ArrayList<>();
delegate.batchDeregisterService(serviceName, groupName, instanceList);
verify(mockGrpcClient, times(1)).batchDeregisterService(serviceName, groupName, instanceList);
reset(mockGrpcClient);
instanceList.add(new Instance());
delegate.batchDeregisterService(serviceName, groupName, instanceList);
verify(mockGrpcClient, times(1)).batchDeregisterService(serviceName, groupName, instanceList);
}
@Test
public void testRegisterPersistentServiceByGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -124,21 +138,15 @@ public class NamingClientProxyDelegateTest {
// persistent instance
instance.setEphemeral(false);
// when server support register persistent instance by grpc, will use grpc to register
when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true);
when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(true);
delegate.registerService(serviceName, groupName, instance);
verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance);
}
@Test
public void testRegisterPersistentServiceByHttp() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
public void testRegisterPersistentServiceByHttp()
throws NacosException, NoSuchFieldException, IllegalAccessException {
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
mockHttpClientField.setAccessible(true);
@ -159,20 +167,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testDeregisterEphemeralServiceGrpc() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testDeregisterEphemeralServiceGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -187,20 +182,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testDeregisterPersistentServiceGrpc() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testDeregisterPersistentServiceGrpc() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -211,21 +193,15 @@ public class NamingClientProxyDelegateTest {
// persistent instance
instance.setEphemeral(false);
// when server support deregister persistent instance by grpc, will use grpc to deregister
when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true);
when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(true);
delegate.deregisterService(serviceName, groupName, instance);
verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance);
}
@Test
public void testDeregisterPersistentServiceHttp() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
public void testDeregisterPersistentServiceHttp()
throws NacosException, NoSuchFieldException, IllegalAccessException {
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
mockHttpClientField.setAccessible(true);
@ -245,15 +221,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testUpdateInstance() throws NacosException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
public void testUpdateInstance() {
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
@ -265,20 +233,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testQueryInstancesOfService() throws NacosException, IllegalAccessException, NoSuchFieldException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testQueryInstancesOfService() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
String clusters = "cluster1";
@ -288,28 +243,12 @@ public class NamingClientProxyDelegateTest {
@Test
public void testQueryService() throws NacosException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Service service = delegate.queryService("a", "b");
Assert.assertNull(service);
}
@Test
public void testCreateService() throws NacosException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
public void testCreateService() {
Service service = new Service();
try {
delegate.createService(service, new NoneSelector());
@ -320,27 +259,11 @@ public class NamingClientProxyDelegateTest {
@Test
public void testDeleteService() throws NacosException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
Assert.assertFalse(delegate.deleteService("service", "group1"));
}
@Test
public void testUpdateService() throws NacosException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
public void testUpdateService() {
Service service = new Service();
try {
delegate.updateService(service, new ExpressionSelector());
@ -350,20 +273,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testGetServiceList() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testGetServiceList() throws NacosException {
AbstractSelector selector = new ExpressionSelector();
int pageNo = 1;
int pageSize = 10;
@ -374,20 +284,7 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testSubscribe() throws NacosException, NoSuchFieldException, IllegalAccessException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testSubscribe() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
String clusters = "cluster1";
@ -405,61 +302,32 @@ public class NamingClientProxyDelegateTest {
}
@Test
public void testUnsubscribe() throws NacosException, IllegalAccessException, NoSuchFieldException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testUnsubscribe() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
String clusters = "cluster1";
delegate.unsubscribe(serviceName, groupName, clusters);
verify(mockGrpcClient, times(1)).unsubscribe(serviceName, groupName, clusters);
}
@Test
public void testServerHealthy() throws IllegalAccessException, NacosException, NoSuchFieldException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testServerHealthy() {
Mockito.when(mockGrpcClient.serverHealthy()).thenReturn(true);
Assert.assertTrue(delegate.serverHealthy());
}
@Test
public void testShutdown() throws NacosException, IllegalAccessException, NoSuchFieldException {
String ns = "ns1";
ServiceInfoHolder holder = Mockito.mock(ServiceInfoHolder.class);
Properties props = new Properties();
props.setProperty("serverAddr", "localhost");
InstancesChangeNotifier notifier = new InstancesChangeNotifier();
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingClientProxyDelegate delegate = new NamingClientProxyDelegate(ns, holder, nacosClientProperties, notifier);
NamingGrpcClientProxy mockGrpcClient = Mockito.mock(NamingGrpcClientProxy.class);
Field grpcClientProxyField = NamingClientProxyDelegate.class.getDeclaredField("grpcClientProxy");
grpcClientProxyField.setAccessible(true);
grpcClientProxyField.set(delegate, mockGrpcClient);
public void testIsSubscribed() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
String clusters = "cluster1";
Assert.assertFalse(delegate.isSubscribed(serviceName, groupName, clusters));
when(mockGrpcClient.isSubscribed(serviceName, groupName, clusters)).thenReturn(true);
Assert.assertTrue(delegate.isSubscribed(serviceName, groupName, clusters));
}
@Test
public void testShutdown() throws NacosException {
delegate.shutdown();
verify(mockGrpcClient, times(1)).shutdown();
}

View File

@ -43,6 +43,7 @@ import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.response.ErrorResponse;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
@ -86,6 +87,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -127,7 +129,7 @@ public class NamingGrpcClientProxyTest {
private Instance instance;
private Instance persistentInstance;
private String uuid;
@Rule
@ -171,8 +173,8 @@ public class NamingGrpcClientProxyTest {
@After
public void tearDown() throws NacosException {
System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "3");
System.setProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT, "3000");
System.clearProperty(GrpcConstants.GRPC_RETRY_TIMES);
System.clearProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT);
client.shutdown();
}
@ -199,7 +201,7 @@ public class NamingGrpcClientProxyTest {
return false;
}));
}
@Test
public void testRegisterServiceThrowsNacosException() throws NacosException {
expectedException.expect(NacosException.class);
@ -243,7 +245,7 @@ public class NamingGrpcClientProxyTest {
return false;
}));
}
@Test
public void testDeregisterPersistentService() throws NacosException {
client.deregisterService(SERVICE_NAME, GROUP_NAME, persistentInstance);
@ -449,6 +451,19 @@ public class NamingGrpcClientProxyTest {
Assert.assertEquals(services, serviceList.getData());
}
@Test
public void testGetServiceListForLabelSelector() throws Exception {
ServiceListResponse res = new ServiceListResponse();
List<String> services = Arrays.asList("service1", "service2");
res.setServiceNames(services);
res.setCount(5);
when(this.rpcClient.request(any())).thenReturn(res);
AbstractSelector selector = new ExpressionSelector();
ListView<String> serviceList = client.getServiceList(1, 10, GROUP_NAME, selector);
Assert.assertEquals(5, serviceList.getCount());
Assert.assertEquals(services, serviceList.getData());
}
@Test
public void testSubscribe() throws Exception {
SubscribeServiceResponse res = new SubscribeServiceResponse();
@ -471,9 +486,9 @@ public class NamingGrpcClientProxyTest {
SubscribeServiceRequest request1 = (SubscribeServiceRequest) request;
// verify request fields
return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME.equals(
request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID.equals(
request1.getNamespace());
return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME
.equals(request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID
.equals(request1.getNamespace());
}
return false;
}));
@ -496,41 +511,37 @@ public class NamingGrpcClientProxyTest {
Assert.assertTrue(client.serverHealthy());
verify(this.rpcClient, times(1)).isRunning();
}
@Test
public void testIsAbilitySupportedByServer1() {
when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(AbilityStatus.SUPPORTED);
Assert.assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC));
verify(this.rpcClient, times(1))
.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
}
@Test
public void testIsAbilitySupportedByServer2() {
when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(AbilityStatus.NOT_SUPPORTED);
Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC));
verify(this.rpcClient, times(1))
.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
}
@Test
public void testIsAbilitySupportedByServer3() {
when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(AbilityStatus.UNKNOWN);
Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC));
verify(this.rpcClient, times(1))
.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
}
@Test
public void testIsAbilitySupportedByServer4() {
when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC))
.thenReturn(null);
Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC));
verify(this.rpcClient, times(1))
.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC);
}
@Test
@ -540,6 +551,20 @@ public class NamingGrpcClientProxyTest {
//verify(this.rpcClient, times(1)).shutdown();
}
@Test
public void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException {
Field field = RpcClientFactory.class.getDeclaredField("CLIENT_MAP");
field.setAccessible(true);
Map<String, RpcClient> map = (Map<String, RpcClient>) field.get(RpcClientFactory.class);
RpcClient oldClient = map.get(uuid);
try {
oldClient.shutdown();
} catch (NacosException ignored) {
}
map.put(uuid, rpcClient);
doThrow(new NacosException()).when(rpcClient).shutdown();
}
@Test
public void testIsEnable() {
when(this.rpcClient.isRunning()).thenReturn(true);

View File

@ -21,6 +21,7 @@ package com.alibaba.nacos.client.naming.remote.gprc;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest;
import com.alibaba.nacos.api.naming.remote.response.NotifySubscriberResponse;
import com.alibaba.nacos.api.remote.request.HealthCheckRequest;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder;
@ -48,4 +49,12 @@ public class NamingPushRequestHandlerTest {
Assert.assertTrue(response instanceof NotifySubscriberResponse);
verify(holder, times(1)).processServiceInfo(info);
}
@Test
public void testRequestReplyOtherType() {
ServiceInfoHolder holder = mock(ServiceInfoHolder.class);
NamingPushRequestHandler handler = new NamingPushRequestHandler(holder);
Assert.assertNull(
handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo())));
}
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy;
import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData;
import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData;
import com.alibaba.nacos.client.naming.remote.gprc.redo.data.SubscriberRedoData;
import org.junit.Before;
@ -27,9 +28,11 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -68,6 +71,20 @@ public class RedoScheduledTaskTest {
verify(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE);
}
@Test
public void testRunRedoRegisterBatchInstance() throws NacosException {
BatchInstanceRedoData redoData = BatchInstanceRedoData
.build(SERVICE, GROUP, Collections.singletonList(INSTANCE));
redoData.setRegistered(false);
redoData.setUnregistering(false);
redoData.setExpectedRegistered(true);
Set<InstanceRedoData> mockData = new HashSet<>();
mockData.add(redoData);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy).doBatchRegisterService(SERVICE, GROUP, redoData.getInstances());
}
@Test
public void testRunRedoDeregisterInstance() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(true, true, false);
@ -93,7 +110,35 @@ public class RedoScheduledTaskTest {
verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE);
}
private Set<InstanceRedoData> generateMockInstanceData(boolean registered, boolean unregistering, boolean expectedRegistered) {
@Test
public void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<InstanceRedoData> mockData = generateMockInstanceData(true, true, false);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE);
}
@Test
public void testRunRedoRegisterInstanceWithNacosException() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false, true);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
doThrow(new NacosException()).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE);
redoTask.run();
// Not any exception thrown
}
@Test
public void testRunRedoRegisterInstanceWithOtherException() throws NacosException {
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false, true);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
doThrow(new RuntimeException("test")).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE);
redoTask.run();
// Not any exception thrown
}
private Set<InstanceRedoData> generateMockInstanceData(boolean registered, boolean unregistering,
boolean expectedRegistered) {
InstanceRedoData redoData = InstanceRedoData.build(SERVICE, GROUP, INSTANCE);
redoData.setRegistered(registered);
redoData.setUnregistering(unregistering);
@ -136,7 +181,26 @@ public class RedoScheduledTaskTest {
verify(clientProxy, never()).doSubscribe(SERVICE, GROUP, CLUSTER);
}
private Set<SubscriberRedoData> generateMockSubscriberData(boolean registered, boolean unregistering, boolean expectedRegistered) {
@Test
public void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(true, true, false);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
redoTask.run();
verify(clientProxy, never()).doUnsubscribe(SERVICE, GROUP, CLUSTER);
}
@Test
public void testRunRedoRegisterSubscriberWithNacosException() throws NacosException {
Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false, true);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
doThrow(new NacosException()).when(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER);
redoTask.run();
// Not any exception thrown
}
private Set<SubscriberRedoData> generateMockSubscriberData(boolean registered, boolean unregistering,
boolean expectedRegistered) {
SubscriberRedoData redoData = SubscriberRedoData.build(SERVICE, GROUP, CLUSTER);
redoData.setRegistered(registered);
redoData.setUnregistering(unregistering);

View File

@ -41,6 +41,8 @@ public class BatchInstanceRedoDataTest {
assertFalse(redoData1.equals(null));
assertFalse(redoData1.equals(redoData2));
assertFalse(redoData1.equals(redoData2));
BatchInstanceRedoData redoData3 = new BatchInstanceRedoData("c", "b");
assertFalse(redoData1.equals(redoData3));
}
@Test

View File

@ -0,0 +1,50 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.remote.gprc.redo.data;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class InstanceRedoDataTest {
@Test
public void testEquals() {
InstanceRedoData redoData1 = new InstanceRedoData("a", "b");
assertTrue(redoData1.equals(redoData1));
assertFalse(redoData1.equals(null));
BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b");
assertFalse(redoData1.equals(redoData2));
InstanceRedoData redoData3 = new InstanceRedoData("a", "b");
assertTrue(redoData1.equals(redoData3));
}
@Test
public void testHashCode() {
InstanceRedoData redoData1 = new InstanceRedoData("a", "b");
redoData1.set(new Instance());
InstanceRedoData redoData2 = new InstanceRedoData("a", "b");
redoData2.set(new Instance());
assertEquals(redoData1.hashCode(), redoData2.hashCode());
redoData2.get().setIp("1.1.1.1");
assertNotEquals(redoData1.hashCode(), redoData2.hashCode());
}
}

View File

@ -19,6 +19,7 @@
package com.alibaba.nacos.client.naming.remote.http;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
import org.junit.Assert;
@ -27,8 +28,12 @@ import org.mockito.Mockito;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;
import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ -41,7 +46,7 @@ public class NamingHttpClientManagerTest {
@Test
public void testGetPrefix() {
Assert.assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix());
assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix());
}
@Test
@ -62,7 +67,22 @@ public class NamingHttpClientManagerTest {
NamingHttpClientManager.getInstance().shutdown();
// then
verify(mockHttpClientRequest, times(1)).close();
}
@Test
public void testShutdownWithException() throws Exception {
String key = "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory";
try {
HttpClientBeanHolder.shutdownNacosSyncRest(key);
} catch (Exception ignored) {
}
Field field = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST");
field.setAccessible(true);
Map<String, NacosRestTemplate> map = (Map<String, NacosRestTemplate>) field.get(null);
NacosRestTemplate mockRest = mock(NacosRestTemplate.class);
map.put(key, mockRest);
doThrow(new RuntimeException("test")).when(mockRest).close();
NamingHttpClientManager.getInstance().shutdown();
assertEquals(mockRest, map.remove(key));
}
}

View File

@ -18,14 +18,16 @@
package com.alibaba.nacos.client.naming.remote.http;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.Service;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.naming.core.ServerListManager;
import com.alibaba.nacos.client.naming.event.ServerListChangedEvent;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.security.SecurityProxy;
import com.alibaba.nacos.common.http.HttpRestResult;
@ -44,15 +46,20 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -84,6 +91,18 @@ public class NamingHttpClientProxyTest {
@After
public void tearDown() throws NacosException {
clientProxy.shutdown();
System.clearProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT);
}
@Test
public void testOnEvent() {
clientProxy.onEvent(new ServerListChangedEvent());
// Do nothing
}
@Test
public void testSubscribeType() {
assertEquals(ServerListChangedEvent.class, clientProxy.subscribeType());
}
@Test
@ -109,6 +128,12 @@ public class NamingHttpClientProxyTest {
verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), any(), any());
}
@Test(expected = UnsupportedOperationException.class)
public void testRegisterEphemeralInstance() throws NacosException {
Instance instance = new Instance();
clientProxy.registerService("a", "b", instance);
}
@Test
public void testRegisterServiceThrowsNacosException() throws Exception {
thrown.expect(NacosException.class);
@ -130,7 +155,7 @@ public class NamingHttpClientProxyTest {
clientProxy.registerService(serviceName, groupName, instance);
} catch (NacosException ex) {
// verify the `NacosException` is directly thrown
Assert.assertEquals(null, ex.getCause());
assertEquals(null, ex.getCause());
throw ex;
}
@ -160,12 +185,22 @@ public class NamingHttpClientProxyTest {
} catch (NacosException ex) {
// verify the `NacosException` is directly thrown
Assert.assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException"));
Assert.assertEquals(NacosException.SERVER_ERROR, ex.getErrCode());
assertEquals(NacosException.SERVER_ERROR, ex.getErrCode());
throw ex;
}
}
@Test(expected = UnsupportedOperationException.class)
public void testBatchRegisterService() {
clientProxy.batchRegisterService("a", "b", null);
}
@Test(expected = UnsupportedOperationException.class)
public void testBatchDeregisterService() {
clientProxy.batchDeregisterService("a", "b", null);
}
@Test
public void testDeregisterService() throws Exception {
//given
@ -189,6 +224,18 @@ public class NamingHttpClientProxyTest {
verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any());
}
@Test
public void testDeregisterServiceForEphemeral() throws Exception {
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
Instance instance = new Instance();
clientProxy.deregisterService("serviceName", "groupName", instance);
verify(nacosRestTemplate, never()).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any());
}
@Test
public void testUpdateInstance() throws Exception {
//given
@ -240,10 +287,10 @@ public class NamingHttpClientProxyTest {
//when
Service service = clientProxy.queryService(serviceName, groupName);
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(),
eq(HttpMethod.GET), any());
Assert.assertEquals(serviceName, service.getName());
Assert.assertEquals(groupName, service.getGroupName());
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.GET), any());
assertEquals(serviceName, service.getName());
assertEquals(groupName, service.getGroupName());
}
@Test
@ -262,8 +309,8 @@ public class NamingHttpClientProxyTest {
//when
clientProxy.createService(new Service(), new NoneSelector());
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(),
eq(HttpMethod.POST), any());
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.POST), any());
}
@Test
@ -284,8 +331,8 @@ public class NamingHttpClientProxyTest {
//when
clientProxy.deleteService(serviceName, groupName);
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(),
eq(HttpMethod.DELETE), any());
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.DELETE), any());
}
@Test
@ -306,8 +353,8 @@ public class NamingHttpClientProxyTest {
//when
clientProxy.updateService(new Service(), new NoneSelector());
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(),
eq(HttpMethod.PUT), any());
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.PUT), any());
}
@ -323,17 +370,26 @@ public class NamingHttpClientProxyTest {
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String serviceName = "service1";
String groupName = "group1";
//when
boolean serverHealthy = clientProxy.serverHealthy();
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/operator/metrics"), any(), any(), any(),
eq(HttpMethod.GET), any());
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), eq(HttpMethod.GET), any());
Assert.assertTrue(serverHealthy);
}
@Test
public void testServerHealthyForException() throws Exception {
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any()))
.thenThrow(new RuntimeException("test"));
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
assertFalse(clientProxy.serverHealthy());
}
@Test
public void testGetServiceList() throws Exception {
//given
@ -351,11 +407,35 @@ public class NamingHttpClientProxyTest {
//when
ListView<String> serviceList = clientProxy.getServiceList(1, 10, groupName, new NoneSelector());
//then
verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/service/list"), any(), any(), any(),
eq(HttpMethod.GET), any());
Assert.assertEquals(2, serviceList.getCount());
Assert.assertEquals("aaa", serviceList.getData().get(0));
Assert.assertEquals("bbb", serviceList.getData().get(1));
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any());
assertEquals(2, serviceList.getCount());
assertEquals("aaa", serviceList.getData().get(0));
assertEquals("bbb", serviceList.getData().get(1));
}
@Test
public void testGetServiceListWithLabelSelector() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("{\"count\":2,\"doms\":[\"aaa\",\"bbb\"]}");
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String groupName = "group1";
//when
ListView<String> serviceList = clientProxy.getServiceList(1, 10, groupName, new ExpressionSelector());
//then
verify(nacosRestTemplate, times(1))
.exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any());
assertEquals(2, serviceList.getCount());
assertEquals("aaa", serviceList.getData().get(0));
assertEquals("bbb", serviceList.getData().get(1));
}
@Test(expected = UnsupportedOperationException.class)
@ -365,7 +445,7 @@ public class NamingHttpClientProxyTest {
String clusters = "clusters";
//when
ServiceInfo serviceInfo = clientProxy.subscribe(serviceName, groupName, clusters);
clientProxy.subscribe(serviceName, groupName, clusters);
}
@Test
@ -376,6 +456,12 @@ public class NamingHttpClientProxyTest {
//when
clientProxy.unsubscribe(serviceName, groupName, clusters);
// do nothing
}
@Test
public void testIsSubscribed() throws NacosException {
assertTrue(clientProxy.isSubscribed("serviceName", "group1", "clusters"));
}
@Test
@ -400,7 +486,7 @@ public class NamingHttpClientProxyTest {
//when
String res = clientProxy.reqApi(api, params, method);
//then
Assert.assertEquals("http://localhost:8848/api", res);
assertEquals("http://localhost:8848/api", res);
}
@ -427,7 +513,7 @@ public class NamingHttpClientProxyTest {
//when
String res = clientProxy.reqApi(api, params, body, method);
//then
Assert.assertEquals("http://localhost:8848/api", res);
assertEquals("http://localhost:8848/api", res);
}
@Test
@ -454,7 +540,7 @@ public class NamingHttpClientProxyTest {
//when
String res = clientProxy.reqApi(api, params, body, servers, method);
//then
Assert.assertEquals("http://127.0.0.1:8848/api", res);
assertEquals("http://127.0.0.1:8848/api", res);
}
@Test
@ -510,7 +596,7 @@ public class NamingHttpClientProxyTest {
//when
String s = clientProxy.callServer(api, params, body, curServer, method);
//then
Assert.assertEquals("", s);
assertEquals("", s);
}
@Test
@ -519,12 +605,32 @@ public class NamingHttpClientProxyTest {
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties);
String actualNamespaceId = clientProxy.getNamespaceId();
Assert.assertEquals(namespaceId, actualNamespaceId);
assertEquals(namespaceId, actualNamespaceId);
}
@Test
public void testSetServerPort() {
clientProxy.setServerPort(1234);
Assert.assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort"));
assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort"));
System.setProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT, "1111");
clientProxy.setServerPort(1234);
assertEquals(1111, ReflectUtils.getFieldValue(clientProxy, "serverPort"));
}
@Test(expected = NacosException.class)
public void testReqApiForEmptyServer() throws NacosException {
Map<String, String> params = new HashMap<>();
clientProxy
.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET);
}
@Test(expected = NacosException.class)
public void testRegApiForDomain() throws NacosException {
Map<String, String> params = new HashMap<>();
when(mgr.isDomain()).thenReturn(true);
when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain");
clientProxy
.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET);
}
}

View File

@ -0,0 +1,65 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CacheDirUtilTest {
@After
public void tearDown() throws Exception {
System.clearProperty("user.home");
System.clearProperty("JM.SNAPSHOT.PATH");
}
@Test
public void testInitCacheDirWithDefaultRootAndWithoutCache() {
System.setProperty("user.home", "/home/admin");
String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive());
assertEquals("/home/admin/nacos/naming/test", actual);
}
@Test
public void testInitCacheDirWithDefaultRootAndWithCache() {
System.setProperty("user.home", "/home/admin");
NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom");
String actual = CacheDirUtil.initCacheDir("test", properties);
assertEquals("/home/admin/nacos/custom/naming/test", actual);
}
@Test
public void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() {
System.setProperty("JM.SNAPSHOT.PATH", "/home/snapshot");
String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive());
assertEquals("/home/snapshot/nacos/naming/test", actual);
}
@Test
public void testInitCacheDirWithJmSnapshotPathRootAndWithCache() {
System.setProperty("user.home", "/home/snapshot");
NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom");
String actual = CacheDirUtil.initCacheDir("test", properties);
assertEquals("/home/snapshot/nacos/custom/naming/test", actual);
}
}

View File

@ -0,0 +1,208 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ChooserTest {
@Test
public void testChooser() {
//Test the correctness of Chooser, the weight of the final selected instance must be greater than 0
List<Instance> hosts = getInstanceList();
Instance target = getRandomInstance(hosts);
assertTrue(hosts.contains(target) && target.getWeight() > 0);
}
@Test
public void testChooserRandomForEmptyList() {
Chooser<String, String> chooser = new Chooser<>("test");
assertEquals("test", chooser.getUniqueKey());
assertNull(chooser.random());
}
@Test
public void testChooserRandomForOneSizeList() {
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
Chooser<String, String> chooser = new Chooser<>("test", list);
String actual = chooser.random();
assertNotNull(actual);
assertEquals("test", actual);
}
@Test
public void testChooserRandom() {
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
list.add(new Pair<>("test2", 1));
Chooser<String, String> chooser = new Chooser<>("test", list);
String actual = chooser.random();
assertNotNull(actual);
assertTrue(actual.equals("test") || actual.equals("test2"));
}
@Test
public void testOnlyOneInstanceWeightIsNotZero() {
// If there is only one instance whose weight is not zero, it will be selected
List<Instance> hosts = getOneInstanceNotZeroList();
Instance target = getRandomInstance(hosts);
assertTrue(target.getWeight() > 0);
}
@Test
public void testInstanceWeightAllZero() {
// Throw an IllegalStateException when all instances have a weight of zero.
List<Instance> hosts = getInstanceWeightAllZero();
try {
getRandomInstance(hosts);
} catch (Exception e) {
assertTrue(e instanceof IllegalStateException);
}
}
@Test(expected = IllegalStateException.class)
public void testRandomWithWeightForNaNAndInfinity() {
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", Double.NaN));
list.add(new Pair<>("test2", Double.POSITIVE_INFINITY));
new Chooser<>("test", list);
}
@Test
public void testRefresh() {
Chooser<String, String> chooser = new Chooser<>("test");
assertEquals("test", chooser.getUniqueKey());
assertNull(chooser.random());
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
chooser.refresh(list);
String actual = chooser.random();
assertNotNull(actual);
assertEquals("test", actual);
}
@Test
public void testEqualsHashCode() {
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
list.add(new Pair<>("test2", 1));
Chooser<String, String> chooser = new Chooser<>("test", list);
assertEquals("test".hashCode(), chooser.hashCode());
assertTrue(chooser.equals(chooser));
assertFalse(chooser.equals(null));
assertFalse(chooser.equals("test"));
Chooser<String, String> chooser1 = new Chooser<>(null, null);
assertFalse(chooser.equals(chooser1));
assertFalse(chooser1.equals(chooser));
Chooser<String, String> chooser2 = new Chooser<>("test", Collections.emptyList());
assertFalse(chooser.equals(chooser2));
assertFalse(chooser2.equals(chooser));
Chooser<String, String> chooser3 = new Chooser<>("test1", list);
assertFalse(chooser.equals(chooser3));
Chooser<String, String> chooser4 = new Chooser<>("test", list);
assertTrue(chooser.equals(chooser4));
}
@Test
public void testRefEqualsHashCode() {
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
list.add(new Pair<>("test2", 1));
Chooser<String, String> chooser = new Chooser<>("test", list);
Chooser.Ref ref = chooser.getRef();
assertEquals(list.hashCode(), ref.hashCode());
assertTrue(ref.equals(ref));
assertFalse(ref.equals(null));
assertFalse(ref.equals(chooser));
Chooser.Ref ref1 = new Chooser<>("test", null).getRef();
assertFalse(ref.equals(ref1));
assertFalse(ref1.equals(ref));
Chooser.Ref ref2 = new Chooser<>("test", list).getRef();
assertTrue(ref.equals(ref2));
}
private List<Instance> getInstanceList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(i);
list.add(instance);
}
return list;
}
private List<Instance> getOneInstanceNotZeroList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
int notZeroIndex = ThreadLocalRandom.current().nextInt(0, size - 1);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
if (i == notZeroIndex) {
instance.setWeight(notZeroIndex + 1);
} else {
instance.setWeight(0);
}
list.add(instance);
}
return list;
}
private List<Instance> getInstanceWeightAllZero() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(0);
list.add(instance);
}
return list;
}
private Instance getRandomInstance(List<Instance> hosts) {
List<Pair<Instance>> hostsWithWeight = new ArrayList<>();
for (Instance host : hosts) {
if (host.isHealthy()) {
hostsWithWeight.add(new Pair<>(host, host.getWeight()));
}
}
Chooser<String, Instance> vipChooser = new Chooser<>("www.taobao.com", hostsWithWeight);
return vipChooser.randomWithWeight();
}
}

View File

@ -49,9 +49,14 @@ public class CollectionUtilsTest {
List<String> list1 = Arrays.asList("2", "2", "3");
List<String> list2 = Arrays.asList("3", "2", "2");
List<String> list3 = Arrays.asList("3", "2", "3");
List<String> list4 = Arrays.asList("3", "2");
List<String> list5 = Arrays.asList("3", "2", "1");
List<String> list6 = Arrays.asList("2", "2", "1");
Assert.assertTrue(CollectionUtils.isEqualCollection(list1, list2));
Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list3));
Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list4));
Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list5));
Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list6));
}
@Test

View File

@ -21,6 +21,8 @@ import com.alibaba.nacos.client.auth.impl.NacosAuthLoginConstant;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
import com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@ -28,12 +30,15 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -79,4 +84,15 @@ public class SecurityProxyTest {
Assert.assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN));
}
@Test
public void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException {
Field clientAuthPluginManagerField = SecurityProxy.class.getDeclaredField("clientAuthPluginManager");
clientAuthPluginManagerField.setAccessible(true);
ClientAuthPluginManager clientAuthPluginManager = mock(ClientAuthPluginManager.class);
clientAuthPluginManagerField.set(securityProxy, clientAuthPluginManager);
when(clientAuthPluginManager.getAuthServiceSpiImplSet()).thenReturn(Collections.emptySet());
securityProxy.login(new Properties());
Map<String, String> header = securityProxy.getIdentityContext(new RequestResource());
Assert.assertTrue(header.isEmpty());
}
}

View File

@ -18,15 +18,58 @@
package com.alibaba.nacos.client.utils;
import org.junit.Assert;
import com.alibaba.nacos.client.constant.Constants;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AppNameUtilsTest {
@Test
public void testGetAppName() {
String appName = AppNameUtils.getAppName();
Assert.assertEquals("unknown", appName);
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
System.clearProperty(Constants.SysEnv.PROJECT_NAME);
System.clearProperty("jboss.server.home.dir");
System.clearProperty("jetty.home");
System.clearProperty("catalina.base");
}
@Test
public void testGetAppNameByDefault() {
String appName = AppNameUtils.getAppName();
assertEquals("unknown", appName);
}
@Test
public void testGetAppNameByProjectName() {
System.setProperty(Constants.SysEnv.PROJECT_NAME, "testAppName");
String appName = AppNameUtils.getAppName();
assertEquals("testAppName", appName);
}
@Test
public void testGetAppNameByServerTypeForJboss() {
System.setProperty("jboss.server.home.dir", "/home/admin/testAppName/");
String appName = AppNameUtils.getAppName();
assertEquals("testAppName", appName);
}
@Test
public void testGetAppNameByServerTypeForJetty() {
System.setProperty("jetty.home", "/home/admin/testAppName/");
String appName = AppNameUtils.getAppName();
assertEquals("testAppName", appName);
}
@Test
public void testGetAppNameByServerTypeForTomcat() {
System.setProperty("catalina.base", "/home/admin/testAppName/");
String appName = AppNameUtils.getAppName();
assertEquals("testAppName", appName);
}
}

View File

@ -1,118 +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.utils;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.utils.Chooser;
import com.alibaba.nacos.client.naming.utils.Pair;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertTrue;
public class ChooserTest {
//Test the correctness of Chooser, the weight of the final selected instance must be greater than 0
@Test
public void testChooser() {
List<Instance> hosts = getInstanceList();
Instance target = getRandomInstance(hosts);
assertTrue(hosts.contains(target) && target.getWeight() > 0);
}
private List<Instance> getInstanceList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(i);
list.add(instance);
}
return list;
}
// If there is only one instance whose weight is not zero, it will be selected
@Test
public void testOnlyOneInstanceWeightIsNotZero() {
List<Instance> hosts = getOneInstanceNotZeroList();
Instance target = getRandomInstance(hosts);
assertTrue(target.getWeight() > 0);
}
// getOneInstanceNotZeroList
private List<Instance> getOneInstanceNotZeroList() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
int notZeroIndex = ThreadLocalRandom.current().nextInt(0, size - 1);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
if (i == notZeroIndex) {
instance.setWeight(notZeroIndex + 1);
} else {
instance.setWeight(0);
}
list.add(instance);
}
return list;
}
// Throw an IllegalStateException when all instances have a weight of zero.
@Test
public void testInstanceWeightAllZero() {
List<Instance> hosts = getInstanceWeightAllZero();
try {
getRandomInstance(hosts);
} catch (Exception e) {
assertTrue(e instanceof IllegalStateException);
}
}
private List<Instance> getInstanceWeightAllZero() {
List<Instance> list = new ArrayList<>();
int size = ThreadLocalRandom.current().nextInt(0, 1000);
for (int i = 0; i < size; i++) {
Instance instance = new Instance();
instance.setInstanceId(String.valueOf(i));
instance.setWeight(0);
list.add(instance);
}
return list;
}
private Instance getRandomInstance(List<Instance> hosts) {
List<Pair<Instance>> hostsWithWeight = new ArrayList<>();
for (Instance host : hosts) {
if (host.isHealthy()) {
hostsWithWeight.add(new Pair<>(host, host.getWeight()));
}
}
Chooser<String, Instance> vipChooser = new Chooser<>("www.taobao.com", hostsWithWeight);
return vipChooser.randomWithWeight();
}
}

View File

@ -23,6 +23,7 @@ import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -39,5 +40,33 @@ public class EnvUtilTest {
Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag());
Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag());
Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag());
// reset by empty list
headers.put(Constants.AMORY_TAG, Collections.emptyList());
headers.put(Constants.VIPSERVER_TAG, Collections.emptyList());
headers.put(Constants.LOCATION_TAG, Collections.emptyList());
EnvUtil.setSelfEnv(headers);
Assert.assertNull(EnvUtil.getSelfAmoryTag());
Assert.assertNull(EnvUtil.getSelfVipserverTag());
Assert.assertNull(EnvUtil.getSelfLocationTag());
}
@Test
public void testSetSelfEnv2() {
Map<String, List<String>> headers = new HashMap<>();
headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1"));
headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2"));
headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3"));
EnvUtil.setSelfEnv(headers);
Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag());
Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag());
Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag());
// reset
headers.put(Constants.AMORY_TAG, null);
headers.put(Constants.VIPSERVER_TAG, null);
headers.put(Constants.LOCATION_TAG, null);
EnvUtil.setSelfEnv(headers);
Assert.assertNull(EnvUtil.getSelfAmoryTag());
Assert.assertNull(EnvUtil.getSelfVipserverTag());
Assert.assertNull(EnvUtil.getSelfLocationTag());
}
}

View File

@ -20,14 +20,18 @@ package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.alibaba.nacos.common.utils.VersionUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
public class ParamUtilTest {
private String defaultAppKey;
@ -53,7 +57,6 @@ public class ParamUtilTest {
defaultConnectTimeout = 1000;
defaultPerTaskConfigSize = 3000.0;
defaultNodesPath = "serverlist";
}
@After
@ -65,82 +68,85 @@ public class ParamUtilTest {
ParamUtil.setConnectTimeout(defaultConnectTimeout);
ParamUtil.setPerTaskConfigSize(defaultPerTaskConfigSize);
ParamUtil.setDefaultNodesPath(defaultNodesPath);
System.clearProperty("NACOS.CONNECT.TIMEOUT");
System.clearProperty("PER_TASK_CONFIG_SIZE");
System.clearProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL);
}
@Test
public void testGetAppKey() {
String defaultVal = ParamUtil.getAppKey();
Assert.assertEquals(defaultAppKey, defaultVal);
assertEquals(defaultAppKey, defaultVal);
String expect = "test";
ParamUtil.setAppKey(expect);
Assert.assertEquals(expect, ParamUtil.getAppKey());
assertEquals(expect, ParamUtil.getAppKey());
}
@Test
public void testGetAppName() {
String defaultVal = ParamUtil.getAppName();
Assert.assertEquals(defaultAppName, defaultVal);
assertEquals(defaultAppName, defaultVal);
String expect = "test";
ParamUtil.setAppName(expect);
Assert.assertEquals(expect, ParamUtil.getAppName());
assertEquals(expect, ParamUtil.getAppName());
}
@Test
public void testGetDefaultContextPath() {
String defaultVal = ParamUtil.getDefaultContextPath();
Assert.assertEquals(defaultContextPath, defaultVal);
assertEquals(defaultContextPath, defaultVal);
String expect = "test";
ParamUtil.setDefaultContextPath(expect);
Assert.assertEquals(expect, ParamUtil.getDefaultContextPath());
assertEquals(expect, ParamUtil.getDefaultContextPath());
}
@Test
public void testGetClientVersion() {
String defaultVal = ParamUtil.getClientVersion();
Assert.assertEquals(defaultVersion, defaultVal);
assertEquals(defaultVersion, defaultVal);
String expect = "test";
ParamUtil.setClientVersion(expect);
Assert.assertEquals(expect, ParamUtil.getClientVersion());
assertEquals(expect, ParamUtil.getClientVersion());
}
@Test
public void testSetConnectTimeout() {
int defaultVal = ParamUtil.getConnectTimeout();
Assert.assertEquals(defaultConnectTimeout, defaultVal);
assertEquals(defaultConnectTimeout, defaultVal);
int expect = 50;
ParamUtil.setConnectTimeout(expect);
Assert.assertEquals(expect, ParamUtil.getConnectTimeout());
assertEquals(expect, ParamUtil.getConnectTimeout());
}
@Test
public void testGetPerTaskConfigSize() {
double defaultVal = ParamUtil.getPerTaskConfigSize();
Assert.assertEquals(defaultPerTaskConfigSize, defaultVal, 0.01);
assertEquals(defaultPerTaskConfigSize, defaultVal, 0.01);
double expect = 50.0;
ParamUtil.setPerTaskConfigSize(expect);
Assert.assertEquals(expect, ParamUtil.getPerTaskConfigSize(), 0.01);
assertEquals(expect, ParamUtil.getPerTaskConfigSize(), 0.01);
}
@Test
public void testGetDefaultServerPort() {
String actual = ParamUtil.getDefaultServerPort();
Assert.assertEquals("8848", actual);
assertEquals("8848", actual);
}
@Test
public void testGetDefaultNodesPath() {
String defaultVal = ParamUtil.getDefaultNodesPath();
Assert.assertEquals("serverlist", defaultVal);
assertEquals("serverlist", defaultVal);
String expect = "test";
ParamUtil.setDefaultNodesPath(expect);
Assert.assertEquals(expect, ParamUtil.getDefaultNodesPath());
assertEquals(expect, ParamUtil.getDefaultNodesPath());
}
@Test
@ -148,16 +154,69 @@ public class ParamUtilTest {
String expect = "test";
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.NAMESPACE, expect);
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
String actual = ParamUtil.parseNamespace(nacosClientProperties);
Assert.assertEquals(expect, actual);
assertEquals(expect, actual);
}
@Test
public void testParsingEndpointRule() {
String url = "${test:www.example.com}";
String actual = ParamUtil.parsingEndpointRule(url);
Assert.assertEquals("www.example.com", actual);
assertEquals("www.example.com", actual);
}
@Test(expected = IllegalArgumentException.class)
public void testInitConnectionTimeoutWithException() throws Throwable {
Method method = ParamUtil.class.getDeclaredMethod("initConnectionTimeout");
method.setAccessible(true);
System.setProperty("NACOS.CONNECT.TIMEOUT", "test");
try {
method.invoke(null);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
@Test(expected = IllegalArgumentException.class)
public void testInitPerTaskConfigSizeWithException() throws Throwable {
Method method = ParamUtil.class.getDeclaredMethod("initPerTaskConfigSize");
method.setAccessible(true);
System.setProperty("PER_TASK_CONFIG_SIZE", "test");
try {
method.invoke(null);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
@Test
public void testParsingEndpointRuleFromSystem() {
System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url");
assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule(null));
}
@Test
public void testParsingEndpointRuleFromSystemWithParam() {
System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url");
assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule("${abc:xxx}"));
}
@Test
public void testSimplyEnvNameIfOverLimit() {
StringBuilder envNameOverLimitBuilder = new StringBuilder("test");
for (int i = 0; i < 50; i++) {
envNameOverLimitBuilder.append(i);
}
String envName = envNameOverLimitBuilder.toString();
String actual = ParamUtil.simplyEnvNameIfOverLimit(envName);
String expect = envName.substring(0, 50) + MD5Utils.md5Hex(envName, "UTF-8");
assertEquals(expect, actual);
}
@Test public void testSimplyEnvNameNotOverLimit() {
String expect = "test";
assertEquals(expect, ParamUtil.simplyEnvNameIfOverLimit(expect));
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.utils;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
public class PreInitUtilsTest {
@Test
public void testAsyncPreLoadCostComponent() throws InterruptedException {
// There is no things need to be assert.
// The method will called when nacos-client init to async to load some components to reduce the sync load time.
PreInitUtils.asyncPreLoadCostComponent();
// No exception is ok.
// Let async thread run completed
TimeUnit.SECONDS.sleep(2);
}
}

View File

@ -22,6 +22,13 @@ import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.concurrent.Callable;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TemplateUtilsTest {
@Test
@ -40,6 +47,16 @@ public class TemplateUtilsTest {
Mockito.verify(task, Mockito.times(0)).run();
}
@Test
public void testStringNotEmptyAndThenExecuteException() {
String word = "run";
Runnable task = Mockito.mock(Runnable.class);
doThrow(new RuntimeException("test")).when(task).run();
TemplateUtils.stringNotEmptyAndThenExecute(word, task);
Mockito.verify(task, Mockito.times(1)).run();
// NO exception thrown
}
@Test
public void testStringEmptyAndThenExecuteSuccess() {
String word = " ";
@ -55,6 +72,14 @@ public class TemplateUtilsTest {
Assert.assertEquals(expect, actual);
}
@Test
public void testStringEmptyAndThenExecuteException() throws Exception {
Callable callable = mock(Callable.class);
when(callable.call()).thenThrow(new RuntimeException("test"));
String actual = TemplateUtils.stringEmptyAndThenExecute(null, callable);
assertNull(actual);
}
@Test
public void testStringBlankAndThenExecuteSuccess() {
String word = "success";
@ -69,4 +94,12 @@ public class TemplateUtilsTest {
String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> expect);
Assert.assertEquals(expect, actual);
}
@Test
public void testStringBlankAndThenExecuteException() throws Exception {
Callable callable = mock(Callable.class);
when(callable.call()).thenThrow(new RuntimeException("test"));
String actual = TemplateUtils.stringBlankAndThenExecute(null, callable);
assertNull(actual);
}
}

View File

@ -36,6 +36,8 @@ public class ValidatorUtilsTest {
ValidatorUtils.checkContextPath(contextPath3);
String contextPath4 = "";
ValidatorUtils.checkContextPath(contextPath4);
// allow null
ValidatorUtils.checkContextPath(null);
}
@Test(expected = IllegalArgumentException.class)
@ -67,7 +69,6 @@ public class ValidatorUtilsTest {
try {
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.CONTEXT_PATH, "test");
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ValidatorUtils.checkInitParam(nacosClientProperties);
} catch (NacosException e) {

View File

@ -0,0 +1 @@
{error_json}

View File

@ -0,0 +1 @@
ignored file

View File

@ -0,0 +1 @@
{"ip":"1.1.1.1","port":1234,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"file","serviceName":"no_name","metadata":{"chinese":"中文"},"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000,"ipDeleteTimeout":30000}

View File

@ -0,0 +1 @@
{"name":"legal@@with_name","clusters":"file","cacheMillis":1000,"hosts":[{"ip":"1.1.1.1","port":1234,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"file","serviceName":"with_name","metadata":{"chinese":"中文"},"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000,"ipDeleteTimeout":30000}],"lastRefTime":0,"checksum":"","allIPs":false,"reachProtectionThreshold":false,"valid":true}

View File

@ -0,0 +1 @@
{"name":"legal@@with_name","clusters":"file","cacheMillis":1000,"hosts":[{"ip":"1.1.1.1","port":1234,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"file","serviceName":"with_name","metadata":{"chinese":"中文"},"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000,"ipDeleteTimeout":30000}],"lastRefTime":0,"checksum":"","allIPs":false,"reachProtectionThreshold":false,"valid":true}

View File

@ -357,6 +357,8 @@
<exclude>**/predefined-classes-config.json</exclude>
<exclude>**/serialization-config.json</exclude>
<exclude>**/filter-config.json</exclude>
<exclude>**/disk_cache_test/**</exclude>
<exclude>**/failover_test/**</exclude>
</excludes>
</configuration>
<executions>