From c4aac2b82f40f6f7d58856f672781fb9fefbf873 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E7=BF=8A=20SionYang?= Date: Fri, 13 Oct 2023 14:46:04 +0800 Subject: [PATCH] Fill ut for common module (#11247) * Do some refactor and add UT for common package. * Do some refactor and add UT for common package. * Do some refactor and add UT for common package. * Fix UT. --- .../config/impl/ConfigHttpClientManager.java | 2 +- .../AbstractAbilityControlManager.java | 15 +- .../discover/NacosAbilityManagerHolder.java | 63 +- .../cache/decorators/AutoExpireCache.java | 13 +- .../alibaba/nacos/common/codec/Base64.java | 62 +- .../nacos/common/model/RequestHttpEntity.java | 2 +- .../nacos/common/model/RestResult.java | 14 +- .../nacos/common/notify/DefaultPublisher.java | 8 +- .../nacos/common/notify/NotifyCenter.java | 2 - .../packagescan/DefaultPackageScan.java | 4 +- .../paramcheck/DefaultParamChecker.java | 6 +- .../pathencoder/impl/WindowsEncoder.java | 2 +- .../engine/NacosDelayTaskExecuteEngine.java | 12 - .../common/task/engine/TaskExecuteWorker.java | 2 +- .../AbstractAbilityControlManagerTest.java | 159 +++++ .../ability/MockAbilityPostProcessor.java | 31 + .../discover/HigherMockAbilityManager.java | 41 ++ .../discover/LowerMockAbilityManager.java | 41 ++ .../NacosAbilityManagerHolderTest.java | 59 ++ .../nacos/common/codec/Base64Test.java | 16 +- .../executor/ThreadPoolManagerTest.java | 17 +- .../nacos/common/http/HttpUtilsTest.java | 87 ++- .../common/model/RequestHttpEntityTest.java | 94 +++ .../nacos/common/model/RestResultTest.java | 45 ++ .../common/model/RestResultUtilsTest.java | 103 +++ .../common/notify/DefaultPublisherTest.java | 169 +++++ .../notify/DefaultSharePublisherTest.java | 142 ++++ .../nacos/common/notify/NotifyCenterTest.java | 633 +++++++----------- .../packagescan/DefaultPackageScanTest.java | 109 +++ .../common/packagescan/PackageScanTest.java | 42 -- .../packagescan/mock/AnnotationClass.java | 22 + .../common/packagescan/mock/MockClass.java | 21 + .../packagescan/mock/NoAnnotationClass.java | 21 + .../common/packagescan/mock/TestScan.java | 25 + .../paramcheck/DefaultParamCheckerTest.java | 281 +++++++- .../common/paramcheck/MockParamChecker.java | 36 + .../paramcheck/ParamCheckerManagerTest.java | 45 ++ .../pathencoder/PathEncoderManagerTest.java | 72 +- .../pathencoder/WindowsEncoderTest.java | 1 + .../common/spi/NacosServiceLoaderTest.java | 18 + .../alibaba/nacos/common/spi/SpiTestImpl.java | 8 + .../NacosDelayTaskExecuteEngineTest.java | 36 + .../NacosExecuteTaskExecuteEngineTest.java | 33 + .../common/tls/SelfTrustManagerTest.java | 73 ++ .../nacos/common/tls/TlsHelperTest.java | 34 + .../HealthStateChangeTraceEventTest.java | 75 +++ .../event/naming/InstanceTraceEventTest.java | 71 ++ .../event/naming/NamingTraceEventTest.java | 47 ++ .../event/naming/ServiceTraceEventTest.java | 54 ++ .../event/naming/SubscribeTraceEventTest.java | 56 ++ .../TraceEventPublisherFactoryTest.java | 17 +- .../publisher/TraceEventPublisherTest.java | 12 +- ...i.ability.initializer.AbilityPostProcessor | 17 + ...mmon.ability.AbstractAbilityControlManager | 18 + ...cos.common.paramcheck.AbstractParamChecker | 17 + common/src/test/resources/test-tls-cert.pem | 18 + .../config/server/manager/TaskManager.java | 8 +- .../grpc/RemoteParamCheckFilterTest.java | 2 +- pom.xml | 3 + 59 files changed, 2508 insertions(+), 628 deletions(-) create mode 100644 common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/ability/MockAbilityPostProcessor.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/ability/discover/HigherMockAbilityManager.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/ability/discover/LowerMockAbilityManager.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java delete mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/PackageScanTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/mock/AnnotationClass.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/mock/MockClass.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/mock/NoAnnotationClass.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/packagescan/mock/TestScan.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/paramcheck/MockParamChecker.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java create mode 100644 common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java create mode 100644 common/src/test/resources/META-INF/services/com.alibaba.nacos.api.ability.initializer.AbilityPostProcessor create mode 100644 common/src/test/resources/META-INF/services/com.alibaba.nacos.common.ability.AbstractAbilityControlManager create mode 100644 common/src/test/resources/META-INF/services/com.alibaba.nacos.common.paramcheck.AbstractParamChecker create mode 100644 common/src/test/resources/test-tls-cert.pem diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManager.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManager.java index 341bf45f3ad..db2bcb140e9 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManager.java @@ -128,7 +128,7 @@ private static class LimiterHttpClientRequestInterceptor implements HttpClientRe @Override public boolean isIntercept(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) { - final String body = requestHttpEntity.getBody() == null ? "" : JacksonUtils.toJson(requestHttpEntity.getBody()); + final String body = requestHttpEntity.isEmptyBody() ? "" : JacksonUtils.toJson(requestHttpEntity.getBody()); return Limiter.isLimit(MD5Utils.md5Hex(uri + body, Constants.ENCODE)); } diff --git a/common/src/main/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManager.java b/common/src/main/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManager.java index 7571f5f7011..fbc71ef63c4 100644 --- a/common/src/main/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManager.java +++ b/common/src/main/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManager.java @@ -102,21 +102,18 @@ private void initAbilityTable() { public void enableCurrentNodeAbility(AbilityKey abilityKey) { Map abilities = this.currentNodeAbilities.get(abilityKey.getMode()); if (abilities != null) { - doTurn(abilities, abilityKey, true, abilityKey.getMode()); + doTurn(abilities, abilityKey, true); } } - protected void doTurn(Map abilities, AbilityKey key, boolean turn, AbilityMode mode) { - if (!key.getMode().equals(mode)) { - throw new IllegalStateException("Except " + mode + " but " + key.getMode()); - } + protected void doTurn(Map abilities, AbilityKey key, boolean turn) { LOGGER.info("Turn current node ability: {}, turn: {}", key, turn); abilities.put(key.getName(), turn); // notify event AbilityUpdateEvent abilityUpdateEvent = new AbilityUpdateEvent(); abilityUpdateEvent.setTable(Collections.unmodifiableMap(abilities)); - abilityUpdateEvent.isOn = turn; - abilityUpdateEvent.abilityKey = key; + abilityUpdateEvent.setOn(turn); + abilityUpdateEvent.setAbilityKey(key); NotifyCenter.publishEvent(abilityUpdateEvent); } @@ -128,7 +125,7 @@ protected void doTurn(Map abilities, AbilityKey key, boolean tu public void disableCurrentNodeAbility(AbilityKey abilityKey) { Map abilities = this.currentNodeAbilities.get(abilityKey.getMode()); if (abilities != null) { - doTurn(abilities, abilityKey, false, abilityKey.getMode()); + doTurn(abilities, abilityKey, false); } } @@ -180,7 +177,7 @@ public Map getCurrentNodeAbilities(AbilityMode mode) { /** * notify when current node ability changing. */ - public class AbilityUpdateEvent extends Event { + public static class AbilityUpdateEvent extends Event { private static final long serialVersionUID = -1232411212311111L; diff --git a/common/src/main/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolder.java b/common/src/main/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolder.java index 3ca141718f6..ac2484dd517 100644 --- a/common/src/main/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolder.java +++ b/common/src/main/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolder.java @@ -24,68 +24,65 @@ import java.util.Collection; import java.util.Comparator; import java.util.List; -import java.util.ServiceConfigurationError; import java.util.stream.Collectors; /** - * This class is used to discover {@link AbstractAbilityControlManager} implements. All the - * ability operation will be finish in this singleton. + * This class is used to discover {@link AbstractAbilityControlManager} implements. All the ability operation will be + * finish in this singleton. * * @author Daydreamer * @date 2022/7/14 19:58 **/ public class NacosAbilityManagerHolder { - /**. - * private constructor + /** + * . private constructor */ private NacosAbilityManagerHolder() { } private static final Logger LOGGER = LoggerFactory.getLogger(NacosAbilityManagerHolder.class); - /**. - * singleton + /** + * . singleton */ private static AbstractAbilityControlManager abstractAbilityControlManager; - static { - // spi discover implement - Collection load = null; - try { - // if server - load = NacosServiceLoader.load(AbstractAbilityControlManager.class); - } catch (ServiceConfigurationError e) { - throw new RuntimeException("[AbilityControlManager] Cannot find AbilityControlManger"); - } - // the priority of the server is higher - List collect = load.stream() - .sorted(Comparator.comparingInt(AbstractAbilityControlManager::getPriority)) - .collect(Collectors.toList()); - // get the highest priority one - if (load.size() > 0) { - abstractAbilityControlManager = collect.get(collect.size() - 1); - LOGGER.info("[AbilityControlManager] Successfully initialize AbilityControlManager"); - } - } - - /**. - * get nacos ability control manager + /** + * . get nacos ability control manager * * @return BaseAbilityControlManager */ - public static AbstractAbilityControlManager getInstance() { + public static synchronized AbstractAbilityControlManager getInstance() { + if (null == abstractAbilityControlManager) { + initAbilityControlManager(); + } return abstractAbilityControlManager; } - /**. - * Return the target type of ability manager + /** + * . Return the target type of ability manager * * @param clazz clazz - * @param target type + * @param target type * @return AbilityControlManager */ public static T getInstance(Class clazz) { return clazz.cast(abstractAbilityControlManager); } + + private static void initAbilityControlManager() { + // spi discover implement + Collection load = null; + load = NacosServiceLoader.load(AbstractAbilityControlManager.class); + // the priority of the server is higher + List collect = load.stream() + .sorted(Comparator.comparingInt(AbstractAbilityControlManager::getPriority)) + .collect(Collectors.toList()); + // get the highest priority one + if (load.size() > 0) { + abstractAbilityControlManager = collect.get(collect.size() - 1); + LOGGER.info("[AbilityControlManager] Successfully initialize AbilityControlManager"); + } + } } diff --git a/common/src/main/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCache.java b/common/src/main/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCache.java index fd3e9a5344d..4cdb180c928 100644 --- a/common/src/main/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCache.java +++ b/common/src/main/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCache.java @@ -24,6 +24,7 @@ /** * A wrapper that automatically expires the cache. + * * @author zzq * @date 2021/7/30 */ @@ -48,14 +49,15 @@ public void put(K key, V val) { @Override public V get(K key) { - if (keyProp.get(key) != null && isExpire(keyProp.get(key))) { + CacheItemProperties itemProperties = keyProp.get(key); + if (itemProperties != null && isExpire(itemProperties)) { this.keyProp.remove(key); this.delegate.remove(key); return null; } return this.delegate.get(key); } - + @Override public V get(K key, Callable call) throws Exception { V cachedValue = this.get(key); @@ -63,10 +65,10 @@ public V get(K key, Callable call) throws Exception { V v2 = call.call(); this.put(key, v2); return v2; - + } return cachedValue; - + } @Override @@ -87,9 +89,6 @@ public int getSize() { } private boolean isExpire(CacheItemProperties itemProperties) { - if (itemProperties == null) { - return true; - } return expireNanos != -1 && (System.nanoTime() - itemProperties.getExpireNanos() > expireNanos); } diff --git a/common/src/main/java/com/alibaba/nacos/common/codec/Base64.java b/common/src/main/java/com/alibaba/nacos/common/codec/Base64.java index 9de619e4ca9..5d4435e0611 100644 --- a/common/src/main/java/com/alibaba/nacos/common/codec/Base64.java +++ b/common/src/main/java/com/alibaba/nacos/common/codec/Base64.java @@ -16,10 +16,9 @@ package com.alibaba.nacos.common.codec; -import java.nio.charset.StandardCharsets; - /** - * Provides Base64 encoding and decoding as defined by RFC 2045. + * From apache common codec, and remove some useless method. Provides Base64 encoding and decoding as defined by RFC 2045. * *

This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 * @@ -168,28 +167,16 @@ public Base64() { * work! * @since 1.4 */ - public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) { - chunkSeparatorLength = lineSeparator == null ? 0 : lineSeparator.length; + private Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) { + chunkSeparatorLength = lineSeparator.length; unencodedBlockSize = BYTES_PER_UNENCODED_BLOCK; encodedBlockSize = BYTES_PER_ENCODED_BLOCK; this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0; - // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0 - // @see test case Base64Test.testConstructors() - if (lineSeparator != null) { - if (containsAlphabetOrPad(lineSeparator)) { - String sep = null; - sep = new String(lineSeparator, StandardCharsets.UTF_8); - throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]"); - } - if (lineLength > 0) { - this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; - this.lineSeparator = new byte[lineSeparator.length]; - System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); - } else { - this.encodeSize = BYTES_PER_ENCODED_BLOCK; - this.lineSeparator = null; - } + if (lineLength > 0) { + this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; + this.lineSeparator = new byte[lineSeparator.length]; + System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); } else { this.encodeSize = BYTES_PER_ENCODED_BLOCK; this.lineSeparator = null; @@ -206,9 +193,6 @@ public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) { */ private byte[] encode(byte[] pArray) { reset(); - if (pArray == null || pArray.length == 0) { - return pArray; - } encode(pArray, 0, pArray.length); encode(pArray, 0, -1); byte[] buf = new byte[pos - readPos]; @@ -431,16 +415,6 @@ public static byte[] decodeBase64(byte[] base64Data) { return new Base64().decode(base64Data); } - /** - * Returns whether or not the octet is in the Base32 alphabet. - * - * @param octet The value to test - * @return true if the value is defined in the the Base32 alphabet false otherwise. - */ - protected boolean isInAlphabet(byte octet) { - return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1; - } - /** * MIME chunk size per RFC 2045 section 6.8. * @@ -578,26 +552,6 @@ private void reset() { eof = false; } - /** - * Tests a given byte array to see if it contains any characters within the alphabet or PAD. - * - *

Intended for use in checking line-ending arrays - * - * @param arrayOctet byte array to test - * @return true if any byte is a valid character in the alphabet or PAD; false otherwise - */ - private boolean containsAlphabetOrPad(byte[] arrayOctet) { - if (arrayOctet == null) { - return false; - } - for (int i = 0; i < arrayOctet.length; i++) { - if (PAD == arrayOctet[i] || isInAlphabet(arrayOctet[i])) { - return true; - } - } - return false; - } - /** * Calculates the amount of space needed to encode the supplied array. * diff --git a/common/src/main/java/com/alibaba/nacos/common/model/RequestHttpEntity.java b/common/src/main/java/com/alibaba/nacos/common/model/RequestHttpEntity.java index 2240002e671..3fa48a13fae 100644 --- a/common/src/main/java/com/alibaba/nacos/common/model/RequestHttpEntity.java +++ b/common/src/main/java/com/alibaba/nacos/common/model/RequestHttpEntity.java @@ -42,7 +42,7 @@ public RequestHttpEntity(Header header, Query query) { } public RequestHttpEntity(Header header, Object body) { - this(null, header, null, body); + this(null, header, body); } public RequestHttpEntity(Header header, Query query, Object body) { diff --git a/common/src/main/java/com/alibaba/nacos/common/model/RestResult.java b/common/src/main/java/com/alibaba/nacos/common/model/RestResult.java index aa31cb4f62e..d0a37dc00f4 100644 --- a/common/src/main/java/com/alibaba/nacos/common/model/RestResult.java +++ b/common/src/main/java/com/alibaba/nacos/common/model/RestResult.java @@ -21,6 +21,8 @@ /** * Rest result. * + *

TODO replaced or extend by {@link com.alibaba.nacos.api.model.v2.Result}. + * * @author liaochuntao */ public class RestResult implements Serializable { @@ -42,16 +44,6 @@ public RestResult(int code, String message, T data) { this.data = data; } - public RestResult(int code, T data) { - this.code = code; - this.data = data; - } - - public RestResult(int code, String message) { - this.code = code; - this.setMessage(message); - } - public int getCode() { return code; } @@ -114,7 +106,7 @@ public ResResultBuilder withData(T data) { this.data = data; return this; } - + /** * Build result. * diff --git a/common/src/main/java/com/alibaba/nacos/common/notify/DefaultPublisher.java b/common/src/main/java/com/alibaba/nacos/common/notify/DefaultPublisher.java index fedee89f51a..8f09b1cabfa 100644 --- a/common/src/main/java/com/alibaba/nacos/common/notify/DefaultPublisher.java +++ b/common/src/main/java/com/alibaba/nacos/common/notify/DefaultPublisher.java @@ -65,7 +65,10 @@ public void init(Class type, int bufferSize) { setName("nacos.publisher-" + type.getName()); this.eventType = type; this.queueMaxSize = bufferSize; - this.queue = new ArrayBlockingQueue<>(bufferSize); + if (this.queueMaxSize == -1) { + this.queueMaxSize = ringBufferSize; + } + this.queue = new ArrayBlockingQueue<>(this.queueMaxSize); start(); } @@ -78,9 +81,6 @@ public synchronized void start() { if (!initialized) { // start just called once super.start(); - if (queueMaxSize == -1) { - queueMaxSize = ringBufferSize; - } initialized = true; } } diff --git a/common/src/main/java/com/alibaba/nacos/common/notify/NotifyCenter.java b/common/src/main/java/com/alibaba/nacos/common/notify/NotifyCenter.java index 293fa26cbe7..72a5d1fdd62 100644 --- a/common/src/main/java/com/alibaba/nacos/common/notify/NotifyCenter.java +++ b/common/src/main/java/com/alibaba/nacos/common/notify/NotifyCenter.java @@ -113,7 +113,6 @@ public static Map getPublisherMap() { return INSTANCE.publisherMap; } - @JustForTest public static EventPublisher getPublisher(Class topic) { if (ClassUtils.isAssignableFrom(SlowEvent.class, topic)) { return INSTANCE.sharePublisher; @@ -121,7 +120,6 @@ public static EventPublisher getPublisher(Class topic) { return INSTANCE.publisherMap.get(topic.getCanonicalName()); } - @JustForTest public static EventPublisher getSharePublisher() { return INSTANCE.sharePublisher; } diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/DefaultPackageScan.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/DefaultPackageScan.java index 8d7d9a3181a..dc403907ff8 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/DefaultPackageScan.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/DefaultPackageScan.java @@ -95,10 +95,8 @@ public Set> getTypesAnnotatedWith(String pkg, Class) scanClass); } } - } catch (IOException e) { + } catch (IOException | ClassNotFoundException e) { LOGGER.error("scan path: {} failed", packageSearchPath, e); - } catch (ClassNotFoundException e) { - e.printStackTrace(); } return set; } diff --git a/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java b/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java index 8c22d46cdba..69ca16048b2 100644 --- a/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java +++ b/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java @@ -208,7 +208,7 @@ public ParamCheckResponse checkDataIdFormat(String dataId) { if (dataId.length() > paramCheckRule.maxDataIdLength) { paramCheckResponse.setSuccess(false); paramCheckResponse.setMessage(String.format("Param 'dataId' is illegal, the param length should not exceed %d.", - paramCheckRule.maxNamespaceIdLength)); + paramCheckRule.maxDataIdLength)); return paramCheckResponse; } if (!dataIdPattern.matcher(dataId).matches()) { @@ -369,13 +369,13 @@ public ParamCheckResponse checkPortFormat(String port) { portInt = Integer.parseInt(port); } catch (Exception e) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d", + paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d.", paramCheckRule.minPort, paramCheckRule.maxPort)); return paramCheckResponse; } if (portInt > paramCheckRule.maxPort || portInt < paramCheckRule.minPort) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d", + paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d.", paramCheckRule.minPort, paramCheckRule.maxPort)); return paramCheckResponse; } diff --git a/common/src/main/java/com/alibaba/nacos/common/pathencoder/impl/WindowsEncoder.java b/common/src/main/java/com/alibaba/nacos/common/pathencoder/impl/WindowsEncoder.java index 863fa6ad85d..85445dec4ac 100644 --- a/common/src/main/java/com/alibaba/nacos/common/pathencoder/impl/WindowsEncoder.java +++ b/common/src/main/java/com/alibaba/nacos/common/pathencoder/impl/WindowsEncoder.java @@ -88,7 +88,7 @@ public String name() { @Override public boolean needEncode(String key) { if (key == null) { - key = ""; + return false; } return !PATTERN.matcher(key).matches(); } diff --git a/common/src/main/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngine.java b/common/src/main/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngine.java index ea8d97c57c5..291bd076339 100644 --- a/common/src/main/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngine.java +++ b/common/src/main/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngine.java @@ -51,14 +51,6 @@ public NacosDelayTaskExecuteEngine(String name, Logger logger) { this(name, 32, logger, 100L); } - public NacosDelayTaskExecuteEngine(String name, Logger logger, long processInterval) { - this(name, 32, logger, processInterval); - } - - public NacosDelayTaskExecuteEngine(String name, int initCapacity, Logger logger) { - this(name, initCapacity, logger, 100L); - } - public NacosDelayTaskExecuteEngine(String name, int initCapacity, Logger logger, long processInterval) { super(logger); tasks = new ConcurrentHashMap<>(initCapacity); @@ -145,10 +137,6 @@ protected void processTasks() { continue; } NacosTaskProcessor processor = getProcessor(taskKey); - if (null == processor) { - getEngineLog().error("processor not found for task, so discarded. " + task); - continue; - } try { // ReAdd task if process failed if (!processor.process(task)) { diff --git a/common/src/main/java/com/alibaba/nacos/common/task/engine/TaskExecuteWorker.java b/common/src/main/java/com/alibaba/nacos/common/task/engine/TaskExecuteWorker.java index 32f1a139f97..48a251ed22a 100644 --- a/common/src/main/java/com/alibaba/nacos/common/task/engine/TaskExecuteWorker.java +++ b/common/src/main/java/com/alibaba/nacos/common/task/engine/TaskExecuteWorker.java @@ -91,7 +91,7 @@ public int pendingTaskCount() { * Worker status. */ public String status() { - return name + ", pending tasks: " + pendingTaskCount(); + return getName() + ", pending tasks: " + pendingTaskCount(); } @Override diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java new file mode 100644 index 00000000000..7da46bfc53e --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java @@ -0,0 +1,159 @@ +/* + * 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.common.ability; + +import com.alibaba.nacos.api.ability.constant.AbilityKey; +import com.alibaba.nacos.api.ability.constant.AbilityMode; +import com.alibaba.nacos.api.ability.constant.AbilityStatus; +import com.alibaba.nacos.common.notify.Event; +import com.alibaba.nacos.common.notify.NotifyCenter; +import com.alibaba.nacos.common.notify.listener.Subscriber; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class AbstractAbilityControlManagerTest { + + private AbstractAbilityControlManager abilityControlManager; + + private Subscriber mockSubscriber; + + private boolean isOn = true; + + private AssertionError assertionError; + + private boolean notified = false; + + @Before + public void setUp() throws Exception { + mockSubscriber = new Subscriber() { + @Override + public void onEvent(AbstractAbilityControlManager.AbilityUpdateEvent event) { + notified = true; + try { + assertEquals(AbilityKey.SERVER_TEST_1, event.getAbilityKey()); + assertEquals(isOn, event.isOn()); + assertEquals(2, event.getAbilityTable().size()); + assertEquals(isOn, event.getAbilityTable().get(AbilityKey.SERVER_TEST_1.getName())); + } catch (AssertionError error) { + assertionError = error; + } + } + + @Override + public Class subscribeType() { + return AbstractAbilityControlManager.AbilityUpdateEvent.class; + } + }; + abilityControlManager = new MockAbilityControlManager(); + NotifyCenter.registerSubscriber(mockSubscriber); + } + + @After + public void tearDown() throws Exception { + NotifyCenter.deregisterSubscriber(mockSubscriber); + assertionError = null; + notified = false; + } + + @Test + public void testEnableCurrentNodeAbility() throws InterruptedException { + isOn = true; + abilityControlManager.enableCurrentNodeAbility(AbilityKey.SERVER_TEST_1); + TimeUnit.MILLISECONDS.sleep(1100); + assertTrue(notified); + if (null != assertionError) { + throw assertionError; + } + } + + @Test + public void testDisableCurrentNodeAbility() throws InterruptedException { + isOn = false; + abilityControlManager.disableCurrentNodeAbility(AbilityKey.SERVER_TEST_1); + TimeUnit.MILLISECONDS.sleep(1100); + assertTrue(notified); + if (null != assertionError) { + throw assertionError; + } + } + + @Test + public void testIsCurrentNodeAbilityRunning() { + assertEquals(AbilityStatus.SUPPORTED, + abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, + abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); + assertEquals(AbilityStatus.UNKNOWN, + abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SDK_CLIENT_TEST_1)); + } + + @Test + public void testGetCurrentNodeAbilities() { + Map actual = abilityControlManager.getCurrentNodeAbilities(AbilityMode.SERVER); + assertEquals(2, actual.size()); + assertTrue(actual.containsKey(AbilityKey.SERVER_TEST_1.getName())); + assertTrue(actual.containsKey(AbilityKey.SERVER_TEST_2.getName())); + actual = abilityControlManager.getCurrentNodeAbilities(AbilityMode.SDK_CLIENT); + assertTrue(actual.isEmpty()); + } + + @Test + public void testGetPriority() { + assertEquals(Integer.MIN_VALUE, abilityControlManager.getPriority()); + } + + @Test(expected = IllegalStateException.class) + public void testInitFailed() { + abilityControlManager = new AbstractAbilityControlManager() { + @Override + protected Map> initCurrentNodeAbilities() { + Map abilities = Collections.singletonMap(AbilityKey.SDK_CLIENT_TEST_1, true); + return Collections.singletonMap(AbilityMode.SERVER, abilities); + } + + @Override + public int getPriority() { + return 0; + } + }; + } + + private static final class MockAbilityControlManager extends AbstractAbilityControlManager { + + @Override + protected Map> initCurrentNodeAbilities() { + Map abilities = new HashMap<>(2); + abilities.put(AbilityKey.SERVER_TEST_1, true); + abilities.put(AbilityKey.SERVER_TEST_2, false); + return Collections.singletonMap(AbilityMode.SERVER, abilities); + } + + @Override + public int getPriority() { + return Integer.MIN_VALUE; + } + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/MockAbilityPostProcessor.java b/common/src/test/java/com/alibaba/nacos/common/ability/MockAbilityPostProcessor.java new file mode 100644 index 00000000000..f2ceb0bc44c --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/ability/MockAbilityPostProcessor.java @@ -0,0 +1,31 @@ +/* + * 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.common.ability; + +import com.alibaba.nacos.api.ability.constant.AbilityKey; +import com.alibaba.nacos.api.ability.constant.AbilityMode; +import com.alibaba.nacos.api.ability.initializer.AbilityPostProcessor; + +import java.util.Map; + +public class MockAbilityPostProcessor implements AbilityPostProcessor { + + @Override + public void process(AbilityMode mode, Map abilities) { + // do nothing. + } +} diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/discover/HigherMockAbilityManager.java b/common/src/test/java/com/alibaba/nacos/common/ability/discover/HigherMockAbilityManager.java new file mode 100644 index 00000000000..d1e2708f4c1 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/ability/discover/HigherMockAbilityManager.java @@ -0,0 +1,41 @@ +/* + * 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.common.ability.discover; + +import com.alibaba.nacos.api.ability.constant.AbilityKey; +import com.alibaba.nacos.api.ability.constant.AbilityMode; +import com.alibaba.nacos.common.ability.AbstractAbilityControlManager; + +import java.util.HashMap; +import java.util.Map; + +public class HigherMockAbilityManager extends AbstractAbilityControlManager { + + @Override + protected Map> initCurrentNodeAbilities() { + Map abilities = new HashMap<>(); + abilities.put(AbilityKey.SERVER_TEST_1, true); + Map> result = new HashMap<>(); + result.put(AbilityMode.SERVER, abilities); + return result; + } + + @Override + public int getPriority() { + return 100; + } +} diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/discover/LowerMockAbilityManager.java b/common/src/test/java/com/alibaba/nacos/common/ability/discover/LowerMockAbilityManager.java new file mode 100644 index 00000000000..56ca1a66400 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/ability/discover/LowerMockAbilityManager.java @@ -0,0 +1,41 @@ +/* + * 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.common.ability.discover; + +import com.alibaba.nacos.api.ability.constant.AbilityKey; +import com.alibaba.nacos.api.ability.constant.AbilityMode; +import com.alibaba.nacos.common.ability.AbstractAbilityControlManager; + +import java.util.HashMap; +import java.util.Map; + +public class LowerMockAbilityManager extends AbstractAbilityControlManager { + + @Override + protected Map> initCurrentNodeAbilities() { + Map abilities = new HashMap<>(); + abilities.put(AbilityKey.SDK_CLIENT_TEST_1, true); + Map> result = new HashMap<>(); + result.put(AbilityMode.SDK_CLIENT, abilities); + return result; + } + + @Override + public int getPriority() { + return 0; + } +} diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java b/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java new file mode 100644 index 00000000000..6cf8dce7f9d --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java @@ -0,0 +1,59 @@ +/* + * 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.common.ability.discover; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.lang.reflect.Field; + +import static org.junit.Assert.assertNotNull; + +@RunWith(MockitoJUnitRunner.class) +public class NacosAbilityManagerHolderTest { + + @Before + public void setUp() throws Exception { + NacosAbilityManagerHolder.getInstance(); + } + + @After + public void tearDown() throws Exception { + Field abilityControlManagerField = NacosAbilityManagerHolder.class + .getDeclaredField("abstractAbilityControlManager"); + abilityControlManagerField.setAccessible(true); + abilityControlManagerField.set(null, null); + } + + @Test + public void testGetInstance() { + assertNotNull(NacosAbilityManagerHolder.getInstance()); + } + + @Test + public void testGetInstanceByType() { + assertNotNull(NacosAbilityManagerHolder.getInstance(HigherMockAbilityManager.class)); + } + + @Test(expected = ClassCastException.class) + public void testGetInstanceByWrongType() { + assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class)); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java b/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java index e32c1dfcdac..accdd7fe4cd 100644 --- a/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java +++ b/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java @@ -37,11 +37,19 @@ public void test() { @Test public void testEncodeNullOrEmpty() { byte[] b1 = Base64.encodeBase64(null); - Assert.assertEquals(null, b1); + Assert.assertNull(b1); byte[] b2 = Base64.encodeBase64(new byte[] {}); Assert.assertEquals(0, b2.length); } + @Test + public void testDecodeNullOrEmpty() { + byte[] b1 = Base64.decodeBase64(null); + Assert.assertNull(b1); + byte[] b2 = Base64.decodeBase64(new byte[] {}); + Assert.assertEquals(0, b2.length); + } + @Test public void testChunk() { String a = "very large characters to test chunk encoding and see if the result is expected or not"; @@ -79,4 +87,10 @@ public void testUrlSafe() { Assert.assertEquals("aa~aa?", s3); Assert.assertEquals("aa~aa?", s4); } + + @Test(expected = IllegalArgumentException.class) + public void testEncodeOverMaxLength() { + String a = "very large characters to test chunk encoding and see if the result is expected or not"; + Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, 10); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java index 54834b24b2f..dbdbf6d37b7 100644 --- a/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java @@ -21,6 +21,8 @@ import java.util.concurrent.ExecutorService; +import static org.junit.Assert.assertTrue; + public class ThreadPoolManagerTest { @Test @@ -31,7 +33,7 @@ public void test() { String group = "test"; manager.register(namespace, group, executor); - Assert.assertTrue(manager.getResourcesManager().containsKey(namespace)); + assertTrue(manager.getResourcesManager().containsKey(namespace)); Assert.assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size()); manager.register(namespace, group, ExecutorFactory.newSingleExecutorService()); @@ -64,4 +66,17 @@ public void test() { manager.destroy(namespace, group); Assert.assertFalse(manager.getResourcesManager().containsKey(namespace)); } + + @Test + public void testDestroyWithNull() { + ThreadPoolManager.getInstance().register("t", "g", ExecutorFactory.newFixedExecutorService(1)); + try { + ThreadPoolManager.getInstance().destroy("null"); + assertTrue(ThreadPoolManager.getInstance().getResourcesManager().containsKey("t")); + ThreadPoolManager.getInstance().destroy("null", "g"); + assertTrue(ThreadPoolManager.getInstance().getResourcesManager().containsKey("t")); + } finally { + ThreadPoolManager.getInstance().destroy("t", "g"); + } + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java index 9ecc2080c5e..5a6250bee83 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java @@ -17,11 +17,14 @@ package com.alibaba.nacos.common.http; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.http.param.Query; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ConnectTimeoutException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,10 +32,21 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; +import java.util.concurrent.TimeoutException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @RunWith(MockitoJUnitRunner.class) @@ -95,7 +109,7 @@ public void testInitRequestEntity1() throws Exception { header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html"); HttpUtils.initRequestEntity(httpRequest, new byte[] {0, 1, 0, 1}, header); - + HttpEntity entity = httpRequest.getEntity(); InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; @@ -153,7 +167,7 @@ public void testInitRequestEntity4() throws Exception { @Test public void testInitRequestEntity5() throws Exception { HttpDelete httpDelete = new HttpDelete(""); - + HttpUtils.initRequestEntity(httpDelete, null, null); // nothing change @@ -166,7 +180,7 @@ public void testInitRequestFromEntity1() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(httpRequest, Collections.singletonMap("k", "v"), "UTF-8"); - + HttpEntity entity = httpRequest.getEntity(); InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; @@ -177,9 +191,9 @@ public void testInitRequestFromEntity1() throws Exception { @Test public void testInitRequestFromEntity2() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); - + HttpUtils.initRequestFromEntity(httpRequest, null, "UTF-8"); - + // nothing change Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); } @@ -228,4 +242,67 @@ public void testDecode() throws UnsupportedEncodingException { Assert.assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8")); Assert.assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8")); } + + @Test + public void testEncodingParamsMapWithNullOrEmpty() throws UnsupportedEncodingException { + assertNull(HttpUtils.encodingParams((Map) null, "UTF-8")); + assertNull(HttpUtils.encodingParams(Collections.emptyMap(), "UTF-8")); + } + + @Test + public void testEncodingParamsMap() throws UnsupportedEncodingException { + Map params = new LinkedHashMap<>(); + params.put("a", ""); + params.put("b", "x"); + params.put("uriChar", "="); + params.put("chinese", "测试"); + assertEquals("b=x&uriChar=%3D&chinese=%E6%B5%8B%E8%AF%95&", HttpUtils.encodingParams(params, "UTF-8")); + } + + @Test + public void testEncodingParamsListWithNull() throws UnsupportedEncodingException { + assertNull(HttpUtils.encodingParams((List) null, "UTF-8")); + } + + @Test + public void testEncodingParamsList() throws UnsupportedEncodingException { + List params = new LinkedList<>(); + params.add("a"); + params.add(""); + params.add("b"); + params.add("x"); + params.add("uriChar"); + params.add("="); + params.add("chinese"); + params.add("测试"); + assertEquals("a=&b=x&uriChar=%3D&chinese=%E6%B5%8B%E8%AF%95", HttpUtils.encodingParams(params, "UTF-8")); + } + + @Test + public void testBuildUriForEmptyQuery() throws URISyntaxException { + URI actual = HttpUtils.buildUri("www.aliyun.com", null); + assertEquals("www.aliyun.com", actual.toString()); + actual = HttpUtils.buildUri("www.aliyun.com", new Query()); + assertEquals("www.aliyun.com", actual.toString()); + } + + @Test + public void testBuildUri() throws URISyntaxException { + Query query = new Query(); + query.addParam("a", ""); + query.addParam("b", "x"); + query.addParam("uriChar", "="); + query.addParam("chinese", "测试"); + URI actual = HttpUtils.buildUri("www.aliyun.com", query); + assertEquals("www.aliyun.com?" + query.toQueryUrl(), actual.toString()); + } + + @Test + public void testIsTimeoutException() { + assertFalse(HttpUtils.isTimeoutException(new NacosRuntimeException(0))); + assertTrue(HttpUtils.isTimeoutException(new TimeoutException())); + assertTrue(HttpUtils.isTimeoutException(new SocketTimeoutException())); + assertTrue(HttpUtils.isTimeoutException(new ConnectTimeoutException())); + assertTrue(HttpUtils.isTimeoutException(new NacosRuntimeException(0, new TimeoutException()))); + } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java new file mode 100644 index 00000000000..3abfaeead32 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java @@ -0,0 +1,94 @@ +/* + * 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.common.model; + +import com.alibaba.nacos.common.http.HttpClientConfig; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.http.param.Query; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class RequestHttpEntityTest { + + Header header; + + Query query; + + HttpClientConfig clientConfig; + + Object body; + + @Before + public void setUp() throws Exception { + header = Header.newInstance(); + header.addParam("testHeader", "test"); + query = Query.newInstance(); + query.addParam("testQuery", "test"); + clientConfig = HttpClientConfig.builder().build(); + body = new HashMap<>(); + } + + @Test + public void testConstructWithoutConfigAndBody() { + RequestHttpEntity entity = new RequestHttpEntity(header, query); + assertTrue(entity.isEmptyBody()); + assertNull(entity.getHttpClientConfig()); + assertNull(entity.getBody()); + assertEquals(header.toString(), entity.getHeaders().toString()); + assertEquals(query.toString(), entity.getQuery().toString()); + } + + @Test + public void testConstructWithoutConfigAndQuery() { + RequestHttpEntity entity = new RequestHttpEntity(header, body); + assertFalse(entity.isEmptyBody()); + assertNull(entity.getHttpClientConfig()); + assertNull(entity.getQuery()); + assertEquals(header.toString(), entity.getHeaders().toString()); + assertEquals(body, entity.getBody()); + } + + @Test + public void testConstructWithoutConfig() { + RequestHttpEntity entity = new RequestHttpEntity(header, query, body); + assertFalse(entity.isEmptyBody()); + assertNull(entity.getHttpClientConfig()); + assertEquals(query.toString(), entity.getQuery().toString()); + assertEquals(header.toString(), entity.getHeaders().toString()); + assertEquals(body, entity.getBody()); + } + + @Test + public void testConstructFull() { + RequestHttpEntity entity = new RequestHttpEntity(clientConfig, header, query, body); + assertFalse(entity.isEmptyBody()); + assertEquals(clientConfig, entity.getHttpClientConfig()); + assertEquals(query.toString(), entity.getQuery().toString()); + assertEquals(header.toString(), entity.getHeaders().toString()); + assertEquals(body, entity.getBody()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java new file mode 100644 index 00000000000..4e66227d050 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java @@ -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.common.model; + +import com.alibaba.nacos.common.utils.JacksonUtils; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class RestResultTest { + + @Test + public void testSerialization() { + RestResult result = new RestResult<>(200, "test", "content"); + String json = JacksonUtils.toJson(result); + assertTrue(json.contains("\"code\":200")); + assertTrue(json.contains("\"message\":\"test\"")); + assertTrue(json.contains("\"data\":\"content\"")); + } + + @Test + public void testDeserialization() { + String json = "{\"code\":200,\"message\":\"test\",\"data\":\"content\"}"; + RestResult restResult = JacksonUtils.toObj(json, RestResult.class); + assertEquals(200, restResult.getCode()); + assertEquals("test", restResult.getMessage()); + assertEquals("content", restResult.getData()); + assertEquals("RestResult{code=200, message='test', data=content}", restResult.toString()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java new file mode 100644 index 00000000000..076f4afe5f7 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java @@ -0,0 +1,103 @@ +/* + * 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.common.model; + +import com.alibaba.nacos.common.model.core.IResultCode; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class RestResultUtilsTest { + + @Test + public void testSuccessWithDefault() { + RestResult restResult = RestResultUtils.success(); + assertRestResult(restResult, 200, null, null, true); + } + + @Test + public void testSuccessWithData() { + RestResult restResult = RestResultUtils.success("content"); + assertRestResult(restResult, 200, null, "content", true); + } + + @Test + public void testSuccessWithMsg() { + RestResult restResult = RestResultUtils.success("test", "content"); + assertRestResult(restResult, 200, "test", "content", true); + } + + @Test + public void testSuccessWithCode() { + RestResult restResult = RestResultUtils.success(203, "content"); + assertRestResult(restResult, 203, null, "content", false); + } + + @Test + public void testFailedWithDefault() { + RestResult restResult = RestResultUtils.failed(); + assertRestResult(restResult, 500, null, null, false); + } + + @Test + public void testFailedWithMsg() { + RestResult restResult = RestResultUtils.failed("test"); + assertRestResult(restResult, 500, "test", null, false); + } + + @Test + public void testFailedWithCode() { + RestResult restResult = RestResultUtils.failed(400, "content"); + assertRestResult(restResult, 400, null, "content", false); + } + + @Test + public void testSuccessWithFull() { + RestResult restResult = RestResultUtils.failed(400, "content", "test"); + assertRestResult(restResult, 400, "test", "content", false); + } + + @Test + public void testFailedWithMsgMethod() { + RestResult restResult = RestResultUtils.failedWithMsg(400, "content"); + assertRestResult(restResult, 400, "content", null, false); + } + + @Test + public void testBuildResult() { + IResultCode mockCode = new IResultCode() { + @Override + public int getCode() { + return 503; + } + + @Override + public String getCodeMsg() { + return "limited"; + } + }; + RestResult restResult = RestResultUtils.buildResult(mockCode, "content"); + assertRestResult(restResult, 503, "limited", "content", false); + } + + private void assertRestResult(RestResult restResult, int code, String message, Object data, boolean isOk) { + assertEquals(code, restResult.getCode()); + assertEquals(message, restResult.getMessage()); + assertEquals(data, restResult.getData()); + assertEquals(isOk, restResult.ok()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java new file mode 100644 index 00000000000..53ac32dfaec --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java @@ -0,0 +1,169 @@ +/* + * 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.common.notify; + +import com.alibaba.nacos.common.notify.listener.Subscriber; +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.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DefaultPublisherTest { + + private DefaultPublisher publisher; + + @Mock + private Subscriber subscriber; + + @Before + public void setUp() throws Exception { + publisher = new DefaultPublisher(); + publisher.init(MockEvent.class, 1); + } + + @After + public void tearDown() throws Exception { + try { + publisher.shutdown(); + } catch (Exception ignored) { + } + } + + @Test + public void testInitWithIllegalSize() { + publisher.shutdown(); + publisher = new DefaultPublisher(); + publisher.init(MockEvent.class, -1); + assertTrue(publisher.isInitialized()); + } + + @Test(expected = IllegalStateException.class) + public void testCheckIsStart() { + publisher.shutdown(); + publisher = new DefaultPublisher(); + publisher.checkIsStart(); + } + + @Test + public void testCurrentEventSize() { + assertEquals(0, publisher.currentEventSize()); + publisher.publish(new MockEvent()); + assertEquals(1, publisher.currentEventSize()); + } + + @Test + public void testRemoveSubscriber() { + publisher.addSubscriber(subscriber); + assertEquals(1, publisher.getSubscribers().size()); + publisher.removeSubscriber(subscriber); + assertEquals(0, publisher.getSubscribers().size()); + } + + @Test + public void publishEventWhenQueueFull() { + // Stop the publisher thread to mock queue full. + publisher.shutdown(); + publisher.publish(new MockEvent()); + // Test throw event when no subscribers. + publisher.publish(new MockEvent()); + verify(subscriber, never()).onEvent(any(MockEvent.class)); + // Add subscriber to test + publisher.addSubscriber(subscriber); + publisher.publish(new MockEvent()); + // Test scopeMatches not pass + verify(subscriber, never()).onEvent(any(MockEvent.class)); + // Test scopeMatches pass + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + publisher.publish(new MockEvent()); + verify(subscriber).onEvent(any(MockEvent.class)); + } + + @Test + public void publishEventQueueNotFull() throws InterruptedException { + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + MockEvent mockEvent = new MockEvent(); + // Make sure Publisher entry waiting subscribers. + TimeUnit.MILLISECONDS.sleep(500); + publisher.addSubscriber(subscriber); + publisher.publish(mockEvent); + // Make sure Publisher find the subscribers. + TimeUnit.MILLISECONDS.sleep(600); + verify(subscriber).onEvent(mockEvent); + // Test subscriber ignore expired event. + publisher.publish(new MockEvent()); + TimeUnit.MILLISECONDS.sleep(100); + reset(subscriber); + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + when(subscriber.ignoreExpireEvent()).thenReturn(true); + publisher.publish(mockEvent); + TimeUnit.MILLISECONDS.sleep(100); + verify(subscriber, never()).onEvent(mockEvent); + } + + @Test + public void testHandleEventWithThrowable() throws InterruptedException { + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + doThrow(new RuntimeException("test")).when(subscriber).onEvent(any(MockEvent.class)); + publisher.addSubscriber(subscriber); + publisher.publish(new MockEvent()); + TimeUnit.MILLISECONDS.sleep(1100); + verify(subscriber).onEvent(any(MockEvent.class)); + } + + @Test + public void testHandleEventWithExecutor() throws InterruptedException { + Executor executor = mock(Executor.class); + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + when(subscriber.executor()).thenReturn(executor); + publisher.addSubscriber(subscriber); + publisher.publish(new MockEvent()); + TimeUnit.MILLISECONDS.sleep(1100); + verify(executor).execute(any(Runnable.class)); + } + + @Test + public void testReceiveEventWithException() throws InterruptedException { + Executor executor = mock(Executor.class); + when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); + when(subscriber.executor()).thenThrow(new RuntimeException("test")); + publisher.addSubscriber(subscriber); + publisher.publish(new MockEvent()); + TimeUnit.MILLISECONDS.sleep(1100); + verify(executor, never()).execute(any(Runnable.class)); + } + + private static class MockEvent extends Event { + + private static final long serialVersionUID = -4081244883427311461L; + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java new file mode 100644 index 00000000000..585c9d55e6e --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java @@ -0,0 +1,142 @@ +/* + * 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.common.notify; + +import com.alibaba.nacos.common.notify.listener.SmartSubscriber; +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.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DefaultSharePublisherTest { + + private static final AtomicLong TEST_SEQUENCE = new AtomicLong(); + + DefaultSharePublisher defaultSharePublisher; + + @Mock + SmartSubscriber smartSubscriber1; + + @Mock + SmartSubscriber smartSubscriber2; + + @Before + public void setUp() throws Exception { + defaultSharePublisher = new DefaultSharePublisher(); + defaultSharePublisher.init(SlowEvent.class, 2); + } + + @After + public void tearDown() throws Exception { + defaultSharePublisher.shutdown(); + } + + @Test + public void testRemoveSubscribers() { + defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); + defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent2.class); + defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); + assertEquals(2, defaultSharePublisher.getSubscribers().size()); + defaultSharePublisher.removeSubscriber(smartSubscriber1, MockSlowEvent1.class); + defaultSharePublisher.removeSubscriber(smartSubscriber1, MockSlowEvent2.class); + defaultSharePublisher.removeSubscriber(smartSubscriber2, MockSlowEvent2.class); + assertEquals(0, defaultSharePublisher.getSubscribers().size()); + } + + @Test + public void testReceiveEventWithoutSubscriber() { + defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); + defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); + defaultSharePublisher.receiveEvent(new SlowEvent() { + private static final long serialVersionUID = 5996336354563933789L; + + @Override + public long sequence() { + return super.sequence(); + } + }); + verify(smartSubscriber1, never()).onEvent(any(SlowEvent.class)); + verify(smartSubscriber2, never()).onEvent(any(SlowEvent.class)); + } + + @Test + public void testReceiveEventWithSubscriber() { + defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); + defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); + defaultSharePublisher.receiveEvent(new MockSlowEvent1()); + verify(smartSubscriber1).onEvent(any(MockSlowEvent1.class)); + verify(smartSubscriber2, never()).onEvent(any(MockSlowEvent1.class)); + defaultSharePublisher.receiveEvent(new MockSlowEvent2()); + verify(smartSubscriber1, never()).onEvent(any(MockSlowEvent2.class)); + verify(smartSubscriber2).onEvent(any(MockSlowEvent2.class)); + } + + @Test + public void testIgnoreExpiredEvent() throws InterruptedException { + MockSlowEvent1 mockSlowEvent1 = new MockSlowEvent1(); + MockSlowEvent2 mockSlowEvent2 = new MockSlowEvent2(); + defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); + defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); + defaultSharePublisher.publish(mockSlowEvent1); + defaultSharePublisher.publish(mockSlowEvent2); + TimeUnit.MILLISECONDS.sleep(1100); + verify(smartSubscriber1).onEvent(mockSlowEvent1); + verify(smartSubscriber2).onEvent(mockSlowEvent2); + reset(smartSubscriber1); + when(smartSubscriber1.ignoreExpireEvent()).thenReturn(true); + defaultSharePublisher.publish(mockSlowEvent1); + TimeUnit.MILLISECONDS.sleep(100); + verify(smartSubscriber1, never()).onEvent(mockSlowEvent1); + } + + private static class MockSlowEvent1 extends SlowEvent { + + private static final long serialVersionUID = -951177705152304999L; + + private final long sequence = TEST_SEQUENCE.incrementAndGet(); + + @Override + public long sequence() { + return sequence; + } + } + + private static class MockSlowEvent2 extends SlowEvent { + + private static final long serialVersionUID = -951177705152304999L; + + private final long sequence = TEST_SEQUENCE.incrementAndGet(); + + @Override + public long sequence() { + return sequence; + } + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java index d1abd7c1e73..aed060a2cff 100644 --- a/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java @@ -16,510 +16,331 @@ package com.alibaba.nacos.common.notify; +import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.ThreadUtils; +import org.junit.After; import org.junit.Assert; -import org.junit.FixMethodOrder; +import org.junit.Before; import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; -import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; import java.util.List; +import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) +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.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) public class NotifyCenterTest { - private static class TestSlowEvent extends SlowEvent { + static { + System.setProperty("nacos.core.notify.share-buffer-size", "8"); + } + + private static AtomicInteger count; + + SmartSubscriber smartSubscriber; + Subscriber subscriber; + + @Mock + ShardedEventPublisher shardedEventPublisher; + + @Before + public void setUp() throws Exception { + count = new AtomicInteger(); + NotifyCenter.registerToSharePublisher(TestSlowEvent.class); + NotifyCenter.registerToPublisher(TestSlowEvent1.class, 10); + NotifyCenter.registerToPublisher(TestEvent.class, 8); + NotifyCenter.registerToPublisher(ExpireEvent.class, 16); + NotifyCenter.registerToPublisher(SharedEvent.class, shardedEventPublisher); } - private static class TestEvent extends Event { - - @Override - public long sequence() { - return System.currentTimeMillis(); + @After + public void tearDown() throws Exception { + if (null != smartSubscriber) { + NotifyCenter.deregisterSubscriber(smartSubscriber); + } + if (null != subscriber) { + NotifyCenter.deregisterSubscriber(subscriber); } + NotifyCenter.deregisterPublisher(TestEvent.class); + NotifyCenter.deregisterPublisher(ExpireEvent.class); } - static { - System.setProperty("nacos.core.notify.share-buffer-size", "8"); + @Test + public void testRegisterNullPublisher() { + int originalSize = NotifyCenter.getPublisherMap().size(); + NotifyCenter.registerToPublisher(NoPublisherEvent.class, null); + assertEquals(originalSize, NotifyCenter.getPublisherMap().size()); } @Test - public void testEventsCanBeSubscribed() throws Exception { - - NotifyCenter.registerToSharePublisher(TestSlowEvent.class); - NotifyCenter.registerToPublisher(TestEvent.class, 8); - - final CountDownLatch latch = new CountDownLatch(2); - final AtomicInteger count = new AtomicInteger(0); - - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(TestSlowEvent event) { - try { - count.incrementAndGet(); - } finally { - latch.countDown(); - } - } - - @Override - public Class subscribeType() { - return TestSlowEvent.class; - } - }); - - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(TestEvent event) { - try { - count.incrementAndGet(); - } finally { - latch.countDown(); - } - } - - @Override - public Class subscribeType() { - return TestEvent.class; - } - }); - - Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); - - ThreadUtils.sleep(5000L); - - latch.await(5000L, TimeUnit.MILLISECONDS); - - Assert.assertEquals(2, count.get()); + public void testGetPublisher() { + assertEquals(NotifyCenter.getSharePublisher(), NotifyCenter.getPublisher(TestSlowEvent.class)); + assertTrue(NotifyCenter.getPublisher(TestEvent.class) instanceof DefaultPublisher); } - static CountDownLatch latch = new CountDownLatch(3); - - static class ExpireEvent extends Event { - - static AtomicLong sequence = new AtomicLong(3); - - private long no = sequence.getAndDecrement(); - - @Override - public long sequence() { - latch.countDown(); - return no; - } + @Test + public void testEventsCanBeSubscribed() { + subscriber = new MockSubscriber<>(TestEvent.class, false); + smartSubscriber = new MockSmartSubscriber(Collections.singletonList(TestSlowEvent.class)); + NotifyCenter.registerSubscriber(subscriber); + NotifyCenter.registerSubscriber(smartSubscriber); + Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + ThreadUtils.sleep(2000L); + assertEquals(2, count.get()); } @Test public void testCanIgnoreExpireEvent() throws Exception { NotifyCenter.registerToPublisher(ExpireEvent.class, 16); - final AtomicInteger count = new AtomicInteger(0); - - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(ExpireEvent event) { - count.incrementAndGet(); - } - - @Override - public Class subscribeType() { - return ExpireEvent.class; - } - - @Override - public boolean ignoreExpireEvent() { - return true; - } - - }); - + CountDownLatch latch = new CountDownLatch(3); + subscriber = new MockSubscriber<>(ExpireEvent.class, true, latch); + NotifyCenter.registerSubscriber(subscriber); for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new ExpireEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new ExpireEvent(3 - i))); } - - latch.await(10000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(1, count.get()); + latch.await(5000L, TimeUnit.MILLISECONDS); + assertEquals(1, count.get()); } - static CountDownLatch latch2 = new CountDownLatch(3); - - static class NoExpireEvent extends Event { - - static AtomicLong sequence = new AtomicLong(3); - - private long no = sequence.getAndDecrement(); - - @Override - public long sequence() { - return no; + @Test + public void testSharePublishEvent() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(20); + Subscriber subscriber = new MockSubscriber<>(TestSlowEvent.class, false, latch); + Subscriber subscriber1 = new MockSubscriber<>(TestSlowEvent1.class, false, latch); + try { + NotifyCenter.registerSubscriber(subscriber); + NotifyCenter.registerSubscriber(subscriber1); + for (int i = 0; i < 10; i++) { + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); + } + latch.await(5000L, TimeUnit.MILLISECONDS); + assertEquals(20, count.get()); + } finally { + NotifyCenter.deregisterSubscriber(subscriber); + NotifyCenter.deregisterSubscriber(subscriber1); } } @Test - public void testNoIgnoreExpireEvent() throws Exception { - NotifyCenter.registerToPublisher(NoExpireEvent.class, 16); - final AtomicInteger count = new AtomicInteger(0); - - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(Event event) { - count.incrementAndGet(); - latch2.countDown(); - } - - @Override - public Class subscribeType() { - return NoExpireEvent.class; - } - }); - + public void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception { + List> subscribedEvents = new LinkedList<>(); + subscribedEvents.add(TestSlowEvent.class); + subscribedEvents.add(TestSlowEvent1.class); + CountDownLatch latch = new CountDownLatch(6); + smartSubscriber = new MockSmartSubscriber(subscribedEvents, latch); + NotifyCenter.registerSubscriber(smartSubscriber); for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new NoExpireEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); } - - latch2.await(10000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(3, count.get()); + latch.await(5000L, TimeUnit.MILLISECONDS); + assertEquals(6, count.get()); } - private static class SlowE1 extends SlowEvent { - - private String info = "SlowE1"; - - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; + @Test + public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception { + List> subscribedEvents = new LinkedList<>(); + subscribedEvents.add(TestEvent.class); + subscribedEvents.add(TestSlowEvent.class); + CountDownLatch latch = new CountDownLatch(6); + smartSubscriber = new MockSmartSubscriber(subscribedEvents, latch); + NotifyCenter.registerSubscriber(smartSubscriber); + for (int i = 0; i < 3; i++) { + Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent())); + Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); } - + latch.await(5000L, TimeUnit.MILLISECONDS); + assertEquals(6, count.get()); } - private static class SlowE2 extends SlowEvent { - - private String info = "SlowE2"; - - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; + @Test + public void testPublishEventByNoPublisher() { + for (int i = 0; i < 3; i++) { + Assert.assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent())); } - } @Test - public void testSharePublishTwoSlowEvents() throws Exception { - NotifyCenter.registerToSharePublisher(SlowE1.class); - NotifyCenter.registerToSharePublisher(SlowE2.class); - - final CountDownLatch latch1 = new CountDownLatch(15); - final CountDownLatch latch2 = new CountDownLatch(15); - - final String[] values = new String[] {null, null}; - - NotifyCenter.registerSubscriber(new Subscriber() { - - @Override - public void onEvent(SlowE1 event) { - ThreadUtils.sleep(1000L); - values[0] = event.info; - latch1.countDown(); - } - - @Override - public Class subscribeType() { - return SlowE1.class; - } - }); - - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(SlowE2 event) { - values[1] = event.info; - latch2.countDown(); - } - - @Override - public Class subscribeType() { - return SlowE2.class; - } - }); - - for (int i = 0; i < 30; i++) { - NotifyCenter.publishEvent(new SlowE1()); - NotifyCenter.publishEvent(new SlowE2()); + public void testPublishEventByPluginEvent() { + for (int i = 0; i < 3; i++) { + Assert.assertTrue(NotifyCenter.publishEvent(new PluginEvent())); } - - latch1.await(); - latch2.await(); - - Assert.assertEquals("SlowE1", values[0]); - Assert.assertEquals("SlowE2", values[1]); - } - static class SmartEvent1 extends Event { - - @Override - public long sequence() { - return System.currentTimeMillis(); - } + @Test + public void testDeregisterPublisherWithException() throws NacosException { + final int originalSize = NotifyCenter.getPublisherMap().size(); + doThrow(new RuntimeException("test")).when(shardedEventPublisher).shutdown(); + NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); + NotifyCenter.deregisterPublisher(SharedEvent.class); + assertEquals(originalSize - 1, NotifyCenter.getPublisherMap().size()); } - static class SmartEvent2 extends Event { - - @Override - public long sequence() { - return System.currentTimeMillis(); - } + @Test + public void testPublishEventWithException() { + when(shardedEventPublisher.publish(any(Event.class))).thenThrow(new RuntimeException("test")); + NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); + assertFalse(NotifyCenter.publishEvent(new SharedEvent())); } @Test - public void testSeveralEventsPublishedBySinglePublisher() throws Exception { + public void testOperateSubscriberForShardedPublisher() { + subscriber = new MockSubscriber(SharedEvent.class, false); + NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); + NotifyCenter.registerSubscriber(subscriber); + verify(shardedEventPublisher).addSubscriber(subscriber, SharedEvent.class); + NotifyCenter.deregisterSubscriber(subscriber); + verify(shardedEventPublisher).removeSubscriber(subscriber, SharedEvent.class); + } + + @Test(expected = NoSuchElementException.class) + public void testDeregisterNonExistSubscriber() { + try { + subscriber = new MockSubscriber(NoPublisherEvent.class, false); + NotifyCenter.deregisterSubscriber(subscriber); + } finally { + subscriber = null; + } + } + + private static class MockSubscriber extends Subscriber { - final AtomicInteger count1 = new AtomicInteger(0); - final AtomicInteger count2 = new AtomicInteger(0); + private final Class subscribedEvent; - final CountDownLatch latch1 = new CountDownLatch(3); - final CountDownLatch latch2 = new CountDownLatch(3); + private final boolean ignoreExpiredEvent; - NotifyCenter.registerToPublisher(SmartEvent1.class, 1024); - NotifyCenter.registerToPublisher(SmartEvent2.class, 1024); + private final CountDownLatch latch; - NotifyCenter.registerSubscriber(new SmartSubscriber() { - @Override - public List> subscribeTypes() { - List> list = new ArrayList>(); - list.add(SmartEvent1.class); - list.add(SmartEvent2.class); - return list; - } - - @Override - public void onEvent(Event event) { - if (event instanceof SmartEvent1) { - count1.incrementAndGet(); - latch1.countDown(); - } - - if (event instanceof SmartEvent2) { - count2.incrementAndGet(); - latch2.countDown(); - - } - } - }); + private MockSubscriber(Class subscribedEvent, boolean ignoreExpiredEvent) { + this(subscribedEvent, ignoreExpiredEvent, null); + } - for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new SmartEvent1())); - Assert.assertTrue(NotifyCenter.publishEvent(new SmartEvent2())); + public MockSubscriber(Class subscribedEvent, boolean ignoreExpiredEvent, CountDownLatch latch) { + this.subscribedEvent = subscribedEvent; + this.ignoreExpiredEvent = ignoreExpiredEvent; + this.latch = latch; } - latch1.await(3000L, TimeUnit.MILLISECONDS); - latch2.await(3000L, TimeUnit.MILLISECONDS); + @Override + public void onEvent(Event event) { + count.incrementAndGet(); + if (null != latch) { + latch.countDown(); + } + } - Assert.assertEquals(3, count1.get()); - Assert.assertEquals(3, count2.get()); + @Override + public Class subscribeType() { + return subscribedEvent; + } + @Override + public boolean ignoreExpireEvent() { + return ignoreExpiredEvent; + } } - private static class TestSlowEvent1 extends SlowEvent { - - } - - private static class TestSlowEvent2 extends SlowEvent { - - } - - @Test - public void testMutipleSlowEventsListenedBySubscriber() throws Exception { + private static class MockSmartSubscriber extends SmartSubscriber { - NotifyCenter.registerToSharePublisher(TestSlowEvent1.class); - NotifyCenter.registerToSharePublisher(TestSlowEvent2.class); + private final List> subscribedEvents; - final AtomicInteger count1 = new AtomicInteger(0); - final AtomicInteger count2 = new AtomicInteger(0); + private final CountDownLatch latch; - final CountDownLatch latch1 = new CountDownLatch(3); - final CountDownLatch latch2 = new CountDownLatch(3); + private MockSmartSubscriber(List> subscribedEvents) { + this(subscribedEvents, null); + } - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(TestSlowEvent1 event) { - count1.incrementAndGet(); - latch1.countDown(); - } - - @Override - public Class subscribeType() { - return TestSlowEvent1.class; - } - }); + public MockSmartSubscriber(List> subscribedEvents, CountDownLatch latch) { + this.subscribedEvents = subscribedEvents; + this.latch = latch; + } - NotifyCenter.registerSubscriber(new Subscriber() { - @Override - public void onEvent(TestSlowEvent2 event) { - count2.incrementAndGet(); - latch2.countDown(); - - } - - @Override - public Class subscribeType() { - return TestSlowEvent2.class; + @Override + public void onEvent(Event event) { + count.incrementAndGet(); + if (null != latch) { + latch.countDown(); } - }); - - for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent2())); } - ThreadUtils.sleep(2000L); - - latch1.await(3000L, TimeUnit.MILLISECONDS); - latch2.await(3000L, TimeUnit.MILLISECONDS); - - Assert.assertEquals(3, count1.get()); - Assert.assertEquals(3, count2.get()); - + @Override + public List> subscribeTypes() { + return subscribedEvents; + } } - private static class TestSlowEvent3 extends SlowEvent { - + private static class TestSlowEvent extends SlowEvent { + + private static final long serialVersionUID = 6713279688910446154L; } - private static class TestSlowEvent4 extends SlowEvent { - + private static class TestSlowEvent1 extends SlowEvent { + + private static final long serialVersionUID = 5946729801676058102L; } - @Test - public void testMutipleSlowEventsListenedBySmartsubscriber() throws Exception { - - NotifyCenter.registerToSharePublisher(TestSlowEvent3.class); - NotifyCenter.registerToSharePublisher(TestSlowEvent4.class); - - final AtomicInteger count1 = new AtomicInteger(0); - final AtomicInteger count2 = new AtomicInteger(0); - - final CountDownLatch latch1 = new CountDownLatch(3); - final CountDownLatch latch2 = new CountDownLatch(3); + private static class TestEvent extends Event { - NotifyCenter.registerSubscriber(new SmartSubscriber() { - - @Override - public void onEvent(Event event) { - if (event instanceof TestSlowEvent3) { - count1.incrementAndGet(); - latch1.countDown(); - } - - if (event instanceof TestSlowEvent4) { - count2.incrementAndGet(); - latch2.countDown(); - } - } - - @Override - public List> subscribeTypes() { - List> subTypes = new ArrayList>(); - subTypes.add(TestSlowEvent3.class); - subTypes.add(TestSlowEvent4.class); - return subTypes; - } - }); + private static final long serialVersionUID = 2522362576233446960L; - for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent3())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent4())); + @Override + public long sequence() { + return System.currentTimeMillis(); } + } + + private static class NoPublisherEvent extends Event { - ThreadUtils.sleep(2000L); - - latch1.await(3000L, TimeUnit.MILLISECONDS); - latch2.await(3000L, TimeUnit.MILLISECONDS); - - Assert.assertEquals(3, count1.get()); - Assert.assertEquals(3, count2.get()); - + private static final long serialVersionUID = 6532409163269714916L; } - private static class TestSlowEvent5 extends SlowEvent { + private static class SharedEvent extends Event { + private static final long serialVersionUID = 7648766983252000074L; } - private static class TestEvent6 extends Event { + private static class PluginEvent extends Event { + + private static final long serialVersionUID = -7787588724415976798L; + @Override + public boolean isPluginEvent() { + return true; + } } - @Test - public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception { - - NotifyCenter.registerToSharePublisher(TestSlowEvent5.class); - NotifyCenter.registerToPublisher(TestEvent6.class, 1024); + private static class ExpireEvent extends Event { - final AtomicInteger count1 = new AtomicInteger(0); - final AtomicInteger count2 = new AtomicInteger(0); + private static final long serialVersionUID = 3024284255874382548L; - final CountDownLatch latch1 = new CountDownLatch(3); - final CountDownLatch latch2 = new CountDownLatch(3); + private final long no; - NotifyCenter.registerSubscriber(new SmartSubscriber() { - - @Override - public void onEvent(Event event) { - if (event instanceof TestSlowEvent5) { - count1.incrementAndGet(); - latch1.countDown(); - } - - if (event instanceof TestEvent6) { - count2.incrementAndGet(); - latch2.countDown(); - } - } - - @Override - public List> subscribeTypes() { - List> subTypes = new ArrayList>(); - subTypes.add(TestSlowEvent5.class); - subTypes.add(TestEvent6.class); - return subTypes; - } - }); - - for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent5())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent6())); + ExpireEvent(long no) { + this.no = no; } - ThreadUtils.sleep(3000L); - - latch1.await(3000L, TimeUnit.MILLISECONDS); - latch2.await(3000L, TimeUnit.MILLISECONDS); - - Assert.assertEquals(3, count1.get()); - Assert.assertEquals(3, count2.get()); - - } - - private static class TestEvent7 extends Event { - - } - - @Test - public void testPublishEventByNoSubscriber() { - - for (int i = 0; i < 3; i++) { - Assert.assertFalse(NotifyCenter.publishEvent(new TestEvent7())); + @Override + public long sequence() { + return no; } } } diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java new file mode 100644 index 00000000000..6eb7e07318d --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java @@ -0,0 +1,109 @@ +/* + * 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.common.packagescan; + +import com.alibaba.nacos.common.packagescan.mock.AnnotationClass; +import com.alibaba.nacos.common.packagescan.mock.MockClass; +import com.alibaba.nacos.common.packagescan.mock.TestScan; +import com.alibaba.nacos.common.packagescan.resource.PathMatchingResourcePatternResolver; +import com.alibaba.nacos.common.packagescan.resource.Resource; +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.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DefaultPackageScanTest { + + @Mock + PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver; + + DefaultPackageScan packageScan; + + @Before + public void setUp() throws Exception { + packageScan = new DefaultPackageScan(); + } + + @Test + public void testGetSubTypesOf() { + packageScan = new DefaultPackageScan(); + Set> subTypesOf = packageScan + .getSubTypesOf(AnnotationClass.class.getPackage().getName(), MockClass.class); + assertEquals(3, subTypesOf.size()); + } + + @Test + public void testGetTypesAnnotatedWith() { + packageScan = new DefaultPackageScan(); + Set> actual = packageScan + .getTypesAnnotatedWith(AnnotationClass.class.getPackage().getName(), TestScan.class); + assertEquals(1, actual.size()); + assertEquals(AnnotationClass.class, actual.iterator().next()); + } + + @Test + public void testGetSubTypesOfWithException() throws NoSuchFieldException, IllegalAccessException, IOException { + setResolver(); + String path = AnnotationClass.class.getPackage().getName(); + when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test")); + Set> subTypesOf = packageScan.getSubTypesOf(path, MockClass.class); + assertTrue(subTypesOf.isEmpty()); + } + + @Test + public void testGetTypesAnnotatedWithException() throws NoSuchFieldException, IllegalAccessException, IOException { + setResolver(); + String path = AnnotationClass.class.getPackage().getName(); + when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test")); + Set> actual = packageScan.getTypesAnnotatedWith(path, TestScan.class); + assertTrue(actual.isEmpty()); + } + + @Test + public void testClassVersionNotMatch() throws NoSuchFieldException, IllegalAccessException, IOException { + setResolver(); + Resource resource = mock(Resource.class); + byte[] testCase = new byte[8]; + testCase[7] = (byte) 64; + InputStream inputStream = new ByteArrayInputStream(testCase); + when(resource.getInputStream()).thenReturn(inputStream); + String path = AnnotationClass.class.getPackage().getName(); + when(pathMatchingResourcePatternResolver.getResources(anyString())).thenReturn(new Resource[] {resource}); + Set> subTypesOf = packageScan.getSubTypesOf(path, MockClass.class); + assertTrue(subTypesOf.isEmpty()); + } + + private void setResolver() throws NoSuchFieldException, IllegalAccessException { + Field field = DefaultPackageScan.class.getDeclaredField("resourcePatternResolver"); + field.setAccessible(true); + field.set(packageScan, pathMatchingResourcePatternResolver); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/PackageScanTest.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/PackageScanTest.java deleted file mode 100644 index 8f4f5bb0731..00000000000 --- a/common/src/test/java/com/alibaba/nacos/common/packagescan/PackageScanTest.java +++ /dev/null @@ -1,42 +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.common.packagescan; - -import com.alibaba.nacos.api.remote.request.Request; -import junit.framework.TestCase; - -import java.util.Set; - -public class PackageScanTest extends TestCase { - - public void setUp() throws Exception { - super.setUp(); - } - - public void tearDown() throws Exception { - } - - /** - * testGetSubTypesOf. - */ - public void testGetSubTypesOf() { - DefaultPackageScan packageScan = new DefaultPackageScan(); - Set> subTypesOf = packageScan.getSubTypesOf("com.alibaba.nacos.api.naming.remote.request", Request.class); - assertTrue(subTypesOf.size() > 0); - } - -} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/AnnotationClass.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/AnnotationClass.java new file mode 100644 index 00000000000..7174c6e4425 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/AnnotationClass.java @@ -0,0 +1,22 @@ +/* + * 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.common.packagescan.mock; + +@TestScan +public class AnnotationClass extends MockClass { + +} diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/MockClass.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/MockClass.java new file mode 100644 index 00000000000..07bb972a904 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/MockClass.java @@ -0,0 +1,21 @@ +/* + * 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.common.packagescan.mock; + +public class MockClass { + +} diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/NoAnnotationClass.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/NoAnnotationClass.java new file mode 100644 index 00000000000..d2af05f2c75 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/NoAnnotationClass.java @@ -0,0 +1,21 @@ +/* + * 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.common.packagescan.mock; + +public class NoAnnotationClass extends MockClass { + +} diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/TestScan.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/TestScan.java new file mode 100644 index 00000000000..b7235bbc256 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/mock/TestScan.java @@ -0,0 +1,25 @@ +/* + * 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.common.packagescan.mock; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface TestScan { + +} diff --git a/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java b/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java index 9f5e0dbfe78..e31d494f148 100644 --- a/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java @@ -16,26 +16,285 @@ package com.alibaba.nacos.common.paramcheck; +import org.junit.Before; import org.junit.Test; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -/** - * The type Default param checker test. - * - * @author zhuoguang - */ public class DefaultParamCheckerTest { - /** - * Check param info list. - */ + DefaultParamChecker paramChecker; + + @Before + public void setUp() throws Exception { + paramChecker = new DefaultParamChecker(); + } + + @Test + public void testCheckerType() { + assertEquals("default", paramChecker.getCheckerType()); + } + + @Test + public void testCheckEmptyParamInfoList() { + ParamCheckResponse actual = paramChecker.checkParamInfoList(null); + assertTrue(actual.isSuccess()); + actual = paramChecker.checkParamInfoList(Collections.emptyList()); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckEmptyParamInfo() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + paramInfos.add(null); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForNamespaceShowName() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String namespaceShowName = buildStringLength(257); + paramInfo.setNamespaceShowName(namespaceShowName); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'namespaceShowName' is illegal, the param length should not exceed 256.", + actual.getMessage()); + // Pattern + paramInfo.setNamespaceShowName("hsbfkj@$!#khdkad"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'namespaceShowName' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setNamespaceShowName("测试"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForNamespaceId() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String namespaceId = buildStringLength(65); + paramInfo.setNamespaceId(namespaceId); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'namespaceId/tenant' is illegal, the param length should not exceed 64.", + actual.getMessage()); + // Pattern + paramInfo.setNamespaceId("hsbfkj@$!#khdkad"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'namespaceId/tenant' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setNamespaceId("123-ashdal"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForDataId() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String dataId = buildStringLength(257); + paramInfo.setDataId(dataId); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'dataId' is illegal, the param length should not exceed 256.", actual.getMessage()); + // Pattern + paramInfo.setDataId("hsbfkj@$!#khdkad"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'dataId' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setDataId("a-zA-Z0-9-_:."); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForServiceName() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String serviceName = buildStringLength(513); + paramInfo.setServiceName(serviceName); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'serviceName' is illegal, the param length should not exceed 512.", actual.getMessage()); + // Pattern + paramInfo.setServiceName("@hsbfkj$@@!#khdkad啊"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'serviceName' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setServiceName("com.aaa@bbb#_{}-b:v1.2.2"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + @Test - public void checkParamInfoList() { - AbstractParamChecker paramChecker = new DefaultParamChecker(); + public void testCheckParamInfoForGroup() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); - paramChecker.checkParamInfoList(paramInfos); + // Max Length + String group = buildStringLength(129); + paramInfo.setGroup(group); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'group' is illegal, the param length should not exceed 128.", actual.getMessage()); + // Pattern + paramInfo.setGroup("@hsbfkj$@@!#khdkad啊@@"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'group' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setGroup("a-zA-Z0-9-_:."); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForClusters() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String cluster = buildStringLength(65); + paramInfo.setClusters(cluster + "," + cluster); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'cluster' is illegal, the param length should not exceed 64.", actual.getMessage()); + // Pattern + paramInfo.setClusters("@hsbfkj$@@!#khdkad啊@@"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setClusters("0-9a-zA-Z-_,DEFAULT_abc-100"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForCluster() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String cluster = buildStringLength(65); + paramInfo.setCluster(cluster); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'cluster' is illegal, the param length should not exceed 64.", actual.getMessage()); + // Pattern + paramInfo.setCluster("@hsbfkj$@@!#khdkad啊@@"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", + actual.getMessage()); + // Success + paramInfo.setCluster("0-9a-zA-Z-_"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForIp() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Max Length + String ip = buildStringLength(129); + paramInfo.setIp(ip); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'ip' is illegal, the param length should not exceed 128.", actual.getMessage()); + // Pattern + paramInfo.setIp("禁止中文"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'ip' is illegal, illegal characters should not appear in the param.", actual.getMessage()); + // Success + paramInfo.setIp("host_or_domain_or_ipv4_or_ipv6"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForPort() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + // Negative port + paramInfo.setPort("-1"); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'port' is illegal, the value should be between 0 and 65535.", actual.getMessage()); + // Over than range + paramInfo.setPort("65536"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'port' is illegal, the value should be between 0 and 65535.", actual.getMessage()); + // Not number + paramInfo.setPort("port"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'port' is illegal, the value should be between 0 and 65535.", actual.getMessage()); + // Success + paramInfo.setPort("8848"); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + @Test + public void testCheckParamInfoForMetadata() { + ParamInfo paramInfo = new ParamInfo(); + ArrayList paramInfos = new ArrayList<>(); + paramInfos.add(paramInfo); + Map metadata = new HashMap<>(); + paramInfo.setMetadata(metadata); + // Max length + metadata.put("key1", ""); + metadata.put("key2", buildStringLength(1024)); + ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); + assertFalse(actual.isSuccess()); + assertEquals("Param 'Metadata' is illegal, the param length should not exceed 1024.", actual.getMessage()); + // Success + metadata.put("key2", "Any key and value, only require length sum not more than 1024."); + actual = paramChecker.checkParamInfoList(paramInfos); + assertTrue(actual.isSuccess()); + } + + private String buildStringLength(int length) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < length; i++) { + builder.append("a"); + } + return builder.toString(); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/paramcheck/MockParamChecker.java b/common/src/test/java/com/alibaba/nacos/common/paramcheck/MockParamChecker.java new file mode 100644 index 00000000000..2660ee6c78f --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/paramcheck/MockParamChecker.java @@ -0,0 +1,36 @@ +/* + * 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.common.paramcheck; + +import java.util.List; + +public class MockParamChecker extends AbstractParamChecker { + + @Override + public String getCheckerType() { + return "mock"; + } + + @Override + public ParamCheckResponse checkParamInfoList(List paramInfos) { + return new ParamCheckResponse(); + } + + @Override + public void initParamCheckRule() { + } +} diff --git a/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java new file mode 100644 index 00000000000..a776de9d46f --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java @@ -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.common.paramcheck; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class ParamCheckerManagerTest { + + @Test + public void testGetParamCheckerNonExistType() { + assertTrue(ParamCheckerManager.getInstance().getParamChecker("non") instanceof DefaultParamChecker); + } + + @Test + public void testGetParamCheckerNull() { + assertTrue(ParamCheckerManager.getInstance().getParamChecker("") instanceof DefaultParamChecker); + assertTrue(ParamCheckerManager.getInstance().getParamChecker(null) instanceof DefaultParamChecker); + } + + @Test + public void testGetParamCheckerDefault() { + assertTrue(ParamCheckerManager.getInstance().getParamChecker("default") instanceof DefaultParamChecker); + } + + @Test + public void testGetParamCheckerOther() { + assertTrue(ParamCheckerManager.getInstance().getParamChecker("mock") instanceof MockParamChecker); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java index 6d85b994eb1..2ed67a0f7fb 100644 --- a/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java @@ -17,24 +17,60 @@ package com.alibaba.nacos.common.pathencoder; import com.alibaba.nacos.common.pathencoder.impl.WindowsEncoder; -import junit.framework.TestCase; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.Charset; -public class PathEncoderManagerTest extends TestCase { +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +public class PathEncoderManagerTest { + + private String cachedOsName; + + private Field targetEncoder; + + private Object cachedEncoder; + + @Before + public void setUp() throws Exception { + cachedOsName = System.getProperty("os.name"); + targetEncoder = PathEncoderManager.class.getDeclaredField("targetEncoder"); + targetEncoder.setAccessible(true); + cachedEncoder = targetEncoder.get(PathEncoderManager.getInstance()); + } + + @After + public void tearDown() throws Exception { + System.setProperty("os.name", cachedOsName); + targetEncoder.set(PathEncoderManager.getInstance(), cachedEncoder); + } + + @Test + public void testInitWithWindows() + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + Constructor constructor = PathEncoderManager.class.getDeclaredConstructor(); + constructor.setAccessible(true); + System.setProperty("os.name", "window"); + PathEncoderManager instance = constructor.newInstance(); + Assert.assertTrue(targetEncoder.get(instance) instanceof WindowsEncoder); + } + /** * test expose method. */ - public void test() throws Exception { + @Test + public void testWindowsEncode() throws Exception { // load static PathEncoderManager instance = PathEncoderManager.getInstance(); - // remove windows impl - Field targetEncoder = PathEncoderManager.class.getDeclaredField("targetEncoder"); - targetEncoder.setAccessible(true); - // remain old path encoder - final Object origin = targetEncoder.get(instance); + // remove impl targetEncoder.set(instance, null); // try to encode, non windows String case1 = "aa||a"; @@ -45,8 +81,22 @@ public void test() throws Exception { targetEncoder.set(instance, new WindowsEncoder()); Assert.assertEquals(PathEncoderManager.getInstance().encode(case1), case2); Assert.assertEquals(PathEncoderManager.getInstance().decode(case2), case1); - // set origin - targetEncoder.set(instance, origin); } - + + @Test + public void testEncodeWithNonExistOs() { + System.setProperty("os.name", "non-exist"); + String testCase = "aa||a"; + Assert.assertEquals(testCase, PathEncoderManager.getInstance().encode(testCase)); + } + + @Test + public void testEncodeForNull() throws IllegalAccessException { + PathEncoder mockPathEncoder = mock(PathEncoder.class); + targetEncoder.set(PathEncoderManager.getInstance(), mockPathEncoder); + Assert.assertNull(PathEncoderManager.getInstance().encode(null)); + Assert.assertNull(PathEncoderManager.getInstance().decode(null)); + verify(mockPathEncoder, never()).encode(null, Charset.defaultCharset().name()); + verify(mockPathEncoder, never()).decode(null, Charset.defaultCharset().name()); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java b/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java index bb7416c723f..f35e2fcc5a1 100644 --- a/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java @@ -108,6 +108,7 @@ public void testNeedEncode() { String case7 = "asdas actual = NacosServiceLoader.load(SpiTestInterface.class); @@ -40,4 +46,16 @@ public void newServiceInstances() { assertEquals(SpiTestImpl.class, actual.iterator().next().getClass()); assertNotEquals(loadInstance, actual.iterator().next()); } + + @Test + public void newServiceInstancesWithException() { + NacosServiceLoader.load(SpiTestInterface.class); + SpiTestImpl.newInstanceException = true; + try { + NacosServiceLoader.newServiceInstances(SpiTestInterface.class); + } catch (ServiceLoaderException e) { + assertEquals(SpiTestImpl.class, e.getClazz()); + assertEquals("Can not load class `" + SpiTestImpl.class.getName() + "` by SPI ", e.getMessage()); + } + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/spi/SpiTestImpl.java b/common/src/test/java/com/alibaba/nacos/common/spi/SpiTestImpl.java index 9d3825366dc..6110cb7365d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/spi/SpiTestImpl.java +++ b/common/src/test/java/com/alibaba/nacos/common/spi/SpiTestImpl.java @@ -17,4 +17,12 @@ package com.alibaba.nacos.common.spi; public class SpiTestImpl implements SpiTestInterface { + + public static boolean newInstanceException; + + public SpiTestImpl() throws IllegalAccessException { + if (newInstanceException) { + throw new IllegalAccessException("test"); + } + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java index 942c3c08ea9..485645d189d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java @@ -90,6 +90,7 @@ public void testAddProcessor() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(200); verify(testTaskProcessor).process(abstractTask); verify(taskProcessor, never()).process(abstractTask); + assertEquals(1, nacosDelayTaskExecuteEngine.getAllProcessorKey().size()); } @Test @@ -110,4 +111,39 @@ public void testRetryTaskAfterFail() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(300); verify(taskProcessor, new Times(2)).process(abstractTask); } + + @Test + public void testProcessorWithException() throws InterruptedException { + when(taskProcessor.process(abstractTask)).thenThrow(new RuntimeException("test")); + nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); + nacosDelayTaskExecuteEngine.removeProcessor("test"); + nacosDelayTaskExecuteEngine.addTask("test", abstractTask); + TimeUnit.MILLISECONDS.sleep(200); + assertEquals(1, nacosDelayTaskExecuteEngine.size()); + } + + @Test + public void testTaskShouldNotExecute() throws InterruptedException { + nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); + nacosDelayTaskExecuteEngine.addTask("test", abstractTask); + abstractTask.setTaskInterval(10000L); + abstractTask.setLastProcessTime(System.currentTimeMillis()); + TimeUnit.MILLISECONDS.sleep(200); + verify(testTaskProcessor, never()).process(abstractTask); + assertEquals(1, nacosDelayTaskExecuteEngine.size()); + } + + @Test + public void testTaskMerge() { + nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); + nacosDelayTaskExecuteEngine.addTask("test", abstractTask); + nacosDelayTaskExecuteEngine.addTask("test", new AbstractDelayTask() { + @Override + public void merge(AbstractDelayTask task) { + setLastProcessTime(task.getLastProcessTime()); + setTaskInterval(task.getTaskInterval()); + } + }); + assertEquals(1, nacosDelayTaskExecuteEngine.size()); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java index 9d47bb528ca..43a926b57e3 100644 --- a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java @@ -18,6 +18,7 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.task.AbstractExecuteTask; +import com.alibaba.nacos.common.task.NacosTaskProcessor; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,13 +37,21 @@ public class NacosExecuteTaskExecuteEngineTest { private NacosExecuteTaskExecuteEngine executeTaskExecuteEngine; + @Mock + NacosTaskProcessor taskProcessor; + + String cachedProcessor; + @Before public void setUp() { + cachedProcessor = System.getProperty("nacos.common.processors"); + System.setProperty("nacos.common.processors", "1"); executeTaskExecuteEngine = new NacosExecuteTaskExecuteEngine("TEST", null); } @After public void tearDown() throws NacosException { + System.setProperty("nacos.common.processors", null == cachedProcessor ? "" : cachedProcessor); executeTaskExecuteEngine.shutdown(); } @@ -57,4 +66,28 @@ public void testAddTask() throws InterruptedException { assertTrue(executeTaskExecuteEngine.isEmpty()); assertEquals(0, executeTaskExecuteEngine.size()); } + + @Test + public void testAddTaskByProcessor() throws InterruptedException { + executeTaskExecuteEngine.addProcessor("test", taskProcessor); + executeTaskExecuteEngine.addTask("test", task); + verify(taskProcessor).process(task); + assertTrue(executeTaskExecuteEngine.isEmpty()); + assertEquals(0, executeTaskExecuteEngine.size()); + } + + @Test(expected = UnsupportedOperationException.class) + public void testRemoveTask() { + executeTaskExecuteEngine.removeTask(task); + } + + @Test(expected = UnsupportedOperationException.class) + public void testGetAllTaskKeys() { + executeTaskExecuteEngine.getAllTaskKeys(); + } + + @Test + public void testWorkersStatus() { + assertEquals("TEST_0%1, pending tasks: 0\n", executeTaskExecuteEngine.workersStatus()); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java new file mode 100644 index 00000000000..fa18a635d83 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java @@ -0,0 +1,73 @@ +/* + * 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.common.tls; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +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 SelfTrustManagerTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testTrustManagerSuccess() throws CertificateException { + URL url = SelfTrustManagerTest.class.getClassLoader().getResource("test-tls-cert.pem"); + String path = url.getPath(); + TrustManager[] actual = SelfTrustManager.trustManager(true, path); + assertNotNull(actual); + assertEquals(1, actual.length); + assertTrue(actual[0] instanceof X509TrustManager); + assertFalse(actual[0].getClass().getCanonicalName().startsWith("com.alibaba.nacos")); + X509TrustManager x509TrustManager = (X509TrustManager) actual[0]; + X509Certificate[] certificates = x509TrustManager.getAcceptedIssuers(); + assertNotNull(certificates); + x509TrustManager.checkClientTrusted(certificates, "a"); + x509TrustManager.checkServerTrusted(certificates, "b"); + } + + @Test + public void testTrustManagerNonExist() throws CertificateException { + TrustManager[] actual = SelfTrustManager.trustManager(true, "non-exist-cert.pem"); + assertNotNull(actual); + assertEquals(1, actual.length); + assertTrue(actual[0] instanceof X509TrustManager); + assertTrue(actual[0].getClass().isAnonymousClass()); + X509TrustManager x509TrustManager = (X509TrustManager) actual[0]; + assertNull(x509TrustManager.getAcceptedIssuers()); + x509TrustManager.checkClientTrusted(null, "a"); + x509TrustManager.checkServerTrusted(null, "b"); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java new file mode 100644 index 00000000000..211f170c713 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java @@ -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.common.tls; + +import org.junit.Test; + +import javax.net.ssl.SSLContext; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +import static org.junit.Assert.assertNotNull; + +public class TlsHelperTest { + + @Test + public void testBuildSslContext() throws KeyManagementException, NoSuchAlgorithmException { + SSLContext actual = TlsHelper.buildSslContext(true); + assertNotNull(actual); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java new file mode 100644 index 00000000000..a9d6d9e2e63 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java @@ -0,0 +1,75 @@ +/* + * 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.common.trace.event.naming; + +import com.alibaba.nacos.common.trace.HealthCheckType; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class HealthStateChangeTraceEventTest extends NamingTraceEventTest { + + @Test + public void testHealthStateChangeTraceEventForClientBeat() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, IP, PORT, false, "client_beat"); + assertBasicInfo(healthStateChangeTraceEvent); + assertHealthChangeInfo(healthStateChangeTraceEvent); + assertEquals(HealthCheckType.CLIENT_BEAT, healthStateChangeTraceEvent.getHealthCheckType()); + assertEquals("client_beat", healthStateChangeTraceEvent.getHealthStateChangeReason()); + } + + @Test + public void testHealthStateChangeTraceEventForTcp() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, IP, PORT, false, "tcp:unable2connect:"); + assertBasicInfo(healthStateChangeTraceEvent); + assertHealthChangeInfo(healthStateChangeTraceEvent); + assertEquals(HealthCheckType.TCP_SUPER_SENSE, healthStateChangeTraceEvent.getHealthCheckType()); + assertEquals("tcp:unable2connect:", healthStateChangeTraceEvent.getHealthStateChangeReason()); + } + + @Test + public void testHealthStateChangeTraceEventForHttp() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, IP, PORT, false, "http:error:"); + assertBasicInfo(healthStateChangeTraceEvent); + assertHealthChangeInfo(healthStateChangeTraceEvent); + assertEquals(HealthCheckType.HTTP_HEALTH_CHECK, healthStateChangeTraceEvent.getHealthCheckType()); + assertEquals("http:error:", healthStateChangeTraceEvent.getHealthStateChangeReason()); + } + + @Test + public void testHealthStateChangeTraceEventForMysql() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, IP, PORT, false, "mysql:timeout:"); + assertBasicInfo(healthStateChangeTraceEvent); + assertHealthChangeInfo(healthStateChangeTraceEvent); + assertEquals(HealthCheckType.MYSQL_HEALTH_CHECK, healthStateChangeTraceEvent.getHealthCheckType()); + assertEquals("mysql:timeout:", healthStateChangeTraceEvent.getHealthStateChangeReason()); + } + + private void assertHealthChangeInfo(HealthStateChangeTraceEvent event) { + assertEquals("HEALTH_STATE_CHANGE_TRACE_EVENT", event.getType()); + assertEquals(IP, event.getInstanceIp()); + assertEquals(PORT, event.getInstancePort()); + assertEquals(IP + ":" + PORT, event.toInetAddr()); + assertFalse(event.isHealthy()); + } + +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java new file mode 100644 index 00000000000..6123a8aea83 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java @@ -0,0 +1,71 @@ +/* + * 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.common.trace.event.naming; + +import com.alibaba.nacos.common.trace.DeregisterInstanceReason; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class InstanceTraceEventTest extends NamingTraceEventTest { + + @Test + public void testRegisterInstanceTraceEvent() { + RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(TIME, CLIENT_IP, true, + NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT); + assertBasicInfo(registerInstanceTraceEvent); + assertEquals("REGISTER_INSTANCE_TRACE_EVENT", registerInstanceTraceEvent.getType()); + assertEquals(CLIENT_IP, registerInstanceTraceEvent.getClientIp()); + assertTrue(registerInstanceTraceEvent.isRpc()); + assertEquals(IP, registerInstanceTraceEvent.getInstanceIp()); + assertEquals(PORT, registerInstanceTraceEvent.getInstancePort()); + assertEquals(IP + ":" + PORT, registerInstanceTraceEvent.toInetAddr()); + } + + @Test + public void testDeregisterInstanceTraceEvent() { + DeregisterInstanceTraceEvent deregisterInstanceTraceEvent = new DeregisterInstanceTraceEvent(TIME, CLIENT_IP, + true, DeregisterInstanceReason.NATIVE_DISCONNECTED, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT); + assertBasicInfo(deregisterInstanceTraceEvent); + assertEquals("DEREGISTER_INSTANCE_TRACE_EVENT", deregisterInstanceTraceEvent.getType()); + assertEquals(CLIENT_IP, deregisterInstanceTraceEvent.getClientIp()); + assertTrue(deregisterInstanceTraceEvent.isRpc()); + assertEquals(IP, deregisterInstanceTraceEvent.getInstanceIp()); + assertEquals(PORT, deregisterInstanceTraceEvent.getInstancePort()); + assertEquals(IP + ":" + PORT, deregisterInstanceTraceEvent.toInetAddr()); + assertEquals(DeregisterInstanceReason.NATIVE_DISCONNECTED, deregisterInstanceTraceEvent.getReason()); + } + + @Test + public void testUpdateInstanceTraceEvent() { + Map metadata = new HashMap<>(); + metadata.put("test1", "testValue"); + UpdateInstanceTraceEvent updateInstanceTraceEvent = new UpdateInstanceTraceEvent(TIME, CLIENT_IP, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, IP, PORT, metadata); + assertBasicInfo(updateInstanceTraceEvent); + assertEquals("UPDATE_INSTANCE_TRACE_EVENT", updateInstanceTraceEvent.getType()); + assertEquals(CLIENT_IP, updateInstanceTraceEvent.getClientIp()); + assertEquals(IP, updateInstanceTraceEvent.getInstanceIp()); + assertEquals(PORT, updateInstanceTraceEvent.getInstancePort()); + assertEquals(IP + ":" + PORT, updateInstanceTraceEvent.toInetAddr()); + assertEquals(metadata, updateInstanceTraceEvent.getMetadata()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java new file mode 100644 index 00000000000..f7d15840d2f --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java @@ -0,0 +1,47 @@ +/* + * 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.common.trace.event.naming; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class NamingTraceEventTest { + + protected static final long TIME = System.currentTimeMillis(); + + protected static final String NAMESPACE_ID = "ns"; + + protected static final String GROUP_NAME = "testG"; + + protected static final String SERVICE_NAME = "testS"; + + protected static final String CLUSTER_NAME = "test_cluster"; + + protected static final String IP = "127.0.0.1"; + + protected static final int PORT = 8848; + + protected static final String CLIENT_IP = "1.1.1.1"; + + protected void assertBasicInfo(NamingTraceEvent event) { + assertEquals(TIME, event.getEventTime()); + assertEquals(NAMESPACE_ID, event.getNamespace()); + assertEquals(GROUP_NAME, event.getGroup()); + assertEquals(SERVICE_NAME, event.getName()); + assertTrue(event.isPluginEvent()); + } +} diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java new file mode 100644 index 00000000000..7ab0c2d98cd --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java @@ -0,0 +1,54 @@ +/* + * 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.common.trace.event.naming; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class ServiceTraceEventTest extends NamingTraceEventTest { + + @Test + public void testRegisterInstanceTraceEvent() { + RegisterServiceTraceEvent registerServiceTraceEvent = new RegisterServiceTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME); + assertBasicInfo(registerServiceTraceEvent); + assertEquals("REGISTER_SERVICE_TRACE_EVENT", registerServiceTraceEvent.getType()); + } + + @Test + public void testDeregisterInstanceTraceEvent() { + DeregisterServiceTraceEvent deregisterServiceTraceEvent = new DeregisterServiceTraceEvent(TIME, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME); + assertBasicInfo(deregisterServiceTraceEvent); + assertEquals("DEREGISTER_SERVICE_TRACE_EVENT", deregisterServiceTraceEvent.getType()); + } + + @Test + public void testUpdateInstanceTraceEvent() { + Map metadata = new HashMap<>(); + metadata.put("test1", "testValue"); + UpdateServiceTraceEvent updateServiceTraceEvent = new UpdateServiceTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME, metadata); + assertBasicInfo(updateServiceTraceEvent); + assertEquals("UPDATE_SERVICE_TRACE_EVENT", updateServiceTraceEvent.getType()); + assertEquals(metadata, updateServiceTraceEvent.getMetadata()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java new file mode 100644 index 00000000000..9adfb214c5f --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java @@ -0,0 +1,56 @@ +/* + * 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.common.trace.event.naming; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SubscribeTraceEventTest extends NamingTraceEventTest { + + @Test + public void testRegisterInstanceTraceEvent() { + SubscribeServiceTraceEvent subscribeServiceTraceEvent = new SubscribeServiceTraceEvent(TIME, CLIENT_IP, + NAMESPACE_ID, GROUP_NAME, SERVICE_NAME); + assertBasicInfo(subscribeServiceTraceEvent); + assertEquals("SUBSCRIBE_SERVICE_TRACE_EVENT", subscribeServiceTraceEvent.getType()); + assertEquals(CLIENT_IP, subscribeServiceTraceEvent.getClientIp()); + } + + @Test + public void testDeregisterInstanceTraceEvent() { + UnsubscribeServiceTraceEvent unsubscribeServiceTraceEvent = new UnsubscribeServiceTraceEvent(TIME, CLIENT_IP, + NAMESPACE_ID, GROUP_NAME, SERVICE_NAME); + assertBasicInfo(unsubscribeServiceTraceEvent); + assertEquals("UNSUBSCRIBE_SERVICE_TRACE_EVENT", unsubscribeServiceTraceEvent.getType()); + assertEquals(CLIENT_IP, unsubscribeServiceTraceEvent.getClientIp()); + } + + @Test + public void testPushServiceTraceEvent() { + PushServiceTraceEvent pushServiceTraceEvent = new PushServiceTraceEvent(TIME, 10, 510, 510, CLIENT_IP, + NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, 100); + assertBasicInfo(pushServiceTraceEvent); + assertEquals("PUSH_SERVICE_TRACE_EVENT", pushServiceTraceEvent.getType()); + assertEquals(CLIENT_IP, pushServiceTraceEvent.getClientIp()); + assertEquals(10L, pushServiceTraceEvent.getPushCostTimeForNetWork()); + assertEquals(510L, pushServiceTraceEvent.getPushCostTimeForAll()); + assertEquals(510L, pushServiceTraceEvent.getServiceLevelAgreementTime()); + assertEquals(100, pushServiceTraceEvent.getInstanceSize()); + + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java index d228a496053..2d996eacc76 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java @@ -26,10 +26,10 @@ import java.util.HashMap; import java.util.Map; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertEquals; public class TraceEventPublisherFactoryTest { + private Map originalEventPublisherMap; @Before @@ -57,6 +57,17 @@ public void testApply() { TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.class, Byte.SIZE); String expectedStatus = "Trace event publisher statues:\n" + "\tPublisher TraceEvent : shutdown=false, queue= 0/8 \n"; - assertThat(TraceEventPublisherFactory.getInstance().getAllPublisherStatues(), is(expectedStatus)); + assertEquals(expectedStatus, TraceEventPublisherFactory.getInstance().getAllPublisherStatues()); + } + + @Test + public void testApplyAfterAddEventType() { + TraceEventPublisherFactory.getInstance().addPublisherEvent(TraceTestEvent.class); + TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent1.class, Byte.SIZE); + TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent2.class, Byte.SIZE); + TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.class, Byte.SIZE); + String expectedStatus = "Trace event publisher statues:\n" + + "\tPublisher TraceTestEvent : shutdown=false, queue= 0/8 \n"; + assertEquals(expectedStatus, TraceEventPublisherFactory.getInstance().getAllPublisherStatues()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java index 39a515d7192..86ab30e1648 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java @@ -30,7 +30,9 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class TraceEventPublisherTest { @@ -56,7 +58,8 @@ public void tearDown() throws Exception { @Test public void testAddSubscriber() { - traceEventPublisher.addSubscriber(subscriber, TraceTestEvent.TraceTestEvent1.class); + when(subscriber.subscribeType()).thenReturn(TraceTestEvent.TraceTestEvent1.class); + traceEventPublisher.addSubscriber(subscriber); traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent2.class); TraceTestEvent.TraceTestEvent1 traceTestEvent1 = new TraceTestEvent.TraceTestEvent1(); TraceTestEvent.TraceTestEvent2 traceTestEvent2 = new TraceTestEvent.TraceTestEvent2(); @@ -82,6 +85,13 @@ public void testRemoveSubscriber() { ThreadUtils.sleep(500L); verify(subscriber).onEvent(traceTestEvent1); verify(smartSubscriber, never()).onEvent(traceTestEvent1); + reset(subscriber); + when(subscriber.subscribeType()).thenReturn(TraceTestEvent.TraceTestEvent1.class); + traceEventPublisher.removeSubscriber(subscriber); + traceEventPublisher.publish(traceTestEvent1); + ThreadUtils.sleep(500L); + verify(subscriber, never()).onEvent(traceTestEvent1); + verify(smartSubscriber, never()).onEvent(traceTestEvent1); } @Test diff --git a/common/src/test/resources/META-INF/services/com.alibaba.nacos.api.ability.initializer.AbilityPostProcessor b/common/src/test/resources/META-INF/services/com.alibaba.nacos.api.ability.initializer.AbilityPostProcessor new file mode 100644 index 00000000000..4f40f992cff --- /dev/null +++ b/common/src/test/resources/META-INF/services/com.alibaba.nacos.api.ability.initializer.AbilityPostProcessor @@ -0,0 +1,17 @@ +# +# 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. +# + +com.alibaba.nacos.common.ability.MockAbilityPostProcessor \ No newline at end of file diff --git a/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.ability.AbstractAbilityControlManager b/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.ability.AbstractAbilityControlManager new file mode 100644 index 00000000000..a6c29aa0447 --- /dev/null +++ b/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.ability.AbstractAbilityControlManager @@ -0,0 +1,18 @@ +# +# 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. +# + +com.alibaba.nacos.common.ability.discover.HigherMockAbilityManager +com.alibaba.nacos.common.ability.discover.LowerMockAbilityManager \ No newline at end of file diff --git a/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.paramcheck.AbstractParamChecker b/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.paramcheck.AbstractParamChecker new file mode 100644 index 00000000000..489d9042d04 --- /dev/null +++ b/common/src/test/resources/META-INF/services/com.alibaba.nacos.common.paramcheck.AbstractParamChecker @@ -0,0 +1,17 @@ +# +# 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. +# + +com.alibaba.nacos.common.paramcheck.MockParamChecker \ No newline at end of file diff --git a/common/src/test/resources/test-tls-cert.pem b/common/src/test/resources/test-tls-cert.pem new file mode 100644 index 00000000000..dcb80b59331 --- /dev/null +++ b/common/src/test/resources/test-tls-cert.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC+zCCAmSgAwIBAgIJAK68bP5/APz/MA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV +BAYTAkNOMRIwEAYDVQQIDAlaaGUgSmlhbmcxEjAQBgNVBAcMCUhhbmcgWmhvdTEW +MBQGA1UECgwNQWxpYmFiYSBDbG91ZDEOMAwGA1UECwwFTmFjb3MxETAPBgNVBAMM +CG5hY29zIGNhMCAXDTIzMDQyMTA4MzI0MVoYDzIxMjMwMzI4MDgzMjQxWjB0MQsw +CQYDVQQGEwJDTjESMBAGA1UECAwJWmhlIEppYW5nMRIwEAYDVQQHDAlIYW5nIFpo +b3UxFjAUBgNVBAoMDUFsaWJhYmEgQ2xvdWQxDjAMBgNVBAsMBU5hY29zMRUwEwYD +VQQDDAxOYWNvcyBDbGllbnQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDCQ93itb/8s1WW9TjBgoH6OZ1lO6dn08hKFy8vq/IhiSv8k8ks78PzCAWeeDYD +xzjA0gsq+2MREt3CE+Vd2Rza/MYCVaHYVdyDzJp2v9kwWrtMrTvUDvtnAf4zq7Oj +tObEbFkUn2hPXN9i8pLfeqYdO//HjKcckniRMfretS+zoRVjMBa9upSapl3zUD6C +eqarvghg/h7RFpaZJ16suW9zfRIImb6skB81bZU39pf38RYgxQzOkQmjhmGQPEom +GFDkM8Y01haPLXI6Un5r6Bohbsh5Or+FOWgW+VW7Ql4smv8Pt+XKDs/3D6wCTXs7 +gMAVG+fMoRySj+B90TfdkwNrAgMBAAGjEzARMA8GA1UdEQQIMAaHBH8AAAEwDQYJ +KoZIhvcNAQEFBQADgYEAb2hcGyID/IEAecjWlc8Q5AMDFE6DRJlh5lI+a08aHT30 +2/o35CxOscoWECKURYD6h24mrGX9XQ1ruOrv4Tga81NX6XE12YwILeKlYK8DDmig +MkS9kjHjwdVOjnfpv8Ixfgwpst1TYAAPfD8jwXYg27bixqyse6dLPZR1adBxCwM= +-----END CERTIFICATE----- \ No newline at end of file diff --git a/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java b/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java index 82729fb6a67..e8655b8fadc 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/manager/TaskManager.java @@ -31,8 +31,8 @@ import java.util.concurrent.locks.Condition; /** - * TaskManager, is aim to process the task which is need to be done. - * And this class process the task by single thread to ensure task should be process successfully. + * TaskManager, is aim to process the task which is need to be done. And this class process the task by single thread to + * ensure task should be process successfully. * * @author huali */ @@ -45,7 +45,7 @@ public final class TaskManager extends NacosDelayTaskExecuteEngine implements Ta Condition notEmpty = this.lock.newCondition(); public TaskManager(String name) { - super(name, LOGGER, 100L); + super(name, 32, LOGGER, 100L); this.name = name; } @@ -79,7 +79,7 @@ public void await() throws InterruptedException { * Await for lock by timeout. * * @param timeout timeout value. - * @param unit time unit. + * @param unit time unit. * @return success or not. * @throws InterruptedException InterruptedException. */ diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/RemoteParamCheckFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/RemoteParamCheckFilterTest.java index 59233e2e550..ded400512a2 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/RemoteParamCheckFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/RemoteParamCheckFilterTest.java @@ -74,7 +74,7 @@ public void filter() { } catch (Exception e) { e.printStackTrace(); } - assertEquals(response.getMessage(), "Param check invalid:Param 'port' is illegal, the value should be between 0 and 65535"); + assertEquals(response.getMessage(), "Param check invalid:Param 'port' is illegal, the value should be between 0 and 65535."); BatchInstanceRequest batchInstanceRequest = new BatchInstanceRequest(); batchInstanceRequest.setServiceName("test@@@@"); diff --git a/pom.xml b/pom.xml index 81396867348..03a116ba2fd 100644 --- a/pom.xml +++ b/pom.xml @@ -392,6 +392,9 @@ true **/grpc/auto/** + **/packagescan/classreading/** + **/packagescan/resource/** + **/packagescan/util/**