* upgrade module naocs-common from junit4 to junit5 * fix checkstyle
This commit is contained in:
parent
94bf8661ad
commit
35e3994bcb
@ -15,4 +15,5 @@
|
||||
*/
|
||||
|
||||
public class ClassUtilsTestMockClass {
|
||||
|
||||
}
|
||||
|
@ -16,21 +16,14 @@
|
||||
|
||||
package com.alibaba.nacos.common;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AppTest extends TestCase {
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class AppTest {
|
||||
|
||||
public AppTest(String testName) {
|
||||
super(testName);
|
||||
}
|
||||
|
||||
public static Test suite() {
|
||||
return new TestSuite(AppTest.class);
|
||||
}
|
||||
|
||||
public void testApp() {
|
||||
@Test
|
||||
void testApp() {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
@ -22,19 +22,20 @@ 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 org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class AbstractAbilityControlManagerTest {
|
||||
class AbstractAbilityControlManagerTest {
|
||||
|
||||
private AbstractAbilityControlManager abilityControlManager;
|
||||
|
||||
@ -46,8 +47,8 @@ public class AbstractAbilityControlManagerTest {
|
||||
|
||||
private boolean notified = false;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
mockSubscriber = new Subscriber<AbstractAbilityControlManager.AbilityUpdateEvent>() {
|
||||
@Override
|
||||
public void onEvent(AbstractAbilityControlManager.AbilityUpdateEvent event) {
|
||||
@ -71,15 +72,15 @@ public class AbstractAbilityControlManagerTest {
|
||||
NotifyCenter.registerSubscriber(mockSubscriber);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
NotifyCenter.deregisterSubscriber(mockSubscriber);
|
||||
assertionError = null;
|
||||
notified = false;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnableCurrentNodeAbility() throws InterruptedException {
|
||||
void testEnableCurrentNodeAbility() throws InterruptedException {
|
||||
isOn = true;
|
||||
abilityControlManager.enableCurrentNodeAbility(AbilityKey.SERVER_TEST_1);
|
||||
TimeUnit.MILLISECONDS.sleep(1100);
|
||||
@ -90,7 +91,7 @@ public class AbstractAbilityControlManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisableCurrentNodeAbility() throws InterruptedException {
|
||||
void testDisableCurrentNodeAbility() throws InterruptedException {
|
||||
isOn = false;
|
||||
abilityControlManager.disableCurrentNodeAbility(AbilityKey.SERVER_TEST_1);
|
||||
TimeUnit.MILLISECONDS.sleep(1100);
|
||||
@ -101,17 +102,14 @@ public class AbstractAbilityControlManagerTest {
|
||||
}
|
||||
|
||||
@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));
|
||||
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() {
|
||||
void testGetCurrentNodeAbilities() {
|
||||
Map<String, Boolean> actual = abilityControlManager.getCurrentNodeAbilities(AbilityMode.SERVER);
|
||||
assertEquals(2, actual.size());
|
||||
assertTrue(actual.containsKey(AbilityKey.SERVER_TEST_1.getName()));
|
||||
@ -121,24 +119,26 @@ public class AbstractAbilityControlManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetPriority() {
|
||||
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;
|
||||
}
|
||||
};
|
||||
@Test
|
||||
void testInitFailed() {
|
||||
assertThrows(IllegalStateException.class, () -> {
|
||||
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 {
|
||||
|
@ -16,44 +16,46 @@
|
||||
|
||||
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 org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NacosAbilityManagerHolderTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NacosAbilityManagerHolderTest {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
NacosAbilityManagerHolder.getInstance();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
Field abilityControlManagerField = NacosAbilityManagerHolder.class
|
||||
.getDeclaredField("abstractAbilityControlManager");
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
Field abilityControlManagerField = NacosAbilityManagerHolder.class.getDeclaredField("abstractAbilityControlManager");
|
||||
abilityControlManagerField.setAccessible(true);
|
||||
abilityControlManagerField.set(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetInstance() {
|
||||
void testGetInstance() {
|
||||
assertNotNull(NacosAbilityManagerHolder.getInstance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetInstanceByType() {
|
||||
void testGetInstanceByType() {
|
||||
assertNotNull(NacosAbilityManagerHolder.getInstance(HigherMockAbilityManager.class));
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void testGetInstanceByWrongType() {
|
||||
assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class));
|
||||
@Test
|
||||
void testGetInstanceByWrongType() {
|
||||
assertThrows(ClassCastException.class, () -> {
|
||||
assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class));
|
||||
});
|
||||
}
|
||||
}
|
@ -16,43 +16,45 @@
|
||||
|
||||
package com.alibaba.nacos.common.cache.builder;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class CacheBuilderTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CacheBuilderTest {
|
||||
|
||||
@Test
|
||||
public void testNegativeDuration() {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage("duration cannot be negative");
|
||||
CacheBuilder.builder().expireNanos(-1, TimeUnit.MINUTES).build();
|
||||
void testNegativeDuration() {
|
||||
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
CacheBuilder.builder().expireNanos(-1, TimeUnit.MINUTES).build();
|
||||
});
|
||||
assertTrue(exception.getMessage().contains("duration cannot be negative"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullTimeUnit() {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage("unit cannot be null");
|
||||
CacheBuilder.builder().expireNanos(500, null).build();
|
||||
void testNullTimeUnit() {
|
||||
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
CacheBuilder.builder().expireNanos(500, null).build();
|
||||
});
|
||||
assertTrue(exception.getMessage().contains("unit cannot be null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNegativeMaximumSize() {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage("size cannot be negative");
|
||||
CacheBuilder.builder().maximumSize(-1).build();
|
||||
void testNegativeMaximumSize() {
|
||||
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
CacheBuilder.builder().maximumSize(-1).build();
|
||||
});
|
||||
assertTrue(exception.getMessage().contains("size cannot be negative"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNegativeInitializeCapacity() {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage("initializeCapacity cannot be negative");
|
||||
CacheBuilder.builder().initializeCapacity(-1).build();
|
||||
void testNegativeInitializeCapacity() {
|
||||
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
|
||||
CacheBuilder.builder().initializeCapacity(-1).build();
|
||||
});
|
||||
assertTrue(exception.getMessage().contains("initializeCapacity cannot be negative"));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -18,47 +18,51 @@ package com.alibaba.nacos.common.cache.decorators;
|
||||
|
||||
import com.alibaba.nacos.common.cache.Cache;
|
||||
import com.alibaba.nacos.common.cache.builder.CacheBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* auto expire cache test.
|
||||
*
|
||||
* @author zzq
|
||||
* @date 2021/8/1
|
||||
*/
|
||||
public class AutoExpireCacheTest {
|
||||
class AutoExpireCacheTest {
|
||||
|
||||
@Test
|
||||
public void testBasic() throws Exception {
|
||||
void testBasic() throws Exception {
|
||||
Cache cache = CacheBuilder.builder().expireNanos(10, TimeUnit.MINUTES).build();
|
||||
IntStream.range(0, 100).forEach(item -> cache.put(item, item));
|
||||
Assert.assertEquals(100, cache.getSize());
|
||||
Assert.assertEquals(99, cache.get(99));
|
||||
Assert.assertEquals(99, cache.get(99, () -> 100));
|
||||
assertEquals(100, cache.getSize());
|
||||
assertEquals(99, cache.get(99));
|
||||
assertEquals(99, cache.get(99, () -> 100));
|
||||
Object removed = cache.remove(99);
|
||||
Assert.assertEquals(99, removed);
|
||||
Assert.assertEquals(99, cache.getSize());
|
||||
Assert.assertEquals(100, cache.get(99, () -> 100));
|
||||
assertEquals(99, removed);
|
||||
assertEquals(99, cache.getSize());
|
||||
assertEquals(100, cache.get(99, () -> 100));
|
||||
cache.clear();
|
||||
Assert.assertEquals(0, cache.getSize());
|
||||
assertEquals(0, cache.getSize());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testExpire() throws Exception {
|
||||
void testExpire() throws Exception {
|
||||
Cache cache = CacheBuilder.builder().expireNanos(1, TimeUnit.SECONDS).build();
|
||||
cache.put("a", "a");
|
||||
cache.put("a", "a");
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
Assert.assertNull(cache.get("a"));
|
||||
assertNull(cache.get("a"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGetCache() {
|
||||
void testGetCache() {
|
||||
Cache cache = CacheBuilder.builder().expireNanos(1, TimeUnit.MINUTES).build();
|
||||
cache.put("test", "test");
|
||||
Assert.assertNotNull(cache.get("test"));
|
||||
Assert.assertNull(cache.get("test2"));
|
||||
assertNotNull(cache.get("test"));
|
||||
assertNull(cache.get("test2"));
|
||||
}
|
||||
}
|
||||
|
@ -18,39 +18,42 @@ package com.alibaba.nacos.common.cache.decorators;
|
||||
|
||||
import com.alibaba.nacos.common.cache.Cache;
|
||||
import com.alibaba.nacos.common.cache.builder.CacheBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* lru test .
|
||||
*
|
||||
* @author zzq
|
||||
* @date 2021/7/30
|
||||
*/
|
||||
public class LruCacheTest {
|
||||
|
||||
class LruCacheTest {
|
||||
|
||||
@Test
|
||||
public void testBasic() throws Exception {
|
||||
void testBasic() throws Exception {
|
||||
int capacity = 10;
|
||||
int start = 0;
|
||||
int end = 99;
|
||||
Cache cache = CacheBuilder.builder().maximumSize(capacity).lru(true).build();
|
||||
IntStream.range(start, end).forEach(item -> cache.put(item, item));
|
||||
Assert.assertEquals(capacity, cache.getSize());
|
||||
Assert.assertNull(cache.get(start));
|
||||
Assert.assertEquals(89, cache.get(89));
|
||||
Assert.assertEquals(94, cache.get(94));
|
||||
Assert.assertEquals(94, cache.get(94, () -> 100));
|
||||
assertEquals(capacity, cache.getSize());
|
||||
assertNull(cache.get(start));
|
||||
assertEquals(89, cache.get(89));
|
||||
assertEquals(94, cache.get(94));
|
||||
assertEquals(94, cache.get(94, () -> 100));
|
||||
Object removed = cache.remove(98);
|
||||
Assert.assertEquals(98, removed);
|
||||
Assert.assertEquals(9, cache.getSize());
|
||||
assertEquals(98, removed);
|
||||
assertEquals(9, cache.getSize());
|
||||
cache.clear();
|
||||
Assert.assertEquals(0, cache.getSize());
|
||||
assertEquals(0, cache.getSize());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testLru() {
|
||||
void testLru() {
|
||||
int capacity = 10;
|
||||
int start = 0;
|
||||
int end = 10;
|
||||
@ -58,7 +61,7 @@ public class LruCacheTest {
|
||||
IntStream.range(start, end).forEach(item -> cache.put(item, item));
|
||||
IntStream.range(start, 2).forEach(item -> cache.get(0));
|
||||
cache.put(100, 100);
|
||||
Assert.assertEquals(start, cache.get(0));
|
||||
Assert.assertNull(cache.get(1));
|
||||
assertEquals(start, cache.get(0));
|
||||
assertNull(cache.get(1));
|
||||
}
|
||||
}
|
||||
|
@ -18,26 +18,27 @@ package com.alibaba.nacos.common.cache.decorators;
|
||||
|
||||
import com.alibaba.nacos.common.cache.Cache;
|
||||
import com.alibaba.nacos.common.cache.builder.CacheBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SynchronizedCacheTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class SynchronizedCacheTest {
|
||||
|
||||
@Test
|
||||
public void testSync() throws Exception {
|
||||
void testSync() throws Exception {
|
||||
Cache cache = CacheBuilder.builder().sync(true).build();
|
||||
IntStream.range(0, 100).forEach(item -> cache.put(item, item));
|
||||
Assert.assertEquals(100, cache.getSize());
|
||||
Assert.assertEquals(99, cache.get(99));
|
||||
Assert.assertEquals(99, cache.get(99, () -> 100));
|
||||
assertEquals(100, cache.getSize());
|
||||
assertEquals(99, cache.get(99));
|
||||
assertEquals(99, cache.get(99, () -> 100));
|
||||
Object removed = cache.remove(99);
|
||||
Assert.assertEquals(99, removed);
|
||||
Assert.assertEquals(99, cache.getSize());
|
||||
Assert.assertEquals(100, cache.get(99, () -> 100));
|
||||
assertEquals(99, removed);
|
||||
assertEquals(99, cache.getSize());
|
||||
assertEquals(100, cache.get(99, () -> 100));
|
||||
cache.clear();
|
||||
Assert.assertEquals(0, cache.getSize());
|
||||
assertEquals(0, cache.getSize());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -18,27 +18,29 @@ package com.alibaba.nacos.common.cache.impl;
|
||||
|
||||
import com.alibaba.nacos.common.cache.Cache;
|
||||
import com.alibaba.nacos.common.cache.builder.CacheBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SimpleCacheTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class SimpleCacheTest {
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
void test() throws Exception {
|
||||
Cache cache = CacheBuilder.builder().initializeCapacity(100).build();
|
||||
IntStream.range(0, 100).forEach(item -> cache.put(item, item));
|
||||
Assert.assertEquals(100, cache.getSize());
|
||||
assertEquals(100, cache.getSize());
|
||||
Object item = cache.remove(89);
|
||||
Assert.assertEquals(89, item);
|
||||
Assert.assertEquals(99, cache.getSize());
|
||||
Assert.assertEquals(null, cache.get(89));
|
||||
Assert.assertEquals(99, cache.get(99));
|
||||
Assert.assertEquals(99, cache.get(99, () -> 99999));
|
||||
Assert.assertEquals(87, cache.get(111, () -> 87));
|
||||
assertEquals(89, item);
|
||||
assertEquals(99, cache.getSize());
|
||||
assertNull(cache.get(89));
|
||||
assertEquals(99, cache.get(99));
|
||||
assertEquals(99, cache.get(99, () -> 99999));
|
||||
assertEquals(87, cache.get(111, () -> 87));
|
||||
cache.clear();
|
||||
Assert.assertEquals(0, cache.getSize());
|
||||
assertEquals(0, cache.getSize());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,81 +16,86 @@
|
||||
|
||||
package com.alibaba.nacos.common.codec;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class Base64Test {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class Base64Test {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
void test() {
|
||||
String origin = "nacos";
|
||||
String encoded = "bmFjb3M=";
|
||||
|
||||
byte[] encodeBase64 = Base64.encodeBase64(origin.getBytes(StandardCharsets.UTF_8));
|
||||
Assert.assertEquals(encoded, new String(encodeBase64));
|
||||
assertEquals(encoded, new String(encodeBase64));
|
||||
byte[] decodeBase64 = Base64.decodeBase64(encoded.getBytes(StandardCharsets.UTF_8));
|
||||
Assert.assertEquals(origin, new String(decodeBase64));
|
||||
assertEquals(origin, new String(decodeBase64));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodeNullOrEmpty() {
|
||||
void testEncodeNullOrEmpty() {
|
||||
byte[] b1 = Base64.encodeBase64(null);
|
||||
Assert.assertNull(b1);
|
||||
assertNull(b1);
|
||||
byte[] b2 = Base64.encodeBase64(new byte[] {});
|
||||
Assert.assertEquals(0, b2.length);
|
||||
assertEquals(0, b2.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecodeNullOrEmpty() {
|
||||
void testDecodeNullOrEmpty() {
|
||||
byte[] b1 = Base64.decodeBase64(null);
|
||||
Assert.assertNull(b1);
|
||||
assertNull(b1);
|
||||
byte[] b2 = Base64.decodeBase64(new byte[] {});
|
||||
Assert.assertEquals(0, b2.length);
|
||||
assertEquals(0, b2.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChunk() {
|
||||
void testChunk() {
|
||||
String a = "very large characters to test chunk encoding and see if the result is expected or not";
|
||||
byte[] b1 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, Integer.MAX_VALUE);
|
||||
byte[] b2 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), true, false, Integer.MAX_VALUE);
|
||||
String s1 = new String(b1);
|
||||
String s2 = new String(b2);
|
||||
Assert.assertEquals(s1, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0"
|
||||
assertEquals(s1, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0"
|
||||
+ "aGUgcmVzdWx0IGlzIGV4cGVjdGVkIG9yIG5vdA==");
|
||||
Assert.assertEquals(s2, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + "\r\n"
|
||||
assertEquals(s2, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + "\r\n"
|
||||
+ "aGUgcmVzdWx0IGlzIGV4cGVjdGVkIG9yIG5vdA==" + "\r\n");
|
||||
|
||||
byte[] c1 = Base64.decodeBase64(b1);
|
||||
byte[] c2 = Base64.decodeBase64(b2);
|
||||
String s3 = new String(c1);
|
||||
String s4 = new String(c2);
|
||||
Assert.assertEquals(a, s3);
|
||||
Assert.assertEquals(a, s4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUrlSafe() {
|
||||
String a = "aa~aa?";
|
||||
byte[] b1 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, Integer.MAX_VALUE);
|
||||
byte[] b2 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, true, Integer.MAX_VALUE);
|
||||
String s1 = new String(b1);
|
||||
String s2 = new String(b2);
|
||||
Assert.assertEquals("YWF+YWE/", s1);
|
||||
Assert.assertEquals("YWF-YWE_", s2);
|
||||
|
||||
byte[] c1 = Base64.decodeBase64(b1);
|
||||
byte[] c2 = Base64.decodeBase64(b2);
|
||||
String s3 = new String(c1);
|
||||
String s4 = new String(c2);
|
||||
Assert.assertEquals("aa~aa?", s3);
|
||||
Assert.assertEquals("aa~aa?", s4);
|
||||
assertEquals(a, s3);
|
||||
assertEquals(a, 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);
|
||||
@Test
|
||||
void testUrlSafe() {
|
||||
String a = "aa~aa?";
|
||||
byte[] b1 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, Integer.MAX_VALUE);
|
||||
byte[] b2 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, true, Integer.MAX_VALUE);
|
||||
String s1 = new String(b1);
|
||||
String s2 = new String(b2);
|
||||
assertEquals("YWF+YWE/", s1);
|
||||
assertEquals("YWF-YWE_", s2);
|
||||
|
||||
byte[] c1 = Base64.decodeBase64(b1);
|
||||
byte[] c2 = Base64.decodeBase64(b2);
|
||||
String s3 = new String(c1);
|
||||
String s4 = new String(c2);
|
||||
assertEquals("aa~aa?", s3);
|
||||
assertEquals("aa~aa?", s4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEncodeOverMaxLength() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -17,14 +17,15 @@
|
||||
package com.alibaba.nacos.common.event;
|
||||
|
||||
import com.alibaba.nacos.common.notify.Event;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ServerConfigChangeEventTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ServerConfigChangeEventTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
void test() {
|
||||
Event event = ServerConfigChangeEvent.newEvent();
|
||||
Assert.assertTrue(event instanceof ServerConfigChangeEvent);
|
||||
assertTrue(event instanceof ServerConfigChangeEvent);
|
||||
}
|
||||
}
|
||||
|
@ -16,8 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.executor;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@ -25,67 +24,71 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
public class ExecutorFactoryTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ExecutorFactoryTest {
|
||||
|
||||
private final NameThreadFactory threadFactory = new NameThreadFactory("test");
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
void test() {
|
||||
ExecutorService executorService;
|
||||
ThreadPoolExecutor threadPoolExecutor;
|
||||
|
||||
executorService = ExecutorFactory.newSingleExecutorService();
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
executorService = ExecutorFactory.newFixedExecutorService(10);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
executorService = ExecutorFactory.newSingleExecutorService(threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
executorService = ExecutorFactory.newFixedExecutorService(10, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
|
||||
|
||||
executorService = ExecutorFactory.newSingleScheduledExecutorService(threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
executorService = ExecutorFactory.newScheduledExecutorService(10, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
|
||||
threadPoolExecutor = ExecutorFactory.newCustomerThreadExecutor(10, 20, 1000, threadFactory);
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(20, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(20, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testManaged() {
|
||||
void testManaged() {
|
||||
String testGroup = "test";
|
||||
ExecutorService executorService;
|
||||
ThreadPoolExecutor threadPoolExecutor;
|
||||
@ -93,59 +96,59 @@ public class ExecutorFactoryTest {
|
||||
final Map<String, Map<String, Set<ExecutorService>>> resourcesManager = manager.getResourcesManager();
|
||||
|
||||
executorService = ExecutorFactory.Managed.newSingleExecutorService(testGroup);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(1, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(1, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
executorService = ExecutorFactory.Managed.newFixedExecutorService(testGroup, 10);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(2, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(2, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
executorService = ExecutorFactory.Managed.newSingleExecutorService(testGroup, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(3, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(1, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(1, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(3, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
executorService = ExecutorFactory.Managed.newFixedExecutorService(testGroup, 10, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ThreadPoolExecutor);
|
||||
threadPoolExecutor = (ThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(4, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(4, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
|
||||
|
||||
executorService = ExecutorFactory.Managed.newSingleScheduledExecutorService(testGroup, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(5, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(5, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
executorService = ExecutorFactory.Managed.newScheduledExecutorService(testGroup, 10, threadFactory);
|
||||
Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
assertTrue(executorService instanceof ScheduledThreadPoolExecutor);
|
||||
scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService;
|
||||
Assert.assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(6, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(6, resourcesManager.get("nacos").get(testGroup).size());
|
||||
|
||||
threadPoolExecutor = ExecutorFactory.Managed.newCustomerThreadExecutor(testGroup, 10, 20, 1000, threadFactory);
|
||||
Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
Assert.assertEquals(20, threadPoolExecutor.getMaximumPoolSize());
|
||||
Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
Assert.assertEquals(7, resourcesManager.get("nacos").get(testGroup).size());
|
||||
assertEquals(10, threadPoolExecutor.getCorePoolSize());
|
||||
assertEquals(20, threadPoolExecutor.getMaximumPoolSize());
|
||||
assertEquals(threadFactory, threadPoolExecutor.getThreadFactory());
|
||||
assertEquals(7, resourcesManager.get("nacos").get(testGroup).size());
|
||||
}
|
||||
}
|
||||
|
@ -16,13 +16,14 @@
|
||||
|
||||
package com.alibaba.nacos.common.executor;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class NameThreadFactoryTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class NameThreadFactoryTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
void test() {
|
||||
NameThreadFactory threadFactory = new NameThreadFactory("test");
|
||||
Thread t1 = threadFactory.newThread(() -> {
|
||||
|
||||
@ -31,8 +32,8 @@ public class NameThreadFactoryTest {
|
||||
|
||||
});
|
||||
|
||||
Assert.assertEquals(t1.getName(), "test.0");
|
||||
Assert.assertEquals(t2.getName(), "test.1");
|
||||
assertEquals("test.0", t1.getName());
|
||||
assertEquals("test.1", t2.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,17 +16,18 @@
|
||||
|
||||
package com.alibaba.nacos.common.executor;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ThreadPoolManagerTest {
|
||||
class ThreadPoolManagerTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
void test() {
|
||||
ThreadPoolManager manager = ThreadPoolManager.getInstance();
|
||||
ExecutorService executor = ExecutorFactory.newSingleExecutorService();
|
||||
String namespace = "test";
|
||||
@ -34,41 +35,41 @@ public class ThreadPoolManagerTest {
|
||||
|
||||
manager.register(namespace, group, executor);
|
||||
assertTrue(manager.getResourcesManager().containsKey(namespace));
|
||||
Assert.assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
|
||||
manager.register(namespace, group, ExecutorFactory.newSingleExecutorService());
|
||||
Assert.assertEquals(2, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
assertEquals(2, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
|
||||
manager.destroy(namespace, group);
|
||||
Assert.assertFalse(manager.getResourcesManager().get(namespace).containsKey(group));
|
||||
assertFalse(manager.getResourcesManager().get(namespace).containsKey(group));
|
||||
|
||||
manager.register(namespace, group, executor);
|
||||
manager.destroy(namespace);
|
||||
Assert.assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
|
||||
manager.register(namespace, group, executor);
|
||||
manager.deregister(namespace, group, ExecutorFactory.newSingleExecutorService());
|
||||
Assert.assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
|
||||
manager.deregister(namespace, group, executor);
|
||||
Assert.assertEquals(0, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
assertEquals(0, manager.getResourcesManager().get(namespace).get(group).size());
|
||||
|
||||
manager.register(namespace, group, executor);
|
||||
manager.deregister(namespace, group);
|
||||
Assert.assertFalse(manager.getResourcesManager().get(namespace).containsKey(group));
|
||||
assertFalse(manager.getResourcesManager().get(namespace).containsKey(group));
|
||||
|
||||
manager.register(namespace, group, executor);
|
||||
manager.register(namespace, group, ExecutorFactory.newSingleExecutorService());
|
||||
ThreadPoolManager.shutdown();
|
||||
Assert.assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
|
||||
manager.destroy(namespace);
|
||||
manager.destroy(namespace, group);
|
||||
Assert.assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
assertFalse(manager.getResourcesManager().containsKey(namespace));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDestroyWithNull() {
|
||||
void testDestroyWithNull() {
|
||||
ThreadPoolManager.getInstance().register("t", "g", ExecutorFactory.newFixedExecutorService(1));
|
||||
try {
|
||||
ThreadPoolManager.getInstance().destroy("null");
|
||||
|
@ -19,35 +19,35 @@ package com.alibaba.nacos.common.http;
|
||||
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||
import com.alibaba.nacos.common.http.client.request.DefaultHttpClientRequest;
|
||||
import com.alibaba.nacos.common.http.client.request.HttpClientRequest;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AbstractApacheHttpClientFactoryTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AbstractApacheHttpClientFactoryTest {
|
||||
|
||||
@Mock
|
||||
private Logger logger;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNacosRestTemplate() throws NoSuchFieldException, IllegalAccessException {
|
||||
void testCreateNacosRestTemplate() throws NoSuchFieldException, IllegalAccessException {
|
||||
HttpClientFactory factory = new AbstractApacheHttpClientFactory() {
|
||||
@Override
|
||||
protected HttpClientConfig buildHttpClientConfig() {
|
||||
|
@ -19,28 +19,28 @@ package com.alibaba.nacos.common.http;
|
||||
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
|
||||
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||
import com.alibaba.nacos.common.tls.TlsSystemConfig;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AbstractHttpClientFactoryTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AbstractHttpClientFactoryTest {
|
||||
|
||||
@Mock
|
||||
private Logger logger;
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
TlsSystemConfig.tlsEnable = false;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNacosRestTemplateWithSsl() throws Exception {
|
||||
void testCreateNacosRestTemplateWithSsl() throws Exception {
|
||||
TlsSystemConfig.tlsEnable = true;
|
||||
HttpClientFactory httpClientFactory = new DefaultHttpClientFactory(logger);
|
||||
NacosRestTemplate nacosRestTemplate = httpClientFactory.createNacosRestTemplate();
|
||||
@ -48,7 +48,7 @@ public class AbstractHttpClientFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNacosAsyncRestTemplate() {
|
||||
void testCreateNacosAsyncRestTemplate() {
|
||||
HttpClientFactory httpClientFactory = new AbstractHttpClientFactory() {
|
||||
@Override
|
||||
protected HttpClientConfig buildHttpClientConfig() {
|
||||
|
@ -17,89 +17,93 @@
|
||||
package com.alibaba.nacos.common.http;
|
||||
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BaseHttpMethodTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class BaseHttpMethodTest {
|
||||
|
||||
@Test
|
||||
public void testHttpGet() {
|
||||
void testHttpGet() {
|
||||
BaseHttpMethod method = BaseHttpMethod.GET;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("GET", request.getMethod());
|
||||
assertEquals("GET", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpGetLarge() {
|
||||
void testHttpGetLarge() {
|
||||
BaseHttpMethod method = BaseHttpMethod.GET_LARGE;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("GET", request.getMethod());
|
||||
assertEquals("GET", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPost() {
|
||||
void testHttpPost() {
|
||||
BaseHttpMethod method = BaseHttpMethod.POST;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("POST", request.getMethod());
|
||||
assertEquals("POST", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPut() {
|
||||
void testHttpPut() {
|
||||
BaseHttpMethod method = BaseHttpMethod.PUT;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("PUT", request.getMethod());
|
||||
assertEquals("PUT", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpDelete() {
|
||||
void testHttpDelete() {
|
||||
BaseHttpMethod method = BaseHttpMethod.DELETE;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("DELETE", request.getMethod());
|
||||
assertEquals("DELETE", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpDeleteLarge() {
|
||||
void testHttpDeleteLarge() {
|
||||
BaseHttpMethod method = BaseHttpMethod.DELETE_LARGE;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("DELETE", request.getMethod());
|
||||
assertEquals("DELETE", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpHead() {
|
||||
void testHttpHead() {
|
||||
BaseHttpMethod method = BaseHttpMethod.HEAD;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("HEAD", request.getMethod());
|
||||
assertEquals("HEAD", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpTrace() {
|
||||
void testHttpTrace() {
|
||||
BaseHttpMethod method = BaseHttpMethod.TRACE;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("TRACE", request.getMethod());
|
||||
assertEquals("TRACE", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpPatch() {
|
||||
void testHttpPatch() {
|
||||
BaseHttpMethod method = BaseHttpMethod.PATCH;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("PATCH", request.getMethod());
|
||||
assertEquals("PATCH", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpOptions() {
|
||||
void testHttpOptions() {
|
||||
BaseHttpMethod method = BaseHttpMethod.OPTIONS;
|
||||
HttpRequestBase request = method.init("http://example.com");
|
||||
Assert.assertEquals("TRACE", request.getMethod());
|
||||
assertEquals("TRACE", request.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSourceOf() {
|
||||
void testSourceOf() {
|
||||
BaseHttpMethod method = BaseHttpMethod.sourceOf("GET");
|
||||
Assert.assertEquals(BaseHttpMethod.GET, method);
|
||||
assertEquals(BaseHttpMethod.GET, method);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSourceOfNotFound() {
|
||||
BaseHttpMethod.sourceOf("Not Found");
|
||||
@Test
|
||||
void testSourceOfNotFound() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
BaseHttpMethod.sourceOf("Not Found");
|
||||
});
|
||||
}
|
||||
}
|
@ -18,24 +18,29 @@ package com.alibaba.nacos.common.http;
|
||||
|
||||
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
|
||||
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HttpClientBeanHolderTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class HttpClientBeanHolderTest {
|
||||
|
||||
private Map<String, NacosRestTemplate> cachedRestTemplateMap;
|
||||
|
||||
@ -54,8 +59,8 @@ public class HttpClientBeanHolderTest {
|
||||
@Mock
|
||||
private HttpClientFactory mockFactory;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
cachedRestTemplateMap = new HashMap<>();
|
||||
cachedAsyncRestTemplateMap = new HashMap<>();
|
||||
restMap = (Map<String, NacosRestTemplate>) getCachedMap("SINGLETON_REST");
|
||||
@ -68,8 +73,8 @@ public class HttpClientBeanHolderTest {
|
||||
when(mockFactory.createNacosAsyncRestTemplate()).thenReturn(mockAsyncRestTemplate);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
restMap.putAll(cachedRestTemplateMap);
|
||||
restAsyncMap.putAll(cachedAsyncRestTemplateMap);
|
||||
cachedRestTemplateMap.clear();
|
||||
@ -83,7 +88,7 @@ public class HttpClientBeanHolderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetNacosRestTemplateWithDefault() {
|
||||
void testGetNacosRestTemplateWithDefault() {
|
||||
assertTrue(restMap.isEmpty());
|
||||
NacosRestTemplate actual = HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||
assertEquals(1, restMap.size());
|
||||
@ -92,13 +97,15 @@ public class HttpClientBeanHolderTest {
|
||||
assertEquals(actual, duplicateGet);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testGetNacosRestTemplateForNullFactory() {
|
||||
HttpClientBeanHolder.getNacosRestTemplate((HttpClientFactory) null);
|
||||
@Test
|
||||
void testGetNacosRestTemplateForNullFactory() {
|
||||
assertThrows(NullPointerException.class, () -> {
|
||||
HttpClientBeanHolder.getNacosRestTemplate((HttpClientFactory) null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetNacosRestTemplateWithCustomFactory() {
|
||||
void testGetNacosRestTemplateWithCustomFactory() {
|
||||
assertTrue(restMap.isEmpty());
|
||||
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||
assertEquals(1, restMap.size());
|
||||
@ -108,7 +115,7 @@ public class HttpClientBeanHolderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetNacosAsyncRestTemplateWithDefault() {
|
||||
void testGetNacosAsyncRestTemplateWithDefault() {
|
||||
assertTrue(restAsyncMap.isEmpty());
|
||||
NacosAsyncRestTemplate actual = HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||
assertEquals(1, restAsyncMap.size());
|
||||
@ -117,13 +124,15 @@ public class HttpClientBeanHolderTest {
|
||||
assertEquals(actual, duplicateGet);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testGetNacosAsyncRestTemplateForNullFactory() {
|
||||
HttpClientBeanHolder.getNacosAsyncRestTemplate((HttpClientFactory) null);
|
||||
@Test
|
||||
void testGetNacosAsyncRestTemplateForNullFactory() {
|
||||
assertThrows(NullPointerException.class, () -> {
|
||||
HttpClientBeanHolder.getNacosAsyncRestTemplate((HttpClientFactory) null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetNacosAsyncRestTemplateWithCustomFactory() {
|
||||
void testGetNacosAsyncRestTemplateWithCustomFactory() {
|
||||
assertTrue(restAsyncMap.isEmpty());
|
||||
HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||
assertEquals(1, restAsyncMap.size());
|
||||
@ -133,7 +142,7 @@ public class HttpClientBeanHolderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shutdown() throws Exception {
|
||||
void shutdown() throws Exception {
|
||||
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
|
||||
HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
|
||||
assertEquals(1, restMap.size());
|
||||
|
@ -16,78 +16,77 @@
|
||||
|
||||
package com.alibaba.nacos.common.http;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
public class HttpClientConfigTest {
|
||||
class HttpClientConfigTest {
|
||||
|
||||
@Test
|
||||
public void testGetConTimeOutMillis() {
|
||||
void testGetConTimeOutMillis() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
assertEquals(1000, config.getConTimeOutMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetReadTimeOutMillis() {
|
||||
void testGetReadTimeOutMillis() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setReadTimeOutMillis(2000).build();
|
||||
assertEquals(2000, config.getReadTimeOutMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnTimeToLive() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS)
|
||||
.build();
|
||||
void testGetConnTimeToLive() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS).build();
|
||||
assertEquals(3000, config.getConnTimeToLive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnTimeToLiveTimeUnit() {
|
||||
void testGetConnTimeToLiveTimeUnit() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(4000, TimeUnit.SECONDS).build();
|
||||
assertEquals(TimeUnit.SECONDS, config.getConnTimeToLiveTimeUnit());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnectionRequestTimeout() {
|
||||
void testGetConnectionRequestTimeout() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConnectionRequestTimeout(5000).build();
|
||||
assertEquals(5000, config.getConnectionRequestTimeout());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMaxRedirects() {
|
||||
void testGetMaxRedirects() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setMaxRedirects(60).build();
|
||||
assertEquals(60, config.getMaxRedirects());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMaxConnTotal() {
|
||||
void testGetMaxConnTotal() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setMaxConnTotal(70).build();
|
||||
assertEquals(70, config.getMaxConnTotal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMaxConnPerRoute() {
|
||||
void testGetMaxConnPerRoute() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setMaxConnPerRoute(80).build();
|
||||
assertEquals(80, config.getMaxConnPerRoute());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetContentCompressionEnabled() {
|
||||
void testGetContentCompressionEnabled() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setContentCompressionEnabled(false).build();
|
||||
assertFalse(config.getContentCompressionEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIoThreadCount() {
|
||||
void testGetIoThreadCount() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setIoThreadCount(90).build();
|
||||
assertEquals(90, config.getIoThreadCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserAgent() {
|
||||
void testGetUserAgent() {
|
||||
HttpClientConfig config = HttpClientConfig.builder().setUserAgent("testUserAgent").build();
|
||||
assertEquals("testUserAgent", config.getUserAgent());
|
||||
}
|
||||
|
@ -17,14 +17,14 @@
|
||||
package com.alibaba.nacos.common.http;
|
||||
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class HttpRestResultTest {
|
||||
class HttpRestResultTest {
|
||||
|
||||
@Test
|
||||
public void testSetHeader() {
|
||||
void testSetHeader() {
|
||||
HttpRestResult<String> result = new HttpRestResult<>();
|
||||
result.setData("test data");
|
||||
Header header = Header.newInstance();
|
||||
@ -34,7 +34,7 @@ public class HttpRestResultTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFullConstructor() {
|
||||
void testFullConstructor() {
|
||||
Header header = Header.newInstance();
|
||||
HttpRestResult<String> result = new HttpRestResult<>(header, 200, "test data", "message");
|
||||
assertEquals(header, result.getHeader());
|
||||
|
@ -25,10 +25,9 @@ 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;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
@ -43,53 +42,60 @@ 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.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HttpUtilsTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HttpUtilsTest {
|
||||
|
||||
String exceptUrl = "http://127.0.0.1:8080/v1/api/test";
|
||||
|
||||
@Test
|
||||
public void testBuildHttpUrl1() {
|
||||
void testBuildHttpUrl1() {
|
||||
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1/api/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "v1/api/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api", "/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", "/api/", "/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "test");
|
||||
Assert.assertEquals(exceptUrl, targetUrl);
|
||||
assertEquals(exceptUrl, targetUrl);
|
||||
targetUrl = HttpUtils.buildUrl(true, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test");
|
||||
Assert.assertEquals("https://127.0.0.1:8080/v1/api/test", targetUrl);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testBuildHttpUrl2() {
|
||||
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "//v1/api/test");
|
||||
Assert.assertNotEquals(exceptUrl, targetUrl);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testBuildHttpUrl3() {
|
||||
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api//", "test");
|
||||
Assert.assertNotEquals(exceptUrl, targetUrl);
|
||||
assertEquals("https://127.0.0.1:8080/v1/api/test", targetUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestHeader() {
|
||||
void testBuildHttpUrl2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "//v1/api/test");
|
||||
assertNotEquals(exceptUrl, targetUrl);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildHttpUrl3() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api//", "test");
|
||||
assertNotEquals(exceptUrl, targetUrl);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitRequestHeader() {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
Header header = Header.newInstance();
|
||||
header.addParam("k", "v");
|
||||
@ -97,13 +103,13 @@ public class HttpUtilsTest {
|
||||
HttpUtils.initRequestHeader(httpRequest, header);
|
||||
|
||||
org.apache.http.Header[] headers = httpRequest.getHeaders("k");
|
||||
Assert.assertEquals(1, headers.length);
|
||||
Assert.assertEquals("k", headers[0].getName());
|
||||
Assert.assertEquals("v", headers[0].getValue());
|
||||
assertEquals(1, headers.length);
|
||||
assertEquals("k", headers[0].getName());
|
||||
assertEquals("v", headers[0].getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestEntity1() throws Exception {
|
||||
void testInitRequestEntity1() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
Header header = Header.newInstance();
|
||||
header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html");
|
||||
@ -114,13 +120,13 @@ public class HttpUtilsTest {
|
||||
InputStream contentStream = entity.getContent();
|
||||
byte[] bytes = new byte[contentStream.available()];
|
||||
contentStream.read(bytes);
|
||||
Assert.assertArrayEquals(new byte[] {0, 1, 0, 1}, bytes);
|
||||
Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
assertArrayEquals(new byte[] {0, 1, 0, 1}, bytes);
|
||||
assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestEntity2() throws Exception {
|
||||
void testInitRequestEntity2() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
Header header = Header.newInstance();
|
||||
header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html");
|
||||
@ -131,13 +137,13 @@ public class HttpUtilsTest {
|
||||
InputStream contentStream = entity.getContent();
|
||||
byte[] bytes = new byte[contentStream.available()];
|
||||
contentStream.read(bytes);
|
||||
Assert.assertEquals("{\"k\":\"v\"}", new String(bytes, Constants.ENCODE));
|
||||
Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
assertEquals("{\"k\":\"v\"}", new String(bytes, Constants.ENCODE));
|
||||
assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestEntity3() throws Exception {
|
||||
void testInitRequestEntity3() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
Header header = Header.newInstance();
|
||||
header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html");
|
||||
@ -148,35 +154,35 @@ public class HttpUtilsTest {
|
||||
InputStream contentStream = entity.getContent();
|
||||
byte[] bytes = new byte[contentStream.available()];
|
||||
contentStream.read(bytes);
|
||||
Assert.assertEquals("common text", new String(bytes, Constants.ENCODE));
|
||||
Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
assertEquals("common text", new String(bytes, Constants.ENCODE));
|
||||
assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName());
|
||||
assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestEntity4() throws Exception {
|
||||
void testInitRequestEntity4() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
|
||||
HttpUtils.initRequestEntity(httpRequest, null, null);
|
||||
|
||||
// nothing change
|
||||
Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
Assert.assertArrayEquals(new BaseHttpMethod.HttpGetWithEntity("").getAllHeaders(), httpRequest.getAllHeaders());
|
||||
assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
assertArrayEquals(new BaseHttpMethod.HttpGetWithEntity("").getAllHeaders(), httpRequest.getAllHeaders());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestEntity5() throws Exception {
|
||||
void testInitRequestEntity5() throws Exception {
|
||||
HttpDelete httpDelete = new HttpDelete("");
|
||||
|
||||
HttpUtils.initRequestEntity(httpDelete, null, null);
|
||||
|
||||
// nothing change
|
||||
Assert.assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod());
|
||||
Assert.assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders());
|
||||
assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod());
|
||||
assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestFromEntity1() throws Exception {
|
||||
void testInitRequestFromEntity1() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
|
||||
HttpUtils.initRequestFromEntity(httpRequest, Collections.singletonMap("k", "v"), "UTF-8");
|
||||
@ -185,72 +191,72 @@ public class HttpUtilsTest {
|
||||
InputStream contentStream = entity.getContent();
|
||||
byte[] bytes = new byte[contentStream.available()];
|
||||
contentStream.read(bytes);
|
||||
Assert.assertEquals("k=v", new String(bytes, StandardCharsets.UTF_8));
|
||||
assertEquals("k=v", new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestFromEntity2() throws Exception {
|
||||
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());
|
||||
assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestFromEntity3() throws Exception {
|
||||
void testInitRequestFromEntity3() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
|
||||
HttpUtils.initRequestFromEntity(httpRequest, Collections.emptyMap(), "UTF-8");
|
||||
|
||||
// nothing change
|
||||
Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestFromEntity4() throws Exception {
|
||||
void testInitRequestFromEntity4() throws Exception {
|
||||
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
|
||||
|
||||
HttpUtils.initRequestFromEntity(mock(HttpRequestBase.class), Collections.emptyMap(), "UTF-8");
|
||||
|
||||
// nothing change
|
||||
Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitRequestFromEntity5() throws Exception {
|
||||
void testInitRequestFromEntity5() throws Exception {
|
||||
HttpDelete httpDelete = new HttpDelete("");
|
||||
|
||||
HttpUtils.initRequestFromEntity(httpDelete, Collections.singletonMap("k", "v"), "UTF-8");
|
||||
|
||||
// nothing change
|
||||
Assert.assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod());
|
||||
Assert.assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders());
|
||||
assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod());
|
||||
assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateParameterMap() throws Exception {
|
||||
void testTranslateParameterMap() throws Exception {
|
||||
Map<String, String[]> map = Collections.singletonMap("K", new String[] {"V1", "V2"});
|
||||
Map<String, String> resultMap = HttpUtils.translateParameterMap(map);
|
||||
Assert.assertEquals(Collections.singletonMap("K", "V1"), resultMap);
|
||||
assertEquals(Collections.singletonMap("K", "V1"), resultMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecode() throws UnsupportedEncodingException {
|
||||
void testDecode() throws UnsupportedEncodingException {
|
||||
// % - %25, { - %7B, } - %7D
|
||||
Assert.assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8"));
|
||||
Assert.assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8"));
|
||||
assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8"));
|
||||
assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodingParamsMapWithNullOrEmpty() throws UnsupportedEncodingException {
|
||||
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 {
|
||||
void testEncodingParamsMap() throws UnsupportedEncodingException {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("a", "");
|
||||
params.put("b", "x");
|
||||
@ -260,12 +266,12 @@ public class HttpUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodingParamsListWithNull() throws UnsupportedEncodingException {
|
||||
void testEncodingParamsListWithNull() throws UnsupportedEncodingException {
|
||||
assertNull(HttpUtils.encodingParams((List<String>) null, "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodingParamsList() throws UnsupportedEncodingException {
|
||||
void testEncodingParamsList() throws UnsupportedEncodingException {
|
||||
List<String> params = new LinkedList<>();
|
||||
params.add("a");
|
||||
params.add("");
|
||||
@ -279,7 +285,7 @@ public class HttpUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildUriForEmptyQuery() throws URISyntaxException {
|
||||
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());
|
||||
@ -287,7 +293,7 @@ public class HttpUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildUri() throws URISyntaxException {
|
||||
void testBuildUri() throws URISyntaxException {
|
||||
Query query = new Query();
|
||||
query.addParam("a", "");
|
||||
query.addParam("b", "x");
|
||||
@ -298,7 +304,7 @@ public class HttpUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsTimeoutException() {
|
||||
void testIsTimeoutException() {
|
||||
assertFalse(HttpUtils.isTimeoutException(new NacosRuntimeException(0)));
|
||||
assertTrue(HttpUtils.isTimeoutException(new TimeoutException()));
|
||||
assertTrue(HttpUtils.isTimeoutException(new SocketTimeoutException()));
|
||||
|
@ -21,50 +21,49 @@ import com.alibaba.nacos.common.http.client.handler.ResponseHandler;
|
||||
import com.alibaba.nacos.common.http.client.handler.RestResultResponseHandler;
|
||||
import com.alibaba.nacos.common.http.client.handler.StringResponseHandler;
|
||||
import com.alibaba.nacos.common.model.RestResult;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AbstractNacosRestTemplateTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AbstractNacosRestTemplateTest {
|
||||
|
||||
MockNacosRestTemplate restTemplate;
|
||||
|
||||
@Mock
|
||||
private ResponseHandler mockResponseHandler;
|
||||
|
||||
MockNacosRestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
restTemplate = new MockNacosRestTemplate(null);
|
||||
restTemplate.registerResponseHandler(MockNacosRestTemplate.class.getName(), mockResponseHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectResponseHandlerForNull() {
|
||||
void testSelectResponseHandlerForNull() {
|
||||
assertTrue(restTemplate.testFindResponseHandler(null) instanceof StringResponseHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectResponseHandlerForRestResult() {
|
||||
void testSelectResponseHandlerForRestResult() {
|
||||
assertTrue(restTemplate.testFindResponseHandler(RestResult.class) instanceof RestResultResponseHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectResponseHandlerForDefault() {
|
||||
assertTrue(restTemplate
|
||||
.testFindResponseHandler(AbstractNacosRestTemplateTest.class) instanceof BeanResponseHandler);
|
||||
void testSelectResponseHandlerForDefault() {
|
||||
assertTrue(restTemplate.testFindResponseHandler(AbstractNacosRestTemplateTest.class) instanceof BeanResponseHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectResponseHandlerForCustom() {
|
||||
void testSelectResponseHandlerForCustom() {
|
||||
assertEquals(mockResponseHandler, restTemplate.testFindResponseHandler(MockNacosRestTemplate.class));
|
||||
}
|
||||
|
||||
|
@ -21,23 +21,29 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.http.param.Query;
|
||||
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class InterceptingHttpClientRequestTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class InterceptingHttpClientRequestTest {
|
||||
|
||||
InterceptingHttpClientRequest clientRequest;
|
||||
|
||||
@Mock
|
||||
private HttpClientRequest httpClientRequest;
|
||||
@ -51,10 +57,8 @@ public class InterceptingHttpClientRequestTest {
|
||||
@Mock
|
||||
private HttpClientResponse httpClientResponse;
|
||||
|
||||
InterceptingHttpClientRequest clientRequest;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
List<HttpClientRequestInterceptor> interceptorList = new LinkedList<>();
|
||||
interceptorList.add(interceptor);
|
||||
clientRequest = new InterceptingHttpClientRequest(httpClientRequest, interceptorList.listIterator());
|
||||
@ -62,23 +66,23 @@ public class InterceptingHttpClientRequestTest {
|
||||
when(httpClientRequest.execute(any(), any(), any())).thenReturn(httpClientResponse);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
clientRequest.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteIntercepted() throws Exception {
|
||||
void testExecuteIntercepted() throws Exception {
|
||||
when(interceptor.isIntercept(any(), any(), any())).thenReturn(true);
|
||||
HttpClientResponse response = clientRequest
|
||||
.execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||
HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET",
|
||||
new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||
assertEquals(interceptorResponse, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteNotIntercepted() throws Exception {
|
||||
HttpClientResponse response = clientRequest
|
||||
.execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||
void testExecuteNotIntercepted() throws Exception {
|
||||
HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET",
|
||||
new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
|
||||
assertEquals(httpClientResponse, response);
|
||||
}
|
||||
}
|
@ -22,25 +22,25 @@ import com.alibaba.nacos.common.http.client.request.AsyncHttpClientRequest;
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.http.param.MediaType;
|
||||
import com.alibaba.nacos.common.http.param.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NacosAsyncRestTemplateTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NacosAsyncRestTemplateTest {
|
||||
|
||||
private static final String TEST_URL = "http://127.0.0.1:8848/nacos/test";
|
||||
|
||||
@ -55,25 +55,25 @@ public class NacosAsyncRestTemplateTest {
|
||||
|
||||
private NacosAsyncRestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
restTemplate = new NacosAsyncRestTemplate(logger, requestClient);
|
||||
when(logger.isDebugEnabled()).thenReturn(true);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
restTemplate.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGet() throws Exception {
|
||||
void testGet() throws Exception {
|
||||
restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetWithException() throws Exception {
|
||||
void testGetWithException() throws Exception {
|
||||
doThrow(new RuntimeException("test")).when(requestClient).execute(any(), any(), any(), any(), any());
|
||||
restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback));
|
||||
@ -81,31 +81,31 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLarge() throws Exception {
|
||||
void testGetLarge() throws Exception {
|
||||
restTemplate.getLarge(TEST_URL, Header.EMPTY, Query.EMPTY, new Object(), String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("GET-LARGE"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteWithBody() throws Exception {
|
||||
void testDeleteWithBody() throws Exception {
|
||||
restTemplate.delete(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("DELETE"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteLarge() throws Exception {
|
||||
void testDeleteLarge() throws Exception {
|
||||
restTemplate.delete(TEST_URL, Header.EMPTY, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("DELETE_LARGE"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPut() throws Exception {
|
||||
void testPut() throws Exception {
|
||||
restTemplate.put(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutJson() throws Exception {
|
||||
void testPutJson() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.putJson(TEST_URL, header, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||
@ -113,7 +113,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutJsonWithQuery() throws Exception {
|
||||
void testPutJsonWithQuery() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.putJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||
@ -121,7 +121,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutForm() throws Exception {
|
||||
void testPutForm() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.putForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||
@ -129,7 +129,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutFormWithQuery() throws Exception {
|
||||
void testPutFormWithQuery() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.putForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback));
|
||||
@ -137,13 +137,13 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPost() throws Exception {
|
||||
void testPost() throws Exception {
|
||||
restTemplate.post(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostJson() throws Exception {
|
||||
void testPostJson() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.postJson(TEST_URL, header, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||
@ -151,7 +151,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostJsonWithQuery() throws Exception {
|
||||
void testPostJsonWithQuery() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.postJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||
@ -159,7 +159,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostForm() throws Exception {
|
||||
void testPostForm() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.postForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||
@ -167,7 +167,7 @@ public class NacosAsyncRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostFormWithQuery() throws Exception {
|
||||
void testPostFormWithQuery() throws Exception {
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
restTemplate.postForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback);
|
||||
verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback));
|
||||
|
@ -24,27 +24,32 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.http.param.MediaType;
|
||||
import com.alibaba.nacos.common.http.param.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NacosRestTemplateTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class NacosRestTemplateTest {
|
||||
|
||||
@Mock
|
||||
private HttpClientRequest requestClient;
|
||||
@ -60,8 +65,8 @@ public class NacosRestTemplateTest {
|
||||
|
||||
private NacosRestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
restTemplate = new NacosRestTemplate(logger, requestClient);
|
||||
when(logger.isDebugEnabled()).thenReturn(true);
|
||||
when(mockResponse.getHeaders()).thenReturn(Header.EMPTY);
|
||||
@ -69,111 +74,112 @@ public class NacosRestTemplateTest {
|
||||
when(interceptor.intercept()).thenReturn(mockResponse);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
restTemplate.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetWithDefaultConfig() throws Exception {
|
||||
void testGetWithDefaultConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||
HttpRestResult<String> result = restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetWithCustomConfig() throws Exception {
|
||||
void testGetWithCustomConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.get("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class);
|
||||
HttpRestResult<String> result = restTemplate.get("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY,
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetWithInterceptor() throws Exception {
|
||||
void testGetWithInterceptor() throws Exception {
|
||||
when(mockResponse.getStatusCode()).thenReturn(300);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test interceptor".getBytes()));
|
||||
restTemplate.setInterceptors(Collections.singletonList(interceptor));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||
HttpRestResult<String> result = restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
String.class);
|
||||
assertFalse(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test interceptor", result.getMessage());
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void testGetWithException() throws Exception {
|
||||
when(requestClient.execute(any(), eq("GET"), any())).thenThrow(new RuntimeException("test"));
|
||||
restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||
@Test
|
||||
void testGetWithException() throws Exception {
|
||||
assertThrows(RuntimeException.class, () -> {
|
||||
when(requestClient.execute(any(), eq("GET"), any())).thenThrow(new RuntimeException("test"));
|
||||
restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLarge() throws Exception {
|
||||
void testGetLarge() throws Exception {
|
||||
when(requestClient.execute(any(), eq("GET-LARGE"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.getLarge("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.getLarge("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
new Object(), String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteWithDefaultConfig() throws Exception {
|
||||
void testDeleteWithDefaultConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.delete("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class);
|
||||
HttpRestResult<String> result = restTemplate.delete("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteWithCustomConfig() throws Exception {
|
||||
void testDeleteWithCustomConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.delete("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class);
|
||||
HttpRestResult<String> result = restTemplate.delete("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY,
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPut() throws Exception {
|
||||
void testPut() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.put("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.put("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
new Object(), String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutJson() throws Exception {
|
||||
void testPutJson() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.putJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||
HttpRestResult<String> result = restTemplate.putJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -181,13 +187,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutJsonWithQuery() throws Exception {
|
||||
void testPutJsonWithQuery() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.putJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class);
|
||||
HttpRestResult<String> result = restTemplate.putJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body",
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -195,13 +201,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutForm() throws Exception {
|
||||
void testPutForm() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.putForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(),
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -209,13 +215,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutFormWithQuery() throws Exception {
|
||||
void testPutFormWithQuery() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.putForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY,
|
||||
new HashMap<>(), String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -223,14 +229,14 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutFormWithConfig() throws Exception {
|
||||
void testPutFormWithConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.putForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(),
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -238,25 +244,24 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPost() throws Exception {
|
||||
void testPost() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.post("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.post("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY,
|
||||
new Object(), String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostJson() throws Exception {
|
||||
void testPostJson() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.postJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||
HttpRestResult<String> result = restTemplate.postJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -264,13 +269,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostJsonWithQuery() throws Exception {
|
||||
void testPostJsonWithQuery() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.postJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class);
|
||||
HttpRestResult<String> result = restTemplate.postJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body",
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -278,13 +283,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostForm() throws Exception {
|
||||
void testPostForm() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.postForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(),
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -292,13 +297,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostFormWithQuery() throws Exception {
|
||||
void testPostFormWithQuery() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.postForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY,
|
||||
new HashMap<>(), String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -306,14 +311,14 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostFormWithConfig() throws Exception {
|
||||
void testPostFormWithConfig() throws Exception {
|
||||
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.postForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class);
|
||||
HttpRestResult<String> result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(),
|
||||
String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -321,14 +326,13 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExchangeForm() throws Exception {
|
||||
void testExchangeForm() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML);
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.exchangeForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), "PUT",
|
||||
String.class);
|
||||
HttpRestResult<String> result = restTemplate.exchangeForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY,
|
||||
new HashMap<>(), "PUT", String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
@ -336,21 +340,20 @@ public class NacosRestTemplateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExchange() throws Exception {
|
||||
void testExchange() throws Exception {
|
||||
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
|
||||
when(mockResponse.getStatusCode()).thenReturn(200);
|
||||
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
|
||||
HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build();
|
||||
HttpRestResult<String> result = restTemplate
|
||||
.exchange("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, new Object(), "PUT",
|
||||
String.class);
|
||||
HttpRestResult<String> result = restTemplate.exchange("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY,
|
||||
Query.EMPTY, new Object(), "PUT", String.class);
|
||||
assertTrue(result.ok());
|
||||
assertEquals(Header.EMPTY, result.getHeader());
|
||||
assertEquals("test", result.getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetInterceptors() {
|
||||
void testGetInterceptors() {
|
||||
assertTrue(restTemplate.getInterceptors().isEmpty());
|
||||
restTemplate.setInterceptors(Collections.singletonList(interceptor));
|
||||
assertEquals(1, restTemplate.getInterceptors().size());
|
||||
|
@ -20,22 +20,22 @@ import com.alibaba.nacos.common.http.HttpRestResult;
|
||||
import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class BeanResponseHandlerTest {
|
||||
class BeanResponseHandlerTest {
|
||||
|
||||
@Test
|
||||
public void testConvertResult() throws Exception {
|
||||
void testConvertResult() throws Exception {
|
||||
List<Integer> testCase = new LinkedList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
testCase.add(i);
|
||||
|
@ -21,19 +21,19 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse;
|
||||
import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.model.RestResult;
|
||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class RestResultResponseHandlerTest {
|
||||
class RestResultResponseHandlerTest {
|
||||
|
||||
@Test
|
||||
public void testConvertResult() throws Exception {
|
||||
void testConvertResult() throws Exception {
|
||||
RestResult<String> testCase = RestResult.<String>builder().withCode(200).withData("ok").withMsg("msg").build();
|
||||
InputStream inputStream = new ByteArrayInputStream(JacksonUtils.toJsonBytes(testCase));
|
||||
HttpClientResponse response = mock(HttpClientResponse.class);
|
||||
|
@ -28,12 +28,12 @@ import org.apache.http.concurrent.FutureCallback;
|
||||
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
|
||||
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
|
||||
import org.apache.http.impl.nio.reactor.ExceptionEvent;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
@ -41,14 +41,16 @@ import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultAsyncHttpClientRequestTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DefaultAsyncHttpClientRequestTest {
|
||||
|
||||
DefaultAsyncHttpClientRequest httpClientRequest;
|
||||
|
||||
@Mock
|
||||
private CloseableHttpAsyncClient client;
|
||||
@ -64,24 +66,22 @@ public class DefaultAsyncHttpClientRequestTest {
|
||||
|
||||
private RequestConfig defaultConfig;
|
||||
|
||||
DefaultAsyncHttpClientRequest httpClientRequest;
|
||||
|
||||
private URI uri;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
defaultConfig = RequestConfig.DEFAULT;
|
||||
httpClientRequest = new DefaultAsyncHttpClientRequest(client, ioReactor, defaultConfig);
|
||||
uri = URI.create("http://127.0.0.1:8080");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
httpClientRequest.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteOnFail() throws Exception {
|
||||
void testExecuteOnFail() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
@ -96,7 +96,7 @@ public class DefaultAsyncHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteOnCancel() throws Exception {
|
||||
void testExecuteOnCancel() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
@ -110,7 +110,7 @@ public class DefaultAsyncHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteOnComplete() throws Exception {
|
||||
void testExecuteOnComplete() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
@ -127,7 +127,7 @@ public class DefaultAsyncHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteOnCompleteWithException() throws Exception {
|
||||
void testExecuteOnCompleteWithException() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
@ -144,7 +144,7 @@ public class DefaultAsyncHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteException() throws Exception {
|
||||
void testExecuteException() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
|
@ -29,24 +29,26 @@ import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultHttpClientRequestTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DefaultHttpClientRequestTest {
|
||||
|
||||
DefaultHttpClientRequest httpClientRequest;
|
||||
|
||||
@Mock
|
||||
private CloseableHttpClient client;
|
||||
@ -56,16 +58,14 @@ public class DefaultHttpClientRequestTest {
|
||||
|
||||
private RequestConfig defaultConfig;
|
||||
|
||||
DefaultHttpClientRequest httpClientRequest;
|
||||
|
||||
private boolean isForm;
|
||||
|
||||
private boolean withConfig;
|
||||
|
||||
private URI uri;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
defaultConfig = RequestConfig.DEFAULT;
|
||||
httpClientRequest = new DefaultHttpClientRequest(client, defaultConfig);
|
||||
when(client.execute(argThat(httpUriRequest -> {
|
||||
@ -81,18 +81,17 @@ public class DefaultHttpClientRequestTest {
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
isForm = false;
|
||||
withConfig = false;
|
||||
httpClientRequest.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteForFormWithoutConfig() throws Exception {
|
||||
void testExecuteForFormWithoutConfig() throws Exception {
|
||||
isForm = true;
|
||||
Header header = Header.newInstance()
|
||||
.addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||
Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body);
|
||||
@ -101,21 +100,19 @@ public class DefaultHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteForFormWithConfig() throws Exception {
|
||||
void testExecuteForFormWithConfig() throws Exception {
|
||||
isForm = true;
|
||||
withConfig = true;
|
||||
Header header = Header.newInstance()
|
||||
.addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||
Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("test", "test");
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(HttpClientConfig.builder().build(), header, Query.EMPTY,
|
||||
body);
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(HttpClientConfig.builder().build(), header, Query.EMPTY, body);
|
||||
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
|
||||
assertEquals(response, getActualResponse(actual));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteForOther() throws Exception {
|
||||
void testExecuteForOther() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, "body");
|
||||
HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity);
|
||||
|
@ -23,12 +23,14 @@ import com.alibaba.nacos.common.http.param.Header;
|
||||
import com.alibaba.nacos.common.http.param.MediaType;
|
||||
import com.alibaba.nacos.common.http.param.Query;
|
||||
import com.alibaba.nacos.common.model.RequestHttpEntity;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
@ -39,7 +41,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@ -47,8 +49,12 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JdkHttpClientRequestTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class JdkHttpClientRequestTest {
|
||||
|
||||
JdkHttpClientRequest httpClientRequest;
|
||||
|
||||
@Mock
|
||||
private HttpURLConnection connection;
|
||||
@ -62,12 +68,10 @@ public class JdkHttpClientRequestTest {
|
||||
@Mock
|
||||
private OutputStream outputStream;
|
||||
|
||||
JdkHttpClientRequest httpClientRequest;
|
||||
|
||||
private HttpClientConfig httpClientConfig;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
when(uri.toURL()).thenReturn(url);
|
||||
when(url.openConnection()).thenReturn(connection);
|
||||
when(connection.getOutputStream()).thenReturn(outputStream);
|
||||
@ -75,13 +79,13 @@ public class JdkHttpClientRequestTest {
|
||||
httpClientRequest = new JdkHttpClientRequest(httpClientConfig);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
httpClientRequest.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteNormal() throws Exception {
|
||||
void testExecuteNormal() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
HttpClientConfig config = HttpClientConfig.builder().build();
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, "a=bo&dy");
|
||||
@ -92,7 +96,7 @@ public class JdkHttpClientRequestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteForm() throws Exception {
|
||||
void testExecuteForm() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
HttpClientConfig config = HttpClientConfig.builder().build();
|
||||
@ -100,14 +104,13 @@ public class JdkHttpClientRequestTest {
|
||||
body.put("a", "bo&dy");
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, body);
|
||||
HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity);
|
||||
byte[] writeBytes = HttpUtils.encodingParams(body, StandardCharsets.UTF_8.name())
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] writeBytes = HttpUtils.encodingParams(body, StandardCharsets.UTF_8.name()).getBytes(StandardCharsets.UTF_8);
|
||||
verify(outputStream).write(writeBytes, 0, writeBytes.length);
|
||||
assertEquals(connection, getActualConnection(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteEmptyBody() throws Exception {
|
||||
void testExecuteEmptyBody() throws Exception {
|
||||
Header header = Header.newInstance();
|
||||
RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY);
|
||||
HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity);
|
||||
@ -116,8 +119,7 @@ public class JdkHttpClientRequestTest {
|
||||
|
||||
}
|
||||
|
||||
private HttpURLConnection getActualConnection(HttpClientResponse actual)
|
||||
throws IllegalAccessException, NoSuchFieldException {
|
||||
private HttpURLConnection getActualConnection(HttpClientResponse actual) throws IllegalAccessException, NoSuchFieldException {
|
||||
Field field = actual.getClass().getDeclaredField("conn");
|
||||
field.setAccessible(true);
|
||||
return (HttpURLConnection) field.get(actual);
|
||||
|
@ -20,21 +20,27 @@ import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.StatusLine;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultClientHttpResponseTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class DefaultClientHttpResponseTest {
|
||||
|
||||
DefaultClientHttpResponse clientHttpResponse;
|
||||
|
||||
@Mock
|
||||
private HttpResponse response;
|
||||
@ -51,10 +57,8 @@ public class DefaultClientHttpResponseTest {
|
||||
@Mock
|
||||
private Header header;
|
||||
|
||||
DefaultClientHttpResponse clientHttpResponse;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
when(httpEntity.getContent()).thenReturn(inputStream);
|
||||
when(response.getEntity()).thenReturn(httpEntity);
|
||||
when(response.getStatusLine()).thenReturn(statusLine);
|
||||
@ -64,36 +68,36 @@ public class DefaultClientHttpResponseTest {
|
||||
clientHttpResponse = new DefaultClientHttpResponse(response);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
clientHttpResponse.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStatusCode() {
|
||||
void testGetStatusCode() {
|
||||
when(statusLine.getStatusCode()).thenReturn(200);
|
||||
assertEquals(200, clientHttpResponse.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStatusText() {
|
||||
void testGetStatusText() {
|
||||
when(statusLine.getReasonPhrase()).thenReturn("test");
|
||||
assertEquals("test", clientHttpResponse.getStatusText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetHeaders() {
|
||||
void testGetHeaders() {
|
||||
assertEquals(3, clientHttpResponse.getHeaders().getHeader().size());
|
||||
assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBody() throws IOException {
|
||||
void testGetBody() throws IOException {
|
||||
assertEquals(inputStream, clientHttpResponse.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseResponseWithException() {
|
||||
void testCloseResponseWithException() {
|
||||
when(response.getEntity()).thenThrow(new RuntimeException("test"));
|
||||
clientHttpResponse.close();
|
||||
}
|
||||
|
@ -18,12 +18,14 @@ package com.alibaba.nacos.common.http.client.response;
|
||||
|
||||
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||
import com.alibaba.nacos.common.utils.IoUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
@ -35,11 +37,15 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JdkClientHttpResponseTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class JdkClientHttpResponseTest {
|
||||
|
||||
JdkHttpClientResponse clientHttpResponse;
|
||||
|
||||
@Mock
|
||||
private HttpURLConnection connection;
|
||||
@ -49,47 +55,45 @@ public class JdkClientHttpResponseTest {
|
||||
|
||||
private Map<String, List<String>> headers;
|
||||
|
||||
JdkHttpClientResponse clientHttpResponse;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
headers = new HashMap<>();
|
||||
headers.put("testName", Collections.singletonList("testValue"));
|
||||
when(connection.getHeaderFields()).thenReturn(headers);
|
||||
clientHttpResponse = new JdkHttpClientResponse(connection);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
clientHttpResponse.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStatusCode() throws IOException {
|
||||
void testGetStatusCode() throws IOException {
|
||||
when(connection.getResponseCode()).thenReturn(200);
|
||||
assertEquals(200, clientHttpResponse.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStatusText() throws IOException {
|
||||
void testGetStatusText() throws IOException {
|
||||
when(connection.getResponseMessage()).thenReturn("test");
|
||||
assertEquals("test", clientHttpResponse.getStatusText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetHeaders() {
|
||||
void testGetHeaders() {
|
||||
assertEquals(3, clientHttpResponse.getHeaders().getHeader().size());
|
||||
assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBody() throws IOException {
|
||||
void testGetBody() throws IOException {
|
||||
when(connection.getInputStream()).thenReturn(inputStream);
|
||||
assertEquals(inputStream, clientHttpResponse.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBodyWithGzip() throws IOException {
|
||||
void testGetBodyWithGzip() throws IOException {
|
||||
byte[] testCase = IoUtils.tryCompress("test", StandardCharsets.UTF_8.name());
|
||||
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(testCase);
|
||||
when(connection.getInputStream()).thenReturn(byteArrayInputStream);
|
||||
|
@ -17,7 +17,7 @@
|
||||
package com.alibaba.nacos.common.http.param;
|
||||
|
||||
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
@ -25,13 +25,14 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class HeaderTest {
|
||||
class HeaderTest {
|
||||
|
||||
@Test
|
||||
public void testSetContentType() {
|
||||
void testSetContentType() {
|
||||
Header header = Header.newInstance();
|
||||
header.setContentType(null);
|
||||
assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE));
|
||||
@ -40,14 +41,14 @@ public class HeaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHeaderKyeIgnoreCase() {
|
||||
void testHeaderKyeIgnoreCase() {
|
||||
Header header = Header.newInstance();
|
||||
header.addParam("Content-Encoding", "gzip");
|
||||
assertEquals("gzip", header.getValue("content-encoding"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToList() {
|
||||
void testToList() {
|
||||
Header header = Header.newInstance();
|
||||
List<String> list = header.toList();
|
||||
assertTrue(list.contains(HttpHeaderConsts.CONTENT_TYPE));
|
||||
@ -59,7 +60,7 @@ public class HeaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAllForMap() {
|
||||
void testAddAllForMap() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("test1", "test2");
|
||||
map.put("test3", "test4");
|
||||
@ -71,7 +72,7 @@ public class HeaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAllForList() {
|
||||
void testAddAllForList() {
|
||||
List<String> list = new ArrayList<>(4);
|
||||
list.add("test1");
|
||||
list.add("test2");
|
||||
@ -84,18 +85,20 @@ public class HeaderTest {
|
||||
assertEquals(4, header.getHeader().size());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testAddAllForListWithWrongLength() {
|
||||
List<String> list = new ArrayList<>(3);
|
||||
list.add("test1");
|
||||
list.add("test2");
|
||||
list.add("test3");
|
||||
Header header = Header.newInstance();
|
||||
header.addAll(list);
|
||||
@Test
|
||||
void testAddAllForListWithWrongLength() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
List<String> list = new ArrayList<>(3);
|
||||
list.add("test1");
|
||||
list.add("test2");
|
||||
list.add("test3");
|
||||
Header header = Header.newInstance();
|
||||
header.addAll(list);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddOriginalResponseHeader() {
|
||||
void testAddOriginalResponseHeader() {
|
||||
List<String> list = new ArrayList<>(4);
|
||||
list.add("test1");
|
||||
list.add("test2");
|
||||
@ -109,7 +112,7 @@ public class HeaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCharset() {
|
||||
void testGetCharset() {
|
||||
Header header = Header.newInstance();
|
||||
assertEquals("UTF-8", header.getCharset());
|
||||
header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, null);
|
||||
@ -124,7 +127,7 @@ public class HeaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear() {
|
||||
void testClear() {
|
||||
Header header = Header.newInstance();
|
||||
header.addOriginalResponseHeader("test", Collections.singletonList("test"));
|
||||
assertEquals(3, header.getHeader().size());
|
||||
|
@ -16,19 +16,20 @@
|
||||
|
||||
package com.alibaba.nacos.common.http.param;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* MediaTypeTest.
|
||||
*
|
||||
* @author mai.jh
|
||||
*/
|
||||
public class MediaTypeTest {
|
||||
class MediaTypeTest {
|
||||
|
||||
@Test
|
||||
public void testValueOf() {
|
||||
void testValueOf() {
|
||||
MediaType mediaType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
String type = "application/x-www-form-urlencoded";
|
||||
String charset = "UTF-8";
|
||||
@ -38,7 +39,7 @@ public class MediaTypeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValueOf2() {
|
||||
void testValueOf2() {
|
||||
MediaType mediaType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED, "ISO-8859-1");
|
||||
String type = "application/x-www-form-urlencoded";
|
||||
String charset = "ISO-8859-1";
|
||||
@ -49,7 +50,7 @@ public class MediaTypeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValueOf3() {
|
||||
void testValueOf3() {
|
||||
MediaType mediaType = MediaType.valueOf("application/x-www-form-urlencoded", "ISO-8859-1");
|
||||
String type = "application/x-www-form-urlencoded";
|
||||
String charset = "ISO-8859-1";
|
||||
@ -59,13 +60,17 @@ public class MediaTypeTest {
|
||||
assertEquals(excepted, mediaType.toString());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testValueOfWithEmpty() {
|
||||
MediaType.valueOf("");
|
||||
@Test
|
||||
void testValueOfWithEmpty() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
MediaType.valueOf("");
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testValueOfWithEmpty2() {
|
||||
MediaType.valueOf("", "UTF-8");
|
||||
@Test
|
||||
void testValueOfWithEmpty2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
MediaType.valueOf("", "UTF-8");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -17,21 +17,21 @@
|
||||
package com.alibaba.nacos.common.http.param;
|
||||
|
||||
import com.alibaba.nacos.api.naming.CommonParams;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class QueryTest {
|
||||
class QueryTest {
|
||||
|
||||
@Test
|
||||
public void testInitParams() {
|
||||
void testInitParams() {
|
||||
Map<String, String> parameters = new LinkedHashMap<String, String>();
|
||||
parameters.put(CommonParams.NAMESPACE_ID, "namespace");
|
||||
parameters.put(CommonParams.SERVICE_NAME, "service");
|
||||
@ -48,17 +48,18 @@ public class QueryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddParams() throws Exception {
|
||||
void testAddParams() throws Exception {
|
||||
Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2");
|
||||
String s1 = query.toQueryUrl();
|
||||
String s2 = "key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name()) + "&key-2=" + URLEncoder
|
||||
.encode("value-2", StandardCharsets.UTF_8.name());
|
||||
String s2 =
|
||||
"key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name()) + "&key-2=" + URLEncoder.encode("value-2",
|
||||
StandardCharsets.UTF_8.name());
|
||||
assertEquals(s2, s1);
|
||||
assertEquals("value-1", query.getValue("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear() {
|
||||
void testClear() {
|
||||
Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2");
|
||||
assertFalse(query.isEmpty());
|
||||
assertEquals("value-1", query.getValue("key-1"));
|
||||
|
@ -17,38 +17,39 @@
|
||||
package com.alibaba.nacos.common.labels.impl;
|
||||
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* description.
|
||||
*
|
||||
* @author rong
|
||||
* @date 2024-02-29 20:13
|
||||
*/
|
||||
public class DefaultLabelsCollectorManagerTest {
|
||||
class DefaultLabelsCollectorManagerTest {
|
||||
|
||||
@Test
|
||||
public void tagV2LabelsCollectorTest() {
|
||||
void tagV2LabelsCollectorTest() {
|
||||
Properties properties = new Properties();
|
||||
properties.put(Constants.APP_CONN_LABELS_KEY, "k1=v1,gray=properties_pre");
|
||||
properties.put(Constants.CONFIG_GRAY_LABEL, "properties_after");
|
||||
DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager();
|
||||
Map<String, String> labels = defaultLabelsCollectorManager.getLabels(properties);
|
||||
Assert.assertEquals("properties_after", labels.get(Constants.CONFIG_GRAY_LABEL));
|
||||
Assert.assertEquals("v1", labels.get("k1"));
|
||||
assertEquals("properties_after", labels.get(Constants.CONFIG_GRAY_LABEL));
|
||||
assertEquals("v1", labels.get("k1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tagV2LabelsCollectorOrderTest() {
|
||||
void tagV2LabelsCollectorOrderTest() {
|
||||
Properties properties = new Properties();
|
||||
DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager();
|
||||
Map<String, String> labels = defaultLabelsCollectorManager.getLabels(properties);
|
||||
String test = labels.get("test");
|
||||
Assert.assertEquals("test2", test);
|
||||
assertEquals("test2", test);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,58 +16,58 @@
|
||||
|
||||
package com.alibaba.nacos.common.logging;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
public class NacosLoggingPropertiesTest {
|
||||
class NacosLoggingPropertiesTest {
|
||||
|
||||
NacosLoggingProperties loggingProperties;
|
||||
|
||||
Properties properties;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
properties = new Properties();
|
||||
loggingProperties = new NacosLoggingProperties("classpath:test.xml", properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLocationWithDefault() {
|
||||
void testGetLocationWithDefault() {
|
||||
assertEquals("classpath:test.xml", loggingProperties.getLocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLocationWithoutDefault() {
|
||||
void testGetLocationWithoutDefault() {
|
||||
properties.setProperty("nacos.logging.default.config.enabled", "false");
|
||||
assertNull(loggingProperties.getLocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLocationForSpecified() {
|
||||
void testGetLocationForSpecified() {
|
||||
properties.setProperty("nacos.logging.config", "classpath:specified-test.xml");
|
||||
properties.setProperty("nacos.logging.default.config.enabled", "false");
|
||||
assertEquals("classpath:specified-test.xml", loggingProperties.getLocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLocationForSpecifiedWithDefault() {
|
||||
void testGetLocationForSpecifiedWithDefault() {
|
||||
properties.setProperty("nacos.logging.config", "classpath:specified-test.xml");
|
||||
assertEquals("classpath:specified-test.xml", loggingProperties.getLocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetReloadInternal() {
|
||||
void testGetReloadInternal() {
|
||||
properties.setProperty("nacos.logging.reload.interval.seconds", "50000");
|
||||
assertEquals(50000L, loggingProperties.getReloadInternal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetValue() {
|
||||
void testGetValue() {
|
||||
properties.setProperty("test.key", "test.value");
|
||||
assertEquals("test.value", loggingProperties.getValue("test.key", "default.value"));
|
||||
properties.clear();
|
||||
|
@ -19,20 +19,20 @@ 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 org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RequestHttpEntityTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RequestHttpEntityTest {
|
||||
|
||||
Header header;
|
||||
|
||||
@ -42,8 +42,8 @@ public class RequestHttpEntityTest {
|
||||
|
||||
Object body;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
header = Header.newInstance();
|
||||
header.addParam("testHeader", "test");
|
||||
query = Query.newInstance();
|
||||
@ -53,7 +53,7 @@ public class RequestHttpEntityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructWithoutConfigAndBody() {
|
||||
void testConstructWithoutConfigAndBody() {
|
||||
RequestHttpEntity entity = new RequestHttpEntity(header, query);
|
||||
assertTrue(entity.isEmptyBody());
|
||||
assertNull(entity.getHttpClientConfig());
|
||||
@ -63,7 +63,7 @@ public class RequestHttpEntityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructWithoutConfigAndQuery() {
|
||||
void testConstructWithoutConfigAndQuery() {
|
||||
RequestHttpEntity entity = new RequestHttpEntity(header, body);
|
||||
assertFalse(entity.isEmptyBody());
|
||||
assertNull(entity.getHttpClientConfig());
|
||||
@ -73,7 +73,7 @@ public class RequestHttpEntityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructWithoutConfig() {
|
||||
void testConstructWithoutConfig() {
|
||||
RequestHttpEntity entity = new RequestHttpEntity(header, query, body);
|
||||
assertFalse(entity.isEmptyBody());
|
||||
assertNull(entity.getHttpClientConfig());
|
||||
@ -83,7 +83,7 @@ public class RequestHttpEntityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructFull() {
|
||||
void testConstructFull() {
|
||||
RequestHttpEntity entity = new RequestHttpEntity(clientConfig, header, query, body);
|
||||
assertFalse(entity.isEmptyBody());
|
||||
assertEquals(clientConfig, entity.getHttpClientConfig());
|
||||
|
@ -17,15 +17,15 @@
|
||||
package com.alibaba.nacos.common.model;
|
||||
|
||||
import com.alibaba.nacos.common.utils.JacksonUtils;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class RestResultTest {
|
||||
class RestResultTest {
|
||||
|
||||
@Test
|
||||
public void testSerialization() {
|
||||
void testSerialization() {
|
||||
RestResult<String> result = new RestResult<>(200, "test", "content");
|
||||
String json = JacksonUtils.toJson(result);
|
||||
assertTrue(json.contains("\"code\":200"));
|
||||
@ -34,7 +34,7 @@ public class RestResultTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeserialization() {
|
||||
void testDeserialization() {
|
||||
String json = "{\"code\":200,\"message\":\"test\",\"data\":\"content\"}";
|
||||
RestResult restResult = JacksonUtils.toObj(json, RestResult.class);
|
||||
assertEquals(200, restResult.getCode());
|
||||
|
@ -17,68 +17,68 @@
|
||||
package com.alibaba.nacos.common.model;
|
||||
|
||||
import com.alibaba.nacos.common.model.core.IResultCode;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class RestResultUtilsTest {
|
||||
class RestResultUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testSuccessWithDefault() {
|
||||
void testSuccessWithDefault() {
|
||||
RestResult<Object> restResult = RestResultUtils.success();
|
||||
assertRestResult(restResult, 200, null, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessWithData() {
|
||||
void testSuccessWithData() {
|
||||
RestResult<String> restResult = RestResultUtils.success("content");
|
||||
assertRestResult(restResult, 200, null, "content", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessWithMsg() {
|
||||
void testSuccessWithMsg() {
|
||||
RestResult<String> restResult = RestResultUtils.success("test", "content");
|
||||
assertRestResult(restResult, 200, "test", "content", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessWithCode() {
|
||||
void testSuccessWithCode() {
|
||||
RestResult<String> restResult = RestResultUtils.success(203, "content");
|
||||
assertRestResult(restResult, 203, null, "content", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedWithDefault() {
|
||||
void testFailedWithDefault() {
|
||||
RestResult<Object> restResult = RestResultUtils.failed();
|
||||
assertRestResult(restResult, 500, null, null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedWithMsg() {
|
||||
void testFailedWithMsg() {
|
||||
RestResult<String> restResult = RestResultUtils.failed("test");
|
||||
assertRestResult(restResult, 500, "test", null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedWithCode() {
|
||||
void testFailedWithCode() {
|
||||
RestResult<String> restResult = RestResultUtils.failed(400, "content");
|
||||
assertRestResult(restResult, 400, null, "content", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessWithFull() {
|
||||
void testSuccessWithFull() {
|
||||
RestResult<String> restResult = RestResultUtils.failed(400, "content", "test");
|
||||
assertRestResult(restResult, 400, "test", "content", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedWithMsgMethod() {
|
||||
void testFailedWithMsgMethod() {
|
||||
RestResult<String> restResult = RestResultUtils.failedWithMsg(400, "content");
|
||||
assertRestResult(restResult, 400, "content", null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildResult() {
|
||||
void testBuildResult() {
|
||||
IResultCode mockCode = new IResultCode() {
|
||||
@Override
|
||||
public int getCode() {
|
||||
|
@ -17,18 +17,19 @@
|
||||
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.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@ -37,22 +38,22 @@ import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultPublisherTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DefaultPublisherTest {
|
||||
|
||||
private DefaultPublisher publisher;
|
||||
|
||||
@Mock
|
||||
private Subscriber<MockEvent> subscriber;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
publisher = new DefaultPublisher();
|
||||
publisher.init(MockEvent.class, 1);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
try {
|
||||
publisher.shutdown();
|
||||
} catch (Exception ignored) {
|
||||
@ -60,29 +61,31 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitWithIllegalSize() {
|
||||
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
|
||||
void testCheckIsStart() {
|
||||
assertThrows(IllegalStateException.class, () -> {
|
||||
publisher.shutdown();
|
||||
publisher = new DefaultPublisher();
|
||||
publisher.checkIsStart();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCurrentEventSize() {
|
||||
void testCurrentEventSize() {
|
||||
assertEquals(0, publisher.currentEventSize());
|
||||
publisher.publish(new MockEvent());
|
||||
assertEquals(1, publisher.currentEventSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveSubscriber() {
|
||||
void testRemoveSubscriber() {
|
||||
publisher.addSubscriber(subscriber);
|
||||
assertEquals(1, publisher.getSubscribers().size());
|
||||
publisher.removeSubscriber(subscriber);
|
||||
@ -90,7 +93,7 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publishEventWhenQueueFull() {
|
||||
void publishEventWhenQueueFull() {
|
||||
// Stop the publisher thread to mock queue full.
|
||||
publisher.shutdown();
|
||||
publisher.publish(new MockEvent());
|
||||
@ -109,7 +112,7 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publishEventQueueNotFull() throws InterruptedException {
|
||||
void publishEventQueueNotFull() throws InterruptedException {
|
||||
when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true);
|
||||
MockEvent mockEvent = new MockEvent();
|
||||
// Make sure Publisher entry waiting subscribers.
|
||||
@ -131,7 +134,7 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleEventWithThrowable() throws InterruptedException {
|
||||
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);
|
||||
@ -141,7 +144,7 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleEventWithExecutor() throws InterruptedException {
|
||||
void testHandleEventWithExecutor() throws InterruptedException {
|
||||
Executor executor = mock(Executor.class);
|
||||
when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true);
|
||||
when(subscriber.executor()).thenReturn(executor);
|
||||
@ -152,7 +155,7 @@ public class DefaultPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReceiveEventWithException() throws InterruptedException {
|
||||
void testReceiveEventWithException() throws InterruptedException {
|
||||
Executor executor = mock(Executor.class);
|
||||
when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true);
|
||||
when(subscriber.executor()).thenThrow(new RuntimeException("test"));
|
||||
|
@ -17,25 +17,25 @@
|
||||
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.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.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 {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DefaultSharePublisherTest {
|
||||
|
||||
private static final AtomicLong TEST_SEQUENCE = new AtomicLong();
|
||||
|
||||
@ -47,19 +47,19 @@ public class DefaultSharePublisherTest {
|
||||
@Mock
|
||||
SmartSubscriber smartSubscriber2;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
defaultSharePublisher = new DefaultSharePublisher();
|
||||
defaultSharePublisher.init(SlowEvent.class, 2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
defaultSharePublisher.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveSubscribers() {
|
||||
void testRemoveSubscribers() {
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class);
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent2.class);
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class);
|
||||
@ -71,7 +71,7 @@ public class DefaultSharePublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReceiveEventWithoutSubscriber() {
|
||||
void testReceiveEventWithoutSubscriber() {
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class);
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class);
|
||||
defaultSharePublisher.receiveEvent(new SlowEvent() {
|
||||
@ -87,7 +87,7 @@ public class DefaultSharePublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReceiveEventWithSubscriber() {
|
||||
void testReceiveEventWithSubscriber() {
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class);
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class);
|
||||
defaultSharePublisher.receiveEvent(new MockSlowEvent1());
|
||||
@ -99,7 +99,7 @@ public class DefaultSharePublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIgnoreExpiredEvent() throws InterruptedException {
|
||||
void testIgnoreExpiredEvent() throws InterruptedException {
|
||||
MockSlowEvent1 mockSlowEvent1 = new MockSlowEvent1();
|
||||
MockSlowEvent2 mockSlowEvent2 = new MockSlowEvent2();
|
||||
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class);
|
||||
|
@ -20,13 +20,12 @@ 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.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
@ -36,23 +35,24 @@ import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.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 {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NotifyCenterTest {
|
||||
|
||||
private static AtomicInteger count;
|
||||
|
||||
static {
|
||||
System.setProperty("nacos.core.notify.share-buffer-size", "8");
|
||||
}
|
||||
|
||||
private static AtomicInteger count;
|
||||
|
||||
SmartSubscriber smartSubscriber;
|
||||
|
||||
Subscriber subscriber;
|
||||
@ -60,8 +60,8 @@ public class NotifyCenterTest {
|
||||
@Mock
|
||||
ShardedEventPublisher shardedEventPublisher;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
count = new AtomicInteger();
|
||||
NotifyCenter.registerToSharePublisher(TestSlowEvent.class);
|
||||
NotifyCenter.registerToPublisher(TestSlowEvent1.class, 10);
|
||||
@ -70,8 +70,8 @@ public class NotifyCenterTest {
|
||||
NotifyCenter.registerToPublisher(SharedEvent.class, shardedEventPublisher);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
if (null != smartSubscriber) {
|
||||
NotifyCenter.deregisterSubscriber(smartSubscriber);
|
||||
}
|
||||
@ -83,45 +83,45 @@ public class NotifyCenterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterNullPublisher() {
|
||||
void testRegisterNullPublisher() {
|
||||
int originalSize = NotifyCenter.getPublisherMap().size();
|
||||
NotifyCenter.registerToPublisher(NoPublisherEvent.class, null);
|
||||
assertEquals(originalSize, NotifyCenter.getPublisherMap().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetPublisher() {
|
||||
void testGetPublisher() {
|
||||
assertEquals(NotifyCenter.getSharePublisher(), NotifyCenter.getPublisher(TestSlowEvent.class));
|
||||
assertTrue(NotifyCenter.getPublisher(TestEvent.class) instanceof DefaultPublisher);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEventsCanBeSubscribed() {
|
||||
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()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestEvent()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent()));
|
||||
ThreadUtils.sleep(2000L);
|
||||
assertEquals(2, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCanIgnoreExpireEvent() throws Exception {
|
||||
void testCanIgnoreExpireEvent() throws Exception {
|
||||
NotifyCenter.registerToPublisher(ExpireEvent.class, 16);
|
||||
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(3 - i)));
|
||||
assertTrue(NotifyCenter.publishEvent(new ExpireEvent(3 - i)));
|
||||
}
|
||||
latch.await(5000L, TimeUnit.MILLISECONDS);
|
||||
assertEquals(1, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSharePublishEvent() throws InterruptedException {
|
||||
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);
|
||||
@ -129,8 +129,8 @@ public class NotifyCenterTest {
|
||||
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()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1()));
|
||||
}
|
||||
latch.await(5000L, TimeUnit.MILLISECONDS);
|
||||
assertEquals(20, count.get());
|
||||
@ -141,7 +141,7 @@ public class NotifyCenterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception {
|
||||
void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception {
|
||||
List<Class<? extends Event>> subscribedEvents = new LinkedList<>();
|
||||
subscribedEvents.add(TestSlowEvent.class);
|
||||
subscribedEvents.add(TestSlowEvent1.class);
|
||||
@ -149,15 +149,15 @@ public class NotifyCenterTest {
|
||||
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()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1()));
|
||||
}
|
||||
latch.await(5000L, TimeUnit.MILLISECONDS);
|
||||
assertEquals(6, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception {
|
||||
void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception {
|
||||
List<Class<? extends Event>> subscribedEvents = new LinkedList<>();
|
||||
subscribedEvents.add(TestEvent.class);
|
||||
subscribedEvents.add(TestSlowEvent.class);
|
||||
@ -165,29 +165,29 @@ public class NotifyCenterTest {
|
||||
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()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestEvent()));
|
||||
assertTrue(NotifyCenter.publishEvent(new TestSlowEvent()));
|
||||
}
|
||||
latch.await(5000L, TimeUnit.MILLISECONDS);
|
||||
assertEquals(6, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPublishEventByNoPublisher() {
|
||||
void testPublishEventByNoPublisher() {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Assert.assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent()));
|
||||
assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPublishEventByPluginEvent() {
|
||||
void testPublishEventByPluginEvent() {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Assert.assertTrue(NotifyCenter.publishEvent(new PluginEvent()));
|
||||
assertTrue(NotifyCenter.publishEvent(new PluginEvent()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeregisterPublisherWithException() throws NacosException {
|
||||
void testDeregisterPublisherWithException() throws NacosException {
|
||||
final int originalSize = NotifyCenter.getPublisherMap().size();
|
||||
doThrow(new RuntimeException("test")).when(shardedEventPublisher).shutdown();
|
||||
NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher);
|
||||
@ -196,14 +196,14 @@ public class NotifyCenterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPublishEventWithException() {
|
||||
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() {
|
||||
void testOperateSubscriberForShardedPublisher() {
|
||||
subscriber = new MockSubscriber(SharedEvent.class, false);
|
||||
NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher);
|
||||
NotifyCenter.registerSubscriber(subscriber);
|
||||
@ -212,14 +212,16 @@ public class NotifyCenterTest {
|
||||
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;
|
||||
}
|
||||
@Test
|
||||
void testDeregisterNonExistSubscriber() {
|
||||
assertThrows(NoSuchElementException.class, () -> {
|
||||
try {
|
||||
subscriber = new MockSubscriber(NoPublisherEvent.class, false);
|
||||
NotifyCenter.deregisterSubscriber(subscriber);
|
||||
} finally {
|
||||
subscriber = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static class MockSubscriber<T extends Event> extends Subscriber<T> {
|
||||
@ -314,14 +316,14 @@ public class NotifyCenterTest {
|
||||
}
|
||||
|
||||
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;
|
||||
|
@ -21,11 +21,11 @@ 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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
@ -33,44 +33,44 @@ 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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.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 {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DefaultPackageScanTest {
|
||||
|
||||
@Mock
|
||||
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver;
|
||||
|
||||
DefaultPackageScan packageScan;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
packageScan = new DefaultPackageScan();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetSubTypesOf() {
|
||||
void testGetSubTypesOf() {
|
||||
packageScan = new DefaultPackageScan();
|
||||
Set<Class<MockClass>> subTypesOf = packageScan
|
||||
.getSubTypesOf(AnnotationClass.class.getPackage().getName(), MockClass.class);
|
||||
Set<Class<MockClass>> subTypesOf = packageScan.getSubTypesOf(AnnotationClass.class.getPackage().getName(),
|
||||
MockClass.class);
|
||||
assertEquals(3, subTypesOf.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTypesAnnotatedWith() {
|
||||
void testGetTypesAnnotatedWith() {
|
||||
packageScan = new DefaultPackageScan();
|
||||
Set<Class<Object>> actual = packageScan
|
||||
.getTypesAnnotatedWith(AnnotationClass.class.getPackage().getName(), TestScan.class);
|
||||
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 {
|
||||
void testGetSubTypesOfWithException() throws NoSuchFieldException, IllegalAccessException, IOException {
|
||||
setResolver();
|
||||
String path = AnnotationClass.class.getPackage().getName();
|
||||
when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test"));
|
||||
@ -79,7 +79,7 @@ public class DefaultPackageScanTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTypesAnnotatedWithException() throws NoSuchFieldException, IllegalAccessException, IOException {
|
||||
void testGetTypesAnnotatedWithException() throws NoSuchFieldException, IllegalAccessException, IOException {
|
||||
setResolver();
|
||||
String path = AnnotationClass.class.getPackage().getName();
|
||||
when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test"));
|
||||
@ -88,7 +88,7 @@ public class DefaultPackageScanTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClassVersionNotMatch() throws NoSuchFieldException, IllegalAccessException, IOException {
|
||||
void testClassVersionNotMatch() throws NoSuchFieldException, IllegalAccessException, IOException {
|
||||
setResolver();
|
||||
Resource resource = mock(Resource.class);
|
||||
byte[] testCase = new byte[8];
|
||||
|
@ -16,34 +16,34 @@
|
||||
|
||||
package com.alibaba.nacos.common.paramcheck;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class DefaultParamCheckerTest {
|
||||
class DefaultParamCheckerTest {
|
||||
|
||||
DefaultParamChecker paramChecker;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
paramChecker = new DefaultParamChecker();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckerType() {
|
||||
void testCheckerType() {
|
||||
assertEquals("default", paramChecker.getCheckerType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckEmptyParamInfoList() {
|
||||
void testCheckEmptyParamInfoList() {
|
||||
ParamCheckResponse actual = paramChecker.checkParamInfoList(null);
|
||||
assertTrue(actual.isSuccess());
|
||||
actual = paramChecker.checkParamInfoList(Collections.emptyList());
|
||||
@ -51,7 +51,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckEmptyParamInfo() {
|
||||
void testCheckEmptyParamInfo() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -61,7 +61,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForNamespaceShowName() {
|
||||
void testCheckParamInfoForNamespaceShowName() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -70,8 +70,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
assertEquals("Param 'namespaceShowName' is illegal, the param length should not exceed 256.", actual.getMessage());
|
||||
// Pattern
|
||||
paramInfo.setNamespaceShowName("hsbfkj@$!#khdkad");
|
||||
actual = paramChecker.checkParamInfoList(paramInfos);
|
||||
@ -85,7 +84,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForNamespaceId() {
|
||||
void testCheckParamInfoForNamespaceId() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -94,8 +93,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
assertEquals("Param 'namespaceId/tenant' is illegal, the param length should not exceed 64.", actual.getMessage());
|
||||
// Pattern
|
||||
paramInfo.setNamespaceId("hsbfkj@$!#khdkad");
|
||||
actual = paramChecker.checkParamInfoList(paramInfos);
|
||||
@ -109,7 +107,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForDataId() {
|
||||
void testCheckParamInfoForDataId() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -123,8 +121,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
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);
|
||||
@ -132,7 +129,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForServiceName() {
|
||||
void testCheckParamInfoForServiceName() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -146,8 +143,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
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);
|
||||
@ -155,7 +151,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForGroup() {
|
||||
void testCheckParamInfoForGroup() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -169,8 +165,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
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);
|
||||
@ -178,7 +173,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForClusters() {
|
||||
void testCheckParamInfoForClusters() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -192,8 +187,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
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);
|
||||
@ -201,7 +195,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForCluster() {
|
||||
void testCheckParamInfoForCluster() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -215,8 +209,7 @@ public class DefaultParamCheckerTest {
|
||||
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());
|
||||
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);
|
||||
@ -224,7 +217,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForIp() {
|
||||
void testCheckParamInfoForIp() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -246,7 +239,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForPort() {
|
||||
void testCheckParamInfoForPort() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
@ -272,7 +265,7 @@ public class DefaultParamCheckerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckParamInfoForMetadata() {
|
||||
void testCheckParamInfoForMetadata() {
|
||||
ParamInfo paramInfo = new ParamInfo();
|
||||
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
|
||||
paramInfos.add(paramInfo);
|
||||
|
@ -16,30 +16,30 @@
|
||||
|
||||
package com.alibaba.nacos.common.paramcheck;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ParamCheckerManagerTest {
|
||||
class ParamCheckerManagerTest {
|
||||
|
||||
@Test
|
||||
public void testGetParamCheckerNonExistType() {
|
||||
void testGetParamCheckerNonExistType() {
|
||||
assertTrue(ParamCheckerManager.getInstance().getParamChecker("non") instanceof DefaultParamChecker);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetParamCheckerNull() {
|
||||
void testGetParamCheckerNull() {
|
||||
assertTrue(ParamCheckerManager.getInstance().getParamChecker("") instanceof DefaultParamChecker);
|
||||
assertTrue(ParamCheckerManager.getInstance().getParamChecker(null) instanceof DefaultParamChecker);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetParamCheckerDefault() {
|
||||
void testGetParamCheckerDefault() {
|
||||
assertTrue(ParamCheckerManager.getInstance().getParamChecker("default") instanceof DefaultParamChecker);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetParamCheckerOther() {
|
||||
void testGetParamCheckerOther() {
|
||||
assertTrue(ParamCheckerManager.getInstance().getParamChecker("mock") instanceof MockParamChecker);
|
||||
}
|
||||
}
|
@ -17,21 +17,23 @@
|
||||
package com.alibaba.nacos.common.pathencoder;
|
||||
|
||||
import com.alibaba.nacos.common.pathencoder.impl.WindowsEncoder;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
public class PathEncoderManagerTest {
|
||||
class PathEncoderManagerTest {
|
||||
|
||||
private String cachedOsName;
|
||||
|
||||
@ -39,64 +41,64 @@ public class PathEncoderManagerTest {
|
||||
|
||||
private Object cachedEncoder;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
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 {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
System.setProperty("os.name", cachedOsName);
|
||||
targetEncoder.set(PathEncoderManager.getInstance(), cachedEncoder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitWithWindows()
|
||||
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);
|
||||
assertTrue(targetEncoder.get(instance) instanceof WindowsEncoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* test expose method.
|
||||
*/
|
||||
@Test
|
||||
public void testWindowsEncode() throws Exception {
|
||||
void testWindowsEncode() throws Exception {
|
||||
// load static
|
||||
PathEncoderManager instance = PathEncoderManager.getInstance();
|
||||
String case1 = "aa||a";
|
||||
String case2 = "aa%A9%%A9%a";
|
||||
// try to encode if in windows
|
||||
targetEncoder.set(instance, new WindowsEncoder());
|
||||
Assert.assertEquals(PathEncoderManager.getInstance().encode(case1), case2);
|
||||
Assert.assertEquals(PathEncoderManager.getInstance().decode(case2), case1);
|
||||
assertEquals(PathEncoderManager.getInstance().encode(case1), case2);
|
||||
assertEquals(PathEncoderManager.getInstance().decode(case2), case1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodeWithNonExistOs() throws Exception {
|
||||
void testEncodeWithNonExistOs() throws Exception {
|
||||
// load static
|
||||
PathEncoderManager instance = PathEncoderManager.getInstance();
|
||||
// remove impl
|
||||
targetEncoder.set(instance, null);
|
||||
// try to encode, non windows
|
||||
String case1 = "aa||a";
|
||||
Assert.assertEquals(PathEncoderManager.getInstance().encode(case1), case1);
|
||||
assertEquals(PathEncoderManager.getInstance().encode(case1), case1);
|
||||
String case2 = "aa%A9%%A9%a";
|
||||
Assert.assertEquals(PathEncoderManager.getInstance().decode(case2), case2);
|
||||
assertEquals(PathEncoderManager.getInstance().decode(case2), case2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodeForNull() throws IllegalAccessException {
|
||||
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));
|
||||
assertNull(PathEncoderManager.getInstance().encode(null));
|
||||
assertNull(PathEncoderManager.getInstance().decode(null));
|
||||
verify(mockPathEncoder, never()).encode(null, Charset.defaultCharset().name());
|
||||
verify(mockPathEncoder, never()).decode(null, Charset.defaultCharset().name());
|
||||
}
|
||||
|
@ -17,106 +17,112 @@
|
||||
package com.alibaba.nacos.common.pathencoder;
|
||||
|
||||
import com.alibaba.nacos.common.pathencoder.impl.WindowsEncoder;
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class WindowsEncoderTest extends TestCase {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class WindowsEncoderTest {
|
||||
|
||||
WindowsEncoder windowsEncoder = new WindowsEncoder();
|
||||
|
||||
|
||||
/**
|
||||
* test encode.
|
||||
*/
|
||||
public void testEncode() {
|
||||
@Test
|
||||
void testEncode() {
|
||||
String charset = Charset.defaultCharset().name();
|
||||
String case1 = "aaaadsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case1, charset), case1);
|
||||
assertEquals(windowsEncoder.encode(case1, charset), case1);
|
||||
// matches one
|
||||
String case2 = "aaaa\\dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case2, charset), "aaaa%A1%dsaknkf");
|
||||
assertEquals("aaaa%A1%dsaknkf", windowsEncoder.encode(case2, charset));
|
||||
String case3 = "aaaa/dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case3, charset), "aaaa%A2%dsaknkf");
|
||||
assertEquals("aaaa%A2%dsaknkf", windowsEncoder.encode(case3, charset));
|
||||
String case4 = "aaaa:dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case4, charset), "aaaa%A3%dsaknkf");
|
||||
assertEquals("aaaa%A3%dsaknkf", windowsEncoder.encode(case4, charset));
|
||||
String case5 = "aaaa*dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case5, charset), "aaaa%A4%dsaknkf");
|
||||
assertEquals("aaaa%A4%dsaknkf", windowsEncoder.encode(case5, charset));
|
||||
String case6 = "aaaa?dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case6, charset), "aaaa%A5%dsaknkf");
|
||||
assertEquals("aaaa%A5%dsaknkf", windowsEncoder.encode(case6, charset));
|
||||
String case7 = "aaaa\"dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case7, charset), "aaaa%A6%dsaknkf");
|
||||
assertEquals("aaaa%A6%dsaknkf", windowsEncoder.encode(case7, charset));
|
||||
String case8 = "aaaa<dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case8, charset), "aaaa%A7%dsaknkf");
|
||||
assertEquals("aaaa%A7%dsaknkf", windowsEncoder.encode(case8, charset));
|
||||
String case9 = "aaaa>dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case9, charset), "aaaa%A8%dsaknkf");
|
||||
assertEquals("aaaa%A8%dsaknkf", windowsEncoder.encode(case9, charset));
|
||||
String case10 = "aaaa|dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case10, charset), "aaaa%A9%dsaknkf");
|
||||
|
||||
assertEquals("aaaa%A9%dsaknkf", windowsEncoder.encode(case10, charset));
|
||||
|
||||
// matches more
|
||||
String case11 = "aaaa<dsa<>>knkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case11, charset), "aaaa%A7%dsa%A7%%A8%%A8%knkf");
|
||||
assertEquals("aaaa%A7%dsa%A7%%A8%%A8%knkf", windowsEncoder.encode(case11, charset));
|
||||
String case12 = "aaaa\"dsa\"\\\\knkf";
|
||||
Assert.assertEquals(windowsEncoder.encode(case12, charset), "aaaa%A6%dsa%A6%%A1%%A1%knkf");
|
||||
assertEquals("aaaa%A6%dsa%A6%%A1%%A1%knkf", windowsEncoder.encode(case12, charset));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* test decode.
|
||||
*/
|
||||
public void testDecode() {
|
||||
@Test
|
||||
void testDecode() {
|
||||
String charset = Charset.defaultCharset().name();
|
||||
String case1 = "aaaadsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case1, charset), case1);
|
||||
assertEquals(windowsEncoder.decode(case1, charset), case1);
|
||||
// matches one
|
||||
String case2 = "aaaa%A1%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case2, charset), "aaaa\\dsaknkf");
|
||||
assertEquals("aaaa\\dsaknkf", windowsEncoder.decode(case2, charset));
|
||||
String case3 = "aaaa%A2%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case3, charset), "aaaa/dsaknkf");
|
||||
assertEquals("aaaa/dsaknkf", windowsEncoder.decode(case3, charset));
|
||||
String case4 = "aaaa%A3%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case4, charset), "aaaa:dsaknkf");
|
||||
assertEquals("aaaa:dsaknkf", windowsEncoder.decode(case4, charset));
|
||||
String case5 = "aaaa%A4%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case5, charset), "aaaa*dsaknkf");
|
||||
assertEquals("aaaa*dsaknkf", windowsEncoder.decode(case5, charset));
|
||||
String case6 = "aaaa%A5%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case6, charset), "aaaa?dsaknkf");
|
||||
assertEquals("aaaa?dsaknkf", windowsEncoder.decode(case6, charset));
|
||||
String case7 = "aaaa%A6%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case7, charset), "aaaa\"dsaknkf");
|
||||
assertEquals("aaaa\"dsaknkf", windowsEncoder.decode(case7, charset));
|
||||
String case8 = "aaaa%A7%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case8, charset), "aaaa<dsaknkf");
|
||||
assertEquals("aaaa<dsaknkf", windowsEncoder.decode(case8, charset));
|
||||
String case9 = "aaaa%A8%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case9, charset), "aaaa>dsaknkf");
|
||||
assertEquals("aaaa>dsaknkf", windowsEncoder.decode(case9, charset));
|
||||
String case10 = "aaaa%A9%dsaknkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case10, charset), "aaaa|dsaknkf");
|
||||
|
||||
assertEquals("aaaa|dsaknkf", windowsEncoder.decode(case10, charset));
|
||||
|
||||
// matches more
|
||||
String case11 = "aaaa%A7%dsa%A7%%A8%%A8%knkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case11, charset), "aaaa<dsa<>>knkf");
|
||||
assertEquals("aaaa<dsa<>>knkf", windowsEncoder.decode(case11, charset));
|
||||
String case12 = "aaaa%A6%dsa%A6%%A1%%A1%knkf";
|
||||
Assert.assertEquals(windowsEncoder.decode(case12, charset), "aaaa\"dsa\"\\\\knkf");
|
||||
assertEquals("aaaa\"dsa\"\\\\knkf", windowsEncoder.decode(case12, charset));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* test needEncode.
|
||||
*/
|
||||
public void testNeedEncode() {
|
||||
String case1 = "aaaadsaknkf";
|
||||
@Test
|
||||
void testNeedEncode() {
|
||||
// / : ? " < > | \
|
||||
assertFalse(windowsEncoder.needEncode(null));
|
||||
String case1 = "aaaadsaknkf";
|
||||
assertFalse(windowsEncoder.needEncode(case1));
|
||||
String case2 = "?asda";
|
||||
assertTrue(windowsEncoder.needEncode(case2));
|
||||
String case3 = "/asdasd";
|
||||
assertTrue(windowsEncoder.needEncode(case3));
|
||||
String case4 = "as\\dasda";
|
||||
assertTrue(windowsEncoder.needEncode(case4));
|
||||
String case5 = "asd::as";
|
||||
assertTrue(windowsEncoder.needEncode(case5));
|
||||
String case6 = "sda\"sda";
|
||||
assertTrue(windowsEncoder.needEncode(case6));
|
||||
String case7 = "asdas<da";
|
||||
assertTrue(windowsEncoder.needEncode(case7));
|
||||
String case8 = "sdasas>a";
|
||||
assertTrue(windowsEncoder.needEncode(case8));
|
||||
String case9 = "das1|2e";
|
||||
Assert.assertFalse(windowsEncoder.needEncode(null));
|
||||
Assert.assertFalse(windowsEncoder.needEncode(case1));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case2));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case3));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case4));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case5));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case6));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case7));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case8));
|
||||
Assert.assertTrue(windowsEncoder.needEncode(case9));
|
||||
assertTrue(windowsEncoder.needEncode(case9));
|
||||
}
|
||||
}
|
||||
|
@ -16,16 +16,16 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
public class ConnectionTypeTest {
|
||||
class ConnectionTypeTest {
|
||||
|
||||
@Test
|
||||
public void testGetByType() {
|
||||
void testGetByType() {
|
||||
ConnectionType connectionType = ConnectionType.getByType("GRPC");
|
||||
assertNotNull(connectionType);
|
||||
assertEquals("GRPC", connectionType.getType());
|
||||
@ -33,7 +33,7 @@ public class ConnectionTypeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetByNonExistType() {
|
||||
void testGetByNonExistType() {
|
||||
ConnectionType connectionType = ConnectionType.getByType("HTTP");
|
||||
assertNull(connectionType);
|
||||
}
|
||||
|
@ -18,26 +18,29 @@ package com.alibaba.nacos.common.remote;
|
||||
|
||||
import com.alibaba.nacos.api.remote.request.Request;
|
||||
import com.alibaba.nacos.api.remote.response.ErrorResponse;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PayloadRegistryTest {
|
||||
class PayloadRegistryTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBefore() {
|
||||
@BeforeAll
|
||||
static void setUpBefore() {
|
||||
PayloadRegistry.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterInvalidClass() {
|
||||
void testRegisterInvalidClass() {
|
||||
PayloadRegistry.register("test", Request.class);
|
||||
assertNull(PayloadRegistry.getClassByType("test"));
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void testRegisterDuplicated() {
|
||||
PayloadRegistry.register("ErrorResponse", ErrorResponse.class);
|
||||
@Test
|
||||
void testRegisterDuplicated() {
|
||||
assertThrows(RuntimeException.class, () -> {
|
||||
PayloadRegistry.register("ErrorResponse", ErrorResponse.class);
|
||||
});
|
||||
}
|
||||
}
|
@ -16,17 +16,17 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TlsConfigTest {
|
||||
class TlsConfigTest {
|
||||
|
||||
@Test
|
||||
public void testTlsConfig() {
|
||||
void testTlsConfig() {
|
||||
TlsConfig tlsConfig = new TlsConfig();
|
||||
assertFalse(tlsConfig.getEnableTls());
|
||||
assertFalse(tlsConfig.getMutualAuthEnable());
|
||||
|
@ -23,23 +23,23 @@ import com.alibaba.nacos.api.remote.RequestCallBack;
|
||||
import com.alibaba.nacos.api.remote.RequestFuture;
|
||||
import com.alibaba.nacos.api.remote.request.Request;
|
||||
import com.alibaba.nacos.api.remote.response.Response;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ConnectionTest {
|
||||
class ConnectionTest {
|
||||
|
||||
Connection connection;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
connection = new Connection(new RpcClient.ServerInfo("127.0.0.1", 8848)) {
|
||||
@Override
|
||||
public Response request(Request request, long timeoutMills) throws NacosException {
|
||||
@ -61,20 +61,20 @@ public class ConnectionTest {
|
||||
};
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetConnectionId() {
|
||||
void testSetConnectionId() {
|
||||
assertNull(connection.getConnectionId());
|
||||
connection.setConnectionId("testConnectionId");
|
||||
assertEquals("testConnectionId", connection.getConnectionId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnectionAbility() {
|
||||
void testGetConnectionAbility() {
|
||||
assertFalse(connection.isAbilitiesSet());
|
||||
assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SDK_CLIENT_TEST_1));
|
||||
connection.setAbilityTable(Collections.singletonMap(AbilityKey.SERVER_TEST_2.getName(), true));
|
||||
@ -86,7 +86,7 @@ public class ConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetAbandon() {
|
||||
void testSetAbandon() {
|
||||
assertFalse(connection.isAbandon());
|
||||
connection.setAbandon(true);
|
||||
assertTrue(connection.isAbandon());
|
||||
|
@ -19,14 +19,13 @@ package com.alibaba.nacos.common.remote.client;
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import com.alibaba.nacos.common.remote.ConnectionType;
|
||||
import com.alibaba.nacos.common.utils.CollectionUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
@ -35,12 +34,16 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RpcClientFactoryTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RpcClientFactoryTest {
|
||||
|
||||
static Field clientMapField;
|
||||
|
||||
@ -53,8 +56,8 @@ public class RpcClientFactoryTest {
|
||||
@Mock(lenient = true)
|
||||
RpcClientTlsConfig rpcClientTlsConfig;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException {
|
||||
@BeforeAll
|
||||
static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException {
|
||||
clientMapField = RpcClientFactory.class.getDeclaredField("CLIENT_MAP");
|
||||
clientMapField.setAccessible(true);
|
||||
Field modifiersField1 = Field.class.getDeclaredField("modifiers");
|
||||
@ -62,136 +65,135 @@ public class RpcClientFactoryTest {
|
||||
modifiersField1.setInt(clientMapField, clientMapField.getModifiers() & ~Modifier.FINAL);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IllegalAccessException {
|
||||
@AfterEach
|
||||
void tearDown() throws IllegalAccessException {
|
||||
clientMapField.set(null, new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAllClientEntries() throws IllegalAccessException {
|
||||
Assert.assertTrue(RpcClientFactory.getAllClientEntries().isEmpty());
|
||||
void testGetAllClientEntries() throws IllegalAccessException {
|
||||
assertTrue(RpcClientFactory.getAllClientEntries().isEmpty());
|
||||
|
||||
clientMapField.set(null, Collections.singletonMap("testClient", rpcClient));
|
||||
Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDestroyClientWhenClientExistThenRemoveAndShutDownRpcClient()
|
||||
throws IllegalAccessException, NacosException {
|
||||
void testDestroyClientWhenClientExistThenRemoveAndShutDownRpcClient() throws IllegalAccessException, NacosException {
|
||||
clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient)));
|
||||
|
||||
RpcClientFactory.destroyClient("testClient");
|
||||
|
||||
Assert.assertTrue(RpcClientFactory.getAllClientEntries().isEmpty());
|
||||
assertTrue(RpcClientFactory.getAllClientEntries().isEmpty());
|
||||
verify(rpcClient).shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDestroyClientWhenClientNotExistThenDoNothing() throws IllegalAccessException, NacosException {
|
||||
void testDestroyClientWhenClientNotExistThenDoNothing() throws IllegalAccessException, NacosException {
|
||||
clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient)));
|
||||
|
||||
RpcClientFactory.destroyClient("notExistClientName");
|
||||
|
||||
Map.Entry<String, RpcClient> element = CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries());
|
||||
Assert.assertEquals("testClient", element.getKey());
|
||||
Assert.assertEquals(rpcClient, element.getValue());
|
||||
assertEquals("testClient", element.getKey());
|
||||
assertEquals(rpcClient, element.getValue());
|
||||
verify(rpcClient, times(0)).shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetClient() throws IllegalAccessException {
|
||||
void testGetClient() throws IllegalAccessException {
|
||||
// may be null
|
||||
Assert.assertNull(RpcClientFactory.getClient("notExistClientName"));
|
||||
assertNull(RpcClientFactory.getClient("notExistClientName"));
|
||||
|
||||
clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient)));
|
||||
Assert.assertEquals(rpcClient, RpcClientFactory.getClient("testClient"));
|
||||
assertEquals(rpcClient, RpcClientFactory.getClient("testClient"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClientWhenNotCreatedThenCreate() {
|
||||
void testCreateClientWhenNotCreatedThenCreate() {
|
||||
RpcClient client = RpcClientFactory.createClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
Map<String, String> labesMap = new HashMap<>();
|
||||
labesMap.put("labelKey", "labelValue");
|
||||
labesMap.put("tls.enable", "false");
|
||||
Assert.assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
Assert.assertEquals("testClient",
|
||||
CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClientWhenAlreadyCreatedThenNotCreateAgain() {
|
||||
void testCreateClientWhenAlreadyCreatedThenNotCreateAgain() {
|
||||
RpcClient client1 = RpcClientFactory.createClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
RpcClient client2 = RpcClientFactory.createClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
|
||||
Assert.assertEquals(client1, client2);
|
||||
Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void testCreatedClientWhenConnectionTypeNotMappingThenThrowException() {
|
||||
RpcClientFactory.createClient("testClient", mock(ConnectionType.class),
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
assertEquals(client1, client2);
|
||||
assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClusterClientWhenNotCreatedThenCreate() {
|
||||
void testCreatedClientWhenConnectionTypeNotMappingThenThrowException() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
RpcClientFactory.createClient("testClient", mock(ConnectionType.class),
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterClientWhenNotCreatedThenCreate() {
|
||||
RpcClient client = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
Map<String, String> labesMap = new HashMap<>();
|
||||
labesMap.put("labelKey", "labelValue");
|
||||
labesMap.put("tls.enable", "false");
|
||||
Assert.assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
Assert.assertEquals("testClient",
|
||||
CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClusterClientWhenAlreadyCreatedThenNotCreateAgain() {
|
||||
void testCreateClusterClientWhenAlreadyCreatedThenNotCreateAgain() {
|
||||
RpcClient client1 = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
RpcClient client2 = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
|
||||
Assert.assertEquals(client1, client2);
|
||||
Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void testCreatedClusterClientWhenConnectionTypeNotMappingThenThrowException() {
|
||||
RpcClientFactory.createClusterClient("testClient", mock(ConnectionType.class),
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
assertEquals(client1, client2);
|
||||
assertEquals(1, RpcClientFactory.getAllClientEntries().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClusterClientTsl() {
|
||||
void testCreatedClusterClientWhenConnectionTypeNotMappingThenThrowException() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
RpcClientFactory.createClusterClient("testClient", mock(ConnectionType.class),
|
||||
Collections.singletonMap("labelKey", "labelValue"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterClientTsl() {
|
||||
Mockito.when(clusterClientTlsConfig.getEnableTls()).thenReturn(true);
|
||||
RpcClient client = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"), clusterClientTlsConfig);
|
||||
Map<String, String> labesMap = new HashMap<>();
|
||||
labesMap.put("labelKey", "labelValue");
|
||||
labesMap.put("tls.enable", "true");
|
||||
Assert.assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
Assert.assertEquals("testClient",
|
||||
CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateClientTsl() {
|
||||
void testCreateClientTsl() {
|
||||
Mockito.when(rpcClientTlsConfig.getEnableTls()).thenReturn(true);
|
||||
RpcClient client = RpcClientFactory.createClient("testClient", ConnectionType.GRPC,
|
||||
Collections.singletonMap("labelKey", "labelValue"), rpcClientTlsConfig);
|
||||
Map<String, String> labesMap = new HashMap<>();
|
||||
labesMap.put("labelKey", "labelValue");
|
||||
labesMap.put("tls.enable", "true");
|
||||
Assert.assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
Assert.assertEquals("testClient",
|
||||
CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
assertEquals(labesMap, client.rpcClientConfig.labels());
|
||||
assertEquals(ConnectionType.GRPC, client.getConnectionType());
|
||||
assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey());
|
||||
}
|
||||
}
|
||||
|
@ -32,13 +32,12 @@ import com.alibaba.nacos.api.remote.response.Response;
|
||||
import com.alibaba.nacos.common.remote.ConnectionType;
|
||||
import com.alibaba.nacos.common.remote.client.grpc.DefaultGrpcClientConfig;
|
||||
import com.alibaba.nacos.common.remote.client.grpc.GrpcConnection;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
@ -57,11 +56,12 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
@ -74,8 +74,8 @@ import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RpcClientTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RpcClientTest {
|
||||
|
||||
RpcClient rpcClient;
|
||||
|
||||
@ -99,8 +99,8 @@ public class RpcClientTest {
|
||||
|
||||
RpcClientConfig rpcClientConfig;
|
||||
|
||||
@Before
|
||||
public void setUp() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException {
|
||||
@BeforeEach
|
||||
void setUp() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException {
|
||||
rpcClientConfig = spy(new RpcClientConfig() {
|
||||
@Override
|
||||
public String name() {
|
||||
@ -178,8 +178,8 @@ public class RpcClientTest {
|
||||
notInvoke = invocationOnMock -> null;
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IllegalAccessException, NacosException {
|
||||
@AfterEach
|
||||
void tearDown() throws IllegalAccessException, NacosException {
|
||||
rpcClientConfig.labels().clear();
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.WAIT_INIT);
|
||||
serverListFactoryField.set(rpcClient, null);
|
||||
@ -191,7 +191,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitServerListFactory() {
|
||||
void testInitServerListFactory() {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.WAIT_INIT);
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
assertEquals(RpcClientStatus.INITIALIZED, rpcClient.rpcClientStatus.get());
|
||||
@ -273,7 +273,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLabels() {
|
||||
void testLabels() {
|
||||
when(rpcClientConfig.labels()).thenReturn(Collections.singletonMap("labelKey1", "labelValue1"));
|
||||
Map.Entry<String, String> element = rpcClient.getLabels().entrySet().iterator().next();
|
||||
assertEquals("labelKey1", element.getKey());
|
||||
@ -288,7 +288,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOnServerListChangeWhenCurrentConnectionIsNullThenDoNothing() throws IllegalAccessException {
|
||||
void testOnServerListChangeWhenCurrentConnectionIsNullThenDoNothing() throws IllegalAccessException {
|
||||
int beforeSize = ((Queue<?>) reconnectionSignalField.get(rpcClient)).size();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
|
||||
@ -299,7 +299,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOnServerListChangeWhenServiceInfoIsNullThenDoNothing() throws IllegalAccessException {
|
||||
void testOnServerListChangeWhenServiceInfoIsNullThenDoNothing() throws IllegalAccessException {
|
||||
int beforeSize = ((Queue<?>) reconnectionSignalField.get(rpcClient)).size();
|
||||
rpcClient.currentConnection = mock(Connection.class);
|
||||
|
||||
@ -310,8 +310,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOnServerListChangeWhenCurrentConnectionIsNotInServerListThenSwitchServerAsync()
|
||||
throws IllegalAccessException {
|
||||
void testOnServerListChangeWhenCurrentConnectionIsNotInServerListThenSwitchServerAsync() throws IllegalAccessException {
|
||||
final int beforeSize = ((Queue<?>) reconnectionSignalField.get(rpcClient)).size();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
rpcClient.currentConnection = new GrpcConnection(new RpcClient.ServerInfo("10.10.10.10", 8848), null);
|
||||
@ -324,7 +323,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOnServerListChangeWhenCurrentConnectionIsInServerListThenDoNothing() throws IllegalAccessException {
|
||||
void testOnServerListChangeWhenCurrentConnectionIsInServerListThenDoNothing() throws IllegalAccessException {
|
||||
final int beforeSize = ((Queue<?>) reconnectionSignalField.get(rpcClient)).size();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
rpcClient.currentConnection = new GrpcConnection(new RpcClient.ServerInfo("10.10.10.10", 8848), null);
|
||||
@ -336,33 +335,30 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveServerInfo1() throws InvocationTargetException, IllegalAccessException {
|
||||
void testResolveServerInfo1() throws InvocationTargetException, IllegalAccessException {
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "10.10.10.10::8848")).getAddress());
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "10.10.10.10:8848")).getAddress());
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10:8848"))
|
||||
.getAddress());
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10:8848")).getAddress());
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10::8848"))
|
||||
.getAddress());
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10::8848")).getAddress());
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10")).getAddress());
|
||||
assertEquals("10.10.10.10:8848",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "https://10.10.10.10::8848"))
|
||||
.getAddress());
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "https://10.10.10.10::8848")).getAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveServerInfo2() throws InvocationTargetException, IllegalAccessException {
|
||||
void testResolveServerInfo2() throws InvocationTargetException, IllegalAccessException {
|
||||
System.setProperty("nacos.server.port", "4424");
|
||||
assertEquals("10.10.10.10:4424",
|
||||
((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10")).getAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestSuccess() throws NacosException, NoSuchFieldException, IllegalAccessException {
|
||||
void testRequestSuccess() throws NacosException, NoSuchFieldException, IllegalAccessException {
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
when(connection.request(any(), anyLong())).thenReturn(new HealthCheckResponse());
|
||||
@ -374,37 +370,45 @@ public class RpcClientTest {
|
||||
assertTrue(lastActiveTimeStamp <= (long) lastActiveTimeStampField.get(rpcClient));
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestWithoutAnyTry() throws NacosException {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.request(null);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.request(null);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestWhenTimeoutThenThrowException() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
doReturn(null).when(connection).request(any(), anyLong());
|
||||
rpcClient.request(null, 10000);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestWhenResponseErrorThenThrowException() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
doReturn(new ErrorResponse()).when(connection).request(any(), anyLong());
|
||||
rpcClient.request(null, 10000);
|
||||
@Test
|
||||
void testRequestWithoutAnyTry() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.request(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestWhenResponseUnregisterThenSwitchServer() throws NacosException {
|
||||
void testRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.request(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRequestWhenTimeoutThenThrowException() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
doReturn(null).when(connection).request(any(), anyLong());
|
||||
rpcClient.request(null, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRequestWhenResponseErrorThenThrowException() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
doReturn(new ErrorResponse()).when(connection).request(any(), anyLong());
|
||||
rpcClient.request(null, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRequestWhenResponseUnregisterThenSwitchServer() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
ErrorResponse errorResponse = new ErrorResponse();
|
||||
@ -420,11 +424,11 @@ public class RpcClientTest {
|
||||
|
||||
assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get());
|
||||
verify(rpcClient).switchServerAsync();
|
||||
Assert.assertNotNull(exception);
|
||||
assertNotNull(exception);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestSuccess() throws NacosException {
|
||||
void testAsyncRequestSuccess() throws NacosException {
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
RequestCallBack<?> requestCallBack = mock(RequestCallBack.class);
|
||||
@ -433,23 +437,27 @@ public class RpcClientTest {
|
||||
verify(connection).asyncRequest(any(), any());
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testAsyncRequestWithoutAnyTry() throws NacosException {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.asyncRequest(null, null);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testAsyncRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
RequestCallBack<?> requestCallBack = mock(RequestCallBack.class);
|
||||
doReturn(10000L).when(requestCallBack).getTimeout();
|
||||
rpcClient.asyncRequest(null, requestCallBack);
|
||||
@Test
|
||||
void testAsyncRequestWithoutAnyTry() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.asyncRequest(null, null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestWhenSendRequestFailedMannyTimesThenSwitchServer() throws NacosException {
|
||||
void testAsyncRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
RequestCallBack<?> requestCallBack = mock(RequestCallBack.class);
|
||||
doReturn(10000L).when(requestCallBack).getTimeout();
|
||||
rpcClient.asyncRequest(null, requestCallBack);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAsyncRequestWhenSendRequestFailedMannyTimesThenSwitchServer() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
rpcClient.currentConnection = connection;
|
||||
doThrow(new NacosException()).when(connection).asyncRequest(any(), any());
|
||||
@ -465,25 +473,29 @@ public class RpcClientTest {
|
||||
|
||||
verify(connection, atLeastOnce()).asyncRequest(any(), any());
|
||||
verify(rpcClient).switchServerAsyncOnRequestFail();
|
||||
Assert.assertNotNull(exception);
|
||||
assertNotNull(exception);
|
||||
assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get());
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestFutureWithoutAnyTry() throws NacosException {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.requestFuture(null);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestFutureWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.requestFuture(null);
|
||||
@Test
|
||||
void testRequestFutureWithoutAnyTry() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(-1);
|
||||
rpcClient.requestFuture(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestFutureWhenRetryReachMaxRetryTimesThenSwitchServer() throws NacosException {
|
||||
void testRequestFutureWhenClientAlreadyShutDownThenThrowException() throws NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.requestFuture(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRequestFutureWhenRetryReachMaxRetryTimesThenSwitchServer() throws NacosException {
|
||||
when(rpcClientConfig.timeOutMills()).thenReturn(5000L);
|
||||
when(rpcClientConfig.retryTimes()).thenReturn(3);
|
||||
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
|
||||
@ -499,12 +511,12 @@ public class RpcClientTest {
|
||||
|
||||
verify(connection, times(4)).requestFuture(any());
|
||||
verify(rpcClient).switchServerAsyncOnRequestFail();
|
||||
Assert.assertNotNull(exception);
|
||||
assertNotNull(exception);
|
||||
assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRpcClientShutdownWhenClientDidntStart() throws NacosException {
|
||||
void testRpcClientShutdownWhenClientDidntStart() throws NacosException {
|
||||
RpcClient rpcClient = new RpcClient(new RpcClientConfig() {
|
||||
@Override
|
||||
public String name() {
|
||||
@ -562,7 +574,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHealthCheck() throws IllegalAccessException, NacosException {
|
||||
void testHealthCheck() throws IllegalAccessException, NacosException {
|
||||
Random random = new Random();
|
||||
int retry = random.nextInt(10);
|
||||
when(rpcClientConfig.healthCheckRetryTimes()).thenReturn(retry);
|
||||
@ -578,7 +590,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForIpv4WithPort() {
|
||||
void testNextRpcServerForIpv4WithPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:7777");
|
||||
@ -589,7 +601,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForIpv4WithoutPort() {
|
||||
void testNextRpcServerForIpv4WithoutPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1");
|
||||
@ -600,7 +612,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForIpv6WithPort() {
|
||||
void testNextRpcServerForIpv6WithPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("[fe80::35ba:6827:c5ff:d161%11]:7777");
|
||||
@ -611,7 +623,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForIpv6WithoutPort() {
|
||||
void testNextRpcServerForIpv6WithoutPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("[fe80::35ba:6827:c5ff:d161%11]");
|
||||
@ -622,7 +634,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForDomainWithPort() {
|
||||
void testNextRpcServerForDomainWithPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("nacos.io:7777");
|
||||
@ -633,7 +645,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForDomainWithoutPort() {
|
||||
void testNextRpcServerForDomainWithoutPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("nacos.io");
|
||||
@ -644,7 +656,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForLocalhostWithPort() {
|
||||
void testNextRpcServerForLocalhostWithPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("localhost:7777");
|
||||
@ -655,7 +667,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextRpcServerForLocalhostWithoutPort() {
|
||||
void testNextRpcServerForLocalhostWithoutPort() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("localhost");
|
||||
@ -665,12 +677,14 @@ public class RpcClientTest {
|
||||
assertEquals(8848, actual.getServerPort());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testNextRpcServerForEmpty() {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("");
|
||||
rpcClient.nextRpcServer();
|
||||
@Test
|
||||
void testNextRpcServerForEmpty() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
when(serverListFactory.genNextServer()).thenReturn("");
|
||||
rpcClient.nextRpcServer();
|
||||
});
|
||||
}
|
||||
|
||||
private RpcClient buildTestNextRpcServerClient() {
|
||||
@ -697,29 +711,31 @@ public class RpcClientTest {
|
||||
};
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void testHandleServerRequestWhenExceptionThenThrowException() throws RuntimeException {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
Request request = new Request() {
|
||||
@Override
|
||||
public String getModule() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
rpcClient.serverRequestHandlers.add((req, conn) -> {
|
||||
throw new RuntimeException();
|
||||
@Test
|
||||
void testHandleServerRequestWhenExceptionThenThrowException() throws RuntimeException {
|
||||
assertThrows(RuntimeException.class, () -> {
|
||||
RpcClient rpcClient = buildTestNextRpcServerClient();
|
||||
Request request = new Request() {
|
||||
@Override
|
||||
public String getModule() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
rpcClient.serverRequestHandlers.add((req, conn) -> {
|
||||
throw new RuntimeException();
|
||||
});
|
||||
rpcClient.handleServerRequest(request);
|
||||
});
|
||||
rpcClient.handleServerRequest(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyDisConnectedForEmpty() {
|
||||
void testNotifyDisConnectedForEmpty() {
|
||||
rpcClient.notifyDisConnected(null);
|
||||
verify(rpcClientConfig, never()).name();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyDisConnected() {
|
||||
void testNotifyDisConnected() {
|
||||
ConnectionEventListener listener = mock(ConnectionEventListener.class);
|
||||
rpcClient.registerConnectionListener(listener);
|
||||
rpcClient.notifyDisConnected(null);
|
||||
@ -728,7 +744,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyDisConnectedException() {
|
||||
void testNotifyDisConnectedException() {
|
||||
ConnectionEventListener listener = mock(ConnectionEventListener.class);
|
||||
rpcClient.registerConnectionListener(listener);
|
||||
doThrow(new RuntimeException("test")).when(listener).onDisConnect(null);
|
||||
@ -737,13 +753,13 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyConnectedForEmpty() {
|
||||
void testNotifyConnectedForEmpty() {
|
||||
rpcClient.notifyConnected(null);
|
||||
verify(rpcClientConfig, never()).name();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyConnected() {
|
||||
void testNotifyConnected() {
|
||||
ConnectionEventListener listener = mock(ConnectionEventListener.class);
|
||||
rpcClient.registerConnectionListener(listener);
|
||||
rpcClient.notifyConnected(null);
|
||||
@ -752,7 +768,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyConnectedException() {
|
||||
void testNotifyConnectedException() {
|
||||
ConnectionEventListener listener = mock(ConnectionEventListener.class);
|
||||
rpcClient.registerConnectionListener(listener);
|
||||
doThrow(new RuntimeException("test")).when(listener).onConnected(null);
|
||||
@ -761,7 +777,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartClient() throws NacosException {
|
||||
void testStartClient() throws NacosException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(new Function<RpcClient.ServerInfo, Connection>() {
|
||||
@ -786,7 +802,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartClientWithFailed() throws NacosException, InterruptedException {
|
||||
void testStartClientWithFailed() throws NacosException, InterruptedException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
try {
|
||||
rpcClient.start();
|
||||
@ -798,7 +814,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartClientAfterShutdown() throws NacosException {
|
||||
void testStartClientAfterShutdown() throws NacosException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
rpcClient.shutdown();
|
||||
rpcClient.start();
|
||||
@ -806,7 +822,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisConnectionEventAfterStart() throws NacosException, InterruptedException {
|
||||
void testDisConnectionEventAfterStart() throws NacosException, InterruptedException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> connection);
|
||||
@ -824,7 +840,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithNullConnection() throws NacosException, InterruptedException {
|
||||
void testReconnectContextAfterStartWithNullConnection() throws NacosException, InterruptedException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
try {
|
||||
when(rpcClientConfig.connectionKeepAlive()).thenReturn(-1L);
|
||||
@ -837,8 +853,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithConnectionHealthCheckFail()
|
||||
throws NacosException, InterruptedException {
|
||||
void testReconnectContextAfterStartWithConnectionHealthCheckFail() throws NacosException, InterruptedException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(new Function<RpcClient.ServerInfo, Connection>() {
|
||||
@ -865,7 +880,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithConnectionHealthCheckSuccess()
|
||||
void testReconnectContextAfterStartWithConnectionHealthCheckSuccess()
|
||||
throws NacosException, InterruptedException, NoSuchFieldException, IllegalAccessException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
@ -887,7 +902,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithActiveTimeIsNew()
|
||||
void testReconnectContextAfterStartWithActiveTimeIsNew()
|
||||
throws NacosException, InterruptedException, NoSuchFieldException, IllegalAccessException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
@ -909,16 +924,15 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithOldServiceInfo()
|
||||
throws NacosException, InterruptedException, IllegalAccessException {
|
||||
void testReconnectContextAfterStartWithOldServiceInfo() throws NacosException, InterruptedException, IllegalAccessException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("127.0.0.1:8848"));
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> connection);
|
||||
try {
|
||||
rpcClient.start();
|
||||
RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(
|
||||
new RpcClient.ServerInfo("127.0.0.1", 0), false);
|
||||
RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(new RpcClient.ServerInfo("127.0.0.1", 0),
|
||||
false);
|
||||
((BlockingQueue<RpcClient.ReconnectContext>) reconnectionSignalField.get(rpcClient)).put(reconnectContext);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
assertEquals(RpcClientStatus.RUNNING, rpcClient.rpcClientStatus.get());
|
||||
@ -929,16 +943,15 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectContextAfterStartWithNewServiceInfo()
|
||||
throws NacosException, InterruptedException, IllegalAccessException {
|
||||
void testReconnectContextAfterStartWithNewServiceInfo() throws NacosException, InterruptedException, IllegalAccessException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("1.1.1.1:8848"));
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> connection);
|
||||
try {
|
||||
rpcClient.start();
|
||||
RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(
|
||||
new RpcClient.ServerInfo("127.0.0.1", 0), false);
|
||||
RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(new RpcClient.ServerInfo("127.0.0.1", 0),
|
||||
false);
|
||||
((BlockingQueue<RpcClient.ReconnectContext>) reconnectionSignalField.get(rpcClient)).put(reconnectContext);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
assertEquals(RpcClientStatus.RUNNING, rpcClient.rpcClientStatus.get());
|
||||
@ -949,7 +962,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleConnectionResetRequestWithoutServer() throws NacosException, InterruptedException {
|
||||
void testHandleConnectionResetRequestWithoutServer() throws NacosException, InterruptedException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> {
|
||||
@ -968,7 +981,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleConnectionResetRequestWithServer() throws NacosException, InterruptedException {
|
||||
void testHandleConnectionResetRequestWithServer() throws NacosException, InterruptedException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848");
|
||||
List<String> serverList = new LinkedList<>();
|
||||
serverList.add("127.0.0.1:8848");
|
||||
@ -995,7 +1008,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleConnectionResetRequestWithException() throws NacosException, InterruptedException {
|
||||
void testHandleConnectionResetRequestWithException() throws NacosException, InterruptedException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848");
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> {
|
||||
@ -1017,7 +1030,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleClientDetectionRequest() throws NacosException {
|
||||
void testHandleClientDetectionRequest() throws NacosException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
try {
|
||||
rpcClient.start();
|
||||
@ -1029,7 +1042,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHandleOtherRequest() throws NacosException {
|
||||
void testHandleOtherRequest() throws NacosException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
try {
|
||||
rpcClient.start();
|
||||
@ -1041,7 +1054,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectForRequestFailButHealthCheckOK() throws NacosException {
|
||||
void testReconnectForRequestFailButHealthCheckOK() throws NacosException {
|
||||
RpcClient rpcClient = buildTestStartClient(serverInfo -> null);
|
||||
rpcClient.currentConnection = connection;
|
||||
connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848);
|
||||
@ -1051,7 +1064,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReconnectFailTimes() throws NacosException {
|
||||
void testReconnectFailTimes() throws NacosException {
|
||||
when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848");
|
||||
when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("127.0.0.1:8848"));
|
||||
final AtomicInteger count = new AtomicInteger(0);
|
||||
@ -1068,7 +1081,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCurrentServer() {
|
||||
void testGetCurrentServer() {
|
||||
assertNull(rpcClient.getCurrentServer());
|
||||
rpcClient.currentConnection = connection;
|
||||
rpcClient.serverListFactory(serverListFactory);
|
||||
@ -1077,7 +1090,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCurrentRpcServer() throws IllegalAccessException {
|
||||
void testCurrentRpcServer() throws IllegalAccessException {
|
||||
when(serverListFactory.getCurrentServer()).thenReturn("127.0.0.1:8848");
|
||||
serverListFactoryField.set(rpcClient, serverListFactory);
|
||||
RpcClient.ServerInfo serverInfo = rpcClient.currentRpcServer();
|
||||
@ -1107,7 +1120,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServerInfoSet() {
|
||||
void testServerInfoSet() {
|
||||
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
|
||||
String ip = "127.0.0.1";
|
||||
int port = 80;
|
||||
@ -1121,7 +1134,7 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetTenant() {
|
||||
void testSetTenant() {
|
||||
String tenant = "testTenant";
|
||||
assertNull(rpcClient.getTenant());
|
||||
rpcClient.setTenant(tenant);
|
||||
@ -1129,13 +1142,13 @@ public class RpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnectionAbilityWithNullConnection() {
|
||||
void testGetConnectionAbilityWithNullConnection() {
|
||||
AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1);
|
||||
assertNull(abilityStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnectionAbilityWithReadyConnection() {
|
||||
void testGetConnectionAbilityWithReadyConnection() {
|
||||
when(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)).thenReturn(AbilityStatus.SUPPORTED);
|
||||
rpcClient.currentConnection = connection;
|
||||
AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1);
|
||||
|
@ -16,17 +16,17 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.client;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class RpcClientTlsConfigTest {
|
||||
class RpcClientTlsConfigTest {
|
||||
|
||||
@Test
|
||||
public void testEnableTls() {
|
||||
void testEnableTls() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -34,7 +34,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSslProvider() {
|
||||
void testSslProvider() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER, "provider");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -42,7 +42,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMutualAuthEnable() {
|
||||
void testMutualAuthEnable() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -50,7 +50,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProtocols() {
|
||||
void testProtocols() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS, "protocols");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -58,7 +58,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCiphers() {
|
||||
void testCiphers() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CIPHERS, "ciphers");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -66,7 +66,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustCollectionCertFile() {
|
||||
void testTrustCollectionCertFile() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -74,7 +74,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertChainFile() {
|
||||
void testCertChainFile() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "certChainFile");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -82,7 +82,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertPrivateKey() {
|
||||
void testCertPrivateKey() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "certPrivateKey");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -90,7 +90,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustAll() {
|
||||
void testTrustAll() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
@ -98,7 +98,7 @@ public class RpcClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertPrivateKeyPassword() {
|
||||
void testCertPrivateKeyPassword() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD, "trustPwd");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties);
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.client;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
@ -31,13 +31,13 @@ import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.T
|
||||
import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_ALL;
|
||||
import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH;
|
||||
import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_PWD;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class RpcClusterClientTlsConfigTest {
|
||||
class RpcClusterClientTlsConfigTest {
|
||||
|
||||
@Test
|
||||
public void testEnableTls() {
|
||||
void testEnableTls() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties);
|
||||
@ -45,7 +45,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSslProvider() {
|
||||
void testSslProvider() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_PROVIDER, "provider");
|
||||
@ -54,7 +54,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMutualAuthEnable() {
|
||||
void testMutualAuthEnable() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + MUTUAL_AUTH, "true");
|
||||
@ -63,7 +63,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProtocols() {
|
||||
void testProtocols() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_PROTOCOLS, "protocols");
|
||||
@ -72,7 +72,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCiphers() {
|
||||
void testCiphers() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_CIPHERS, "ciphers");
|
||||
@ -81,7 +81,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustCollectionCertFile() {
|
||||
void testTrustCollectionCertFile() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile");
|
||||
@ -90,7 +90,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertChainFile() {
|
||||
void testCertChainFile() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_CERT_CHAIN_PATH, "certChainFile");
|
||||
@ -99,7 +99,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertPrivateKey() {
|
||||
void testCertPrivateKey() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_CERT_KEY, "certPrivateKey");
|
||||
@ -108,7 +108,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustAll() {
|
||||
void testTrustAll() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_ALL, "true");
|
||||
@ -117,7 +117,7 @@ public class RpcClusterClientTlsConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertPrivateKeyPassword() {
|
||||
void testCertPrivateKeyPassword() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true");
|
||||
properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_PWD, "trustPwd");
|
||||
|
@ -16,16 +16,16 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.client;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class RpcConstantsTest {
|
||||
class RpcConstantsTest {
|
||||
|
||||
@Test
|
||||
public void testGetRpcParams() {
|
||||
void testGetRpcParams() {
|
||||
Field[] declaredFields = RpcConstants.class.getDeclaredFields();
|
||||
int i = 0;
|
||||
for (Field declaredField : declaredFields) {
|
||||
|
@ -17,33 +17,33 @@
|
||||
package com.alibaba.nacos.common.remote.client.grpc;
|
||||
|
||||
import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
public class DefaultGrpcClientConfigTest {
|
||||
class DefaultGrpcClientConfigTest {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
System.setProperty("nacos.common.processors", "2");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
System.clearProperty("nacos.common.processors");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefault() {
|
||||
void testDefault() {
|
||||
DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) DefaultGrpcClientConfig.newBuilder().build();
|
||||
assertNull(config.name());
|
||||
assertEquals(3, config.retryTimes());
|
||||
@ -65,7 +65,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromProperties() {
|
||||
void testFromProperties() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(GrpcConstants.GRPC_NAME, "test");
|
||||
properties.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "3");
|
||||
@ -106,7 +106,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testName() {
|
||||
void testName() {
|
||||
String name = "test";
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setName(name);
|
||||
@ -115,7 +115,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetRetryTimes() {
|
||||
void testSetRetryTimes() {
|
||||
int retryTimes = 3;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setRetryTimes(retryTimes);
|
||||
@ -124,7 +124,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetTimeOutMills() {
|
||||
void testSetTimeOutMills() {
|
||||
long timeOutMills = 3000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setTimeOutMills(timeOutMills);
|
||||
@ -133,7 +133,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetConnectionKeepAlive() {
|
||||
void testSetConnectionKeepAlive() {
|
||||
long connectionKeepAlive = 5000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setConnectionKeepAlive(connectionKeepAlive);
|
||||
@ -142,7 +142,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetThreadPoolKeepAlive() {
|
||||
void testSetThreadPoolKeepAlive() {
|
||||
long threadPoolKeepAlive = 10000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setThreadPoolKeepAlive(threadPoolKeepAlive);
|
||||
@ -151,7 +151,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetThreadPoolCoreSize() {
|
||||
void testSetThreadPoolCoreSize() {
|
||||
int threadPoolCoreSize = 2;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setThreadPoolCoreSize(threadPoolCoreSize);
|
||||
@ -160,7 +160,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetThreadPoolMaxSize() {
|
||||
void testSetThreadPoolMaxSize() {
|
||||
int threadPoolMaxSize = 8;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setThreadPoolMaxSize(threadPoolMaxSize);
|
||||
@ -169,7 +169,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetServerCheckTimeOut() {
|
||||
void testSetServerCheckTimeOut() {
|
||||
long serverCheckTimeOut = 3000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setServerCheckTimeOut(serverCheckTimeOut);
|
||||
@ -178,7 +178,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetThreadPoolQueueSize() {
|
||||
void testSetThreadPoolQueueSize() {
|
||||
int threadPoolQueueSize = 10000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setThreadPoolQueueSize(threadPoolQueueSize);
|
||||
@ -187,7 +187,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetMaxInboundMessageSize() {
|
||||
void testSetMaxInboundMessageSize() {
|
||||
int maxInboundMessageSize = 10485760;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setMaxInboundMessageSize(maxInboundMessageSize);
|
||||
@ -196,7 +196,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetChannelKeepAlive() {
|
||||
void testSetChannelKeepAlive() {
|
||||
int channelKeepAlive = 60000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setChannelKeepAlive(channelKeepAlive);
|
||||
@ -205,7 +205,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetChannelKeepAliveTimeout() {
|
||||
void testSetChannelKeepAliveTimeout() {
|
||||
int channelKeepAliveTimeout = 20000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setChannelKeepAliveTimeout(channelKeepAliveTimeout);
|
||||
@ -214,7 +214,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetCapabilityNegotiationTimeout() {
|
||||
void testSetCapabilityNegotiationTimeout() {
|
||||
long capabilityNegotiationTimeout = 5000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setCapabilityNegotiationTimeout(capabilityNegotiationTimeout);
|
||||
@ -223,7 +223,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetHealthCheckRetryTimes() {
|
||||
void testSetHealthCheckRetryTimes() {
|
||||
int healthCheckRetryTimes = 3;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setHealthCheckRetryTimes(healthCheckRetryTimes);
|
||||
@ -232,7 +232,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetHealthCheckTimeOut() {
|
||||
void testSetHealthCheckTimeOut() {
|
||||
long healthCheckTimeOut = 3000;
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setHealthCheckTimeOut(healthCheckTimeOut);
|
||||
@ -241,7 +241,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetLabels() {
|
||||
void testSetLabels() {
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
labels.put("key1", "value1");
|
||||
labels.put("key2", "value2");
|
||||
@ -254,7 +254,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetTlsConfig() {
|
||||
void testSetTlsConfig() {
|
||||
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
builder.setTlsConfig(tlsConfig);
|
||||
@ -263,7 +263,7 @@ public class DefaultGrpcClientConfigTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetTlsConfigDirectly() {
|
||||
void testSetTlsConfigDirectly() {
|
||||
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder();
|
||||
DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) builder.build();
|
||||
|
@ -38,12 +38,14 @@ import io.grpc.Channel;
|
||||
import io.grpc.ClientCall;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
@ -55,11 +57,11 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
@ -70,23 +72,25 @@ import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class GrpcClientTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GrpcClientTest {
|
||||
|
||||
protected GrpcClient grpcClient;
|
||||
|
||||
@Mock
|
||||
RpcClientTlsConfig tlsConfig;
|
||||
|
||||
protected RpcClient.ServerInfo serverInfo;
|
||||
|
||||
protected GrpcClientConfig clientConfig;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
clientConfig = DefaultGrpcClientConfig.newBuilder().setServerCheckTimeOut(100L)
|
||||
.setCapabilityNegotiationTimeout(100L).setChannelKeepAliveTimeout((int) TimeUnit.SECONDS.toMillis(3L))
|
||||
.setChannelKeepAlive(1000).setName("testClient").build();
|
||||
@Mock
|
||||
RpcClientTlsConfig tlsConfig;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
clientConfig = DefaultGrpcClientConfig.newBuilder().setServerCheckTimeOut(100L).setCapabilityNegotiationTimeout(100L)
|
||||
.setChannelKeepAliveTimeout((int) TimeUnit.SECONDS.toMillis(3L)).setChannelKeepAlive(1000).setName("testClient")
|
||||
.build();
|
||||
clientConfig.setTlsConfig(tlsConfig);
|
||||
grpcClient = spy(new GrpcClient(clientConfig) {
|
||||
@Override
|
||||
@ -102,29 +106,29 @@ public class GrpcClientTest {
|
||||
serverInfo = new RpcClient.ServerInfo("10.10.10.10", 8848);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws NacosException {
|
||||
@AfterEach
|
||||
void tearDown() throws NacosException {
|
||||
grpcClient.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConnectionType() {
|
||||
void testGetConnectionType() {
|
||||
assertEquals(ConnectionType.GRPC, grpcClient.getConnectionType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectToServerFailed() {
|
||||
void testConnectToServerFailed() {
|
||||
assertNull(grpcClient.connectToServer(serverInfo));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectToServerException() {
|
||||
void testConnectToServerException() {
|
||||
doThrow(new RuntimeException("test")).when(grpcClient).createNewChannelStub(any(ManagedChannel.class));
|
||||
assertNull(grpcClient.connectToServer(serverInfo));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectToServerMockSuccess() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
void testConnectToServerMockSuccess() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
RequestGrpc.RequestFutureStub stub = mockStub(new ServerCheckResponse(), null);
|
||||
doReturn(stub).when(grpcClient).createNewChannelStub(any(ManagedChannel.class));
|
||||
Connection connection = grpcClient.connectToServer(serverInfo);
|
||||
@ -134,8 +138,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectToServerMockSuccessWithAbility()
|
||||
throws ExecutionException, InterruptedException, TimeoutException {
|
||||
void testConnectToServerMockSuccessWithAbility() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
ServerCheckResponse response = new ServerCheckResponse();
|
||||
response.setSupportAbilityNegotiation(true);
|
||||
RequestGrpc.RequestFutureStub stub = mockStub(response, null);
|
||||
@ -145,8 +148,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectToServerMockHealthCheckFailed()
|
||||
throws ExecutionException, InterruptedException, TimeoutException {
|
||||
void testConnectToServerMockHealthCheckFailed() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
RequestGrpc.RequestFutureStub stub = mockStub(null, new RuntimeException("test"));
|
||||
doReturn(stub).when(grpcClient).createNewChannelStub(any(ManagedChannel.class));
|
||||
Connection connection = grpcClient.connectToServer(serverInfo);
|
||||
@ -171,13 +173,12 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnNextSetupAckRequest()
|
||||
void testBindRequestStreamOnNextSetupAckRequest()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
when(stub.requestBiStream(any())).thenAnswer((Answer<StreamObserver<Payload>>) invocationOnMock -> {
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(
|
||||
GrpcUtils.convert(new SetupAckRequest()));
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new SetupAckRequest()));
|
||||
return null;
|
||||
});
|
||||
setCurrentConnection(grpcConnection, grpcClient);
|
||||
@ -186,13 +187,12 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnNextOtherRequest()
|
||||
void testBindRequestStreamOnNextOtherRequest()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
when(stub.requestBiStream(any())).thenAnswer((Answer<StreamObserver<Payload>>) invocationOnMock -> {
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(
|
||||
GrpcUtils.convert(new ConnectResetRequest()));
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest()));
|
||||
return null;
|
||||
});
|
||||
grpcClient.registerServerRequestHandler((request, connection) -> {
|
||||
@ -207,13 +207,12 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnNextNoRequest()
|
||||
void testBindRequestStreamOnNextNoRequest()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
when(stub.requestBiStream(any())).thenAnswer((Answer<StreamObserver<Payload>>) invocationOnMock -> {
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(
|
||||
GrpcUtils.convert(new ConnectResetRequest()));
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest()));
|
||||
return null;
|
||||
});
|
||||
grpcClient.registerServerRequestHandler((request, connection) -> null);
|
||||
@ -223,13 +222,12 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnNextHandleException()
|
||||
void testBindRequestStreamOnNextHandleException()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
when(stub.requestBiStream(any())).thenAnswer((Answer<StreamObserver<Payload>>) invocationOnMock -> {
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(
|
||||
GrpcUtils.convert(new ConnectResetRequest()));
|
||||
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest()));
|
||||
return null;
|
||||
});
|
||||
grpcClient.registerServerRequestHandler((request, connection) -> {
|
||||
@ -241,7 +239,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnNextParseException()
|
||||
void testBindRequestStreamOnNextParseException()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
@ -255,7 +253,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnErrorFromRunning()
|
||||
void testBindRequestStreamOnErrorFromRunning()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
@ -271,7 +269,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnErrorFromNotRunning()
|
||||
void testBindRequestStreamOnErrorFromNotRunning()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
@ -289,7 +287,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnCompletedFromRunning()
|
||||
void testBindRequestStreamOnCompletedFromRunning()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
@ -305,7 +303,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindRequestStreamOnCompletedFromNotRunning()
|
||||
void testBindRequestStreamOnCompletedFromNotRunning()
|
||||
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
|
||||
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
|
||||
GrpcConnection grpcConnection = mock(GrpcConnection.class);
|
||||
@ -323,8 +321,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
private void invokeBindRequestStream(GrpcClient grpcClient, BiRequestStreamGrpc.BiRequestStreamStub stub,
|
||||
GrpcConnection grpcConnection)
|
||||
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
GrpcConnection grpcConnection) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
Method bindRequestStreamMethod = GrpcClient.class.getDeclaredMethod("bindRequestStream",
|
||||
BiRequestStreamGrpc.BiRequestStreamStub.class, GrpcConnection.class);
|
||||
bindRequestStreamMethod.setAccessible(true);
|
||||
@ -338,15 +335,14 @@ public class GrpcClientTest {
|
||||
connectionField.set(client, connection);
|
||||
}
|
||||
|
||||
private void setStatus(GrpcClient grpcClient, RpcClientStatus status)
|
||||
throws IllegalAccessException, NoSuchFieldException {
|
||||
private void setStatus(GrpcClient grpcClient, RpcClientStatus status) throws IllegalAccessException, NoSuchFieldException {
|
||||
Field statusField = RpcClient.class.getDeclaredField("rpcClientStatus");
|
||||
statusField.setAccessible(true);
|
||||
statusField.set(grpcClient, new AtomicReference<>(status));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterReset() throws NoSuchFieldException, IllegalAccessException {
|
||||
void testAfterReset() throws NoSuchFieldException, IllegalAccessException {
|
||||
Field recAbilityContextField = GrpcClient.class.getDeclaredField("recAbilityContext");
|
||||
recAbilityContextField.setAccessible(true);
|
||||
GrpcClient.RecAbilityContext context = mock(GrpcClient.RecAbilityContext.class);
|
||||
@ -356,7 +352,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAppendRecAbilityContext() {
|
||||
void testAppendRecAbilityContext() {
|
||||
GrpcClient.RecAbilityContext context = new GrpcClient.RecAbilityContext(null);
|
||||
GrpcConnection connection = mock(GrpcConnection.class);
|
||||
context.reset(connection);
|
||||
@ -370,7 +366,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendResponseWithException()
|
||||
void testSendResponseWithException()
|
||||
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
|
||||
GrpcConnection connection = mock(GrpcConnection.class);
|
||||
setCurrentConnection(connection, grpcClient);
|
||||
@ -382,7 +378,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructorWithServerListFactory() {
|
||||
void testConstructorWithServerListFactory() {
|
||||
ServerListFactory serverListFactory = mock(ServerListFactory.class);
|
||||
GrpcClient grpcClient = new GrpcClient(clientConfig, serverListFactory) {
|
||||
@Override
|
||||
@ -399,7 +395,7 @@ public class GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructorWithoutServerListFactory() {
|
||||
void testConstructorWithoutServerListFactory() {
|
||||
GrpcClient grpcClient = new GrpcClient("testNoFactory", 2, 2, Collections.emptyMap()) {
|
||||
@Override
|
||||
protected AbilityMode abilityMode() {
|
||||
|
@ -16,18 +16,18 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.client.grpc;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Currently not good way to test tls relative codes, and it's a optional feature, single test first.
|
||||
*/
|
||||
public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
class GrpcClientTlsTest extends GrpcClientTest {
|
||||
|
||||
@Test
|
||||
public void testGrpcEnableTlsAndTrustPart() throws Exception {
|
||||
void testGrpcEnableTlsAndTrustPart() throws Exception {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
@ -36,7 +36,7 @@ public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcEnableTlsAndTrustAll() throws Exception {
|
||||
void testGrpcEnableTlsAndTrustAll() throws Exception {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
@ -46,7 +46,7 @@ public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcEnableTlsAndEnableMutualAuth() throws Exception {
|
||||
void testGrpcEnableTlsAndEnableMutualAuth() throws Exception {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
@ -58,7 +58,7 @@ public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcSslProvider() {
|
||||
void testGrpcSslProvider() {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
@ -71,7 +71,7 @@ public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcEmptyTrustCollectionCertFile() {
|
||||
void testGrpcEmptyTrustCollectionCertFile() {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("");
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
@ -80,7 +80,7 @@ public class GrpcClientTlsTest extends GrpcClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcMutualAuth() {
|
||||
void testGrpcMutualAuth() {
|
||||
when(tlsConfig.getEnableTls()).thenReturn(true);
|
||||
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
|
||||
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
|
||||
|
@ -18,20 +18,20 @@ package com.alibaba.nacos.common.remote.client.grpc;
|
||||
|
||||
import com.alibaba.nacos.api.ability.constant.AbilityMode;
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class GrpcClusterClientTest {
|
||||
class GrpcClusterClientTest {
|
||||
|
||||
GrpcClusterClient grpcClusterClient;
|
||||
|
||||
@After
|
||||
public void tearDown() throws NacosException {
|
||||
@AfterEach
|
||||
void tearDown() throws NacosException {
|
||||
System.clearProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY);
|
||||
if (grpcClusterClient != null) {
|
||||
grpcClusterClient.shutdown();
|
||||
@ -39,28 +39,28 @@ public class GrpcClusterClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAbilityMode() {
|
||||
void testAbilityMode() {
|
||||
grpcClusterClient = new GrpcClusterClient("test");
|
||||
assertEquals(AbilityMode.CLUSTER_CLIENT, grpcClusterClient.abilityMode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRpcPortOffsetDefault() {
|
||||
void testRpcPortOffsetDefault() {
|
||||
DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder()
|
||||
.buildClusterFromProperties(new Properties());
|
||||
grpcClusterClient = new GrpcClusterClient(builder.build());
|
||||
grpcClusterClient = new GrpcClusterClient(builder.build());
|
||||
assertEquals(1001, grpcClusterClient.rpcPortOffset());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRpcPortOffsetFromSystemProperty() {
|
||||
void testRpcPortOffsetFromSystemProperty() {
|
||||
System.setProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, "10001");
|
||||
grpcClusterClient = new GrpcClusterClient("test", 8, 8, Collections.emptyMap());
|
||||
assertEquals(10001, grpcClusterClient.rpcPortOffset());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcClientByConfig() {
|
||||
void testGrpcClientByConfig() {
|
||||
GrpcClientConfig config = DefaultGrpcClientConfig.newBuilder().setName("test111").build();
|
||||
grpcClusterClient = new GrpcClusterClient(config);
|
||||
assertEquals("test111", grpcClusterClient.getName());
|
||||
|
@ -34,13 +34,15 @@ import com.google.protobuf.Any;
|
||||
import com.google.protobuf.UnsafeByteOperations;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@ -48,8 +50,9 @@ import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
@ -58,8 +61,19 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class GrpcConnectionTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GrpcConnectionTest {
|
||||
|
||||
@Mock
|
||||
ListenableFuture<Payload> future;
|
||||
|
||||
Payload responsePayload;
|
||||
|
||||
Payload errorResponsePayload;
|
||||
|
||||
GrpcConnection connection;
|
||||
|
||||
@Mock
|
||||
private Executor executor;
|
||||
@ -73,22 +87,13 @@ public class GrpcConnectionTest {
|
||||
@Mock
|
||||
private RequestGrpc.RequestFutureStub requestFutureStub;
|
||||
|
||||
@Mock
|
||||
ListenableFuture<Payload> future;
|
||||
|
||||
Payload responsePayload;
|
||||
|
||||
Payload errorResponsePayload;
|
||||
|
||||
GrpcConnection connection;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() {
|
||||
@BeforeAll
|
||||
static void setUpBeforeClass() {
|
||||
PayloadRegistry.init();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
connection = new GrpcConnection(new RpcClient.ServerInfo(), executor);
|
||||
connection.setChannel(channel);
|
||||
connection.setPayloadStreamObserver(payloadStreamObserver);
|
||||
@ -101,38 +106,40 @@ public class GrpcConnectionTest {
|
||||
when(future.isDone()).thenReturn(true);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAll() {
|
||||
void testGetAll() {
|
||||
assertEquals(channel, connection.getChannel());
|
||||
assertEquals(payloadStreamObserver, connection.getPayloadStreamObserver());
|
||||
assertEquals(requestFutureStub, connection.getGrpcFutureServiceStub());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestSuccessSync() throws NacosException {
|
||||
void testRequestSuccessSync() throws NacosException {
|
||||
Response response = connection.request(new HealthCheckRequest(), -1);
|
||||
assertTrue(response instanceof HealthCheckResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestSuccessAsync() throws NacosException {
|
||||
void testRequestSuccessAsync() throws NacosException {
|
||||
Response response = connection.request(new HealthCheckRequest(), 100);
|
||||
assertTrue(response instanceof HealthCheckResponse);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestTimeout() throws InterruptedException, ExecutionException, TimeoutException, NacosException {
|
||||
when(future.get(100L, TimeUnit.MILLISECONDS)).thenThrow(new TimeoutException("test"));
|
||||
connection.request(new HealthCheckRequest(), 100);
|
||||
@Test
|
||||
void testRequestTimeout() throws InterruptedException, ExecutionException, TimeoutException, NacosException {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(future.get(100L, TimeUnit.MILLISECONDS)).thenThrow(new TimeoutException("test"));
|
||||
connection.request(new HealthCheckRequest(), 100);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestFuture() throws Exception {
|
||||
void testRequestFuture() throws Exception {
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
Response response = requestFuture.get();
|
||||
@ -140,43 +147,47 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestFutureWithTimeout() throws Exception {
|
||||
void testRequestFutureWithTimeout() throws Exception {
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
Response response = requestFuture.get(100L);
|
||||
assertTrue(response instanceof HealthCheckResponse);
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestFutureFailure() throws Exception {
|
||||
when(future.get()).thenReturn(errorResponsePayload);
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
requestFuture.get();
|
||||
}
|
||||
|
||||
@Test(expected = NacosException.class)
|
||||
public void testRequestFutureWithTimeoutFailure() throws Exception {
|
||||
when(future.get(100L, TimeUnit.MILLISECONDS)).thenReturn(errorResponsePayload);
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
requestFuture.get(100L);
|
||||
@Test
|
||||
void testRequestFutureFailure() throws Exception {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(future.get()).thenReturn(errorResponsePayload);
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
requestFuture.get();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendResponse() {
|
||||
void testRequestFutureWithTimeoutFailure() throws Exception {
|
||||
assertThrows(NacosException.class, () -> {
|
||||
when(future.get(100L, TimeUnit.MILLISECONDS)).thenReturn(errorResponsePayload);
|
||||
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
|
||||
assertTrue(requestFuture.isDone());
|
||||
requestFuture.get(100L);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendResponse() {
|
||||
connection.sendResponse(new HealthCheckResponse());
|
||||
verify(payloadStreamObserver).onNext(any(Payload.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendRequest() {
|
||||
void testSendRequest() {
|
||||
connection.sendRequest(new HealthCheckRequest());
|
||||
verify(payloadStreamObserver).onNext(any(Payload.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestSuccess() throws NacosException {
|
||||
void testAsyncRequestSuccess() throws NacosException {
|
||||
doAnswer(invocationOnMock -> {
|
||||
((Runnable) invocationOnMock.getArgument(0)).run();
|
||||
return null;
|
||||
@ -187,7 +198,7 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestError() throws NacosException, ExecutionException, InterruptedException {
|
||||
void testAsyncRequestError() throws NacosException, ExecutionException, InterruptedException {
|
||||
when(future.get()).thenReturn(errorResponsePayload);
|
||||
doAnswer(invocationOnMock -> {
|
||||
((Runnable) invocationOnMock.getArgument(0)).run();
|
||||
@ -199,12 +210,12 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestNullResponse() throws NacosException, ExecutionException, InterruptedException {
|
||||
void testAsyncRequestNullResponse() throws NacosException, ExecutionException, InterruptedException {
|
||||
byte[] jsonBytes = JacksonUtils.toJsonBytes(null);
|
||||
Metadata.Builder metaBuilder = Metadata.newBuilder().setType(HealthCheckResponse.class.getSimpleName());
|
||||
Payload nullResponsePayload = Payload.newBuilder()
|
||||
.setBody(Any.newBuilder().setValue(UnsafeByteOperations.unsafeWrap(jsonBytes)))
|
||||
.setMetadata(metaBuilder.build()).build();
|
||||
.setBody(Any.newBuilder().setValue(UnsafeByteOperations.unsafeWrap(jsonBytes))).setMetadata(metaBuilder.build())
|
||||
.build();
|
||||
when(future.get()).thenReturn(nullResponsePayload);
|
||||
doAnswer(invocationOnMock -> {
|
||||
((Runnable) invocationOnMock.getArgument(0)).run();
|
||||
@ -216,7 +227,7 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestWithCancelException() throws NacosException, ExecutionException, InterruptedException {
|
||||
void testAsyncRequestWithCancelException() throws NacosException, ExecutionException, InterruptedException {
|
||||
when(future.get()).thenThrow(new CancellationException("test"));
|
||||
doAnswer(invocationOnMock -> {
|
||||
((Runnable) invocationOnMock.getArgument(0)).run();
|
||||
@ -228,7 +239,7 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsyncRequestWithOtherException() throws NacosException, ExecutionException, InterruptedException {
|
||||
void testAsyncRequestWithOtherException() throws NacosException, ExecutionException, InterruptedException {
|
||||
when(future.get()).thenThrow(new RuntimeException("test"));
|
||||
doAnswer(invocationOnMock -> {
|
||||
((Runnable) invocationOnMock.getArgument(0)).run();
|
||||
@ -240,7 +251,7 @@ public class GrpcConnectionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseWithException() {
|
||||
void testCloseWithException() {
|
||||
doThrow(new RuntimeException("test")).when(payloadStreamObserver).onCompleted();
|
||||
when(channel.shutdownNow()).thenThrow(new RuntimeException("test"));
|
||||
connection.close();
|
||||
|
@ -16,16 +16,16 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.client.grpc;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class GrpcConstantsTest {
|
||||
class GrpcConstantsTest {
|
||||
|
||||
@Test
|
||||
public void testGetRpcParams() {
|
||||
void testGetRpcParams() {
|
||||
Class clazz = GrpcConstants.class;
|
||||
Field[] declaredFields = clazz.getDeclaredFields();
|
||||
int i = 0;
|
||||
|
@ -18,19 +18,19 @@ package com.alibaba.nacos.common.remote.client.grpc;
|
||||
|
||||
import com.alibaba.nacos.api.ability.constant.AbilityMode;
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class GrpcSdkClientTest {
|
||||
class GrpcSdkClientTest {
|
||||
|
||||
GrpcSdkClient grpcSdkClient;
|
||||
|
||||
@After
|
||||
public void tearDown() throws NacosException {
|
||||
@AfterEach
|
||||
void tearDown() throws NacosException {
|
||||
System.clearProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY);
|
||||
if (grpcSdkClient != null) {
|
||||
grpcSdkClient.shutdown();
|
||||
@ -38,26 +38,26 @@ public class GrpcSdkClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAbilityMode() {
|
||||
void testAbilityMode() {
|
||||
grpcSdkClient = new GrpcSdkClient("test");
|
||||
assertEquals(AbilityMode.SDK_CLIENT, grpcSdkClient.abilityMode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRpcPortOffsetDefault() {
|
||||
void testRpcPortOffsetDefault() {
|
||||
grpcSdkClient = new GrpcSdkClient("test");
|
||||
assertEquals(1000, grpcSdkClient.rpcPortOffset());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRpcPortOffsetFromSystemProperty() {
|
||||
void testRpcPortOffsetFromSystemProperty() {
|
||||
System.setProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, "10000");
|
||||
grpcSdkClient = new GrpcSdkClient("test", 8, 8, Collections.emptyMap());
|
||||
assertEquals(10000, grpcSdkClient.rpcPortOffset());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGrpcClientByConfig() {
|
||||
void testGrpcClientByConfig() {
|
||||
GrpcClientConfig config = DefaultGrpcClientConfig.newBuilder().setName("test111").build();
|
||||
grpcSdkClient = new GrpcSdkClient(config);
|
||||
assertEquals("test111", grpcSdkClient.getName());
|
||||
|
@ -25,23 +25,24 @@ import com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest;
|
||||
import com.alibaba.nacos.api.remote.request.RequestMeta;
|
||||
import com.alibaba.nacos.common.remote.PayloadRegistry;
|
||||
import com.alibaba.nacos.common.remote.exception.RemoteException;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class GrpcUtilsTest {
|
||||
class GrpcUtilsTest {
|
||||
|
||||
private ServiceQueryRequest request;
|
||||
|
||||
private ClientConfigMetricResponse response;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
PayloadRegistry.init();
|
||||
this.request = createRequest();
|
||||
this.response = createResponse();
|
||||
@ -73,7 +74,7 @@ public class GrpcUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertRequest() {
|
||||
void testConvertRequest() {
|
||||
Payload convert = GrpcUtils.convert(request);
|
||||
assertEquals(request.getClass().getSimpleName(), convert.getMetadata().getType());
|
||||
assertEquals("v1", convert.getMetadata().getHeadersMap().get("h1"));
|
||||
@ -82,7 +83,7 @@ public class GrpcUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertRequestWithMeta() {
|
||||
void testConvertRequestWithMeta() {
|
||||
RequestMeta meta = new RequestMeta();
|
||||
Payload convert = GrpcUtils.convert(request, meta);
|
||||
assertEquals(request.getClass().getSimpleName(), convert.getMetadata().getType());
|
||||
@ -92,32 +93,34 @@ public class GrpcUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertResponse() {
|
||||
void testConvertResponse() {
|
||||
Payload convert = GrpcUtils.convert(response);
|
||||
assertEquals(response.getClass().getSimpleName(), convert.getMetadata().getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParse() {
|
||||
void testParse() {
|
||||
Payload requestPayload = GrpcUtils.convert(request);
|
||||
|
||||
|
||||
ServiceQueryRequest request = (ServiceQueryRequest) GrpcUtils.parse(requestPayload);
|
||||
assertEquals(this.request.getHeaders(), request.getHeaders());
|
||||
assertEquals(this.request.getCluster(), request.getCluster());
|
||||
assertEquals(this.request.isHealthyOnly(), request.isHealthyOnly());
|
||||
assertEquals(this.request.getNamespace(), request.getNamespace());
|
||||
|
||||
|
||||
Payload responsePayload = GrpcUtils.convert(response);
|
||||
ClientConfigMetricResponse response = (ClientConfigMetricResponse) GrpcUtils.parse(responsePayload);
|
||||
assertEquals(this.response.getMetrics(), response.getMetrics());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = RemoteException.class)
|
||||
public void testParseNullType() {
|
||||
Payload mockPayload = mock(Payload.class);
|
||||
Metadata mockMetadata = mock(Metadata.class);
|
||||
when(mockPayload.getMetadata()).thenReturn(mockMetadata);
|
||||
GrpcUtils.parse(mockPayload);
|
||||
@Test
|
||||
void testParseNullType() {
|
||||
assertThrows(RemoteException.class, () -> {
|
||||
Payload mockPayload = mock(Payload.class);
|
||||
Metadata mockMetadata = mock(Metadata.class);
|
||||
when(mockPayload.getMetadata()).thenReturn(mockMetadata);
|
||||
GrpcUtils.parse(mockPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -16,15 +16,15 @@
|
||||
|
||||
package com.alibaba.nacos.common.remote.exception;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
public class RemoteExceptionTest {
|
||||
class RemoteExceptionTest {
|
||||
|
||||
@Test
|
||||
public void testConnectionAlreadyClosedException() {
|
||||
void testConnectionAlreadyClosedException() {
|
||||
ConnectionAlreadyClosedException exception = new ConnectionAlreadyClosedException("test message");
|
||||
|
||||
assertEquals(600, exception.getErrCode());
|
||||
@ -45,7 +45,7 @@ public class RemoteExceptionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConnectionBusyException() {
|
||||
void testConnectionBusyException() {
|
||||
String msg = "Connection is busy";
|
||||
ConnectionBusyException exception = new ConnectionBusyException(msg);
|
||||
|
||||
|
@ -16,30 +16,30 @@
|
||||
|
||||
package com.alibaba.nacos.common.spi;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
public class NacosServiceLoaderTest {
|
||||
class NacosServiceLoaderTest {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
SpiTestImpl.newInstanceException = false;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoad() {
|
||||
void testLoad() {
|
||||
Collection<SpiTestInterface> actual = NacosServiceLoader.load(SpiTestInterface.class);
|
||||
assertEquals(1, actual.size());
|
||||
assertEquals(SpiTestImpl.class, actual.iterator().next().getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newServiceInstances() {
|
||||
void newServiceInstances() {
|
||||
SpiTestInterface loadInstance = NacosServiceLoader.load(SpiTestInterface.class).iterator().next();
|
||||
Collection<SpiTestInterface> actual = NacosServiceLoader.newServiceInstances(SpiTestInterface.class);
|
||||
assertEquals(1, actual.size());
|
||||
@ -48,7 +48,7 @@ public class NacosServiceLoaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newServiceInstancesWithException() {
|
||||
void newServiceInstancesWithException() {
|
||||
NacosServiceLoader.load(SpiTestInterface.class);
|
||||
SpiTestImpl.newInstanceException = true;
|
||||
try {
|
||||
|
@ -18,25 +18,25 @@ package com.alibaba.nacos.common.task.engine;
|
||||
|
||||
import com.alibaba.nacos.common.task.AbstractDelayTask;
|
||||
import com.alibaba.nacos.common.task.NacosTaskProcessor;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.internal.verification.Times;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NacosDelayTaskExecuteEngineTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NacosDelayTaskExecuteEngineTest {
|
||||
|
||||
private NacosDelayTaskExecuteEngine nacosDelayTaskExecuteEngine;
|
||||
|
||||
@ -48,8 +48,8 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
|
||||
private AbstractDelayTask abstractTask;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
nacosDelayTaskExecuteEngine = new NacosDelayTaskExecuteEngine(NacosDelayTaskExecuteEngineTest.class.getName());
|
||||
nacosDelayTaskExecuteEngine.setDefaultTaskProcessor(taskProcessor);
|
||||
abstractTask = new AbstractDelayTask() {
|
||||
@ -59,13 +59,13 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
};
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
nacosDelayTaskExecuteEngine.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
void testSize() {
|
||||
assertEquals(0, nacosDelayTaskExecuteEngine.size());
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
assertEquals(1, nacosDelayTaskExecuteEngine.size());
|
||||
@ -74,7 +74,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmpty() {
|
||||
void testIsEmpty() {
|
||||
assertTrue(nacosDelayTaskExecuteEngine.isEmpty());
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
assertFalse(nacosDelayTaskExecuteEngine.isEmpty());
|
||||
@ -83,7 +83,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddProcessor() throws InterruptedException {
|
||||
void testAddProcessor() throws InterruptedException {
|
||||
when(testTaskProcessor.process(abstractTask)).thenReturn(true);
|
||||
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
@ -94,7 +94,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveProcessor() throws InterruptedException {
|
||||
void testRemoveProcessor() throws InterruptedException {
|
||||
when(taskProcessor.process(abstractTask)).thenReturn(true);
|
||||
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
|
||||
nacosDelayTaskExecuteEngine.removeProcessor("test");
|
||||
@ -105,7 +105,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetryTaskAfterFail() throws InterruptedException {
|
||||
void testRetryTaskAfterFail() throws InterruptedException {
|
||||
when(taskProcessor.process(abstractTask)).thenReturn(false, true);
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
TimeUnit.MILLISECONDS.sleep(300);
|
||||
@ -113,7 +113,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessorWithException() throws InterruptedException {
|
||||
void testProcessorWithException() throws InterruptedException {
|
||||
when(taskProcessor.process(abstractTask)).thenThrow(new RuntimeException("test"));
|
||||
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
|
||||
nacosDelayTaskExecuteEngine.removeProcessor("test");
|
||||
@ -123,7 +123,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTaskShouldNotExecute() throws InterruptedException {
|
||||
void testTaskShouldNotExecute() throws InterruptedException {
|
||||
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
abstractTask.setTaskInterval(10000L);
|
||||
@ -134,7 +134,7 @@ public class NacosDelayTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTaskMerge() {
|
||||
void testTaskMerge() {
|
||||
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
|
||||
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
|
||||
nacosDelayTaskExecuteEngine.addTask("test", new AbstractDelayTask() {
|
||||
|
@ -19,47 +19,48 @@ 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;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class NacosExecuteTaskExecuteEngineTest {
|
||||
|
||||
private NacosExecuteTaskExecuteEngine executeTaskExecuteEngine;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NacosExecuteTaskExecuteEngineTest {
|
||||
|
||||
@Mock
|
||||
NacosTaskProcessor taskProcessor;
|
||||
|
||||
String cachedProcessor;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
private NacosExecuteTaskExecuteEngine executeTaskExecuteEngine;
|
||||
|
||||
@Mock
|
||||
private AbstractExecuteTask task;
|
||||
|
||||
@BeforeEach
|
||||
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 {
|
||||
@AfterEach
|
||||
void tearDown() throws NacosException {
|
||||
System.setProperty("nacos.common.processors", null == cachedProcessor ? "" : cachedProcessor);
|
||||
executeTaskExecuteEngine.shutdown();
|
||||
}
|
||||
|
||||
@Mock
|
||||
private AbstractExecuteTask task;
|
||||
|
||||
@Test
|
||||
public void testAddTask() throws InterruptedException {
|
||||
void testAddTask() throws InterruptedException {
|
||||
executeTaskExecuteEngine.addTask("test", task);
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
verify(task).run();
|
||||
@ -68,7 +69,7 @@ public class NacosExecuteTaskExecuteEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddTaskByProcessor() throws InterruptedException {
|
||||
void testAddTaskByProcessor() throws InterruptedException {
|
||||
executeTaskExecuteEngine.addProcessor("test", taskProcessor);
|
||||
executeTaskExecuteEngine.addTask("test", task);
|
||||
verify(taskProcessor).process(task);
|
||||
@ -76,18 +77,22 @@ public class NacosExecuteTaskExecuteEngineTest {
|
||||
assertEquals(0, executeTaskExecuteEngine.size());
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testRemoveTask() {
|
||||
executeTaskExecuteEngine.removeTask(task);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testGetAllTaskKeys() {
|
||||
executeTaskExecuteEngine.getAllTaskKeys();
|
||||
@Test
|
||||
void testRemoveTask() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> {
|
||||
executeTaskExecuteEngine.removeTask(task);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWorkersStatus() {
|
||||
void testGetAllTaskKeys() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> {
|
||||
executeTaskExecuteEngine.getAllTaskKeys();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testWorkersStatus() {
|
||||
assertEquals("TEST_0%1, pending tasks: 0\n", executeTaskExecuteEngine.workersStatus());
|
||||
}
|
||||
}
|
||||
|
@ -16,16 +16,17 @@
|
||||
|
||||
package com.alibaba.nacos.common.tls;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLSession;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@ -33,8 +34,9 @@ import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SelfHostnameVerifierTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SelfHostnameVerifierTest {
|
||||
|
||||
@Mock
|
||||
HostnameVerifier hostnameVerifier;
|
||||
|
||||
@ -43,22 +45,22 @@ public class SelfHostnameVerifierTest {
|
||||
|
||||
SelfHostnameVerifier selfHostnameVerifier;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
selfHostnameVerifier = new SelfHostnameVerifier(hostnameVerifier);
|
||||
doReturn(false).when(hostnameVerifier).verify(anyString(), eq(sslSession));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerify() {
|
||||
Assert.assertTrue(selfHostnameVerifier.verify("localhost", sslSession));
|
||||
Assert.assertTrue(selfHostnameVerifier.verify("127.0.0.1", sslSession));
|
||||
Assert.assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession));
|
||||
void testVerify() {
|
||||
assertTrue(selfHostnameVerifier.verify("localhost", sslSession));
|
||||
assertTrue(selfHostnameVerifier.verify("127.0.0.1", sslSession));
|
||||
assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession));
|
||||
// hit cache
|
||||
Assert.assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession));
|
||||
assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession));
|
||||
|
||||
Assert.assertFalse(selfHostnameVerifier.verify("", sslSession));
|
||||
Assert.assertFalse(selfHostnameVerifier.verify(null, sslSession));
|
||||
assertFalse(selfHostnameVerifier.verify("", sslSession));
|
||||
assertFalse(selfHostnameVerifier.verify(null, sslSession));
|
||||
verify(hostnameVerifier, times(2)).verify(any(), eq(sslSession));
|
||||
}
|
||||
}
|
@ -16,9 +16,9 @@
|
||||
|
||||
package com.alibaba.nacos.common.tls;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
@ -26,24 +26,24 @@ 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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class SelfTrustManagerTest {
|
||||
class SelfTrustManagerTest {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustManagerSuccess() throws CertificateException {
|
||||
void testTrustManagerSuccess() throws CertificateException {
|
||||
URL url = SelfTrustManagerTest.class.getClassLoader().getResource("test-tls-cert.pem");
|
||||
String path = url.getPath();
|
||||
TrustManager[] actual = SelfTrustManager.trustManager(true, path);
|
||||
@ -59,7 +59,7 @@ public class SelfTrustManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrustManagerNonExist() throws CertificateException {
|
||||
void testTrustManagerNonExist() throws CertificateException {
|
||||
TrustManager[] actual = SelfTrustManager.trustManager(true, "non-exist-cert.pem");
|
||||
assertNotNull(actual);
|
||||
assertEquals(1, actual.length);
|
||||
|
@ -16,14 +16,15 @@
|
||||
|
||||
package com.alibaba.nacos.common.tls;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.io.File;
|
||||
@ -35,14 +36,19 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class TlsFileWatcherTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
// todo remove this
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class TlsFileWatcherTest {
|
||||
|
||||
static Field watchFilesMapField;
|
||||
|
||||
@ -57,23 +63,23 @@ public class TlsFileWatcherTest {
|
||||
@Mock
|
||||
ScheduledExecutorService executorService;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException {
|
||||
@BeforeAll
|
||||
static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException {
|
||||
watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap");
|
||||
watchFilesMapField.setAccessible(true);
|
||||
Field modifiersField1 = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField1.setAccessible(true);
|
||||
modifiersField1.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
|
||||
|
||||
|
||||
fileMd5MapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("fileMd5Map");
|
||||
fileMd5MapField.setAccessible(true);
|
||||
|
||||
|
||||
serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service");
|
||||
serviceField.setAccessible(true);
|
||||
Field modifiersField2 = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField2.setAccessible(true);
|
||||
modifiersField2.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
|
||||
|
||||
|
||||
startedField = TlsFileWatcher.getInstance().getClass().getDeclaredField("started");
|
||||
startedField.setAccessible(true);
|
||||
Field modifiersField3 = Field.class.getDeclaredField("modifiers");
|
||||
@ -81,8 +87,8 @@ public class TlsFileWatcherTest {
|
||||
modifiersField3.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException, IllegalAccessException {
|
||||
@BeforeEach
|
||||
void setUp() throws IOException, IllegalAccessException {
|
||||
tempFile = new File("test.txt");
|
||||
tempFile.createNewFile();
|
||||
serviceField.set(TlsFileWatcher.getInstance(), executorService);
|
||||
@ -95,86 +101,74 @@ public class TlsFileWatcherTest {
|
||||
doAnswer(answer).when(executorService).scheduleAtFixedRate(any(), anyLong(), anyLong(), any());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IllegalAccessException {
|
||||
@AfterEach
|
||||
void tearDown() throws IllegalAccessException {
|
||||
((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).clear();
|
||||
((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).clear();
|
||||
tempFile.deleteOnExit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddFileChangeListener1() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(
|
||||
filePath -> { },
|
||||
"not/exist/path"
|
||||
);
|
||||
|
||||
Assert.assertTrue(((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
Assert.assertTrue(((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddFileChangeListener2() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(
|
||||
filePath -> { },
|
||||
(String) null
|
||||
);
|
||||
void testAddFileChangeListener1() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(filePath -> {
|
||||
}, "not/exist/path");
|
||||
|
||||
Assert.assertTrue(((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
Assert.assertTrue(((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
assertTrue(((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
assertTrue(((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddFileChangeListener3() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(
|
||||
filePath -> { },
|
||||
tempFile.getPath()
|
||||
);
|
||||
void testAddFileChangeListener2() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(filePath -> {
|
||||
}, (String) null);
|
||||
|
||||
Assert.assertEquals(1, ((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).size());
|
||||
Assert.assertEquals(1, ((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).size());
|
||||
assertTrue(((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
assertTrue(((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartGivenTlsFileNotChangeThenNoNotify() throws IllegalAccessException, InterruptedException, IOException {
|
||||
void testAddFileChangeListener3() throws IOException, IllegalAccessException {
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(filePath -> {
|
||||
}, tempFile.getPath());
|
||||
|
||||
assertEquals(1, ((Map<?, ?>) watchFilesMapField.get(TlsFileWatcher.getInstance())).size());
|
||||
assertEquals(1, ((Map<?, ?>) fileMd5MapField.get(TlsFileWatcher.getInstance())).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStartGivenTlsFileNotChangeThenNoNotify() throws IllegalAccessException, InterruptedException, IOException {
|
||||
// given
|
||||
AtomicBoolean notified = new AtomicBoolean(false);
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(
|
||||
filePath -> notified.set(true),
|
||||
tempFile.getPath()
|
||||
);
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(filePath -> notified.set(true), tempFile.getPath());
|
||||
|
||||
// when
|
||||
TlsFileWatcher.getInstance().start();
|
||||
|
||||
// then
|
||||
Assert.assertFalse(notified.get());
|
||||
assertFalse(notified.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartGivenTlsFileChangeThenNotifyTheChangeFilePath() throws IllegalAccessException, IOException {
|
||||
void testStartGivenTlsFileChangeThenNotifyTheChangeFilePath() throws IllegalAccessException, IOException {
|
||||
// given
|
||||
AtomicBoolean notified = new AtomicBoolean(false);
|
||||
AtomicReference<String> changedFilePath = new AtomicReference<>();
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(
|
||||
filePath -> {
|
||||
notified.set(true);
|
||||
changedFilePath.set(filePath);
|
||||
},
|
||||
tempFile.getPath()
|
||||
);
|
||||
TlsFileWatcher.getInstance().addFileChangeListener(filePath -> {
|
||||
notified.set(true);
|
||||
changedFilePath.set(filePath);
|
||||
}, tempFile.getPath());
|
||||
((Map<String, String>) fileMd5MapField.get(TlsFileWatcher.getInstance())).put("test.txt", "");
|
||||
|
||||
|
||||
// when
|
||||
TlsFileWatcher.getInstance().start();
|
||||
|
||||
// then
|
||||
Assert.assertTrue(notified.get());
|
||||
Assert.assertEquals("test.txt", changedFilePath.get());
|
||||
assertTrue(notified.get());
|
||||
assertEquals("test.txt", changedFilePath.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartGivenTaskIsAlreadyRunThenNotRunAgain() {
|
||||
void testStartGivenTaskIsAlreadyRunThenNotRunAgain() {
|
||||
TlsFileWatcher.getInstance().start();
|
||||
TlsFileWatcher.getInstance().start();
|
||||
|
||||
|
@ -16,18 +16,18 @@
|
||||
|
||||
package com.alibaba.nacos.common.tls;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TlsHelperTest {
|
||||
class TlsHelperTest {
|
||||
|
||||
@Test
|
||||
public void testBuildSslContext() throws KeyManagementException, NoSuchAlgorithmException {
|
||||
void testBuildSslContext() throws KeyManagementException, NoSuchAlgorithmException {
|
||||
SSLContext actual = TlsHelper.buildSslContext(true);
|
||||
assertNotNull(actual);
|
||||
}
|
||||
|
@ -17,17 +17,17 @@
|
||||
package com.alibaba.nacos.common.trace.event.naming;
|
||||
|
||||
import com.alibaba.nacos.common.trace.HealthCheckType;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
public class HealthStateChangeTraceEventTest extends NamingTraceEventTest {
|
||||
class HealthStateChangeTraceEventTest extends NamingTraceEventTest {
|
||||
|
||||
@Test
|
||||
public void testHealthStateChangeTraceEventForClientBeat() {
|
||||
HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID,
|
||||
GROUP_NAME, SERVICE_NAME, IP, PORT, false, "client_beat");
|
||||
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());
|
||||
@ -35,9 +35,9 @@ public class HealthStateChangeTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHealthStateChangeTraceEventForTcp() {
|
||||
HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID,
|
||||
GROUP_NAME, SERVICE_NAME, IP, PORT, false, "tcp:unable2connect:");
|
||||
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());
|
||||
@ -45,9 +45,9 @@ public class HealthStateChangeTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHealthStateChangeTraceEventForHttp() {
|
||||
HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID,
|
||||
GROUP_NAME, SERVICE_NAME, IP, PORT, false, "http:error:");
|
||||
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());
|
||||
@ -55,9 +55,9 @@ public class HealthStateChangeTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHealthStateChangeTraceEventForMysql() {
|
||||
HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID,
|
||||
GROUP_NAME, SERVICE_NAME, IP, PORT, false, "mysql:timeout:");
|
||||
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());
|
||||
|
@ -17,18 +17,18 @@
|
||||
package com.alibaba.nacos.common.trace.event.naming;
|
||||
|
||||
import com.alibaba.nacos.common.trace.DeregisterInstanceReason;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class InstanceTraceEventTest extends NamingTraceEventTest {
|
||||
class InstanceTraceEventTest extends NamingTraceEventTest {
|
||||
|
||||
@Test
|
||||
public void testRegisterInstanceTraceEvent() {
|
||||
void testRegisterInstanceTraceEvent() {
|
||||
RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(TIME, CLIENT_IP, true,
|
||||
NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT);
|
||||
assertBasicInfo(registerInstanceTraceEvent);
|
||||
@ -41,9 +41,9 @@ public class InstanceTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeregisterInstanceTraceEvent() {
|
||||
DeregisterInstanceTraceEvent deregisterInstanceTraceEvent = new DeregisterInstanceTraceEvent(TIME, CLIENT_IP,
|
||||
true, DeregisterInstanceReason.NATIVE_DISCONNECTED, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT);
|
||||
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());
|
||||
@ -55,7 +55,7 @@ public class InstanceTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateInstanceTraceEvent() {
|
||||
void testUpdateInstanceTraceEvent() {
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
metadata.put("test1", "testValue");
|
||||
UpdateInstanceTraceEvent updateInstanceTraceEvent = new UpdateInstanceTraceEvent(TIME, CLIENT_IP, NAMESPACE_ID,
|
||||
|
@ -16,8 +16,8 @@
|
||||
|
||||
package com.alibaba.nacos.common.trace.event.naming;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class NamingTraceEventTest {
|
||||
|
||||
|
@ -16,33 +16,33 @@
|
||||
|
||||
package com.alibaba.nacos.common.trace.event.naming;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ServiceTraceEventTest extends NamingTraceEventTest {
|
||||
class ServiceTraceEventTest extends NamingTraceEventTest {
|
||||
|
||||
@Test
|
||||
public void testRegisterInstanceTraceEvent() {
|
||||
RegisterServiceTraceEvent registerServiceTraceEvent = new RegisterServiceTraceEvent(TIME, NAMESPACE_ID,
|
||||
GROUP_NAME, SERVICE_NAME);
|
||||
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);
|
||||
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() {
|
||||
void testUpdateInstanceTraceEvent() {
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
metadata.put("test1", "testValue");
|
||||
UpdateServiceTraceEvent updateServiceTraceEvent = new UpdateServiceTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME,
|
||||
|
@ -16,23 +16,23 @@
|
||||
|
||||
package com.alibaba.nacos.common.trace.event.naming;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class SubscribeTraceEventTest extends NamingTraceEventTest {
|
||||
class SubscribeTraceEventTest extends NamingTraceEventTest {
|
||||
|
||||
@Test
|
||||
public void testRegisterInstanceTraceEvent() {
|
||||
SubscribeServiceTraceEvent subscribeServiceTraceEvent = new SubscribeServiceTraceEvent(TIME, CLIENT_IP,
|
||||
NAMESPACE_ID, GROUP_NAME, SERVICE_NAME);
|
||||
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() {
|
||||
void testDeregisterInstanceTraceEvent() {
|
||||
UnsubscribeServiceTraceEvent unsubscribeServiceTraceEvent = new UnsubscribeServiceTraceEvent(TIME, CLIENT_IP,
|
||||
NAMESPACE_ID, GROUP_NAME, SERVICE_NAME);
|
||||
assertBasicInfo(unsubscribeServiceTraceEvent);
|
||||
@ -41,9 +41,9 @@ public class SubscribeTraceEventTest extends NamingTraceEventTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPushServiceTraceEvent() {
|
||||
PushServiceTraceEvent pushServiceTraceEvent = new PushServiceTraceEvent(TIME, 10, 510, 510, CLIENT_IP,
|
||||
NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, 100);
|
||||
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());
|
||||
|
@ -18,22 +18,22 @@ package com.alibaba.nacos.common.trace.publisher;
|
||||
|
||||
import com.alibaba.nacos.common.notify.EventPublisher;
|
||||
import com.alibaba.nacos.common.notify.NotifyCenter;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TraceEventPublisherFactoryTest {
|
||||
class TraceEventPublisherFactoryTest {
|
||||
|
||||
private Map<String, EventPublisher> originalEventPublisherMap;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
originalEventPublisherMap = new HashMap<>(NotifyCenter.getPublisherMap());
|
||||
NotifyCenter.getPublisherMap().clear();
|
||||
// Protect other unit test publisher affect this case.
|
||||
@ -43,15 +43,15 @@ public class TraceEventPublisherFactoryTest {
|
||||
map.clear();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
NotifyCenter.getPublisherMap().clear();
|
||||
NotifyCenter.getPublisherMap().putAll(originalEventPublisherMap);
|
||||
originalEventPublisherMap = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApply() {
|
||||
void testApply() {
|
||||
TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent1.class, Byte.SIZE);
|
||||
TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent2.class, Byte.SIZE);
|
||||
TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.class, Byte.SIZE);
|
||||
@ -61,7 +61,7 @@ public class TraceEventPublisherFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApplyAfterAddEventType() {
|
||||
void testApplyAfterAddEventType() {
|
||||
TraceEventPublisherFactory.getInstance().addPublisherEvent(TraceTestEvent.class);
|
||||
TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent1.class, Byte.SIZE);
|
||||
TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent2.class, Byte.SIZE);
|
||||
|
@ -20,22 +20,22 @@ 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.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.MatcherAssert.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 {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TraceEventPublisherTest {
|
||||
|
||||
@Mock
|
||||
private Subscriber subscriber;
|
||||
@ -45,19 +45,19 @@ public class TraceEventPublisherTest {
|
||||
|
||||
private TraceEventPublisher traceEventPublisher;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
traceEventPublisher = new TraceEventPublisher();
|
||||
traceEventPublisher.init(TraceTestEvent.class, Byte.SIZE);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
traceEventPublisher.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddSubscriber() {
|
||||
void testAddSubscriber() {
|
||||
when(subscriber.subscribeType()).thenReturn(TraceTestEvent.TraceTestEvent1.class);
|
||||
traceEventPublisher.addSubscriber(subscriber);
|
||||
traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent2.class);
|
||||
@ -71,7 +71,7 @@ public class TraceEventPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveSubscriber() {
|
||||
void testRemoveSubscriber() {
|
||||
traceEventPublisher.addSubscriber(subscriber, TraceTestEvent.TraceTestEvent1.class);
|
||||
traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent1.class);
|
||||
TraceTestEvent.TraceTestEvent1 traceTestEvent1 = new TraceTestEvent.TraceTestEvent1();
|
||||
@ -95,7 +95,7 @@ public class TraceEventPublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getStatus() throws NacosException {
|
||||
void getStatus() throws NacosException {
|
||||
traceEventPublisher.publish(new TraceTestEvent());
|
||||
traceEventPublisher.publish(new TraceTestEvent.TraceTestEvent1());
|
||||
traceEventPublisher.publish(new TraceTestEvent.TraceTestEvent2());
|
||||
|
@ -19,6 +19,7 @@ package com.alibaba.nacos.common.trace.publisher;
|
||||
import com.alibaba.nacos.common.notify.Event;
|
||||
|
||||
public class TraceTestEvent extends Event {
|
||||
|
||||
private static final long serialVersionUID = 8568231862586636388L;
|
||||
|
||||
static class TraceTestEvent1 extends TraceTestEvent {
|
||||
|
@ -16,37 +16,40 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Test ArrayUtils.
|
||||
*
|
||||
* @author zzq
|
||||
*/
|
||||
public class ArrayUtilsTest {
|
||||
class ArrayUtilsTest {
|
||||
|
||||
Integer[] nullArr = null;
|
||||
|
||||
Integer[] nothingArr = new Integer[]{};
|
||||
Integer[] nothingArr = new Integer[] {};
|
||||
|
||||
@Test
|
||||
public void testisEmpty() {
|
||||
Integer[] arr = new Integer[]{1, 2};
|
||||
Assert.assertTrue(ArrayUtils.isEmpty(nullArr));
|
||||
Assert.assertTrue(ArrayUtils.isEmpty(nothingArr));
|
||||
Assert.assertFalse(ArrayUtils.isEmpty(arr));
|
||||
void testisEmpty() {
|
||||
Integer[] arr = new Integer[] {1, 2};
|
||||
assertTrue(ArrayUtils.isEmpty(nullArr));
|
||||
assertTrue(ArrayUtils.isEmpty(nothingArr));
|
||||
assertFalse(ArrayUtils.isEmpty(arr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contains() {
|
||||
Integer[] arr = new Integer[]{1, 2, 3};
|
||||
Integer[] arr1 = new Integer[]{1, 2, 3, null};
|
||||
Assert.assertFalse(ArrayUtils.contains(nullArr, "a"));
|
||||
Assert.assertFalse(ArrayUtils.contains(nullArr, null));
|
||||
Assert.assertFalse(ArrayUtils.contains(nothingArr, "b"));
|
||||
Assert.assertFalse(ArrayUtils.contains(arr, null));
|
||||
Assert.assertTrue(ArrayUtils.contains(arr1, null));
|
||||
Assert.assertTrue(ArrayUtils.contains(arr, 1));
|
||||
Assert.assertFalse(ArrayUtils.contains(arr, "1"));
|
||||
void contains() {
|
||||
assertFalse(ArrayUtils.contains(nullArr, "a"));
|
||||
assertFalse(ArrayUtils.contains(nullArr, null));
|
||||
assertFalse(ArrayUtils.contains(nothingArr, "b"));
|
||||
Integer[] arr = new Integer[] {1, 2, 3};
|
||||
assertFalse(ArrayUtils.contains(arr, null));
|
||||
Integer[] arr1 = new Integer[] {1, 2, 3, null};
|
||||
assertTrue(ArrayUtils.contains(arr1, null));
|
||||
assertTrue(ArrayUtils.contains(arr, 1));
|
||||
assertFalse(ArrayUtils.contains(arr, "1"));
|
||||
}
|
||||
}
|
||||
|
@ -17,8 +17,12 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import com.alibaba.nacos.common.utils.to.User;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* ByteUtils Test.
|
||||
@ -27,51 +31,51 @@ import org.junit.Test;
|
||||
* @Author: ChenHao26
|
||||
* @Date: 2022/8/22 10:58
|
||||
*/
|
||||
public class ByteUtilsTest {
|
||||
class ByteUtilsTest {
|
||||
|
||||
@Test
|
||||
public void objectToByte() {
|
||||
void objectToByte() {
|
||||
User user = new User(1, "google");
|
||||
byte[] bytes = ByteUtils.toBytes(user);
|
||||
Assert.assertNotNull(bytes);
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stringToByte() {
|
||||
void stringToByte() {
|
||||
byte[] bytes = ByteUtils.toBytes("google");
|
||||
Assert.assertNotNull(bytes);
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringTest() {
|
||||
void toStringTest() {
|
||||
byte[] bytes = ByteUtils.toBytes("google");
|
||||
String str = ByteUtils.toString(bytes);
|
||||
Assert.assertEquals(str, "google");
|
||||
assertEquals("google", str);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForInputNull() {
|
||||
Assert.assertEquals(0, ByteUtils.toBytes(null).length);
|
||||
Assert.assertEquals(0, ByteUtils.toBytes((Object) null).length);
|
||||
Assert.assertEquals("", ByteUtils.toString(null));
|
||||
void testForInputNull() {
|
||||
assertEquals(0, ByteUtils.toBytes(null).length);
|
||||
assertEquals(0, ByteUtils.toBytes((Object) null).length);
|
||||
assertEquals("", ByteUtils.toString(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEmpty() {
|
||||
void isEmpty() {
|
||||
byte[] bytes = ByteUtils.toBytes("");
|
||||
Assert.assertTrue(ByteUtils.isEmpty(bytes));
|
||||
assertTrue(ByteUtils.isEmpty(bytes));
|
||||
byte[] byte2 = new byte[1024];
|
||||
Assert.assertFalse(ByteUtils.isEmpty(byte2));
|
||||
assertFalse(ByteUtils.isEmpty(byte2));
|
||||
byte[] byte3 = null;
|
||||
Assert.assertTrue(ByteUtils.isEmpty(byte3));
|
||||
assertTrue(ByteUtils.isEmpty(byte3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEmpty() {
|
||||
void isNotEmpty() {
|
||||
byte[] bytes = ByteUtils.toBytes("google");
|
||||
Assert.assertTrue(ByteUtils.isNotEmpty(bytes));
|
||||
assertTrue(ByteUtils.isNotEmpty(bytes));
|
||||
byte[] bytes2 = ByteUtils.toBytes("");
|
||||
Assert.assertFalse(ByteUtils.isNotEmpty(bytes2));
|
||||
assertFalse(ByteUtils.isNotEmpty(bytes2));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -17,94 +17,99 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClassUtilsTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ClassUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testFindClassByName1() {
|
||||
void testFindClassByName1() {
|
||||
Class<?> clazz = ClassUtils.findClassByName("java.lang.Integer");
|
||||
Assert.assertEquals("java.lang.Integer", clazz.getName());
|
||||
}
|
||||
|
||||
@Test(expected = NacosRuntimeException.class)
|
||||
public void testFindClassByName2() {
|
||||
ClassUtils.findClassByName("not.exist.Class");
|
||||
assertEquals("java.lang.Integer", clazz.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetName() {
|
||||
void testFindClassByName2() {
|
||||
assertThrows(NacosRuntimeException.class, () -> {
|
||||
ClassUtils.findClassByName("not.exist.Class");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetName() {
|
||||
final String name = "java.lang.Integer";
|
||||
Integer val = 1;
|
||||
Assert.assertEquals(name, ClassUtils.getName(val));
|
||||
Assert.assertEquals(name, ClassUtils.getName(Integer.class));
|
||||
assertEquals(name, ClassUtils.getName(val));
|
||||
assertEquals(name, ClassUtils.getName(Integer.class));
|
||||
|
||||
Assert.assertEquals(name, ClassUtils.getCanonicalName(val));
|
||||
Assert.assertEquals(name, ClassUtils.getCanonicalName(Integer.class));
|
||||
assertEquals(name, ClassUtils.getCanonicalName(val));
|
||||
assertEquals(name, ClassUtils.getCanonicalName(Integer.class));
|
||||
|
||||
Assert.assertEquals("Integer", ClassUtils.getSimpleName(val));
|
||||
Assert.assertEquals("Integer", ClassUtils.getSimpleName(Integer.class));
|
||||
assertEquals("Integer", ClassUtils.getSimpleName(val));
|
||||
assertEquals("Integer", ClassUtils.getSimpleName(Integer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsAssignableFrom() {
|
||||
Assert.assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class));
|
||||
void testIsAssignableFrom() {
|
||||
assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForNameArray() throws ClassNotFoundException {
|
||||
void testForNameArray() throws ClassNotFoundException {
|
||||
Class clazz = ClassUtils.forName("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", null);
|
||||
Assert.assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName());
|
||||
assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName());
|
||||
clazz = ClassUtils.forName("java.lang.String[]", null);
|
||||
Assert.assertEquals("[Ljava.lang.String;", clazz.getName());
|
||||
assertEquals("[Ljava.lang.String;", clazz.getName());
|
||||
clazz = ClassUtils.forName("[[Ljava.lang.String;", null);
|
||||
Assert.assertEquals("[[Ljava.lang.String;", clazz.getName());
|
||||
}
|
||||
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void testForNameNonExist() throws ClassNotFoundException {
|
||||
ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null);
|
||||
assertEquals("[[Ljava.lang.String;", clazz.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
|
||||
void testForNameNonExist() throws ClassNotFoundException {
|
||||
assertThrows(ClassNotFoundException.class, () -> {
|
||||
ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
|
||||
Field field = ClassUtils.class.getDeclaredField("PRIMITIVE_TYPE_NAME_MAP");
|
||||
field.setAccessible(true);
|
||||
Map<String, Class<?>> map = (Map<String, Class<?>>) field.get(null);
|
||||
map.put("Test", ClassUtilsTest.class);
|
||||
Assert.assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null));
|
||||
assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDefaultClassLoader() {
|
||||
void testGetDefaultClassLoader() {
|
||||
ClassLoader cachedClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
try {
|
||||
Thread.currentThread().setContextClassLoader(null);
|
||||
Assert.assertNotNull(ClassUtils.getDefaultClassLoader());
|
||||
assertNotNull(ClassUtils.getDefaultClassLoader());
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(cachedClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClassPackageAsResourcePath() throws ClassNotFoundException {
|
||||
void testClassPackageAsResourcePath() throws ClassNotFoundException {
|
||||
Class noPackageClass = ClassUtils.forName("ClassUtilsTestMockClass", null);
|
||||
Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(null));
|
||||
Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass));
|
||||
Assert.assertEquals("com/alibaba/nacos/common/utils",
|
||||
ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class));
|
||||
assertEquals("", ClassUtils.classPackageAsResourcePath(null));
|
||||
assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass));
|
||||
assertEquals("com/alibaba/nacos/common/utils", ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertClassNameAndClassPath() {
|
||||
void testConvertClassNameAndClassPath() {
|
||||
String name = ClassUtilsTest.class.getName();
|
||||
Assert.assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest",
|
||||
ClassUtils.convertClassNameToResourcePath(name));
|
||||
Assert.assertEquals(name,
|
||||
ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest"));
|
||||
assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest", ClassUtils.convertClassNameToResourcePath(name));
|
||||
assertEquals(name, ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest"));
|
||||
}
|
||||
}
|
@ -16,8 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@ -36,277 +35,323 @@ import java.util.Vector;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit test of CollectionUtil.
|
||||
*
|
||||
* @author <a href="mailto:jifeng.sun@outlook.com">sunjifeng</a>
|
||||
*/
|
||||
public class CollectionUtilsTest {
|
||||
class CollectionUtilsTest {
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetList1() {
|
||||
CollectionUtils.get(Collections.emptyList(), -1);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetList2() {
|
||||
CollectionUtils.get(Collections.emptyList(), 1);
|
||||
@Test
|
||||
void testGetList1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptyList(), -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetList3() {
|
||||
Assert.assertEquals("element", CollectionUtils.get(Collections.singletonList("element"), 0));
|
||||
Assert.assertEquals("element2", CollectionUtils.get(Arrays.asList("element1", "element2"), 1));
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetMap1() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
CollectionUtils.get(map, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetMap2() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
CollectionUtils.get(map, -1);
|
||||
CollectionUtils.get(map, 1);
|
||||
void testGetList2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptyList(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMap3() {
|
||||
void testGetList3() {
|
||||
assertEquals("element", CollectionUtils.get(Collections.singletonList("element"), 0));
|
||||
assertEquals("element2", CollectionUtils.get(Arrays.asList("element1", "element2"), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetMap1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
CollectionUtils.get(map, -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetMap2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
CollectionUtils.get(map, -1);
|
||||
CollectionUtils.get(map, 1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetMap3() {
|
||||
Map<String, String> map1 = new LinkedHashMap(1);
|
||||
Map<String, String> map2 = new LinkedHashMap(2);
|
||||
map1.put("key", "value");
|
||||
map2.put("key1", "value1");
|
||||
map2.put("key2", "value2");
|
||||
Iterator<Map.Entry<String, String>> iter = map1.entrySet().iterator();
|
||||
Assert.assertEquals(iter.next(), CollectionUtils.get(map1, 0));
|
||||
assertEquals(iter.next(), CollectionUtils.get(map1, 0));
|
||||
Iterator<Map.Entry<String, String>> iter2 = map2.entrySet().iterator();
|
||||
iter2.next();
|
||||
Map.Entry<String, String> second = iter2.next();
|
||||
Assert.assertEquals(second, CollectionUtils.get(map2, 1));
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetArray1() {
|
||||
CollectionUtils.get(new Object[] {}, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetArray2() {
|
||||
CollectionUtils.get(new Object[] {}, 0);
|
||||
assertEquals(second, CollectionUtils.get(map2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetArray3() {
|
||||
Assert.assertEquals("1", CollectionUtils.get(new Object[] {"1"}, 0));
|
||||
Assert.assertEquals("2", CollectionUtils.get(new Object[] {"1", "2"}, 1));
|
||||
}
|
||||
|
||||
@Test(expected = ArrayIndexOutOfBoundsException.class)
|
||||
public void testGetArray4() {
|
||||
CollectionUtils.get(new int[] {}, 0);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetArray5() {
|
||||
CollectionUtils.get(new int[] {}, -1);
|
||||
void testGetArray1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(new Object[] {}, -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetArray6() {
|
||||
Assert.assertEquals(1, CollectionUtils.get(new int[] {1, 2}, 0));
|
||||
Assert.assertEquals(2, CollectionUtils.get(new int[] {1, 2}, 1));
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetIterator1() {
|
||||
CollectionUtils.get(Collections.emptyIterator(), 0);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetIterator2() {
|
||||
CollectionUtils.get(Collections.emptyIterator(), -1);
|
||||
void testGetArray2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(new Object[] {}, 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIterator3() {
|
||||
Assert.assertEquals("1", CollectionUtils.get(Collections.singleton("1").iterator(), 0));
|
||||
Assert.assertEquals("2", CollectionUtils.get(Arrays.asList("1", "2").iterator(), 1));
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetCollection1() {
|
||||
CollectionUtils.get(Collections.emptySet(), 0);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetCollection2() {
|
||||
CollectionUtils.get(Collections.emptySet(), -1);
|
||||
void testGetArray3() {
|
||||
assertEquals("1", CollectionUtils.get(new Object[] {"1"}, 0));
|
||||
assertEquals("2", CollectionUtils.get(new Object[] {"1", "2"}, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCollection3() {
|
||||
Assert.assertEquals("1", CollectionUtils.get(Collections.singleton("1"), 0));
|
||||
Assert.assertEquals("2", CollectionUtils.get(CollectionUtils.set("1", "2"), 1));
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetEnumeration1() {
|
||||
CollectionUtils.get(asEnumeration(Collections.emptyIterator()), 0);
|
||||
}
|
||||
|
||||
@Test(expected = IndexOutOfBoundsException.class)
|
||||
public void testGetEnumeration2() {
|
||||
CollectionUtils.get(asEnumeration(Collections.emptyIterator()), -1);
|
||||
void testGetArray4() {
|
||||
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(new int[] {}, 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetEnumeration3() {
|
||||
void testGetArray5() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(new int[] {}, -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetArray6() {
|
||||
assertEquals(1, CollectionUtils.get(new int[] {1, 2}, 0));
|
||||
assertEquals(2, CollectionUtils.get(new int[] {1, 2}, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetIterator1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptyIterator(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetIterator2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptyIterator(), -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetIterator3() {
|
||||
assertEquals("1", CollectionUtils.get(Collections.singleton("1").iterator(), 0));
|
||||
assertEquals("2", CollectionUtils.get(Arrays.asList("1", "2").iterator(), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCollection1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptySet(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCollection2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(Collections.emptySet(), -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCollection3() {
|
||||
assertEquals("1", CollectionUtils.get(Collections.singleton("1"), 0));
|
||||
assertEquals("2", CollectionUtils.get(CollectionUtils.set("1", "2"), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetEnumeration1() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(asEnumeration(Collections.emptyIterator()), 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetEnumeration2() {
|
||||
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||
CollectionUtils.get(asEnumeration(Collections.emptyIterator()), -1);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetEnumeration3() {
|
||||
Vector<Object> vector = new Vector<>();
|
||||
vector.add("1");
|
||||
vector.add("2");
|
||||
|
||||
Assert.assertEquals("1", CollectionUtils.get(vector.elements(), 0));
|
||||
Assert.assertEquals("2", CollectionUtils.get(vector.elements(), 1));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGet1() {
|
||||
CollectionUtils.get(null, 0);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGet2() {
|
||||
CollectionUtils.get("string", 0);
|
||||
assertEquals("1", CollectionUtils.get(vector.elements(), 0));
|
||||
assertEquals("2", CollectionUtils.get(vector.elements(), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
void testGet1() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.get(null, 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGet2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.get("string", 0);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSize() {
|
||||
// collection
|
||||
Assert.assertEquals(0, CollectionUtils.size(Collections.emptyList()));
|
||||
Assert.assertEquals(1, CollectionUtils.size(Collections.singletonList("")));
|
||||
Assert.assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList())));
|
||||
assertEquals(0, CollectionUtils.size(Collections.emptyList()));
|
||||
assertEquals(1, CollectionUtils.size(Collections.singletonList("")));
|
||||
assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList())));
|
||||
|
||||
// map
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
Assert.assertEquals(1, CollectionUtils.size(map));
|
||||
assertEquals(1, CollectionUtils.size(map));
|
||||
map.put("key2", "value2");
|
||||
Assert.assertEquals(2, CollectionUtils.size(map));
|
||||
assertEquals(2, CollectionUtils.size(map));
|
||||
map.put("key3", "value3");
|
||||
Assert.assertEquals(3, CollectionUtils.size(map));
|
||||
assertEquals(3, CollectionUtils.size(map));
|
||||
|
||||
// array
|
||||
Assert.assertEquals(1, CollectionUtils.size(new Object[] {"1"}));
|
||||
Assert.assertEquals(2, CollectionUtils.size(new Object[] {"1", "2"}));
|
||||
Assert.assertEquals(6, CollectionUtils.size(new Object[] {"1", "2", "3", "4", "5", "6"}));
|
||||
Assert.assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).boxed().toArray()));
|
||||
assertEquals(1, CollectionUtils.size(new Object[] {"1"}));
|
||||
assertEquals(2, CollectionUtils.size(new Object[] {"1", "2"}));
|
||||
assertEquals(6, CollectionUtils.size(new Object[] {"1", "2", "3", "4", "5", "6"}));
|
||||
assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).boxed().toArray()));
|
||||
|
||||
// primitive array
|
||||
Assert.assertEquals(1, CollectionUtils.size(new int[] {1}));
|
||||
Assert.assertEquals(2, CollectionUtils.size(new int[] {1, 2}));
|
||||
Assert.assertEquals(6, CollectionUtils.size(new int[] {1, 2, 3, 4, 5, 6}));
|
||||
Assert.assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).toArray()));
|
||||
assertEquals(1, CollectionUtils.size(new int[] {1}));
|
||||
assertEquals(2, CollectionUtils.size(new int[] {1, 2}));
|
||||
assertEquals(6, CollectionUtils.size(new int[] {1, 2, 3, 4, 5, 6}));
|
||||
assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).toArray()));
|
||||
|
||||
// iterator
|
||||
Assert.assertEquals(1, CollectionUtils.size(Collections.singleton("1").iterator()));
|
||||
Assert.assertEquals(2, CollectionUtils.size(Arrays.asList("1", "2").iterator()));
|
||||
assertEquals(1, CollectionUtils.size(Collections.singleton("1").iterator()));
|
||||
assertEquals(2, CollectionUtils.size(Arrays.asList("1", "2").iterator()));
|
||||
|
||||
// enumeration
|
||||
Assert.assertEquals(0, CollectionUtils.size(asEnumeration(Collections.emptyIterator())));
|
||||
Assert.assertEquals(1, CollectionUtils.size(asEnumeration(Collections.singleton("").iterator())));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSize1() {
|
||||
CollectionUtils.size(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSize2() {
|
||||
CollectionUtils.size("string");
|
||||
assertEquals(0, CollectionUtils.size(asEnumeration(Collections.emptyIterator())));
|
||||
assertEquals(1, CollectionUtils.size(asEnumeration(Collections.singleton("").iterator())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSizeIsEmpty() {
|
||||
void testSize1() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.size(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSize2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.size("string");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSizeIsEmpty() {
|
||||
// collection
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyList()));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(Collections.singletonList("")));
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyList()));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(Collections.singletonList("")));
|
||||
|
||||
// map
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyMap()));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(map));
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyMap()));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(map));
|
||||
|
||||
// array
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(new Object[] {}));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(new Object[] {"1", "2"}));
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(new Object[] {}));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(new Object[] {"1", "2"}));
|
||||
|
||||
// primitive array
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(new int[] {}));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(new int[] {1, 2}));
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(new int[] {}));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(new int[] {1, 2}));
|
||||
|
||||
// iterator
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyIterator()));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(Arrays.asList("1", "2").iterator()));
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyIterator()));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(Arrays.asList("1", "2").iterator()));
|
||||
|
||||
// enumeration
|
||||
Assert.assertTrue(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.emptyIterator())));
|
||||
Assert.assertFalse(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.singleton("").iterator())));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSizeIsEmpty1() {
|
||||
CollectionUtils.sizeIsEmpty(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSizeIsEmpty2() {
|
||||
CollectionUtils.sizeIsEmpty("string");
|
||||
assertTrue(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.emptyIterator())));
|
||||
assertFalse(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.singleton("").iterator())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContains() {
|
||||
Assert.assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target"));
|
||||
Assert.assertFalse(CollectionUtils.contains(Collections.emptyList(), "target"));
|
||||
void testSizeIsEmpty1() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.sizeIsEmpty(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmpty() {
|
||||
Assert.assertFalse(CollectionUtils.isEmpty(Collections.singletonList("target")));
|
||||
Assert.assertTrue(CollectionUtils.isEmpty(Collections.emptyList()));
|
||||
Assert.assertTrue(CollectionUtils.isEmpty(null));
|
||||
void testSizeIsEmpty2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.sizeIsEmpty("string");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsNotEmpty() {
|
||||
Assert.assertTrue(CollectionUtils.isNotEmpty(Collections.singletonList("target")));
|
||||
Assert.assertFalse(CollectionUtils.isNotEmpty(Collections.emptyList()));
|
||||
Assert.assertFalse(CollectionUtils.isNotEmpty(null));
|
||||
void testContains() {
|
||||
assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target"));
|
||||
assertFalse(CollectionUtils.contains(Collections.emptyList(), "target"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetOrDefault() {
|
||||
Assert.assertEquals("default", CollectionUtils.getOrDefault(Collections.emptyList(), 1, "default"));
|
||||
Assert.assertEquals("element",
|
||||
CollectionUtils.getOrDefault(Collections.singletonList("element"), 0, "default"));
|
||||
void testIsEmpty() {
|
||||
assertFalse(CollectionUtils.isEmpty(Collections.singletonList("target")));
|
||||
assertTrue(CollectionUtils.isEmpty(Collections.emptyList()));
|
||||
assertTrue(CollectionUtils.isEmpty(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testList() {
|
||||
Assert.assertEquals(Arrays.asList(null, null, null), CollectionUtils.list(null, null, null));
|
||||
Assert.assertEquals(Arrays.asList("", "a", "b"), CollectionUtils.list("", "a", "b"));
|
||||
Assert.assertEquals(new ArrayList(), CollectionUtils.list());
|
||||
void testIsNotEmpty() {
|
||||
assertTrue(CollectionUtils.isNotEmpty(Collections.singletonList("target")));
|
||||
assertFalse(CollectionUtils.isNotEmpty(Collections.emptyList()));
|
||||
assertFalse(CollectionUtils.isNotEmpty(null));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testListNullPointerException() {
|
||||
CollectionUtils.list(null);
|
||||
@Test
|
||||
void testGetOrDefault() {
|
||||
assertEquals("default", CollectionUtils.getOrDefault(Collections.emptyList(), 1, "default"));
|
||||
assertEquals("element", CollectionUtils.getOrDefault(Collections.singletonList("element"), 0, "default"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testList() {
|
||||
assertEquals(Arrays.asList(null, null, null), CollectionUtils.list(null, null, null));
|
||||
assertEquals(Arrays.asList("", "a", "b"), CollectionUtils.list("", "a", "b"));
|
||||
assertEquals(new ArrayList(), CollectionUtils.list());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testListNullPointerException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.list(null);
|
||||
});
|
||||
}
|
||||
|
||||
private <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
|
||||
@ -325,71 +370,79 @@ public class CollectionUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet() {
|
||||
void testSet() {
|
||||
Set<Object> set = new HashSet<>();
|
||||
set.add(null);
|
||||
Assert.assertEquals(set, CollectionUtils.set(null, null, null));
|
||||
Assert.assertEquals(new LinkedHashSet(Arrays.asList("", "a", "b")), CollectionUtils.set("", "a", "b"));
|
||||
Assert.assertEquals(new HashSet(), CollectionUtils.set());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testSetNullPointerException() {
|
||||
CollectionUtils.set(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetOnlyElementIllegalArgumentException() {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
CollectionUtils.getOnlyElement(list);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetOnlyElementIllegalArgumentException2() {
|
||||
CollectionUtils.getOnlyElement(null);
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void testGetOnlyElementNoSuchElementException() {
|
||||
List<Object> list = new ArrayList<>();
|
||||
CollectionUtils.getOnlyElement(list);
|
||||
assertEquals(set, CollectionUtils.set(null, null, null));
|
||||
assertEquals(new LinkedHashSet(Arrays.asList("", "a", "b")), CollectionUtils.set("", "a", "b"));
|
||||
assertEquals(new HashSet(), CollectionUtils.set());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetOnly() {
|
||||
void testSetNullPointerException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.set(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetOnlyElementIllegalArgumentException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
CollectionUtils.getOnlyElement(list);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetOnlyElementIllegalArgumentException2() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
CollectionUtils.getOnlyElement(null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetOnlyElementNoSuchElementException() {
|
||||
assertThrows(NoSuchElementException.class, () -> {
|
||||
List<Object> list = new ArrayList<>();
|
||||
CollectionUtils.getOnlyElement(list);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetOnly() {
|
||||
List<Integer> list = Arrays.asList(1);
|
||||
int element = CollectionUtils.getOnlyElement(list);
|
||||
Assert.assertEquals(1, element);
|
||||
assertEquals(1, element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForNull() {
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(null, null));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList()));
|
||||
void testIsListEqualForNull() {
|
||||
assertTrue(CollectionUtils.isListEqual(null, null));
|
||||
assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null));
|
||||
assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForEquals() {
|
||||
void testIsListEqualForEquals() {
|
||||
List<String> list1 = Arrays.asList("1", "2", "3");
|
||||
List<String> list2 = Arrays.asList("1", "2", "3");
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list1, list1));
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list1, list2));
|
||||
Assert.assertTrue(CollectionUtils.isListEqual(list2, list1));
|
||||
assertTrue(CollectionUtils.isListEqual(list1, list1));
|
||||
assertTrue(CollectionUtils.isListEqual(list1, list2));
|
||||
assertTrue(CollectionUtils.isListEqual(list2, list1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsListEqualForNotEquals() {
|
||||
void testIsListEqualForNotEquals() {
|
||||
List<String> list1 = Arrays.asList("1", "2", "3");
|
||||
List<String> list2 = Arrays.asList("1", "2", "3", "4");
|
||||
List<String> list3 = Arrays.asList("1", "2", "3", "5");
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(list1, list2));
|
||||
Assert.assertFalse(CollectionUtils.isListEqual(list2, list3));
|
||||
assertFalse(CollectionUtils.isListEqual(list1, list2));
|
||||
assertFalse(CollectionUtils.isListEqual(list2, list3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsMapEmpty() {
|
||||
Assert.assertTrue(CollectionUtils.isMapEmpty(null));
|
||||
Assert.assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap()));
|
||||
void testIsMapEmpty() {
|
||||
assertTrue(CollectionUtils.isMapEmpty(null));
|
||||
assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap()));
|
||||
}
|
||||
}
|
||||
|
@ -16,55 +16,60 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* ConcurrentHashSet Test.
|
||||
*
|
||||
* @ClassName: ConcurrentHashSetTest
|
||||
* @Author: ChenHao26
|
||||
* @Date: 2022/8/22 11:21
|
||||
*/
|
||||
public class ConcurrentHashSetTest {
|
||||
class ConcurrentHashSetTest {
|
||||
|
||||
@Test
|
||||
public void testBasicOps() {
|
||||
void testBasicOps() {
|
||||
Set<Integer> set = new ConcurrentHashSet<>();
|
||||
|
||||
// addition
|
||||
Assert.assertTrue(set.add(0));
|
||||
Assert.assertTrue(set.add(1));
|
||||
Assert.assertTrue(set.contains(0));
|
||||
Assert.assertTrue(set.contains(1));
|
||||
Assert.assertFalse(set.contains(-1));
|
||||
Assert.assertEquals(2, set.size());
|
||||
assertTrue(set.add(0));
|
||||
assertTrue(set.add(1));
|
||||
assertTrue(set.contains(0));
|
||||
assertTrue(set.contains(1));
|
||||
assertFalse(set.contains(-1));
|
||||
assertEquals(2, set.size());
|
||||
|
||||
// iter
|
||||
for (int i : set) {
|
||||
Assert.assertTrue(i == 0 || i == 1);
|
||||
assertTrue(i == 0 || i == 1);
|
||||
}
|
||||
|
||||
// removal
|
||||
Assert.assertTrue(set.remove(0));
|
||||
Assert.assertFalse(set.remove(0));
|
||||
Assert.assertFalse(set.contains(0));
|
||||
Assert.assertTrue(set.contains(1));
|
||||
Assert.assertEquals(1, set.size());
|
||||
|
||||
assertTrue(set.remove(0));
|
||||
assertFalse(set.remove(0));
|
||||
assertFalse(set.contains(0));
|
||||
assertTrue(set.contains(1));
|
||||
assertEquals(1, set.size());
|
||||
|
||||
// clear
|
||||
Assert.assertFalse(set.isEmpty());
|
||||
assertFalse(set.isEmpty());
|
||||
set.clear();
|
||||
Assert.assertEquals(0, set.size());
|
||||
Assert.assertTrue(set.isEmpty());
|
||||
assertEquals(0, set.size());
|
||||
assertTrue(set.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultiThread() throws Exception {
|
||||
void testMultiThread() throws Exception {
|
||||
int count = 5;
|
||||
SetMultiThreadChecker hashSetChecker = new SetMultiThreadChecker(new HashSet<>());
|
||||
hashSetChecker.start();
|
||||
@ -75,8 +80,8 @@ public class ConcurrentHashSetTest {
|
||||
}
|
||||
count--;
|
||||
}
|
||||
Assert.assertTrue(hashSetChecker.hasConcurrentError());
|
||||
|
||||
assertTrue(hashSetChecker.hasConcurrentError());
|
||||
|
||||
count = 5;
|
||||
SetMultiThreadChecker concurrentSetChecker = new SetMultiThreadChecker(new ConcurrentHashSet<>());
|
||||
concurrentSetChecker.start();
|
||||
@ -87,17 +92,17 @@ public class ConcurrentHashSetTest {
|
||||
}
|
||||
count--;
|
||||
}
|
||||
Assert.assertFalse(concurrentSetChecker.hasConcurrentError());
|
||||
assertFalse(concurrentSetChecker.hasConcurrentError());
|
||||
}
|
||||
|
||||
static class SetMultiThreadChecker {
|
||||
|
||||
|
||||
private final AddDataThread addThread;
|
||||
|
||||
private final DeleteDataThread deleteThread;
|
||||
|
||||
|
||||
private final IteratorThread iteratorThread;
|
||||
|
||||
|
||||
public SetMultiThreadChecker(Set<Integer> setToCheck) {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
setToCheck.add(i);
|
||||
@ -120,7 +125,7 @@ public class ConcurrentHashSetTest {
|
||||
public boolean isRunning() {
|
||||
return addThread.isRunning() || deleteThread.isRunning() || iteratorThread.isRunning();
|
||||
}
|
||||
|
||||
|
||||
public void stop() {
|
||||
addThread.stop();
|
||||
deleteThread.stop();
|
||||
@ -130,17 +135,17 @@ public class ConcurrentHashSetTest {
|
||||
}
|
||||
|
||||
abstract static class ConcurrentCheckThread implements Runnable {
|
||||
|
||||
|
||||
protected final Set<Integer> hashSet;
|
||||
|
||||
|
||||
protected boolean concurrentError = false;
|
||||
|
||||
protected boolean finish = false;
|
||||
|
||||
|
||||
public ConcurrentCheckThread(Set<Integer> hashSet) {
|
||||
this.hashSet = hashSet;
|
||||
}
|
||||
|
||||
|
||||
public boolean hasConcurrentError() {
|
||||
return concurrentError;
|
||||
}
|
||||
@ -148,11 +153,11 @@ public class ConcurrentHashSetTest {
|
||||
public void stop() {
|
||||
finish = true;
|
||||
}
|
||||
|
||||
|
||||
public boolean isRunning() {
|
||||
return !finish;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
@ -165,17 +170,17 @@ public class ConcurrentHashSetTest {
|
||||
finish = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected abstract void process();
|
||||
}
|
||||
|
||||
//add data thread
|
||||
static class AddDataThread extends ConcurrentCheckThread implements Runnable {
|
||||
|
||||
|
||||
public AddDataThread(Set<Integer> hashSet) {
|
||||
super(hashSet);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void process() {
|
||||
int random = new Random().nextInt(1000);
|
||||
@ -186,11 +191,11 @@ public class ConcurrentHashSetTest {
|
||||
|
||||
// delete data thread
|
||||
static class DeleteDataThread extends ConcurrentCheckThread implements Runnable {
|
||||
|
||||
|
||||
public DeleteDataThread(Set<Integer> hashSet) {
|
||||
super(hashSet);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void process() {
|
||||
int random = new Random().nextInt(1000);
|
||||
@ -200,11 +205,11 @@ public class ConcurrentHashSetTest {
|
||||
}
|
||||
|
||||
static class IteratorThread extends ConcurrentCheckThread implements Runnable {
|
||||
|
||||
|
||||
public IteratorThread(Set<Integer> hashSet) {
|
||||
super(hashSet);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("start -- hashSet.size() : " + hashSet.size());
|
||||
@ -223,7 +228,7 @@ public class ConcurrentHashSetTest {
|
||||
System.out.println("finished at " + f);
|
||||
System.out.println("end -- hashSet.size() : " + hashSet.size());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void process() {
|
||||
}
|
||||
|
@ -16,13 +16,14 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* description.
|
||||
@ -30,10 +31,10 @@ import static org.junit.Assert.assertTrue;
|
||||
* @author rong
|
||||
* @date 2024-03-01 15:10
|
||||
*/
|
||||
public class ConnLabelsUtilsTest {
|
||||
class ConnLabelsUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testParsePropertyValue2Map() {
|
||||
void testParsePropertyValue2Map() {
|
||||
Properties properties = new Properties();
|
||||
String property = "property";
|
||||
String rawValue = "k1 = v1, k2 = v2";
|
||||
@ -50,7 +51,7 @@ public class ConnLabelsUtilsTest {
|
||||
Map<String, String> m1 = ConnLabelsUtils.parsePropertyValue2Map(properties, property1);
|
||||
assertEquals(1, m1.size());
|
||||
assertEquals("v11", m1.get("k11"));
|
||||
assertEquals(null, m1.get("kk2"));
|
||||
assertNull(m1.get("kk2"));
|
||||
|
||||
m = ConnLabelsUtils.mergeMapByOrder(m, m1);
|
||||
assertEquals(3, m.size());
|
||||
|
@ -16,306 +16,310 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit test of ConvertUtils.
|
||||
*
|
||||
* @author <a href="mailto:jifeng.sun@outlook.com">sunjifeng</a>
|
||||
*/
|
||||
public class ConvertUtilsTest {
|
||||
class ConvertUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testToInt() {
|
||||
void testToInt() {
|
||||
// ConvertUtils.toInt(String)
|
||||
Assert.assertEquals(0, ConvertUtils.toInt("0"));
|
||||
Assert.assertEquals(-1, ConvertUtils.toInt("-1"));
|
||||
Assert.assertEquals(10, ConvertUtils.toInt("10"));
|
||||
Assert.assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE)));
|
||||
Assert.assertEquals(Integer.MIN_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MIN_VALUE)));
|
||||
Assert.assertEquals(0, ConvertUtils.toInt("notIntValue"));
|
||||
assertEquals(0, ConvertUtils.toInt("0"));
|
||||
assertEquals(-1, ConvertUtils.toInt("-1"));
|
||||
assertEquals(10, ConvertUtils.toInt("10"));
|
||||
assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE)));
|
||||
assertEquals(Integer.MIN_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MIN_VALUE)));
|
||||
assertEquals(0, ConvertUtils.toInt("notIntValue"));
|
||||
|
||||
// ConvertUtils.toInt(String, Integer)
|
||||
Assert.assertEquals(0, ConvertUtils.toInt("0", 100));
|
||||
Assert.assertEquals(100, ConvertUtils.toInt(null, 100));
|
||||
Assert.assertEquals(100, ConvertUtils.toInt("null", 100));
|
||||
Assert.assertEquals(100, ConvertUtils.toInt("notIntValue", 100));
|
||||
assertEquals(0, ConvertUtils.toInt("0", 100));
|
||||
assertEquals(100, ConvertUtils.toInt(null, 100));
|
||||
assertEquals(100, ConvertUtils.toInt("null", 100));
|
||||
assertEquals(100, ConvertUtils.toInt("notIntValue", 100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToLong() {
|
||||
void testToLong() {
|
||||
// ConvertUtils.toLong(Object)
|
||||
Assert.assertEquals(0L, ConvertUtils.toLong(new ArrayList<>()));
|
||||
Assert.assertEquals(10L, ConvertUtils.toLong((Object) 10L));
|
||||
assertEquals(0L, ConvertUtils.toLong(new ArrayList<>()));
|
||||
assertEquals(10L, ConvertUtils.toLong((Object) 10L));
|
||||
|
||||
// ConvertUtils.toLong(String)
|
||||
Assert.assertEquals(0L, ConvertUtils.toLong("0"));
|
||||
Assert.assertEquals(-1L, ConvertUtils.toLong("-1"));
|
||||
Assert.assertEquals(10L, ConvertUtils.toLong("10"));
|
||||
Assert.assertEquals(Long.MAX_VALUE, ConvertUtils.toLong(String.valueOf(Long.MAX_VALUE)));
|
||||
Assert.assertEquals(Long.MIN_VALUE, ConvertUtils.toLong(String.valueOf(Long.MIN_VALUE)));
|
||||
Assert.assertEquals(0L, ConvertUtils.toLong("notIntValue"));
|
||||
assertEquals(0L, ConvertUtils.toLong("0"));
|
||||
assertEquals(-1L, ConvertUtils.toLong("-1"));
|
||||
assertEquals(10L, ConvertUtils.toLong("10"));
|
||||
assertEquals(Long.MAX_VALUE, ConvertUtils.toLong(String.valueOf(Long.MAX_VALUE)));
|
||||
assertEquals(Long.MIN_VALUE, ConvertUtils.toLong(String.valueOf(Long.MIN_VALUE)));
|
||||
assertEquals(0L, ConvertUtils.toLong("notIntValue"));
|
||||
|
||||
// ConvertUtils.toLong(String, Integer)
|
||||
Assert.assertEquals(0L, ConvertUtils.toLong("0", 100L));
|
||||
Assert.assertEquals(100L, ConvertUtils.toLong(null, 100L));
|
||||
Assert.assertEquals(100L, ConvertUtils.toLong("null", 100L));
|
||||
Assert.assertEquals(100L, ConvertUtils.toLong("notIntValue", 100L));
|
||||
assertEquals(0L, ConvertUtils.toLong("0", 100L));
|
||||
assertEquals(100L, ConvertUtils.toLong(null, 100L));
|
||||
assertEquals(100L, ConvertUtils.toLong("null", 100L));
|
||||
assertEquals(100L, ConvertUtils.toLong("notIntValue", 100L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToBoolean() {
|
||||
void testToBoolean() {
|
||||
// ConvertUtils.toBoolean(String)
|
||||
Assert.assertTrue(ConvertUtils.toBoolean("true"));
|
||||
Assert.assertTrue(ConvertUtils.toBoolean("True"));
|
||||
Assert.assertTrue(ConvertUtils.toBoolean("TRUE"));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("false"));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("False"));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("FALSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean(null));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("notBoolean"));
|
||||
assertTrue(ConvertUtils.toBoolean("true"));
|
||||
assertTrue(ConvertUtils.toBoolean("True"));
|
||||
assertTrue(ConvertUtils.toBoolean("TRUE"));
|
||||
assertFalse(ConvertUtils.toBoolean("false"));
|
||||
assertFalse(ConvertUtils.toBoolean("False"));
|
||||
assertFalse(ConvertUtils.toBoolean("FALSE"));
|
||||
assertFalse(ConvertUtils.toBoolean(null));
|
||||
assertFalse(ConvertUtils.toBoolean("notBoolean"));
|
||||
|
||||
// ConvertUtils.toBoolean(String, boolean)
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("", false));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean(null, false));
|
||||
Assert.assertFalse(ConvertUtils.toBoolean("notBoolean", false));
|
||||
Assert.assertTrue(ConvertUtils.toBoolean("true", false));
|
||||
assertFalse(ConvertUtils.toBoolean("", false));
|
||||
assertFalse(ConvertUtils.toBoolean(null, false));
|
||||
assertFalse(ConvertUtils.toBoolean("notBoolean", false));
|
||||
assertTrue(ConvertUtils.toBoolean("true", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToBooleanObject() {
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("T"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("t"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("Y"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("y"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("f"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("F"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("n"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("N"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("a"));
|
||||
void testToBooleanObject() {
|
||||
assertTrue(ConvertUtils.toBooleanObject("T"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("t"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("Y"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("y"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("f"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("F"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("n"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("N"));
|
||||
assertNull(ConvertUtils.toBooleanObject("a"));
|
||||
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("on"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("oN"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("On"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("ON"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("No"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("NO"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("an"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aN"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("oa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Oa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Na"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("na"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aO"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("ao"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("on"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("oN"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("On"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("ON"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("No"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("NO"));
|
||||
assertNull(ConvertUtils.toBooleanObject("an"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aN"));
|
||||
assertNull(ConvertUtils.toBooleanObject("oa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Oa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Na"));
|
||||
assertNull(ConvertUtils.toBooleanObject("na"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aO"));
|
||||
assertNull(ConvertUtils.toBooleanObject("ao"));
|
||||
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("off"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("ofF"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("oFf"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("oFF"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("Off"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("OfF"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("OFf"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("OFF"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("yes"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("yeS"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("yEs"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("yES"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("Yes"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("YeS"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("YEs"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("YES"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("ono"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aes"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aeS"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aEs"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aES"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("yas"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("yaS"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Yas"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("YaS"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("yea"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("yEa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Yea"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("YEa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aff"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("afF"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aFf"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("aFF"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("oaf"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("oaF"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Oaf"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("OaF"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Ofa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("ofa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("OFa"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("oFa"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("off"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("ofF"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("oFf"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("oFF"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("Off"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("OfF"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("OFf"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("OFF"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("yes"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("yeS"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("yEs"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("yES"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("Yes"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("YeS"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("YEs"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("YES"));
|
||||
assertNull(ConvertUtils.toBooleanObject("ono"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aes"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aeS"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aEs"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aES"));
|
||||
assertNull(ConvertUtils.toBooleanObject("yas"));
|
||||
assertNull(ConvertUtils.toBooleanObject("yaS"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Yas"));
|
||||
assertNull(ConvertUtils.toBooleanObject("YaS"));
|
||||
assertNull(ConvertUtils.toBooleanObject("yea"));
|
||||
assertNull(ConvertUtils.toBooleanObject("yEa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Yea"));
|
||||
assertNull(ConvertUtils.toBooleanObject("YEa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aff"));
|
||||
assertNull(ConvertUtils.toBooleanObject("afF"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aFf"));
|
||||
assertNull(ConvertUtils.toBooleanObject("aFF"));
|
||||
assertNull(ConvertUtils.toBooleanObject("oaf"));
|
||||
assertNull(ConvertUtils.toBooleanObject("oaF"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Oaf"));
|
||||
assertNull(ConvertUtils.toBooleanObject("OaF"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Ofa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("ofa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("OFa"));
|
||||
assertNull(ConvertUtils.toBooleanObject("oFa"));
|
||||
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("true"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("truE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("trUe"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("trUE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("tRue"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("tRuE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("tRUe"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("tRUE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("True"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TruE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TrUe"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TrUE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TRue"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TRuE"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TRUe"));
|
||||
Assert.assertTrue(ConvertUtils.toBooleanObject("TRUE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Xrue"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XruE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XrUe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XrUE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XRue"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XRuE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XRUe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XRUE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tXue"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tXuE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tXUe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tXUE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TXue"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TXuE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TXUe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TXUE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("trXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("trXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tRXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tRXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TrXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TrXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TRXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TRXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("truX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("trUX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tRuX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("tRUX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TruX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TrUX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TRuX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("TRUX"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("true"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("truE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("trUe"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("trUE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("tRue"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("tRuE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("tRUe"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("tRUE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("True"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TruE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TrUe"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TrUE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TRue"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TRuE"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TRUe"));
|
||||
assertTrue(ConvertUtils.toBooleanObject("TRUE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Xrue"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XruE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XrUe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XrUE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XRue"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XRuE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XRUe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XRUE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tXue"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tXuE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tXUe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tXUE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TXue"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TXuE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TXUe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TXUE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("trXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("trXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tRXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tRXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TrXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TrXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TRXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TRXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("truX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("trUX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tRuX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("tRUX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TruX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TrUX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TRuX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("TRUX"));
|
||||
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("false"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("falsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("falSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("falSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("faLse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("faLsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("faLSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("faLSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fAlse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fAlsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fALse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fALsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fALSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("fALSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("False"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FalsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FalSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FalSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FaLse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FaLsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FAlse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FAlsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FALse"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FALsE"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FALSe"));
|
||||
Assert.assertFalse(ConvertUtils.toBooleanObject("FALSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("Xalse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XalsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XalSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XalSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XaLse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XaLsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XaLSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XaLSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XAlse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XAlsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XAlSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XAlSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XALse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XALsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XALSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("XALSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXlse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXlsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXlSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXlSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXLse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXLsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXLSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fXLSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXlse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXlsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXlSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXlSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXLse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXLsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXLSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FXLSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faXse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faXsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faXSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faXSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAXse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAXsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAXSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAXSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaXse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaXsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaXSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaXSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAXse"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAXsE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAXSe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAXSE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("falXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("falXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faLXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faLXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAlXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAlXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fALXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fALXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FalXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FalXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaLXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaLXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAlXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAlXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FALXe"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FALXE"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("falsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("falSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faLsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("faLSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAlsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fAlSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fALsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("fALSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FalsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FalSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaLsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FaLSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAlsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FAlSX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FALsX"));
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject("FALSX"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("false"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("falsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("falSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("falSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("faLse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("faLsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("faLSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("faLSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fAlse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fAlsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fAlSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fAlSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fALse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fALsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fALSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("fALSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("False"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FalsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FalSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FalSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FaLse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FaLsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FaLSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FaLSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FAlse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FAlsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FAlSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FAlSE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FALse"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FALsE"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FALSe"));
|
||||
assertFalse(ConvertUtils.toBooleanObject("FALSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("Xalse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XalsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XalSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XalSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XaLse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XaLsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XaLSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XaLSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XAlse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XAlsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XAlSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XAlSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XALse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XALsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XALSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("XALSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXlse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXlsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXlSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXlSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXLse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXLsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXLSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fXLSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXlse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXlsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXlSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXlSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXLse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXLsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXLSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FXLSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faXse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faXsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faXSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faXSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAXse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAXsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAXSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAXSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaXse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaXsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaXSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaXSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAXse"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAXsE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAXSe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAXSE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("falXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("falXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faLXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faLXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAlXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAlXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fALXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fALXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FalXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FalXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaLXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaLXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAlXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAlXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FALXe"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FALXE"));
|
||||
assertNull(ConvertUtils.toBooleanObject("falsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("falSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faLsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("faLSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAlsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fAlSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fALsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("fALSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FalsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FalSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaLsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FaLSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAlsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FAlSX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FALsX"));
|
||||
assertNull(ConvertUtils.toBooleanObject("FALSX"));
|
||||
|
||||
Assert.assertNull(ConvertUtils.toBooleanObject(null));
|
||||
assertNull(ConvertUtils.toBooleanObject(null));
|
||||
}
|
||||
}
|
@ -16,21 +16,24 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* DateFormatUtils test.
|
||||
*
|
||||
* @author zzq
|
||||
*/
|
||||
public class DateFormatUtilsTest {
|
||||
class DateFormatUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testformat() {
|
||||
void testformat() {
|
||||
final Calendar c = Calendar.getInstance(TimeZone.getDefault());
|
||||
c.set(2021, Calendar.JANUARY, 1, 12, 0, 0);
|
||||
c.setTimeZone(TimeZone.getDefault());
|
||||
@ -43,16 +46,20 @@ public class DateFormatUtilsTest {
|
||||
buffer.append(month);
|
||||
buffer.append(day);
|
||||
buffer.append(hour);
|
||||
Assert.assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH"));
|
||||
assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH"));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testForNullPointerExceptionWithDate() {
|
||||
DateFormatUtils.format(new Date(), null);
|
||||
@Test
|
||||
void testForNullPointerExceptionWithDate() {
|
||||
assertThrows(NullPointerException.class, () -> {
|
||||
DateFormatUtils.format(new Date(), null);
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void testForNullPointerExceptionWithPattern() {
|
||||
DateFormatUtils.format(null, "yyyyMdH");
|
||||
@Test
|
||||
void testForNullPointerExceptionWithPattern() {
|
||||
assertThrows(NullPointerException.class, () -> {
|
||||
DateFormatUtils.format(null, "yyyyMdH");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -17,42 +17,42 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ExceptionUtilTest {
|
||||
class ExceptionUtilTest {
|
||||
|
||||
NacosRuntimeException nacosRuntimeException;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
RuntimeException caused = new RuntimeException("I'm caused exception.");
|
||||
nacosRuntimeException = new NacosRuntimeException(500, "Test", caused);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAllExceptionMsg() {
|
||||
void testGetAllExceptionMsg() {
|
||||
String msg = ExceptionUtil.getAllExceptionMsg(nacosRuntimeException);
|
||||
assertEquals("caused: errCode: 500, errMsg: Test ;caused: I'm caused exception.;", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCause() {
|
||||
void testGetCause() {
|
||||
assertEquals("I'm caused exception.", ExceptionUtil.getCause(nacosRuntimeException).getMessage());
|
||||
NacosRuntimeException nreWithoutCaused = new NacosRuntimeException(500);
|
||||
assertEquals(nreWithoutCaused, ExceptionUtil.getCause(nreWithoutCaused));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStackTrace() {
|
||||
void testGetStackTrace() {
|
||||
assertEquals("", ExceptionUtil.getStackTrace(null));
|
||||
String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException);
|
||||
assertTrue(stackTrace.contains(
|
||||
"com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test"));
|
||||
assertTrue(
|
||||
stackTrace.contains("com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test"));
|
||||
assertTrue(stackTrace.contains("at"));
|
||||
assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception."));
|
||||
}
|
||||
|
@ -16,46 +16,49 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* InetAddressValidator Test.
|
||||
*
|
||||
* @ClassName: InetAddressValidatorTest
|
||||
* @Author: ChenHao26
|
||||
* @Date: 2022/8/22 13:07
|
||||
*/
|
||||
public class InetAddressValidatorTest {
|
||||
class InetAddressValidatorTest {
|
||||
|
||||
@Test
|
||||
public void isIPv6Address() {
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6Address("2000:0000:0000:0000:0001:2345:6789:abcd"));
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6Address("2001:DB8:0:0:8:800:200C:417A"));
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C:417A"));
|
||||
Assert.assertFalse(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C141aA"));
|
||||
void isIPv6Address() {
|
||||
assertTrue(InetAddressValidator.isIPv6Address("2000:0000:0000:0000:0001:2345:6789:abcd"));
|
||||
assertTrue(InetAddressValidator.isIPv6Address("2001:DB8:0:0:8:800:200C:417A"));
|
||||
assertTrue(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C:417A"));
|
||||
assertFalse(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C141aA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isIPv6MixedAddress() {
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18"));
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18"));
|
||||
Assert.assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA"));
|
||||
void isIPv6MixedAddress() {
|
||||
assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18"));
|
||||
assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18"));
|
||||
assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isIPv6IPv4MappedAddress() {
|
||||
Assert.assertFalse(InetAddressValidator.isIPv6IPv4MappedAddress(":ffff:1.1.1.1"));
|
||||
Assert.assertTrue(InetAddressValidator.isIPv6IPv4MappedAddress("::FFFF:192.168.1.2"));
|
||||
void isIPv6IPv4MappedAddress() {
|
||||
assertFalse(InetAddressValidator.isIPv6IPv4MappedAddress(":ffff:1.1.1.1"));
|
||||
assertTrue(InetAddressValidator.isIPv6IPv4MappedAddress("::FFFF:192.168.1.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isIPv4Address() {
|
||||
Assert.assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2"));
|
||||
void isIPv4Address() {
|
||||
assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isLinkLocalIPv6WithZoneIndex() {
|
||||
Assert.assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0"));
|
||||
Assert.assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd"));
|
||||
void isLinkLocalIPv6WithZoneIndex() {
|
||||
assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0"));
|
||||
assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd"));
|
||||
}
|
||||
}
|
||||
|
@ -16,12 +16,17 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* test IpUtil.
|
||||
*
|
||||
@ -31,70 +36,90 @@ import java.lang.reflect.Modifier;
|
||||
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
|
||||
public class InternetAddressUtilTest {
|
||||
|
||||
@Test
|
||||
public void testIsIPv4() {
|
||||
Assert.assertTrue(InternetAddressUtil.isIPv4("127.0.0.1"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv4("[::1]"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv4("asdfasf"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv4("ffgertert"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv4("127.100.19"));
|
||||
/**
|
||||
* checkSplitIpPortStr. 2020/9/4 14:12
|
||||
*
|
||||
* @param addr addr
|
||||
* @param isEx isEx
|
||||
* @param equalsStrs equalsStrs
|
||||
*/
|
||||
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
|
||||
try {
|
||||
String[] array = InternetAddressUtil.splitIPPortStr(addr);
|
||||
assertEquals(array.length, equalsStrs.length);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
assertEquals(array[i], equalsStrs[i]);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (!isEx) {
|
||||
// No exception is expected here, but an exception has occurred
|
||||
fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsIPv6() {
|
||||
Assert.assertTrue(InternetAddressUtil.isIPv6("[::1]"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv6("127.0.0.1"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIPv6("er34234"));
|
||||
void testIsIPv4() {
|
||||
assertTrue(InternetAddressUtil.isIPv4("127.0.0.1"));
|
||||
assertFalse(InternetAddressUtil.isIPv4("[::1]"));
|
||||
assertFalse(InternetAddressUtil.isIPv4("asdfasf"));
|
||||
assertFalse(InternetAddressUtil.isIPv4("ffgertert"));
|
||||
assertFalse(InternetAddressUtil.isIPv4("127.100.19"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsIP() {
|
||||
Assert.assertTrue(InternetAddressUtil.isIP("[::1]"));
|
||||
Assert.assertTrue(InternetAddressUtil.isIP("127.0.0.1"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIP("er34234"));
|
||||
Assert.assertFalse(InternetAddressUtil.isIP("127.100.19"));
|
||||
void testIsIPv6() {
|
||||
assertTrue(InternetAddressUtil.isIPv6("[::1]"));
|
||||
assertFalse(InternetAddressUtil.isIPv6("127.0.0.1"));
|
||||
assertFalse(InternetAddressUtil.isIPv6("er34234"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIPFromString() {
|
||||
Assert.assertEquals("[::1]",
|
||||
InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString(
|
||||
void testIsIP() {
|
||||
assertTrue(InternetAddressUtil.isIP("[::1]"));
|
||||
assertTrue(InternetAddressUtil.isIP("127.0.0.1"));
|
||||
assertFalse(InternetAddressUtil.isIP("er34234"));
|
||||
assertFalse(InternetAddressUtil.isIP("127.100.19"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetIPFromString() {
|
||||
assertEquals("[::1]", InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
assertEquals("[::1]", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("127.0.0.1",
|
||||
assertEquals("127.0.0.1",
|
||||
InternetAddressUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666"));
|
||||
assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666"));
|
||||
|
||||
Assert.assertEquals("",
|
||||
InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://[127.0.0.1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://666.288.333.444:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://292.168.1.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://29.168.1.288:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://29.168.288.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(
|
||||
"jdbc:mysql://29.288.28.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
|
||||
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(""));
|
||||
Assert.assertEquals("", InternetAddressUtil.getIPFromString(null));
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(""));
|
||||
assertEquals("", InternetAddressUtil.getIPFromString(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitIpPort() {
|
||||
void testSplitIpPort() {
|
||||
checkSplitIPPortStr("[::1]:88", false, "[::1]", "88");
|
||||
checkSplitIPPortStr("[::1]", false, "[::1]");
|
||||
checkSplitIPPortStr("127.0.0.1:88", false, "127.0.0.1", "88");
|
||||
@ -121,48 +146,48 @@ public class InternetAddressUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckIPs() {
|
||||
Assert.assertEquals("ok", InternetAddressUtil.checkIPs("127.0.0.1"));
|
||||
Assert.assertEquals("ok", InternetAddressUtil.checkIPs());
|
||||
Assert.assertEquals("ok", InternetAddressUtil.checkIPs());
|
||||
Assert.assertEquals("ok", InternetAddressUtil.checkIPs(null));
|
||||
void testCheckIPs() {
|
||||
assertEquals("ok", InternetAddressUtil.checkIPs("127.0.0.1"));
|
||||
assertEquals("ok", InternetAddressUtil.checkIPs());
|
||||
assertEquals("ok", InternetAddressUtil.checkIPs());
|
||||
assertEquals("ok", InternetAddressUtil.checkIPs(null));
|
||||
|
||||
Assert.assertEquals("illegal ip: 127.100.19", InternetAddressUtil.checkIPs("127.100.19", "127.0.0.1"));
|
||||
assertEquals("illegal ip: 127.100.19", InternetAddressUtil.checkIPs("127.100.19", "127.0.0.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsDomain() {
|
||||
Assert.assertTrue(InternetAddressUtil.isDomain("localhost"));
|
||||
Assert.assertTrue(InternetAddressUtil.isDomain("github.com"));
|
||||
Assert.assertTrue(InternetAddressUtil.isDomain("prefix.infix.suffix"));
|
||||
Assert.assertTrue(InternetAddressUtil.isDomain("p-hub.com"));
|
||||
void testIsDomain() {
|
||||
assertTrue(InternetAddressUtil.isDomain("localhost"));
|
||||
assertTrue(InternetAddressUtil.isDomain("github.com"));
|
||||
assertTrue(InternetAddressUtil.isDomain("prefix.infix.suffix"));
|
||||
assertTrue(InternetAddressUtil.isDomain("p-hub.com"));
|
||||
|
||||
Assert.assertFalse(InternetAddressUtil.isDomain(""));
|
||||
Assert.assertFalse(InternetAddressUtil.isDomain(null));
|
||||
assertFalse(InternetAddressUtil.isDomain(""));
|
||||
assertFalse(InternetAddressUtil.isDomain(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveBrackets() {
|
||||
Assert.assertEquals(InternetAddressUtil.removeBrackets("[2001:DB8:0:0:1::1]"), "2001:DB8:0:0:1::1");
|
||||
Assert.assertEquals(InternetAddressUtil.removeBrackets("[2077[]]]"), "2077");
|
||||
Assert.assertEquals(InternetAddressUtil.removeBrackets(""), "");
|
||||
Assert.assertEquals(InternetAddressUtil.removeBrackets(null), "");
|
||||
void testRemoveBrackets() {
|
||||
assertEquals("2001:DB8:0:0:1::1", InternetAddressUtil.removeBrackets("[2001:DB8:0:0:1::1]"));
|
||||
assertEquals("2077", InternetAddressUtil.removeBrackets("[2077[]]]"));
|
||||
assertEquals("", InternetAddressUtil.removeBrackets(""));
|
||||
assertEquals("", InternetAddressUtil.removeBrackets(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckOk() {
|
||||
Assert.assertTrue(InternetAddressUtil.checkOK("ok"));
|
||||
Assert.assertFalse(InternetAddressUtil.checkOK("ojbk"));
|
||||
void testCheckOk() {
|
||||
assertTrue(InternetAddressUtil.checkOK("ok"));
|
||||
assertFalse(InternetAddressUtil.checkOK("ojbk"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContainsPort() {
|
||||
Assert.assertTrue(InternetAddressUtil.containsPort("127.0.0.1:80"));
|
||||
Assert.assertFalse(InternetAddressUtil.containsPort("127.0.0.1:80:80"));
|
||||
void testContainsPort() {
|
||||
assertTrue(InternetAddressUtil.containsPort("127.0.0.1:80"));
|
||||
assertFalse(InternetAddressUtil.containsPort("127.0.0.1:80:80"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException {
|
||||
void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException {
|
||||
Field field = InternetAddressUtil.class.getField("PREFER_IPV6_ADDRESSES");
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
@ -170,43 +195,23 @@ public class InternetAddressUtilTest {
|
||||
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
|
||||
|
||||
field.set(null, false);
|
||||
Assert.assertEquals("127.0.0.1", InternetAddressUtil.localHostIP());
|
||||
assertEquals("127.0.0.1", InternetAddressUtil.localHostIP());
|
||||
|
||||
field.set(null, true);
|
||||
Assert.assertEquals("[::1]", InternetAddressUtil.localHostIP());
|
||||
assertEquals("[::1]", InternetAddressUtil.localHostIP());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIpToInt() {
|
||||
Assert.assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1"));
|
||||
Assert.assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1"));
|
||||
void testIpToInt() {
|
||||
assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1"));
|
||||
assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testIllegalIpToInt() {
|
||||
InternetAddressUtil.ipToInt("127.0.0.256");
|
||||
}
|
||||
|
||||
/**
|
||||
* checkSplitIpPortStr. 2020/9/4 14:12
|
||||
*
|
||||
* @param addr addr
|
||||
* @param isEx isEx
|
||||
* @param equalsStrs equalsStrs
|
||||
*/
|
||||
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
|
||||
try {
|
||||
String[] array = InternetAddressUtil.splitIPPortStr(addr);
|
||||
Assert.assertEquals(array.length, equalsStrs.length);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
Assert.assertEquals(array[i], equalsStrs[i]);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (!isEx) {
|
||||
// No exception is expected here, but an exception has occurred
|
||||
Assert.fail("Unexpected exception");
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void testIllegalIpToInt() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
InternetAddressUtil.ipToInt("127.0.0.256");
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -17,8 +17,7 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.apache.commons.io.Charsets;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import sun.security.action.GetPropertyAction;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
@ -33,6 +32,12 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.AccessController;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@ -42,35 +47,35 @@ import static org.mockito.Mockito.when;
|
||||
*
|
||||
* @author karsonto
|
||||
*/
|
||||
public class IoUtilsTest {
|
||||
class IoUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testTryDecompressForNotGzip() throws Exception {
|
||||
void testTryDecompressForNotGzip() throws Exception {
|
||||
byte[] testCase = "123".getBytes(Charsets.toCharset("UTF-8"));
|
||||
Assert.assertEquals(testCase, IoUtils.tryDecompress(testCase));
|
||||
assertEquals(testCase, IoUtils.tryDecompress(testCase));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTryDecompressForGzip() throws Exception {
|
||||
void testTryDecompressForGzip() throws Exception {
|
||||
byte[] testCase = IoUtils.tryCompress("123", "UTF-8");
|
||||
Assert.assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8));
|
||||
assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTryCompressWithEmptyString() {
|
||||
Assert.assertEquals(0, IoUtils.tryCompress("", "UTF-8").length);
|
||||
Assert.assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length);
|
||||
void testTryCompressWithEmptyString() {
|
||||
assertEquals(0, IoUtils.tryCompress("", "UTF-8").length);
|
||||
assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWriteStringToFile() throws IOException {
|
||||
void testWriteStringToFile() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
file = File.createTempFile("test_writeStringToFile", ".txt");
|
||||
IoUtils.writeStringToFile(file, "123", "UTF-8");
|
||||
List<String> actual = IoUtils.readLines(new FileReader(file));
|
||||
Assert.assertEquals(1, actual.size());
|
||||
Assert.assertEquals("123", actual.get(0));
|
||||
assertEquals(1, actual.size());
|
||||
assertEquals("123", actual.get(0));
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.deleteOnExit();
|
||||
@ -79,30 +84,30 @@ public class IoUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToStringWithNull() throws IOException {
|
||||
Assert.assertEquals("", IoUtils.toString(null, "UTF-8"));
|
||||
void testToStringWithNull() throws IOException {
|
||||
assertEquals("", IoUtils.toString(null, "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToStringWithReader() throws IOException {
|
||||
void testToStringWithReader() throws IOException {
|
||||
String testCase = "123";
|
||||
Assert.assertEquals(testCase,
|
||||
assertEquals(testCase,
|
||||
IoUtils.toString(new ByteArrayInputStream(testCase.getBytes(Charsets.toCharset("UTF-8"))), "UTF-8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForNullFile() throws IOException {
|
||||
void testDeleteForNullFile() throws IOException {
|
||||
IoUtils.delete(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSuccess() throws IOException {
|
||||
void testDeleteSuccess() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
file = File.createTempFile("test_deleteForFile", ".txt");
|
||||
Assert.assertTrue(file.exists());
|
||||
assertTrue(file.exists());
|
||||
IoUtils.delete(file);
|
||||
Assert.assertFalse(file.exists());
|
||||
assertFalse(file.exists());
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.deleteOnExit();
|
||||
@ -110,26 +115,28 @@ public class IoUtilsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testDeleteFileFailure() throws IOException {
|
||||
File file = mock(File.class);
|
||||
when(file.exists()).thenReturn(true);
|
||||
when(file.delete()).thenReturn(false);
|
||||
IoUtils.delete(file);
|
||||
@Test
|
||||
void testDeleteFileFailure() throws IOException {
|
||||
assertThrows(IOException.class, () -> {
|
||||
File file = mock(File.class);
|
||||
when(file.exists()).thenReturn(true);
|
||||
when(file.delete()).thenReturn(false);
|
||||
IoUtils.delete(file);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForDirectory() throws IOException {
|
||||
void testDeleteForDirectory() throws IOException {
|
||||
File file = null;
|
||||
try {
|
||||
String tmpDir = AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir"));
|
||||
File tmpDirFile = new File(tmpDir, "IoUtilsTest");
|
||||
tmpDirFile.mkdirs();
|
||||
file = File.createTempFile("test_deleteForDirectory", ".txt", tmpDirFile);
|
||||
Assert.assertTrue(file.exists());
|
||||
assertTrue(file.exists());
|
||||
IoUtils.delete(file.getParentFile());
|
||||
Assert.assertTrue(tmpDirFile.exists());
|
||||
Assert.assertFalse(file.exists());
|
||||
assertTrue(tmpDirFile.exists());
|
||||
assertFalse(file.exists());
|
||||
} finally {
|
||||
if (null != file) {
|
||||
file.getParentFile().deleteOnExit();
|
||||
@ -138,88 +145,96 @@ public class IoUtilsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCleanDirectoryForNonExistingDirectory() throws IOException {
|
||||
File nonexistentDir = new File("non_exist");
|
||||
IoUtils.cleanDirectory(nonexistentDir);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCleanDirectoryForFile() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testCleanDirectoryWithEmptyDirectory() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void testCleanDirectory() throws IOException {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
File mockSubFile = mock(File.class);
|
||||
when(mockSubFile.exists()).thenReturn(true);
|
||||
when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile});
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
@Test
|
||||
void testCleanDirectoryForNonExistingDirectory() throws IOException {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
File nonexistentDir = new File("non_exist");
|
||||
IoUtils.cleanDirectory(nonexistentDir);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsGzipStreamWithNull() {
|
||||
Assert.assertFalse(IoUtils.isGzipStream(null));
|
||||
void testCleanDirectoryForFile() throws IOException {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsGzipStreamWithEmpty() {
|
||||
Assert.assertFalse(IoUtils.isGzipStream(new byte[0]));
|
||||
void testCleanDirectoryWithEmptyDirectory() throws IOException {
|
||||
assertThrows(IOException.class, () -> {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
});
|
||||
}
|
||||
|
||||
@Test()
|
||||
public void testCloseQuietly() throws IOException {
|
||||
@Test
|
||||
void testCleanDirectory() throws IOException {
|
||||
assertThrows(IOException.class, () -> {
|
||||
File mockFile = mock(File.class);
|
||||
when(mockFile.exists()).thenReturn(true);
|
||||
when(mockFile.isDirectory()).thenReturn(true);
|
||||
File mockSubFile = mock(File.class);
|
||||
when(mockSubFile.exists()).thenReturn(true);
|
||||
when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile});
|
||||
IoUtils.cleanDirectory(mockFile);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsGzipStreamWithNull() {
|
||||
assertFalse(IoUtils.isGzipStream(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsGzipStreamWithEmpty() {
|
||||
assertFalse(IoUtils.isGzipStream(new byte[0]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCloseQuietly() throws IOException {
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(new ByteArrayInputStream("111".getBytes(Charsets.toCharset("UTF-8")))));
|
||||
Assert.assertEquals("111", br.readLine());
|
||||
assertEquals("111", br.readLine());
|
||||
IoUtils.closeQuietly(br);
|
||||
try {
|
||||
br.readLine();
|
||||
} catch (IOException e) {
|
||||
Assert.assertNotNull(e);
|
||||
assertNotNull(e);
|
||||
return;
|
||||
}
|
||||
Assert.fail();
|
||||
fail();
|
||||
}
|
||||
|
||||
@Test()
|
||||
public void testCloseQuietly2() throws IOException {
|
||||
@Test
|
||||
void testCloseQuietly2() throws IOException {
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(new ByteArrayInputStream("123".getBytes(Charsets.toCharset("UTF-8")))));
|
||||
Assert.assertEquals("123", br.readLine());
|
||||
assertEquals("123", br.readLine());
|
||||
BufferedReader br2 = new BufferedReader(
|
||||
new InputStreamReader(new ByteArrayInputStream("456".getBytes(Charsets.toCharset("UTF-8")))));
|
||||
Assert.assertEquals("456", br2.readLine());
|
||||
assertEquals("456", br2.readLine());
|
||||
IoUtils.closeQuietly(br, br2);
|
||||
try {
|
||||
br.readLine();
|
||||
} catch (IOException e) {
|
||||
Assert.assertNotNull(e);
|
||||
assertNotNull(e);
|
||||
}
|
||||
try {
|
||||
br2.readLine();
|
||||
} catch (IOException e) {
|
||||
Assert.assertNotNull(e);
|
||||
assertNotNull(e);
|
||||
return;
|
||||
}
|
||||
Assert.fail();
|
||||
fail();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseQuietlyForHttpConnection() throws IOException {
|
||||
void testCloseQuietlyForHttpConnection() throws IOException {
|
||||
HttpURLConnection conn = mock(HttpURLConnection.class);
|
||||
InputStream inputStream = mock(InputStream.class);
|
||||
when(conn.getInputStream()).thenReturn(inputStream);
|
||||
|
@ -29,8 +29,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
@ -45,154 +44,161 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class JacksonUtilsTest {
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class JacksonUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testToJson1() {
|
||||
Assert.assertEquals("null", JacksonUtils.toJson(null));
|
||||
Assert.assertEquals("\"string\"", JacksonUtils.toJson("string"));
|
||||
Assert.assertEquals("30", JacksonUtils.toJson(new BigDecimal(30)));
|
||||
Assert.assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value")));
|
||||
Assert.assertEquals("[{\"key\":\"value\"}]",
|
||||
void testToJson1() {
|
||||
assertEquals("null", JacksonUtils.toJson(null));
|
||||
assertEquals("\"string\"", JacksonUtils.toJson("string"));
|
||||
assertEquals("30", JacksonUtils.toJson(new BigDecimal(30)));
|
||||
assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value")));
|
||||
assertEquals("[{\"key\":\"value\"}]",
|
||||
JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value"))));
|
||||
Assert.assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}",
|
||||
JacksonUtils.toJson(new TestOfAtomicObject()));
|
||||
Assert.assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate()));
|
||||
assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}", JacksonUtils.toJson(new TestOfAtomicObject()));
|
||||
assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate()));
|
||||
// only public
|
||||
Assert.assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier()));
|
||||
assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier()));
|
||||
// getter is also recognized
|
||||
Assert.assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter()));
|
||||
assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter()));
|
||||
// annotation available
|
||||
Assert.assertEquals(
|
||||
assertEquals(
|
||||
"{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}", JacksonUtils.toJson(new TestOfAnnotationSub()));
|
||||
}
|
||||
|
||||
@Test(expected = NacosSerializationException.class)
|
||||
public void testToJson2() {
|
||||
// object without field will throw exceptions
|
||||
JacksonUtils.toJson(new Object());
|
||||
@Test
|
||||
void testToJson2() {
|
||||
assertThrows(NacosSerializationException.class, () -> {
|
||||
// object without field will throw exceptions
|
||||
JacksonUtils.toJson(new Object());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToJsonBytes1() {
|
||||
Assert.assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null));
|
||||
Assert.assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string"));
|
||||
Assert.assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30)));
|
||||
Assert.assertArrayEquals("{\"key\":\"value\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value")));
|
||||
Assert.assertArrayEquals("[{\"key\":\"value\"}]".getBytes(),
|
||||
void testToJsonBytes1() {
|
||||
assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null));
|
||||
assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string"));
|
||||
assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30)));
|
||||
assertArrayEquals("{\"key\":\"value\"}".getBytes(), JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value")));
|
||||
assertArrayEquals("[{\"key\":\"value\"}]".getBytes(),
|
||||
JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value"))));
|
||||
Assert.assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAtomicObject()));
|
||||
Assert.assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate()));
|
||||
assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate()));
|
||||
// only public
|
||||
Assert.assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(),
|
||||
assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfAccessModifier()));
|
||||
// getter is also recognized
|
||||
Assert.assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(),
|
||||
JacksonUtils.toJsonBytes(new TestOfGetter()));
|
||||
assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), JacksonUtils.toJsonBytes(new TestOfGetter()));
|
||||
// annotation available
|
||||
Assert.assertArrayEquals(
|
||||
assertArrayEquals(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\","
|
||||
+ "\"camelCase\":\"value\"}").getBytes(), JacksonUtils.toJsonBytes(new TestOfAnnotationSub()));
|
||||
}
|
||||
|
||||
@Test(expected = NacosSerializationException.class)
|
||||
public void testToJsonBytes2() {
|
||||
// object without field will throw exceptions
|
||||
JacksonUtils.toJsonBytes(new Object());
|
||||
@Test
|
||||
void testToJsonBytes2() {
|
||||
assertThrows(NacosSerializationException.class, () -> {
|
||||
// object without field will throw exceptions
|
||||
JacksonUtils.toJsonBytes(new Object());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], Class)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject1() {
|
||||
Assert.assertNull(JacksonUtils.toObj("null".getBytes(), Object.class));
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class));
|
||||
Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class));
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
void testToObject1() {
|
||||
assertNull(JacksonUtils.toObj("null".getBytes(), Object.class));
|
||||
assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class));
|
||||
assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class));
|
||||
assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class));
|
||||
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class));
|
||||
Assert.assertEquals(new TestOfAccessModifier(),
|
||||
assertEquals(new TestOfAtomicObject(),
|
||||
JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class));
|
||||
assertEquals(new TestOfDate(), JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class));
|
||||
assertEquals(new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class));
|
||||
Assert.assertEquals(new TestOfGetter(),
|
||||
assertEquals(new TestOfGetter(),
|
||||
JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils
|
||||
.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], Class)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject2() {
|
||||
JacksonUtils.toObj(("{not_A}Json:String}").getBytes(), TestOfAnnotationSub.class);
|
||||
@Test
|
||||
void testToObject2() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj(("{not_A}Json:String}").getBytes(), TestOfAnnotationSub.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], Type)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject3() {
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils
|
||||
.toObj("{\"key\":\"value\"}".getBytes(),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils
|
||||
.toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils
|
||||
.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
void testToObject3() {
|
||||
assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)));
|
||||
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(),
|
||||
TypeUtils.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], Type)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject4() {
|
||||
JacksonUtils
|
||||
.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
@Test
|
||||
void testToObject4() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], Type)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject5() {
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Object.class.getGenericSuperclass());
|
||||
@Test
|
||||
void testToObject5() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Object.class.getGenericSuperclass());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Class)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject6() {
|
||||
Assert.assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class));
|
||||
Assert.assertEquals("string",
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class));
|
||||
Assert.assertEquals(new BigDecimal(30),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class));
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
void testToObject6() {
|
||||
assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class));
|
||||
assertEquals("string", JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class));
|
||||
assertEquals(new BigDecimal(30), JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class));
|
||||
assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()),
|
||||
assertEquals(new TestOfAtomicObject(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()),
|
||||
TestOfAtomicObject.class));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class));
|
||||
Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()),
|
||||
assertEquals(new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()),
|
||||
TestOfAccessModifier.class));
|
||||
Assert.assertEquals(new TestOfGetter(), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()),
|
||||
assertEquals(new TestOfGetter(),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()),
|
||||
TestOfGetter.class));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream(
|
||||
assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\","
|
||||
+ "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes())),
|
||||
TestOfAnnotation.class));
|
||||
@ -201,62 +207,66 @@ public class JacksonUtilsTest {
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Class)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject7() {
|
||||
JacksonUtils.toObj((ByteArrayInputStream) null, BigDecimal.class);
|
||||
@Test
|
||||
void testToObject7() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj((ByteArrayInputStream) null, BigDecimal.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Class)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject8() {
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), Object.class);
|
||||
@Test
|
||||
void testToObject8() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), Object.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], TypeReference)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject9() {
|
||||
Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference<Object>() {
|
||||
void testToObject9() {
|
||||
assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference<Object>() {
|
||||
}));
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference<String>() {
|
||||
assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference<String>() {
|
||||
}));
|
||||
Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference<BigDecimal>() {
|
||||
assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference<BigDecimal>() {
|
||||
}));
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"),
|
||||
assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference<Map<String, String>>() {
|
||||
}));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference<List<Map<String, String>>>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils
|
||||
.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
new TypeReference<TestOfAtomicObject>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfDate(),
|
||||
JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference<TestOfDate>() {
|
||||
assertEquals(new TestOfAtomicObject(), JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(),
|
||||
new TypeReference<TestOfAtomicObject>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils
|
||||
.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference<TestOfAccessModifier>() {
|
||||
assertEquals(new TestOfDate(), JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference<TestOfDate>() {
|
||||
}));
|
||||
assertEquals(new TestOfAccessModifier(),
|
||||
JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference<TestOfAccessModifier>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfGetter(), JacksonUtils
|
||||
.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference<TestOfGetter>() {
|
||||
assertEquals(new TestOfGetter(),
|
||||
JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference<TestOfGetter>() {
|
||||
}));
|
||||
assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj(
|
||||
("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(),
|
||||
new TypeReference<TestOfAnnotation>() {
|
||||
}));
|
||||
Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils
|
||||
.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\","
|
||||
+ "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(),
|
||||
new TypeReference<TestOfAnnotation>() {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(byte[], TypeReference)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject10() {
|
||||
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() {
|
||||
@Test
|
||||
void testToObject10() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -264,106 +274,113 @@ public class JacksonUtilsTest {
|
||||
* JacksonUtils.toObj(InputStream, Type)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject11() {
|
||||
Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()),
|
||||
void testToObject11() {
|
||||
assertEquals(Collections.singletonMap("key", "value"),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class)));
|
||||
Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils
|
||||
.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()),
|
||||
TypeUtils.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))));
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Type)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject12() {
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
@Test
|
||||
void testToObject12() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()),
|
||||
TypeUtils.parameterize(Map.class, String.class, String.class));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Type)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject13() {
|
||||
JacksonUtils
|
||||
.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass());
|
||||
@Test
|
||||
void testToObject13() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(InputStream, Type)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject14() {
|
||||
JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass());
|
||||
@Test
|
||||
void testToObject14() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(String)
|
||||
*/
|
||||
@Test
|
||||
public void testToObject15() {
|
||||
Assert.assertEquals("null", JacksonUtils.toObj("null").asText());
|
||||
Assert.assertEquals("string", JacksonUtils.toObj("\"string\"").asText());
|
||||
Assert.assertEquals(30, JacksonUtils.toObj("30").asInt());
|
||||
Assert.assertEquals("value", JacksonUtils.toObj("{\"key\":\"value\"}").get("key").asText());
|
||||
Assert.assertEquals("value", JacksonUtils.toObj("[{\"key\":\"value\"}]").get(0).get("key").asText());
|
||||
void testToObject15() {
|
||||
assertEquals("null", JacksonUtils.toObj("null").asText());
|
||||
assertEquals("string", JacksonUtils.toObj("\"string\"").asText());
|
||||
assertEquals(30, JacksonUtils.toObj("30").asInt());
|
||||
assertEquals("value", JacksonUtils.toObj("{\"key\":\"value\"}").get("key").asText());
|
||||
assertEquals("value", JacksonUtils.toObj("[{\"key\":\"value\"}]").get(0).get("key").asText());
|
||||
|
||||
JsonNode jsonNode = JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}");
|
||||
Assert.assertEquals(0L, jsonNode.get("aLong").asLong());
|
||||
Assert.assertEquals(1, jsonNode.get("aInteger").asInt());
|
||||
assertEquals(0L, jsonNode.get("aLong").asLong());
|
||||
assertEquals(1, jsonNode.get("aInteger").asInt());
|
||||
}
|
||||
|
||||
/**
|
||||
* JacksonUtils.toObj(String)
|
||||
*/
|
||||
@Test(expected = Exception.class)
|
||||
public void testToObject16() {
|
||||
JacksonUtils.toObj("{not_A}Json:String}");
|
||||
@Test
|
||||
void testToObject16() {
|
||||
assertThrows(Exception.class, () -> {
|
||||
JacksonUtils.toObj("{not_A}Json:String}");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterSubtype() {
|
||||
void testRegisterSubtype() {
|
||||
JacksonUtils.registerSubtype(TestOfChild.class, "JacksonUtilsTest$TestOfChild");
|
||||
|
||||
Assert.assertEquals(new TestOfChild(), JacksonUtils
|
||||
.toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\","
|
||||
+ "\"childField\":\"childValue\"}", TestOfParent.class));
|
||||
assertEquals(new TestOfChild(), JacksonUtils.toObj(
|
||||
"{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\"," + "\"childField\":\"childValue\"}",
|
||||
TestOfParent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEmptyJsonNode() {
|
||||
Assert.assertEquals("", JacksonUtils.createEmptyJsonNode().asText());
|
||||
Assert.assertTrue(JacksonUtils.createEmptyJsonNode().isEmpty());
|
||||
void testCreateEmptyJsonNode() {
|
||||
assertEquals("", JacksonUtils.createEmptyJsonNode().asText());
|
||||
assertTrue(JacksonUtils.createEmptyJsonNode().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEmptyArrayNode() {
|
||||
Assert.assertEquals("", JacksonUtils.createEmptyJsonNode().asText());
|
||||
Assert.assertEquals(0, JacksonUtils.createEmptyArrayNode().size());
|
||||
Assert.assertTrue(JacksonUtils.createEmptyArrayNode().isEmpty());
|
||||
void testCreateEmptyArrayNode() {
|
||||
assertEquals("", JacksonUtils.createEmptyJsonNode().asText());
|
||||
assertEquals(0, JacksonUtils.createEmptyArrayNode().size());
|
||||
assertTrue(JacksonUtils.createEmptyArrayNode().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTransferToJsonNode() {
|
||||
void testTransferToJsonNode() {
|
||||
JsonNode jsonNode1 = JacksonUtils.transferToJsonNode(Collections.singletonMap("key", "value"));
|
||||
Assert.assertEquals("value", jsonNode1.get("key").asText());
|
||||
assertEquals("value", jsonNode1.get("key").asText());
|
||||
|
||||
JsonNode jsonNode2 = JacksonUtils.transferToJsonNode(new TestOfAtomicObject());
|
||||
Assert.assertEquals("0", jsonNode2.get("aLong").asText());
|
||||
Assert.assertEquals("1", jsonNode2.get("aInteger").asText());
|
||||
Assert.assertEquals("false", jsonNode2.get("aBoolean").asText());
|
||||
assertEquals("0", jsonNode2.get("aLong").asText());
|
||||
assertEquals("1", jsonNode2.get("aInteger").asText());
|
||||
assertEquals("false", jsonNode2.get("aBoolean").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructJavaType() {
|
||||
Assert.assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName());
|
||||
Assert.assertTrue(JacksonUtils.constructJavaType(String.class).isFinal());
|
||||
void testConstructJavaType() {
|
||||
assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName());
|
||||
assertTrue(JacksonUtils.constructJavaType(String.class).isFinal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToJsonBytes() {
|
||||
void testToJsonBytes() {
|
||||
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
||||
map.put("string", "你好,中国!");
|
||||
map.put("integer", 999);
|
||||
@ -372,8 +389,8 @@ public class JacksonUtilsTest {
|
||||
|
||||
byte[] bytes = JacksonUtils.toJsonBytes(restResult);
|
||||
String jsonFromBytes = ByteUtils.toString(bytes);
|
||||
Assert.assertTrue(jsonFromBytes.contains("\"code\":0"));
|
||||
Assert.assertTrue(jsonFromBytes.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}"));
|
||||
assertTrue(jsonFromBytes.contains("\"code\":0"));
|
||||
assertTrue(jsonFromBytes.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}"));
|
||||
// old `toJsonBytes` method implementation:
|
||||
// public static byte[] toJsonBytes(Object obj) {
|
||||
// try {
|
||||
@ -385,41 +402,46 @@ public class JacksonUtilsTest {
|
||||
|
||||
// here is a verification to compare with the old implementation
|
||||
byte[] bytesFromOldImplementation = ByteUtils.toBytes(JacksonUtils.toJson(restResult));
|
||||
String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation,
|
||||
Charset.forName(Constants.ENCODE));
|
||||
Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0"));
|
||||
Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}"));
|
||||
String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, Charset.forName(Constants.ENCODE));
|
||||
assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0"));
|
||||
assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToObjFromBytes() {
|
||||
void testToObjFromBytes() {
|
||||
String json = "{\"code\":0,\"data\":{\"string\":\"你好,中国!\",\"integer\":999}}";
|
||||
|
||||
RestResult<Map<String, Object>> restResult = JacksonUtils.toObj(json, RestResult.class);
|
||||
Assert.assertEquals(0, restResult.getCode());
|
||||
Assert.assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
Assert.assertEquals(999, restResult.getData().get("integer"));
|
||||
assertEquals(0, restResult.getCode());
|
||||
assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
assertEquals(999, restResult.getData().get("integer"));
|
||||
|
||||
restResult = JacksonUtils.toObj(json, new TypeReference<RestResult<Map<String, Object>>>() {
|
||||
});
|
||||
Assert.assertEquals(0, restResult.getCode());
|
||||
Assert.assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
Assert.assertEquals(999, restResult.getData().get("integer"));
|
||||
assertEquals(0, restResult.getCode());
|
||||
assertEquals("你好,中国!", restResult.getData().get("string"));
|
||||
assertEquals(999, restResult.getData().get("integer"));
|
||||
}
|
||||
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForClassWithException() {
|
||||
JacksonUtils.toObj("aaa", JsonNode.class);
|
||||
@Test
|
||||
void tesToObjForClassWithException() {
|
||||
assertThrows(NacosDeserializationException.class, () -> {
|
||||
JacksonUtils.toObj("aaa", JsonNode.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForTypeWithException() {
|
||||
JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class));
|
||||
@Test
|
||||
void tesToObjForTypeWithException() {
|
||||
assertThrows(NacosDeserializationException.class, () -> {
|
||||
JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class));
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = NacosDeserializationException.class)
|
||||
public void tesToObjForTypeTypeReferenceWithException() {
|
||||
JacksonUtils.toObj("aaa", new TypeReference<JsonNode>() {
|
||||
@Test
|
||||
void tesToObjForTypeTypeReferenceWithException() {
|
||||
assertThrows(NacosDeserializationException.class, () -> {
|
||||
JacksonUtils.toObj("aaa", new TypeReference<JsonNode>() {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -16,14 +16,14 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class LoggerUtilsTest {
|
||||
class LoggerUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testPrintIfDebugEnabled() {
|
||||
void testPrintIfDebugEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isDebugEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfDebugEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
@ -31,7 +31,7 @@ public class LoggerUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfInfoEnabled() {
|
||||
void testPrintIfInfoEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isInfoEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfInfoEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
@ -39,7 +39,7 @@ public class LoggerUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfTraceEnabled() {
|
||||
void testPrintIfTraceEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isTraceEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfTraceEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
@ -47,7 +47,7 @@ public class LoggerUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfWarnEnabled() {
|
||||
void testPrintIfWarnEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isWarnEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfWarnEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
@ -55,7 +55,7 @@ public class LoggerUtilsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrintIfErrorEnabled() {
|
||||
void testPrintIfErrorEnabled() {
|
||||
Logger logger = Mockito.mock(Logger.class);
|
||||
Mockito.when(logger.isErrorEnabled()).thenReturn(true);
|
||||
LoggerUtils.printIfErrorEnabled(logger, "test", "arg1", "arg2", "arg3");
|
||||
|
@ -17,29 +17,29 @@
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class MD5UtilsTest {
|
||||
class MD5UtilsTest {
|
||||
|
||||
@Test
|
||||
public void testMd5Hex() throws NoSuchAlgorithmException {
|
||||
Assert.assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex("", Constants.ENCODE));
|
||||
Assert.assertEquals("acbd18db4cc2f85cedef654fccc4a4d8", MD5Utils.md5Hex("foo", Constants.ENCODE));
|
||||
Assert.assertEquals("02f463eb799797e2a978fb1a2ae2991e", MD5Utils.md5Hex(
|
||||
void testMd5Hex() throws NoSuchAlgorithmException {
|
||||
assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex("", Constants.ENCODE));
|
||||
assertEquals("acbd18db4cc2f85cedef654fccc4a4d8", MD5Utils.md5Hex("foo", Constants.ENCODE));
|
||||
assertEquals("02f463eb799797e2a978fb1a2ae2991e", MD5Utils.md5Hex(
|
||||
"38c5ee9532f037a20b93d0f804cf111fca4003e451d09a692d9dea8032308d9c64eda9047fcd5e850284a49b1a0cfb2ecd45",
|
||||
Constants.ENCODE));
|
||||
|
||||
Assert.assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex(new byte[0]));
|
||||
Assert.assertEquals("5289df737df57326fcdd22597afb1fac", MD5Utils.md5Hex(new byte[] {1, 2, 3}));
|
||||
assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex(new byte[0]));
|
||||
assertEquals("5289df737df57326fcdd22597afb1fac", MD5Utils.md5Hex(new byte[] {1, 2, 3}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncodeHexString() {
|
||||
Assert.assertEquals("", MD5Utils.encodeHexString(new byte[0]));
|
||||
Assert.assertEquals("010203", MD5Utils.encodeHexString(new byte[] {1, 2, 3}));
|
||||
void testEncodeHexString() {
|
||||
assertEquals("", MD5Utils.encodeHexString(new byte[0]));
|
||||
assertEquals("010203", MD5Utils.encodeHexString(new byte[] {1, 2, 3}));
|
||||
}
|
||||
}
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Collections;
|
||||
@ -27,15 +27,15 @@ import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MapUtilTest {
|
||||
class MapUtilTest {
|
||||
|
||||
@Test
|
||||
public void testIsEmptyAndNotEmptyMap() {
|
||||
void testIsEmptyAndNotEmptyMap() {
|
||||
Map<Object, Object> map = null;
|
||||
assertTrue(MapUtil.isEmpty(map));
|
||||
assertFalse(MapUtil.isNotEmpty(map));
|
||||
@ -48,7 +48,7 @@ public class MapUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmptyOrEmptyDictionary() {
|
||||
void testIsEmptyOrEmptyDictionary() {
|
||||
Dictionary<Object, Object> dictionary = null;
|
||||
assertTrue(MapUtil.isEmpty(dictionary));
|
||||
assertFalse(MapUtil.isNotEmpty(dictionary));
|
||||
@ -61,7 +61,7 @@ public class MapUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutIfValNoNull() {
|
||||
void testPutIfValNoNull() {
|
||||
Map<Object, Object> map = new HashMap<>();
|
||||
MapUtil.putIfValNoNull(map, "key-1", null);
|
||||
assertTrue(map.isEmpty());
|
||||
@ -70,7 +70,7 @@ public class MapUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPutIfValNoEmptyMap() {
|
||||
void testPutIfValNoEmptyMap() {
|
||||
Map<Object, Object> map = new HashMap<>();
|
||||
|
||||
MapUtil.putIfValNoEmpty(map, "key-str", null);
|
||||
@ -113,7 +113,7 @@ public class MapUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComputeIfAbsent() {
|
||||
void testComputeIfAbsent() {
|
||||
Map<String, String> target = new HashMap<>();
|
||||
String key = "key";
|
||||
String param1 = "param1";
|
||||
@ -136,7 +136,7 @@ public class MapUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveKey() {
|
||||
void testRemoveKey() {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
map.put("A", 1);
|
||||
map.put("B", 2);
|
||||
|
@ -16,9 +16,10 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* test NamespaceUtil.
|
||||
@ -26,33 +27,33 @@ import org.junit.Test;
|
||||
* @author klw(213539 @ qq.com)
|
||||
* @date 2020/10/13 9:46
|
||||
*/
|
||||
public class NamespaceUtilTest {
|
||||
class NamespaceUtilTest {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
NamespaceUtil.setNamespaceDefaultId("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessTenantParameter() {
|
||||
void testProcessTenantParameter() {
|
||||
String strPublic = "public";
|
||||
String strNull = "null";
|
||||
String strEmpty = "";
|
||||
assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strPublic));
|
||||
String strNull = "null";
|
||||
assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strNull));
|
||||
assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strEmpty));
|
||||
assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(null));
|
||||
String strAbc = "abc";
|
||||
assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbc));
|
||||
String strdef123 = "def123";
|
||||
assertEquals(strdef123, NamespaceUtil.processNamespaceParameter(strdef123));
|
||||
String strAbcHasSpace = " abc ";
|
||||
Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strPublic));
|
||||
Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strNull));
|
||||
Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strEmpty));
|
||||
Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(null));
|
||||
Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbc));
|
||||
Assert.assertEquals(strdef123, NamespaceUtil.processNamespaceParameter(strdef123));
|
||||
Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace));
|
||||
assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetNamespaceDefaultId() {
|
||||
void testSetNamespaceDefaultId() {
|
||||
NamespaceUtil.setNamespaceDefaultId("Deprecated");
|
||||
Assert.assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId());
|
||||
assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId());
|
||||
}
|
||||
}
|
||||
|
@ -16,78 +16,82 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Number utils.
|
||||
*
|
||||
* @author zzq
|
||||
*/
|
||||
public class NumberUtilsTest {
|
||||
class NumberUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testToInt() {
|
||||
Assert.assertEquals(0, NumberUtils.toInt(null));
|
||||
Assert.assertEquals(0, NumberUtils.toInt(StringUtils.EMPTY));
|
||||
Assert.assertEquals(1, NumberUtils.toInt("1"));
|
||||
void testToInt() {
|
||||
assertEquals(0, NumberUtils.toInt(null));
|
||||
assertEquals(0, NumberUtils.toInt(StringUtils.EMPTY));
|
||||
assertEquals(1, NumberUtils.toInt("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTestToInt() {
|
||||
Assert.assertEquals(1, NumberUtils.toInt(null, 1));
|
||||
Assert.assertEquals(1, NumberUtils.toInt("", 1));
|
||||
Assert.assertEquals(1, NumberUtils.toInt("1", 0));
|
||||
void testTestToInt() {
|
||||
assertEquals(1, NumberUtils.toInt(null, 1));
|
||||
assertEquals(1, NumberUtils.toInt("", 1));
|
||||
assertEquals(1, NumberUtils.toInt("1", 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToLong() {
|
||||
Assert.assertEquals(1L, NumberUtils.toLong(null, 1L));
|
||||
Assert.assertEquals(1L, NumberUtils.toLong("", 1L));
|
||||
Assert.assertEquals(1L, NumberUtils.toLong("1", 0L));
|
||||
void testToLong() {
|
||||
assertEquals(1L, NumberUtils.toLong(null, 1L));
|
||||
assertEquals(1L, NumberUtils.toLong("", 1L));
|
||||
assertEquals(1L, NumberUtils.toLong("1", 0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToDouble() {
|
||||
Assert.assertEquals(1.1d, NumberUtils.toDouble(null, 1.1d), 0);
|
||||
Assert.assertEquals(1.1d, NumberUtils.toDouble("", 1.1d), 0);
|
||||
Assert.assertEquals(1.5d, NumberUtils.toDouble("1.5", 0.0d), 0);
|
||||
void testToDouble() {
|
||||
assertEquals(1.1d, NumberUtils.toDouble(null, 1.1d), 0);
|
||||
assertEquals(1.1d, NumberUtils.toDouble("", 1.1d), 0);
|
||||
assertEquals(1.5d, NumberUtils.toDouble("1.5", 0.0d), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsDigits() {
|
||||
Assert.assertFalse(NumberUtils.isDigits(null));
|
||||
Assert.assertFalse(NumberUtils.isDigits(""));
|
||||
Assert.assertTrue(NumberUtils.isDigits("12345"));
|
||||
Assert.assertFalse(NumberUtils.isDigits("1234.5"));
|
||||
Assert.assertFalse(NumberUtils.isDigits("1ab"));
|
||||
Assert.assertFalse(NumberUtils.isDigits("abc"));
|
||||
void testIsDigits() {
|
||||
assertFalse(NumberUtils.isDigits(null));
|
||||
assertFalse(NumberUtils.isDigits(""));
|
||||
assertTrue(NumberUtils.isDigits("12345"));
|
||||
assertFalse(NumberUtils.isDigits("1234.5"));
|
||||
assertFalse(NumberUtils.isDigits("1ab"));
|
||||
assertFalse(NumberUtils.isDigits("abc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToFloatString() {
|
||||
Assert.assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0);
|
||||
Assert.assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0);
|
||||
Assert.assertEquals(0.0f, NumberUtils.toFloat("abc"), 0);
|
||||
|
||||
Assert.assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0);
|
||||
Assert.assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), 0);
|
||||
Assert.assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), 0);
|
||||
Assert.assertEquals(0f, NumberUtils.toFloat("000.00"), 0);
|
||||
|
||||
Assert.assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, 0);
|
||||
Assert.assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, 0);
|
||||
Assert.assertEquals(0.0f, NumberUtils.toFloat(""), 0);
|
||||
Assert.assertEquals(0.0f, NumberUtils.toFloat(null), 0);
|
||||
void testToFloatString() {
|
||||
assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0);
|
||||
assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0);
|
||||
assertEquals(0.0f, NumberUtils.toFloat("abc"), 0);
|
||||
|
||||
assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0);
|
||||
assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), 0);
|
||||
assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), 0);
|
||||
assertEquals(0f, NumberUtils.toFloat("000.00"), 0);
|
||||
|
||||
assertEquals(Float.MAX_VALUE, NumberUtils.toFloat(Float.MAX_VALUE + ""), 0);
|
||||
assertEquals(Float.MIN_VALUE, NumberUtils.toFloat(Float.MIN_VALUE + ""), 0);
|
||||
assertEquals(0.0f, NumberUtils.toFloat(""), 0);
|
||||
assertEquals(0.0f, NumberUtils.toFloat(null), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToFloatStringString() {
|
||||
Assert.assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), 0);
|
||||
Assert.assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), 0);
|
||||
void testToFloatStringString() {
|
||||
assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), 0);
|
||||
assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), 0);
|
||||
// LANG-1060
|
||||
Assert.assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), 0);
|
||||
Assert.assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), 0);
|
||||
Assert.assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), 0);
|
||||
assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), 0);
|
||||
assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), 0);
|
||||
assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,46 +16,46 @@
|
||||
|
||||
package com.alibaba.nacos.common.utils;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ObservableTest {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ObservableTest {
|
||||
|
||||
@Mock
|
||||
private Observer observer;
|
||||
|
||||
private Observable observable;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
observable = new Observable();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddObserver() {
|
||||
void testAddObserver() {
|
||||
observable.addObserver(observer);
|
||||
assertEquals(1, observable.countObservers());
|
||||
verify(observer).update(observable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteObserver() {
|
||||
void testDeleteObserver() {
|
||||
observable.addObserver(observer);
|
||||
assertEquals(1, observable.countObservers());
|
||||
observable.deleteObserver(observer);
|
||||
@ -63,7 +63,7 @@ public class ObservableTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyObservers() {
|
||||
void testNotifyObservers() {
|
||||
observable.addObserver(observer);
|
||||
reset(observer);
|
||||
observable.notifyObservers();
|
||||
@ -77,7 +77,7 @@ public class ObservableTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteObservers() {
|
||||
void testDeleteObservers() {
|
||||
observable.addObserver(observer);
|
||||
observable.deleteObservers();
|
||||
assertEquals(1, observable.countObservers());
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user