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.
This commit is contained in:
杨翊 SionYang 2023-10-13 14:46:04 +08:00 committed by GitHub
parent 49f34868ff
commit c4aac2b82f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 2569 additions and 689 deletions

View File

@ -128,7 +128,7 @@ public class ConfigHttpClientManager implements Closeable {
@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));
}

View File

@ -102,21 +102,18 @@ public abstract class AbstractAbilityControlManager {
public void enableCurrentNodeAbility(AbilityKey abilityKey) {
Map<String, Boolean> abilities = this.currentNodeAbilities.get(abilityKey.getMode());
if (abilities != null) {
doTurn(abilities, abilityKey, true, abilityKey.getMode());
doTurn(abilities, abilityKey, true);
}
}
protected void doTurn(Map<String, Boolean> abilities, AbilityKey key, boolean turn, AbilityMode mode) {
if (!key.getMode().equals(mode)) {
throw new IllegalStateException("Except " + mode + " but " + key.getMode());
}
protected void doTurn(Map<String, Boolean> 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 @@ public abstract class AbstractAbilityControlManager {
public void disableCurrentNodeAbility(AbilityKey abilityKey) {
Map<String, Boolean> abilities = this.currentNodeAbilities.get(abilityKey.getMode());
if (abilities != null) {
doTurn(abilities, abilityKey, false, abilityKey.getMode());
doTurn(abilities, abilityKey, false);
}
}
@ -180,7 +177,7 @@ public abstract class AbstractAbilityControlManager {
/**
* notify when current node ability changing.
*/
public class AbilityUpdateEvent extends Event {
public static class AbilityUpdateEvent extends Event {
private static final long serialVersionUID = -1232411212311111L;

View File

@ -24,40 +24,57 @@ import org.slf4j.LoggerFactory;
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 {
/**
* . get nacos ability control manager
*
* @return BaseAbilityControlManager
*/
public static synchronized AbstractAbilityControlManager getInstance() {
if (null == abstractAbilityControlManager) {
initAbilityControlManager();
}
return abstractAbilityControlManager;
}
/**
* . Return the target type of ability manager
*
* @param clazz clazz
* @param <T> target type
* @return AbilityControlManager
*/
public static <T extends AbstractAbilityControlManager> T getInstance(Class<T> clazz) {
return clazz.cast(abstractAbilityControlManager);
}
private static void initAbilityControlManager() {
// spi discover implement
Collection<AbstractAbilityControlManager> load = null;
try {
// if server
load = NacosServiceLoader.load(AbstractAbilityControlManager.class);
} catch (ServiceConfigurationError e) {
throw new RuntimeException("[AbilityControlManager] Cannot find AbilityControlManger");
}
load = NacosServiceLoader.load(AbstractAbilityControlManager.class);
// the priority of the server is higher
List<AbstractAbilityControlManager> collect = load.stream()
.sorted(Comparator.comparingInt(AbstractAbilityControlManager::getPriority))
@ -68,24 +85,4 @@ public class NacosAbilityManagerHolder {
LOGGER.info("[AbilityControlManager] Successfully initialize AbilityControlManager");
}
}
/**.
* get nacos ability control manager
*
* @return BaseAbilityControlManager
*/
public static AbstractAbilityControlManager getInstance() {
return abstractAbilityControlManager;
}
/**.
* Return the target type of ability manager
*
* @param clazz clazz
* @param <T> target type
* @return AbilityControlManager
*/
public static <T extends AbstractAbilityControlManager> T getInstance(Class<T> clazz) {
return clazz.cast(abstractAbilityControlManager);
}
}

View File

@ -24,6 +24,7 @@ import java.util.concurrent.Callable;
/**
* A wrapper that automatically expires the cache.
*
* @author zzq
* @date 2021/7/30
*/
@ -48,14 +49,15 @@ public class AutoExpireCache<K, V> implements Cache<K, V> {
@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<? extends V> call) throws Exception {
V cachedValue = this.get(key);
@ -63,10 +65,10 @@ public class AutoExpireCache<K, V> implements Cache<K, V> {
V v2 = call.call();
this.put(key, v2);
return v2;
}
return cachedValue;
}
@Override
@ -87,9 +89,6 @@ public class AutoExpireCache<K, V> implements Cache<K, V> {
}
private boolean isExpire(CacheItemProperties itemProperties) {
if (itemProperties == null) {
return true;
}
return expireNanos != -1 && (System.nanoTime() - itemProperties.getExpireNanos() > expireNanos);
}

View File

@ -16,10 +16,9 @@
package com.alibaba.nacos.common.codec;
import java.nio.charset.StandardCharsets;
/**
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
* From apache common codec, and remove some useless method. Provides Base64 encoding and decoding as defined by <a
* href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*
* <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045
*
@ -168,28 +167,16 @@ public class 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 class Base64 {
*/
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 class Base64 {
return new Base64().decode(base64Data);
}
/**
* Returns whether or not the <code>octet</code> is in the Base32 alphabet.
*
* @param octet The value to test
* @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> 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 @@ public class Base64 {
eof = false;
}
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* <p>Intended for use in checking line-ending arrays
*
* @param arrayOctet byte array to test
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> 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.
*

View File

@ -42,7 +42,7 @@ public class RequestHttpEntity {
}
public RequestHttpEntity(Header header, Object body) {
this(null, header, null, body);
this(null, header, body);
}
public RequestHttpEntity(Header header, Query query, Object body) {

View File

@ -21,6 +21,8 @@ import java.io.Serializable;
/**
* Rest result.
*
* <p>TODO replaced or extend by {@link com.alibaba.nacos.api.model.v2.Result}.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class RestResult<T> implements Serializable {
@ -42,16 +44,6 @@ public class RestResult<T> implements Serializable {
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 class RestResult<T> implements Serializable {
this.data = data;
return this;
}
/**
* Build result.
*

View File

@ -65,7 +65,10 @@ public class DefaultPublisher extends Thread implements EventPublisher {
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 class DefaultPublisher extends Thread implements EventPublisher {
if (!initialized) {
// start just called once
super.start();
if (queueMaxSize == -1) {
queueMaxSize = ringBufferSize;
}
initialized = true;
}
}

View File

@ -113,7 +113,6 @@ public class NotifyCenter {
return INSTANCE.publisherMap;
}
@JustForTest
public static EventPublisher getPublisher(Class<? extends Event> topic) {
if (ClassUtils.isAssignableFrom(SlowEvent.class, topic)) {
return INSTANCE.sharePublisher;
@ -121,7 +120,6 @@ public class NotifyCenter {
return INSTANCE.publisherMap.get(topic.getCanonicalName());
}
@JustForTest
public static EventPublisher getSharePublisher() {
return INSTANCE.sharePublisher;
}

View File

@ -95,10 +95,8 @@ public class DefaultPackageScan implements PackageScan {
set.add((Class<T>) scanClass);
}
}
} catch (IOException e) {
} catch (IOException | ClassNotFoundException e) {
LOGGER.error("scan path: {} failed", packageSearchPath, e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return set;
}

View File

@ -208,7 +208,7 @@ public class DefaultParamChecker extends AbstractParamChecker {
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 class DefaultParamChecker extends AbstractParamChecker {
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;
}

View File

@ -88,7 +88,7 @@ public class WindowsEncoder implements PathEncoder {
@Override
public boolean needEncode(String key) {
if (key == null) {
key = "";
return false;
}
return !PATTERN.matcher(key).matches();
}

View File

@ -51,14 +51,6 @@ public class NacosDelayTaskExecuteEngine extends AbstractNacosTaskExecuteEngine<
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 @@ public class NacosDelayTaskExecuteEngine extends AbstractNacosTaskExecuteEngine<
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)) {

View File

@ -91,7 +91,7 @@ public final class TaskExecuteWorker implements NacosTaskProcessor, Closeable {
* Worker status.
*/
public String status() {
return name + ", pending tasks: " + pendingTaskCount();
return getName() + ", pending tasks: " + pendingTaskCount();
}
@Override

View File

@ -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<AbstractAbilityControlManager.AbilityUpdateEvent> mockSubscriber;
private boolean isOn = true;
private AssertionError assertionError;
private boolean notified = false;
@Before
public void setUp() throws Exception {
mockSubscriber = new Subscriber<AbstractAbilityControlManager.AbilityUpdateEvent>() {
@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<? extends Event> 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<String, Boolean> 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<AbilityMode, Map<AbilityKey, Boolean>> initCurrentNodeAbilities() {
Map<AbilityKey, Boolean> 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<AbilityMode, Map<AbilityKey, Boolean>> initCurrentNodeAbilities() {
Map<AbilityKey, Boolean> 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;
}
}
}

View File

@ -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<AbilityKey, Boolean> abilities) {
// do nothing.
}
}

View File

@ -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<AbilityMode, Map<AbilityKey, Boolean>> initCurrentNodeAbilities() {
Map<AbilityKey, Boolean> abilities = new HashMap<>();
abilities.put(AbilityKey.SERVER_TEST_1, true);
Map<AbilityMode, Map<AbilityKey, Boolean>> result = new HashMap<>();
result.put(AbilityMode.SERVER, abilities);
return result;
}
@Override
public int getPriority() {
return 100;
}
}

View File

@ -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<AbilityMode, Map<AbilityKey, Boolean>> initCurrentNodeAbilities() {
Map<AbilityKey, Boolean> abilities = new HashMap<>();
abilities.put(AbilityKey.SDK_CLIENT_TEST_1, true);
Map<AbilityMode, Map<AbilityKey, Boolean>> result = new HashMap<>();
result.put(AbilityMode.SDK_CLIENT, abilities);
return result;
}
@Override
public int getPriority() {
return 0;
}
}

View File

@ -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));
}
}

View File

@ -37,11 +37,19 @@ public class Base64Test {
@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 class Base64Test {
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);
}
}

View File

@ -21,6 +21,8 @@ import org.junit.Test;
import java.util.concurrent.ExecutorService;
import static org.junit.Assert.assertTrue;
public class ThreadPoolManagerTest {
@Test
@ -31,7 +33,7 @@ public class ThreadPoolManagerTest {
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 class ThreadPoolManagerTest {
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");
}
}
}

View File

@ -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 org.mockito.junit.MockitoJUnitRunner;
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 class HttpUtilsTest {
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 class HttpUtilsTest {
@Test
public void testInitRequestEntity5() throws Exception {
HttpDelete httpDelete = new HttpDelete("");
HttpUtils.initRequestEntity(httpDelete, null, null);
// nothing change
@ -166,7 +180,7 @@ public class HttpUtilsTest {
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 class HttpUtilsTest {
@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 class HttpUtilsTest {
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<String, String>) null, "UTF-8"));
assertNull(HttpUtils.encodingParams(Collections.emptyMap(), "UTF-8"));
}
@Test
public void testEncodingParamsMap() throws UnsupportedEncodingException {
Map<String, String> 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<String>) null, "UTF-8"));
}
@Test
public void testEncodingParamsList() throws UnsupportedEncodingException {
List<String> 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())));
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.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<String> 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());
}
}

View File

@ -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<Object> restResult = RestResultUtils.success();
assertRestResult(restResult, 200, null, null, true);
}
@Test
public void testSuccessWithData() {
RestResult<String> restResult = RestResultUtils.success("content");
assertRestResult(restResult, 200, null, "content", true);
}
@Test
public void testSuccessWithMsg() {
RestResult<String> restResult = RestResultUtils.success("test", "content");
assertRestResult(restResult, 200, "test", "content", true);
}
@Test
public void testSuccessWithCode() {
RestResult<String> restResult = RestResultUtils.success(203, "content");
assertRestResult(restResult, 203, null, "content", false);
}
@Test
public void testFailedWithDefault() {
RestResult<Object> restResult = RestResultUtils.failed();
assertRestResult(restResult, 500, null, null, false);
}
@Test
public void testFailedWithMsg() {
RestResult<String> restResult = RestResultUtils.failed("test");
assertRestResult(restResult, 500, "test", null, false);
}
@Test
public void testFailedWithCode() {
RestResult<String> restResult = RestResultUtils.failed(400, "content");
assertRestResult(restResult, 400, null, "content", false);
}
@Test
public void testSuccessWithFull() {
RestResult<String> restResult = RestResultUtils.failed(400, "content", "test");
assertRestResult(restResult, 400, "test", "content", false);
}
@Test
public void testFailedWithMsgMethod() {
RestResult<String> 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<String> 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());
}
}

View File

@ -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<MockEvent> 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;
}
}

View File

@ -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;
}
}
}

View File

@ -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 {
}
private static class TestEvent extends Event {
@Override
public long sequence() {
return System.currentTimeMillis();
}
}
static {
System.setProperty("nacos.core.notify.share-buffer-size", "8");
}
@Test
public void testEventsCanBeSubscribed() throws Exception {
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);
final CountDownLatch latch = new CountDownLatch(2);
final AtomicInteger count = new AtomicInteger(0);
NotifyCenter.registerSubscriber(new Subscriber<TestSlowEvent>() {
@Override
public void onEvent(TestSlowEvent event) {
try {
count.incrementAndGet();
} finally {
latch.countDown();
}
}
@Override
public Class<? extends Event> subscribeType() {
return TestSlowEvent.class;
}
});
NotifyCenter.registerSubscriber(new Subscriber<TestEvent>() {
@Override
public void onEvent(TestEvent event) {
try {
count.incrementAndGet();
} finally {
latch.countDown();
}
}
@Override
public Class<? extends Event> 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());
NotifyCenter.registerToPublisher(ExpireEvent.class, 16);
NotifyCenter.registerToPublisher(SharedEvent.class, shardedEventPublisher);
}
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;
@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);
}
@Test
public void testRegisterNullPublisher() {
int originalSize = NotifyCenter.getPublisherMap().size();
NotifyCenter.registerToPublisher(NoPublisherEvent.class, null);
assertEquals(originalSize, NotifyCenter.getPublisherMap().size());
}
@Test
public void testGetPublisher() {
assertEquals(NotifyCenter.getSharePublisher(), NotifyCenter.getPublisher(TestSlowEvent.class));
assertTrue(NotifyCenter.getPublisher(TestEvent.class) instanceof DefaultPublisher);
}
@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<ExpireEvent>() {
@Override
public void onEvent(ExpireEvent event) {
count.incrementAndGet();
}
@Override
public Class<? extends Event> 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);
@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);
}
}
static class NoExpireEvent extends Event {
@Test
public void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception {
List<Class<? extends Event>> 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 TestSlowEvent()));
Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1()));
}
latch.await(5000L, TimeUnit.MILLISECONDS);
assertEquals(6, count.get());
}
@Test
public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception {
List<Class<? extends Event>> 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());
}
@Test
public void testPublishEventByNoPublisher() {
for (int i = 0; i < 3; i++) {
Assert.assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent()));
}
}
@Test
public void testPublishEventByPluginEvent() {
for (int i = 0; i < 3; i++) {
Assert.assertTrue(NotifyCenter.publishEvent(new PluginEvent()));
}
}
@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());
}
@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 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<T extends Event> extends Subscriber<T> {
static AtomicLong sequence = new AtomicLong(3);
private final Class<T> subscribedEvent;
private long no = sequence.getAndDecrement();
private final boolean ignoreExpiredEvent;
private final CountDownLatch latch;
private MockSubscriber(Class<T> subscribedEvent, boolean ignoreExpiredEvent) {
this(subscribedEvent, ignoreExpiredEvent, null);
}
public MockSubscriber(Class<T> subscribedEvent, boolean ignoreExpiredEvent, CountDownLatch latch) {
this.subscribedEvent = subscribedEvent;
this.ignoreExpiredEvent = ignoreExpiredEvent;
this.latch = latch;
}
@Override
public void onEvent(Event event) {
count.incrementAndGet();
if (null != latch) {
latch.countDown();
}
}
@Override
public Class<? extends Event> subscribeType() {
return subscribedEvent;
}
@Override
public boolean ignoreExpireEvent() {
return ignoreExpiredEvent;
}
}
private static class MockSmartSubscriber extends SmartSubscriber {
private final List<Class<? extends Event>> subscribedEvents;
private final CountDownLatch latch;
private MockSmartSubscriber(List<Class<? extends Event>> subscribedEvents) {
this(subscribedEvents, null);
}
public MockSmartSubscriber(List<Class<? extends Event>> subscribedEvents, CountDownLatch latch) {
this.subscribedEvents = subscribedEvents;
this.latch = latch;
}
@Override
public void onEvent(Event event) {
count.incrementAndGet();
if (null != latch) {
latch.countDown();
}
}
@Override
public List<Class<? extends Event>> subscribeTypes() {
return subscribedEvents;
}
}
private static class TestSlowEvent extends SlowEvent {
private static final long serialVersionUID = 6713279688910446154L;
}
private static class TestSlowEvent1 extends SlowEvent {
private static final long serialVersionUID = 5946729801676058102L;
}
private static class TestEvent extends Event {
private static final long serialVersionUID = 2522362576233446960L;
@Override
public long sequence() {
return System.currentTimeMillis();
}
}
private static class NoPublisherEvent extends Event {
private static final long serialVersionUID = 6532409163269714916L;
}
private static class SharedEvent extends Event {
private static final long serialVersionUID = 7648766983252000074L;
}
private static class PluginEvent extends Event {
private static final long serialVersionUID = -7787588724415976798L;
@Override
public boolean isPluginEvent() {
return true;
}
}
private static class ExpireEvent extends Event {
private static final long serialVersionUID = 3024284255874382548L;
private final long no;
ExpireEvent(long no) {
this.no = no;
}
@Override
public long sequence() {
return no;
}
}
@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<? extends Event> subscribeType() {
return NoExpireEvent.class;
}
});
for (int i = 0; i < 3; i++) {
Assert.assertTrue(NotifyCenter.publishEvent(new NoExpireEvent()));
}
latch2.await(10000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(3, 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;
}
}
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 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<SlowE1>() {
@Override
public void onEvent(SlowE1 event) {
ThreadUtils.sleep(1000L);
values[0] = event.info;
latch1.countDown();
}
@Override
public Class<? extends Event> subscribeType() {
return SlowE1.class;
}
});
NotifyCenter.registerSubscriber(new Subscriber<SlowE2>() {
@Override
public void onEvent(SlowE2 event) {
values[1] = event.info;
latch2.countDown();
}
@Override
public Class<? extends Event> subscribeType() {
return SlowE2.class;
}
});
for (int i = 0; i < 30; i++) {
NotifyCenter.publishEvent(new SlowE1());
NotifyCenter.publishEvent(new SlowE2());
}
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();
}
}
static class SmartEvent2 extends Event {
@Override
public long sequence() {
return System.currentTimeMillis();
}
}
@Test
public void testSeveralEventsPublishedBySinglePublisher() throws Exception {
final AtomicInteger count1 = new AtomicInteger(0);
final AtomicInteger count2 = new AtomicInteger(0);
final CountDownLatch latch1 = new CountDownLatch(3);
final CountDownLatch latch2 = new CountDownLatch(3);
NotifyCenter.registerToPublisher(SmartEvent1.class, 1024);
NotifyCenter.registerToPublisher(SmartEvent2.class, 1024);
NotifyCenter.registerSubscriber(new SmartSubscriber() {
@Override
public List<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> list = new ArrayList<Class<? extends Event>>();
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();
}
}
});
for (int i = 0; i < 3; i++) {
Assert.assertTrue(NotifyCenter.publishEvent(new SmartEvent1()));
Assert.assertTrue(NotifyCenter.publishEvent(new SmartEvent2()));
}
latch1.await(3000L, TimeUnit.MILLISECONDS);
latch2.await(3000L, TimeUnit.MILLISECONDS);
Assert.assertEquals(3, count1.get());
Assert.assertEquals(3, count2.get());
}
private static class TestSlowEvent1 extends SlowEvent {
}
private static class TestSlowEvent2 extends SlowEvent {
}
@Test
public void testMutipleSlowEventsListenedBySubscriber() throws Exception {
NotifyCenter.registerToSharePublisher(TestSlowEvent1.class);
NotifyCenter.registerToSharePublisher(TestSlowEvent2.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);
NotifyCenter.registerSubscriber(new Subscriber<TestSlowEvent1>() {
@Override
public void onEvent(TestSlowEvent1 event) {
count1.incrementAndGet();
latch1.countDown();
}
@Override
public Class<? extends Event> subscribeType() {
return TestSlowEvent1.class;
}
});
NotifyCenter.registerSubscriber(new Subscriber<TestSlowEvent2>() {
@Override
public void onEvent(TestSlowEvent2 event) {
count2.incrementAndGet();
latch2.countDown();
}
@Override
public Class<? extends Event> subscribeType() {
return TestSlowEvent2.class;
}
});
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());
}
private static class TestSlowEvent3 extends SlowEvent {
}
private static class TestSlowEvent4 extends SlowEvent {
}
@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);
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<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> subTypes = new ArrayList<Class<? extends Event>>();
subTypes.add(TestSlowEvent3.class);
subTypes.add(TestSlowEvent4.class);
return subTypes;
}
});
for (int i = 0; i < 3; i++) {
Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent3()));
Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent4()));
}
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 class TestSlowEvent5 extends SlowEvent {
}
private static class TestEvent6 extends Event {
}
@Test
public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception {
NotifyCenter.registerToSharePublisher(TestSlowEvent5.class);
NotifyCenter.registerToPublisher(TestEvent6.class, 1024);
final AtomicInteger count1 = new AtomicInteger(0);
final AtomicInteger count2 = new AtomicInteger(0);
final CountDownLatch latch1 = new CountDownLatch(3);
final CountDownLatch latch2 = new CountDownLatch(3);
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<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> subTypes = new ArrayList<Class<? extends Event>>();
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()));
}
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()));
}
}
}

View File

@ -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<Class<MockClass>> subTypesOf = packageScan
.getSubTypesOf(AnnotationClass.class.getPackage().getName(), MockClass.class);
assertEquals(3, subTypesOf.size());
}
@Test
public void testGetTypesAnnotatedWith() {
packageScan = new DefaultPackageScan();
Set<Class<Object>> 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<Class<MockClass>> 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<Class<Object>> 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<Class<MockClass>> 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);
}
}

View File

@ -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<Class<Request>> subTypesOf = packageScan.getSubTypesOf("com.alibaba.nacos.api.naming.remote.request", Request.class);
assertTrue(subTypesOf.size() > 0);
}
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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 checkParamInfoList() {
AbstractParamChecker paramChecker = new DefaultParamChecker();
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<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
paramChecker.checkParamInfoList(paramInfos);
paramInfos.add(null);
ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos);
assertTrue(actual.isSuccess());
}
@Test
public void testCheckParamInfoForNamespaceShowName() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> 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<ParamInfo> 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<ParamInfo> 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<ParamInfo> 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 testCheckParamInfoForGroup() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
// 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<ParamInfo> 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<ParamInfo> 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<ParamInfo> 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<ParamInfo> 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<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
Map<String, String> 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();
}
}

View File

@ -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<ParamInfo> paramInfos) {
return new ParamCheckResponse();
}
@Override
public void initParamCheckRule() {
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.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);
}
}

View File

@ -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<PathEncoderManager> 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 class PathEncoderManagerTest extends TestCase {
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());
}
}

View File

@ -108,6 +108,7 @@ public class WindowsEncoderTest extends TestCase {
String case7 = "asdas<da";
String case8 = "sdasas>a";
String case9 = "das1|2e";
Assert.assertFalse(windowsEncoder.needEncode(null));
Assert.assertFalse(windowsEncoder.needEncode(case1));
Assert.assertTrue(windowsEncoder.needEncode(case2));
Assert.assertTrue(windowsEncoder.needEncode(case3));

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.common.spi;
import org.junit.After;
import org.junit.Test;
import java.util.Collection;
@ -25,6 +26,11 @@ import static org.junit.Assert.assertNotEquals;
public class NacosServiceLoaderTest {
@After
public void tearDown() {
SpiTestImpl.newInstanceException = false;
}
@Test
public void testLoad() {
Collection<SpiTestInterface> actual = NacosServiceLoader.load(SpiTestInterface.class);
@ -40,4 +46,16 @@ public class NacosServiceLoaderTest {
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());
}
}
}

View File

@ -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");
}
}
}

View File

@ -90,6 +90,7 @@ public class NacosDelayTaskExecuteEngineTest {
TimeUnit.MILLISECONDS.sleep(200);
verify(testTaskProcessor).process(abstractTask);
verify(taskProcessor, never()).process(abstractTask);
assertEquals(1, nacosDelayTaskExecuteEngine.getAllProcessorKey().size());
}
@Test
@ -110,4 +111,39 @@ public class NacosDelayTaskExecuteEngineTest {
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());
}
}

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.common.task.engine;
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 class NacosExecuteTaskExecuteEngineTest {
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());
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.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);
}
}

View File

@ -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());
}
}

View File

@ -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<String, String> 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());
}
}

View File

@ -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());
}
}

View File

@ -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<String, String> 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());
}
}

View File

@ -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());
}
}

View File

@ -26,10 +26,10 @@ import java.lang.reflect.Field;
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<String, EventPublisher> originalEventPublisherMap;
@Before
@ -57,6 +57,17 @@ public class TraceEventPublisherFactoryTest {
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());
}
}

View File

@ -30,7 +30,9 @@ import org.mockito.junit.MockitoJUnitRunner;
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 class TraceEventPublisherTest {
@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 class TraceEventPublisherTest {
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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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-----

View File

@ -31,8 +31,8 @@ import java.util.concurrent.TimeUnit;
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 final class TaskManager extends NacosDelayTaskExecuteEngine implements Ta
* Await for lock by timeout.
*
* @param timeout timeout value.
* @param unit time unit.
* @param unit time unit.
* @return success or not.
* @throws InterruptedException InterruptedException.
*/

View File

@ -74,7 +74,7 @@ public class RemoteParamCheckFilterTest {
} 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@@@@");

View File

@ -392,6 +392,9 @@
<append>true</append>
<excludes>
<exclude>**/grpc/auto/**</exclude>
<exclude>**/packagescan/classreading/**</exclude>
<exclude>**/packagescan/resource/**</exclude>
<exclude>**/packagescan/util/**</exclude>
</excludes>
</configuration>
<executions>