upgrade module naocs-plugin from junit4 to junit5 (#12229)

This commit is contained in:
shalk(xiao kun) 2024-06-17 14:08:09 +08:00 committed by GitHub
parent ab6591ac83
commit 21bfac76e7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
43 changed files with 1208 additions and 1224 deletions

View File

@ -16,32 +16,33 @@
package com.alibaba.nacos.plugin.auth.api; package com.alibaba.nacos.plugin.auth.api;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
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.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class IdentityContextTest { class IdentityContextTest {
private static final String TEST = "test"; private static final String TEST = "test";
private IdentityContext identityContext; private IdentityContext identityContext;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
identityContext = new IdentityContext(); identityContext = new IdentityContext();
} }
@Test @Test
public void testGetParameter() { void testGetParameter() {
assertNull(identityContext.getParameter(TEST)); assertNull(identityContext.getParameter(TEST));
identityContext.setParameter(TEST, TEST); identityContext.setParameter(TEST, TEST);
assertEquals(TEST, identityContext.getParameter(TEST)); assertEquals(TEST, identityContext.getParameter(TEST));
} }
@Test @Test
public void testGetParameterWithDefaultValue() { void testGetParameterWithDefaultValue() {
assertEquals(TEST, identityContext.getParameter(TEST, TEST)); assertEquals(TEST, identityContext.getParameter(TEST, TEST));
identityContext.setParameter(TEST, TEST + "new"); identityContext.setParameter(TEST, TEST + "new");
assertEquals(TEST + "new", identityContext.getParameter(TEST, TEST)); assertEquals(TEST + "new", identityContext.getParameter(TEST, TEST));
@ -49,8 +50,10 @@ public class IdentityContextTest {
assertEquals(1L, actual); assertEquals(1L, actual);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetParameterWithNullDefaultValue() { void testGetParameterWithNullDefaultValue() {
identityContext.getParameter(TEST, null); assertThrows(IllegalArgumentException.class, () -> {
identityContext.getParameter(TEST, null);
});
} }
} }

View File

@ -16,29 +16,29 @@
package com.alibaba.nacos.plugin.auth.api; package com.alibaba.nacos.plugin.auth.api;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class LoginIdentityContextTest { class LoginIdentityContextTest {
private static final String TEST = "test"; private static final String TEST = "test";
private LoginIdentityContext loginIdentityContext; private LoginIdentityContext loginIdentityContext;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
loginIdentityContext = new LoginIdentityContext(); loginIdentityContext = new LoginIdentityContext();
} }
@Test @Test
public void testSetParameter() { void testSetParameter() {
assertNull(loginIdentityContext.getParameter(TEST)); assertNull(loginIdentityContext.getParameter(TEST));
assertTrue(loginIdentityContext.getAllKey().isEmpty()); assertTrue(loginIdentityContext.getAllKey().isEmpty());
loginIdentityContext.setParameter(TEST, TEST); loginIdentityContext.setParameter(TEST, TEST);
@ -47,7 +47,7 @@ public class LoginIdentityContextTest {
} }
@Test @Test
public void testSetParameters() { void testSetParameters() {
assertNull(loginIdentityContext.getParameter(TEST)); assertNull(loginIdentityContext.getParameter(TEST));
assertTrue(loginIdentityContext.getAllKey().isEmpty()); assertTrue(loginIdentityContext.getAllKey().isEmpty());
Map<String, String> map = new HashMap<>(2); Map<String, String> map = new HashMap<>(2);

View File

@ -17,31 +17,30 @@
package com.alibaba.nacos.plugin.auth.api; package com.alibaba.nacos.plugin.auth.api;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class PermissionTest { class PermissionTest {
private Permission permission; private Permission permission;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
permission = new Permission(Resource.EMPTY_RESOURCE, ActionTypes.WRITE.toString()); permission = new Permission(Resource.EMPTY_RESOURCE, ActionTypes.WRITE.toString());
} }
@Test @Test
public void testToString() { void testToString() {
assertEquals( assertEquals("Permission{resource='Resource{namespaceId='', group='', name='', type='', properties=null}', action='w'}",
"Permission{resource='Resource{namespaceId='', group='', name='', type='', properties=null}', action='w'}",
permission.toString()); permission.toString());
} }
@Test @Test
public void testSetResource() { void testSetResource() {
Permission permission = new Permission(); Permission permission = new Permission();
Properties properties = new Properties(); Properties properties = new Properties();
Resource resource = new Resource("NS", "G", "N", "TEST", properties); Resource resource = new Resource("NS", "G", "N", "TEST", properties);
@ -54,7 +53,7 @@ public class PermissionTest {
} }
@Test @Test
public void testSetAction() { void testSetAction() {
Permission permission = new Permission(); Permission permission = new Permission();
permission.setAction(ActionTypes.READ.toString()); permission.setAction(ActionTypes.READ.toString());
assertEquals(ActionTypes.READ.toString(), permission.getAction()); assertEquals(ActionTypes.READ.toString(), permission.getAction());

View File

@ -17,21 +17,20 @@
package com.alibaba.nacos.plugin.auth.api; package com.alibaba.nacos.plugin.auth.api;
import com.alibaba.nacos.plugin.auth.constant.SignType; import com.alibaba.nacos.plugin.auth.constant.SignType;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
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 RequestResourceTest { class RequestResourceTest {
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
} }
@Test @Test
public void testBuildNamingRequestResource() { void testBuildNamingRequestResource() {
RequestResource actual = RequestResource.namingBuilder().setNamespace("NS").setGroup("G").setResource("Service") RequestResource actual = RequestResource.namingBuilder().setNamespace("NS").setGroup("G").setResource("Service").build();
.build();
assertEquals(SignType.NAMING, actual.getType()); assertEquals(SignType.NAMING, actual.getType());
assertEquals("NS", actual.getNamespace()); assertEquals("NS", actual.getNamespace());
assertEquals("G", actual.getGroup()); assertEquals("G", actual.getGroup());
@ -39,9 +38,8 @@ public class RequestResourceTest {
} }
@Test @Test
public void testBuildConfigRequestResource() { void testBuildConfigRequestResource() {
RequestResource actual = RequestResource.configBuilder().setNamespace("NS").setGroup("G").setResource("dataId") RequestResource actual = RequestResource.configBuilder().setNamespace("NS").setGroup("G").setResource("dataId").build();
.build();
assertEquals(SignType.CONFIG, actual.getType()); assertEquals(SignType.CONFIG, actual.getType());
assertEquals("NS", actual.getNamespace()); assertEquals("NS", actual.getNamespace());
assertEquals("G", actual.getGroup()); assertEquals("G", actual.getGroup());

View File

@ -16,20 +16,20 @@
package com.alibaba.nacos.plugin.auth.constant; package com.alibaba.nacos.plugin.auth.constant;
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 ActionTypesTest { class ActionTypesTest {
@Test @Test
public void testToStringForRead() { void testToStringForRead() {
ActionTypes actual = ActionTypes.valueOf("READ"); ActionTypes actual = ActionTypes.valueOf("READ");
assertEquals("r", actual.toString()); assertEquals("r", actual.toString());
} }
@Test @Test
public void testToStringForWrite() { void testToStringForWrite() {
ActionTypes actual = ActionTypes.valueOf("WRITE"); ActionTypes actual = ActionTypes.valueOf("WRITE");
assertEquals("w", actual.toString()); assertEquals("w", actual.toString());
} }

View File

@ -16,25 +16,24 @@
package com.alibaba.nacos.plugin.auth.constant; package com.alibaba.nacos.plugin.auth.constant;
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 ConstantsTest { class ConstantsTest {
@Test @Test
public void testConstantsForAuth() { void testConstantsForAuth() {
assertEquals("nacos.core.auth.enabled", Constants.Auth.NACOS_CORE_AUTH_ENABLED); assertEquals("nacos.core.auth.enabled", Constants.Auth.NACOS_CORE_AUTH_ENABLED);
assertEquals("nacos.core.auth.system.type", Constants.Auth.NACOS_CORE_AUTH_SYSTEM_TYPE); assertEquals("nacos.core.auth.system.type", Constants.Auth.NACOS_CORE_AUTH_SYSTEM_TYPE);
assertEquals("nacos.core.auth.caching.enabled", Constants.Auth.NACOS_CORE_AUTH_CACHING_ENABLED); assertEquals("nacos.core.auth.caching.enabled", Constants.Auth.NACOS_CORE_AUTH_CACHING_ENABLED);
assertEquals("nacos.core.auth.server.identity.key", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_KEY); assertEquals("nacos.core.auth.server.identity.key", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_KEY);
assertEquals("nacos.core.auth.server.identity.value", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_VALUE); assertEquals("nacos.core.auth.server.identity.value", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_VALUE);
assertEquals("nacos.core.auth.enable.userAgentAuthWhite", assertEquals("nacos.core.auth.enable.userAgentAuthWhite", Constants.Auth.NACOS_CORE_AUTH_ENABLE_USER_AGENT_AUTH_WHITE);
Constants.Auth.NACOS_CORE_AUTH_ENABLE_USER_AGENT_AUTH_WHITE);
} }
@Test @Test
public void testConstantsForResource() { void testConstantsForResource() {
assertEquals(":", Constants.Resource.SPLITTER); assertEquals(":", Constants.Resource.SPLITTER);
assertEquals("*", Constants.Resource.ANY); assertEquals("*", Constants.Resource.ANY);
assertEquals("action", Constants.Resource.ACTION); assertEquals("action", Constants.Resource.ACTION);
@ -42,14 +41,14 @@ public class ConstantsTest {
} }
@Test @Test
public void testConstantsForIdentity() { void testConstantsForIdentity() {
assertEquals("identity_id", Constants.Identity.IDENTITY_ID); assertEquals("identity_id", Constants.Identity.IDENTITY_ID);
assertEquals("X-Real-IP", Constants.Identity.X_REAL_IP); assertEquals("X-Real-IP", Constants.Identity.X_REAL_IP);
assertEquals("remote_ip", Constants.Identity.REMOTE_IP); assertEquals("remote_ip", Constants.Identity.REMOTE_IP);
} }
@Test @Test
public void testConstantsForSignType() { void testConstantsForSignType() {
assertEquals("naming", SignType.NAMING); assertEquals("naming", SignType.NAMING);
assertEquals("config", SignType.CONFIG); assertEquals("config", SignType.CONFIG);
assertEquals("console", SignType.CONSOLE); assertEquals("console", SignType.CONSOLE);

View File

@ -17,28 +17,28 @@
package com.alibaba.nacos.plugin.auth.exception; package com.alibaba.nacos.plugin.auth.exception;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
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 AccessExceptionTest { class AccessExceptionTest {
@Test @Test
public void testNewAccessExceptionWithCode() { void testNewAccessExceptionWithCode() {
AccessException actual = new AccessException(403); AccessException actual = new AccessException(403);
assertEquals(403, actual.getErrCode()); assertEquals(403, actual.getErrCode());
assertEquals(Constants.NULL, actual.getErrMsg()); assertEquals(Constants.NULL, actual.getErrMsg());
} }
@Test @Test
public void testNewAccessExceptionWithMsg() { void testNewAccessExceptionWithMsg() {
AccessException actual = new AccessException("Test"); AccessException actual = new AccessException("Test");
assertEquals("Test", actual.getErrMsg()); assertEquals("Test", actual.getErrMsg());
assertEquals(0, actual.getErrCode()); assertEquals(0, actual.getErrCode());
} }
@Test @Test
public void testNewAccessExceptionWithNoArgs() { void testNewAccessExceptionWithNoArgs() {
AccessException actual = new AccessException(); AccessException actual = new AccessException();
assertEquals(Constants.NULL, actual.getErrMsg()); assertEquals(Constants.NULL, actual.getErrMsg());
assertEquals(0, actual.getErrCode()); assertEquals(0, actual.getErrCode());

View File

@ -19,13 +19,12 @@ package com.alibaba.nacos.plugin.auth.spi.client;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.spi.NacosServiceLoader; import com.alibaba.nacos.common.spi.NacosServiceLoader;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collection; import java.util.Collection;
@ -34,6 +33,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* {@link ClientAuthPluginManager} unit test. * {@link ClientAuthPluginManager} unit test.
* *
@ -41,8 +43,8 @@ import java.util.Set;
* @date 2021-08-12 12:56 * @date 2021-08-12 12:56
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class ClientAuthPluginManagerTest { class ClientAuthPluginManagerTest {
private ClientAuthPluginManager clientAuthPluginManager; private ClientAuthPluginManager clientAuthPluginManager;
@ -52,37 +54,36 @@ public class ClientAuthPluginManagerTest {
@Mock @Mock
private NacosRestTemplate nacosRestTemplate; private NacosRestTemplate nacosRestTemplate;
@Before @BeforeEach
public void setUp() throws NoSuchFieldException, IllegalAccessException { void setUp() throws NoSuchFieldException, IllegalAccessException {
clientAuthPluginManager = new ClientAuthPluginManager(); clientAuthPluginManager = new ClientAuthPluginManager();
} }
@After @AfterEach
public void tearDown() throws NacosException, NoSuchFieldException, IllegalAccessException { void tearDown() throws NacosException, NoSuchFieldException, IllegalAccessException {
getServiceLoaderMap().remove(AbstractClientAuthService.class); getServiceLoaderMap().remove(AbstractClientAuthService.class);
clientAuthPluginManager.shutdown(); clientAuthPluginManager.shutdown();
} }
private Map<Class<?>, Collection<Class<?>>> getServiceLoaderMap() private Map<Class<?>, Collection<Class<?>>> getServiceLoaderMap() throws NoSuchFieldException, IllegalAccessException {
throws NoSuchFieldException, IllegalAccessException {
Field servicesField = NacosServiceLoader.class.getDeclaredField("SERVICES"); Field servicesField = NacosServiceLoader.class.getDeclaredField("SERVICES");
servicesField.setAccessible(true); servicesField.setAccessible(true);
return (Map<Class<?>, Collection<Class<?>>>) servicesField.get(null); return (Map<Class<?>, Collection<Class<?>>>) servicesField.get(null);
} }
@Test @Test
public void testGetAuthServiceSpiImplSet() { void testGetAuthServiceSpiImplSet() {
clientAuthPluginManager.init(serverlist, nacosRestTemplate); clientAuthPluginManager.init(serverlist, nacosRestTemplate);
Set<ClientAuthService> clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet(); Set<ClientAuthService> clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet();
Assert.assertFalse(clientAuthServiceSet.isEmpty()); assertFalse(clientAuthServiceSet.isEmpty());
} }
@Test @Test
public void testGetAuthServiceSpiImplSetForEmpty() throws NoSuchFieldException, IllegalAccessException { void testGetAuthServiceSpiImplSetForEmpty() throws NoSuchFieldException, IllegalAccessException {
getServiceLoaderMap().put(AbstractClientAuthService.class, Collections.emptyList()); getServiceLoaderMap().put(AbstractClientAuthService.class, Collections.emptyList());
clientAuthPluginManager.init(serverlist, nacosRestTemplate); clientAuthPluginManager.init(serverlist, nacosRestTemplate);
Set<ClientAuthService> clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet(); Set<ClientAuthService> clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet();
Assert.assertTrue(clientAuthServiceSet.isEmpty()); assertTrue(clientAuthServiceSet.isEmpty());
} }
} }

View File

@ -16,17 +16,19 @@
package com.alibaba.nacos.plugin.auth.spi.server; package com.alibaba.nacos.plugin.auth.spi.server;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* {@link AuthPluginManager} unit test. * {@link AuthPluginManager} unit test.
* *
@ -34,38 +36,37 @@ import java.util.Optional;
* @date 2021-08-12 12:56 * @date 2021-08-12 12:56
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class AuthPluginManagerTest { class AuthPluginManagerTest {
private static final String TYPE = "test";
private AuthPluginManager authPluginManager; private AuthPluginManager authPluginManager;
@Mock @Mock
private AuthPluginService authPluginService; private AuthPluginService authPluginService;
private static final String TYPE = "test"; @BeforeEach
void setUp() throws NoSuchFieldException, IllegalAccessException {
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
authPluginManager = AuthPluginManager.getInstance(); authPluginManager = AuthPluginManager.getInstance();
Class<AuthPluginManager> authPluginManagerClass = AuthPluginManager.class; Class<AuthPluginManager> authPluginManagerClass = AuthPluginManager.class;
Field authPlugins = authPluginManagerClass.getDeclaredField("authServiceMap"); Field authPlugins = authPluginManagerClass.getDeclaredField("authServiceMap");
authPlugins.setAccessible(true); authPlugins.setAccessible(true);
Map<String, AuthPluginService> authServiceMap = (Map<String, AuthPluginService>) authPlugins Map<String, AuthPluginService> authServiceMap = (Map<String, AuthPluginService>) authPlugins.get(authPluginManager);
.get(authPluginManager);
authServiceMap.put(TYPE, authPluginService); authServiceMap.put(TYPE, authPluginService);
} }
@Test @Test
public void testGetInstance() { void testGetInstance() {
AuthPluginManager instance = AuthPluginManager.getInstance(); AuthPluginManager instance = AuthPluginManager.getInstance();
Assert.assertNotNull(instance); assertNotNull(instance);
} }
@Test @Test
public void testFindAuthServiceSpiImpl() { void testFindAuthServiceSpiImpl() {
Optional<AuthPluginService> authServiceImpl = authPluginManager.findAuthServiceSpiImpl(TYPE); Optional<AuthPluginService> authServiceImpl = authPluginManager.findAuthServiceSpiImpl(TYPE);
Assert.assertTrue(authServiceImpl.isPresent()); assertTrue(authServiceImpl.isPresent());
} }
} }

View File

@ -21,52 +21,58 @@ import com.alibaba.nacos.plugin.config.constants.ConfigChangePointCutTypes;
import com.alibaba.nacos.plugin.config.model.ConfigChangeRequest; import com.alibaba.nacos.plugin.config.model.ConfigChangeRequest;
import com.alibaba.nacos.plugin.config.model.ConfigChangeResponse; import com.alibaba.nacos.plugin.config.model.ConfigChangeResponse;
import com.alibaba.nacos.plugin.config.spi.ConfigChangePluginService; import com.alibaba.nacos.plugin.config.spi.ConfigChangePluginService;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.IntStream; 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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* ConfigChangePluginManagerTests. * ConfigChangePluginManagerTests.
* *
* @author liyunfei * @author liyunfei
**/ **/
public class ConfigChangePluginManagerTests { class ConfigChangePluginManagerTests {
@Test @Test
public void testInstance() { void testInstance() {
ConfigChangePluginManager instance = ConfigChangePluginManager.getInstance(); ConfigChangePluginManager instance = ConfigChangePluginManager.getInstance();
Assert.assertNotNull(instance); assertNotNull(instance);
} }
@Before @BeforeEach
public void initPluginServices() { void initPluginServices() {
ConfigChangePluginManager.join(new ConfigChangePluginService() { ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override @Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore // ignore
} }
@Override @Override
public ConfigChangeExecuteTypes executeType() { public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE; return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE;
} }
@Override @Override
public String getServiceType() { public String getServiceType() {
return "test1"; return "test1";
} }
@Override @Override
public int getOrder() { public int getOrder() {
return 0; return 0;
} }
@Override @Override
public ConfigChangePointCutTypes[] pointcutMethodNames() { public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.PUBLISH_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC}; return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP,
ConfigChangePointCutTypes.PUBLISH_BY_RPC};
} }
}); });
ConfigChangePluginManager.join(new ConfigChangePluginService() { ConfigChangePluginManager.join(new ConfigChangePluginService() {
@ -74,25 +80,25 @@ public class ConfigChangePluginManagerTests {
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore // ignore
} }
@Override @Override
public ConfigChangeExecuteTypes executeType() { public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE; return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE;
} }
@Override @Override
public String getServiceType() { public String getServiceType() {
return "test2"; return "test2";
} }
@Override @Override
public int getOrder() { public int getOrder() {
return 200; return 200;
} }
@Override @Override
public ConfigChangePointCutTypes[] pointcutMethodNames() { public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC}; return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC};
} }
}); });
ConfigChangePluginManager.join(new ConfigChangePluginService() { ConfigChangePluginManager.join(new ConfigChangePluginService() {
@ -100,105 +106,100 @@ public class ConfigChangePluginManagerTests {
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore // ignore
} }
@Override @Override
public ConfigChangeExecuteTypes executeType() { public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE; return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE;
} }
@Override @Override
public String getServiceType() { public String getServiceType() {
return "test3"; return "test3";
} }
@Override @Override
public int getOrder() { public int getOrder() {
return 400; return 400;
} }
@Override @Override
public ConfigChangePointCutTypes[] pointcutMethodNames() { public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC, return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC, ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BY_HTTP}; ConfigChangePointCutTypes.REMOVE_BY_HTTP};
} }
}); });
ConfigChangePluginManager.join(new ConfigChangePluginService() { ConfigChangePluginManager.join(new ConfigChangePluginService() {
@Override @Override
public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) {
// ignore // ignore
} }
@Override @Override
public ConfigChangeExecuteTypes executeType() { public ConfigChangeExecuteTypes executeType() {
return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE; return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE;
} }
@Override @Override
public String getServiceType() { public String getServiceType() {
return "test4"; return "test4";
} }
@Override @Override
public int getOrder() { public int getOrder() {
return 600; return 600;
} }
@Override @Override
public ConfigChangePointCutTypes[] pointcutMethodNames() { public ConfigChangePointCutTypes[] pointcutMethodNames() {
return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.PUBLISH_BY_HTTP, ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP,
ConfigChangePointCutTypes.REMOVE_BY_RPC, ConfigChangePointCutTypes.REMOVE_BY_HTTP}; ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC,
ConfigChangePointCutTypes.REMOVE_BY_HTTP};
} }
}); });
} }
@Test @Test
public void testFindPluginServiceQueueByPointcut() { void testFindPluginServiceQueueByPointcut() {
List<ConfigChangePluginService> configChangePluginServices = ConfigChangePluginManager List<ConfigChangePluginService> configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(
.findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_HTTP); ConfigChangePointCutTypes.PUBLISH_BY_HTTP);
Assert.assertEquals(2, configChangePluginServices.size()); assertEquals(2, configChangePluginServices.size());
Assert.assertTrue(isSorted(configChangePluginServices)); assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_RPC);
.findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_RPC); assertEquals(3, configChangePluginServices.size());
Assert.assertEquals(3, configChangePluginServices.size()); assertTrue(isSorted(configChangePluginServices));
Assert.assertTrue(isSorted(configChangePluginServices)); configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.IMPORT_BY_HTTP);
configChangePluginServices = ConfigChangePluginManager assertEquals(2, configChangePluginServices.size());
.findPluginServicesByPointcut(ConfigChangePointCutTypes.IMPORT_BY_HTTP); assertTrue(isSorted(configChangePluginServices));
Assert.assertEquals(2, configChangePluginServices.size()); configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BATCH_HTTP);
Assert.assertTrue(isSorted(configChangePluginServices)); assertEquals(2, configChangePluginServices.size());
configChangePluginServices = ConfigChangePluginManager assertTrue(isSorted(configChangePluginServices));
.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BATCH_HTTP); configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_RPC);
Assert.assertEquals(2, configChangePluginServices.size()); assertEquals(2, configChangePluginServices.size());
Assert.assertTrue(isSorted(configChangePluginServices)); assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_HTTP);
.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_RPC); assertEquals(2, configChangePluginServices.size());
Assert.assertEquals(2, configChangePluginServices.size()); assertTrue(isSorted(configChangePluginServices));
Assert.assertTrue(isSorted(configChangePluginServices));
configChangePluginServices = ConfigChangePluginManager
.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_HTTP);
Assert.assertEquals(2, configChangePluginServices.size());
Assert.assertTrue(isSorted(configChangePluginServices));
} }
@Test @Test
public void testFindPluginServiceByServiceType() { void testFindPluginServiceByServiceType() {
Optional<ConfigChangePluginService> configChangePluginServiceOptional = ConfigChangePluginManager Optional<ConfigChangePluginService> configChangePluginServiceOptional = ConfigChangePluginManager.getInstance()
.getInstance().findPluginServiceImpl("test1"); .findPluginServiceImpl("test1");
Assert.assertTrue(configChangePluginServiceOptional.isPresent()); assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test2"); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test2");
Assert.assertTrue(configChangePluginServiceOptional.isPresent()); assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test3"); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test3");
Assert.assertTrue(configChangePluginServiceOptional.isPresent()); assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test4"); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test4");
Assert.assertTrue(configChangePluginServiceOptional.isPresent()); assertTrue(configChangePluginServiceOptional.isPresent());
configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test5"); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test5");
Assert.assertFalse(configChangePluginServiceOptional.isPresent()); assertFalse(configChangePluginServiceOptional.isPresent());
} }
private boolean isSorted(List<ConfigChangePluginService> list) { private boolean isSorted(List<ConfigChangePluginService> list) {
return IntStream.range(0, list.size() - 1) return IntStream.range(0, list.size() - 1).allMatch(i -> list.get(i).getOrder() <= list.get(i + 1).getOrder());
.allMatch(i -> list.get(i).getOrder() <= list.get(i + 1).getOrder());
} }
} }

View File

@ -26,9 +26,8 @@ import com.alibaba.nacos.plugin.control.tps.TpsControlManager;
import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail; import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail;
import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule; import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule;
import com.alibaba.nacos.plugin.control.utils.EnvUtils; import com.alibaba.nacos.plugin.control.utils.EnvUtils;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.File; import java.io.File;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
@ -36,10 +35,13 @@ import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class ControlManagerCenterTest { import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ControlManagerCenterTest {
@Before @BeforeEach
public void initInstance() throws NoSuchFieldException, IllegalAccessException { void initInstance() throws NoSuchFieldException, IllegalAccessException {
//reset instance for reload spi //reset instance for reload spi
Field instanceControlConfigs = ControlConfigs.class.getDeclaredField("instance"); Field instanceControlConfigs = ControlConfigs.class.getDeclaredField("instance");
instanceControlConfigs.setAccessible(true); instanceControlConfigs.setAccessible(true);
@ -69,29 +71,28 @@ public class ControlManagerCenterTest {
} }
@Test @Test
public void testGetInstance() { void testGetInstance() {
ControlConfigs.getInstance().setControlManagerType("test"); ControlConfigs.getInstance().setControlManagerType("test");
ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance();
ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager(); ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager();
Assert.assertEquals("testConnection", connectionControlManager.getName()); assertEquals("testConnection", connectionControlManager.getName());
TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager(); TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager();
Assert.assertEquals("testTps", tpsControlManager.getName()); assertEquals("testTps", tpsControlManager.getName());
Assert.assertNotNull(controlManagerCenter.getRuleStorageProxy()); assertNotNull(controlManagerCenter.getRuleStorageProxy());
} }
@Test @Test
public void testGetInstanceWithDefault() { void testGetInstanceWithDefault() {
ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance();
ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager(); ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager();
Assert.assertEquals("noLimit", connectionControlManager.getName()); assertEquals("noLimit", connectionControlManager.getName());
TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager(); TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager();
Assert.assertEquals("noLimit", tpsControlManager.getName()); assertEquals("noLimit", tpsControlManager.getName());
} }
@Test @Test
public void testReloadTpsControlRule() throws Exception { void testReloadTpsControlRule() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator;
EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
resetRuleStorageProxy(); resetRuleStorageProxy();
final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance();
@ -108,8 +109,8 @@ public class ControlManagerCenterTest {
controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule); controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule);
TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test"); TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test");
Assert.assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); assertEquals(100, testTpsControlRule.getPointRule().getMaxCount());
Assert.assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); assertEquals("test", testTpsControlRule.getPointRule().getRuleName());
TpsControlRule tpsControlRule2 = new TpsControlRule(); TpsControlRule tpsControlRule2 = new TpsControlRule();
tpsControlRule2.setPointName("test"); tpsControlRule2.setPointName("test");
@ -126,12 +127,12 @@ public class ControlManagerCenterTest {
//wait event //wait event
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test"); TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test");
Assert.assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount());
Assert.assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName());
} }
@Test @Test
public void testReloadTpsControlRuleExternal() throws Exception { void testReloadTpsControlRuleExternal() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tpsExternal" + File.separator; EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tpsExternal" + File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
@ -152,8 +153,8 @@ public class ControlManagerCenterTest {
controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule); controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule);
TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test"); TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test");
Assert.assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); assertEquals(100, testTpsControlRule.getPointRule().getMaxCount());
Assert.assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); assertEquals("test", testTpsControlRule.getPointRule().getRuleName());
TpsControlRule tpsControlRule2 = new TpsControlRule(); TpsControlRule tpsControlRule2 = new TpsControlRule();
tpsControlRule2.setPointName("test"); tpsControlRule2.setPointName("test");
@ -170,15 +171,14 @@ public class ControlManagerCenterTest {
//wait event //wait event
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test"); TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test");
Assert.assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount());
Assert.assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName());
} }
@Test @Test
public void testReloadConnectionControlRule() throws Exception { void testReloadConnectionControlRule() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" + File.separator;
+ File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
resetRuleStorageProxy(); resetRuleStorageProxy();
ConnectionControlRule connectionLimitRule = new ConnectionControlRule(); ConnectionControlRule connectionLimitRule = new ConnectionControlRule();
@ -191,7 +191,7 @@ public class ControlManagerCenterTest {
//apply rule //apply rule
connectionControlManager.applyConnectionLimitRule(connectionLimitRule); connectionControlManager.applyConnectionLimitRule(connectionLimitRule);
ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule(); ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule();
Assert.assertEquals(100, connectionLimitRule1.getCountLimit()); assertEquals(100, connectionLimitRule1.getCountLimit());
ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule(); ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule();
connectionLimitRule2.setCountLimit(200); connectionLimitRule2.setCountLimit(200);
@ -203,14 +203,13 @@ public class ControlManagerCenterTest {
//wait event //wait event
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule(); ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule();
Assert.assertEquals(200, connectionLimitRule3.getCountLimit()); assertEquals(200, connectionLimitRule3.getCountLimit());
} }
@Test @Test
public void testReloadConnectionControlRuleExternal() throws Exception { void testReloadConnectionControlRuleExternal() throws Exception {
String localRuleStorageBaseDir = String localRuleStorageBaseDir =
EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" + File.separator;
+ File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
ControlConfigs.getInstance().setRuleExternalStorage("test"); ControlConfigs.getInstance().setRuleExternalStorage("test");
resetRuleStorageProxy(); resetRuleStorageProxy();
@ -224,7 +223,7 @@ public class ControlManagerCenterTest {
//apply rule //apply rule
connectionControlManager.applyConnectionLimitRule(connectionLimitRule); connectionControlManager.applyConnectionLimitRule(connectionLimitRule);
ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule(); ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule();
Assert.assertEquals(100, connectionLimitRule1.getCountLimit()); assertEquals(100, connectionLimitRule1.getCountLimit());
ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule(); ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule();
connectionLimitRule2.setCountLimit(200); connectionLimitRule2.setCountLimit(200);
@ -236,6 +235,6 @@ public class ControlManagerCenterTest {
//wait event //wait event
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule(); ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule();
Assert.assertEquals(200, connectionLimitRule3.getCountLimit()); assertEquals(200, connectionLimitRule3.getCountLimit());
} }
} }

View File

@ -20,18 +20,20 @@ import com.alibaba.nacos.plugin.control.connection.request.ConnectionCheckReques
import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckCode; import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckCode;
import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse; import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse;
import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule; import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* two fixed metrics, total 30, iptotal 15, detail is testa(total-20,iptotal-10),testb(total-10,iptotal-5). * two fixed metrics, total 30, iptotal 15, detail is testa(total-20,iptotal-10),testb(total-10,iptotal-5).
*/ */
public class DefaultConnectionControlManagerTest { class DefaultConnectionControlManagerTest {
DefaultConnectionControlManager connectionControlManager = new DefaultConnectionControlManager(); DefaultConnectionControlManager connectionControlManager = new DefaultConnectionControlManager();
@Test @Test
public void test() { void test() {
ConnectionControlRule connectionControlRule = new ConnectionControlRule(); ConnectionControlRule connectionControlRule = new ConnectionControlRule();
@ -40,8 +42,8 @@ public class DefaultConnectionControlManagerTest {
connectionControlRule.setCountLimit(40); connectionControlRule.setCountLimit(40);
connectionControlManager.applyConnectionLimitRule(connectionControlRule); connectionControlManager.applyConnectionLimitRule(connectionControlRule);
check = connectionControlManager.check(connectionCheckRequest); check = connectionControlManager.check(connectionCheckRequest);
Assert.assertTrue(check.isSuccess()); assertTrue(check.isSuccess());
Assert.assertEquals(ConnectionCheckCode.CHECK_SKIP, check.getCode()); assertEquals(ConnectionCheckCode.CHECK_SKIP, check.getCode());
} }

View File

@ -16,31 +16,32 @@
package com.alibaba.nacos.plugin.control.tps; package com.alibaba.nacos.plugin.control.tps;
import com.alibaba.nacos.plugin.control.tps.barrier.TpsBarrier;
import com.alibaba.nacos.plugin.control.tps.barrier.DefaultNacosTpsBarrier; import com.alibaba.nacos.plugin.control.tps.barrier.DefaultNacosTpsBarrier;
import com.alibaba.nacos.plugin.control.tps.barrier.TpsBarrier;
import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest;
import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse;
import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail; import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail;
import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule; import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class DefaultNacosTpsBarrierTest { import static org.junit.jupiter.api.Assertions.assertTrue;
class DefaultNacosTpsBarrierTest {
@Before @BeforeEach
public void setUp() { void setUp() {
} }
@After @AfterEach
public void after() { void after() {
} }
@Test @Test
public void testNormalPointPassAndDeny() { void testNormalPointPassAndDeny() {
String testTpsBarrier = "test_barrier"; String testTpsBarrier = "test_barrier";
// max 5tps // max 5tps
@ -63,7 +64,7 @@ public class DefaultNacosTpsBarrierTest {
// 5tps check pass // 5tps check pass
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
TpsCheckResponse tpsCheckResponse = tpsBarrier.applyTps(tpsCheckRequest); TpsCheckResponse tpsCheckResponse = tpsBarrier.applyTps(tpsCheckRequest);
Assert.assertTrue(tpsCheckResponse.isSuccess()); assertTrue(tpsCheckResponse.isSuccess());
} }
} }

View File

@ -16,10 +16,9 @@
package com.alibaba.nacos.plugin.control.utils; package com.alibaba.nacos.plugin.control.utils;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -30,46 +29,52 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.UUID; import java.util.UUID;
public class DiskUtilsTest { import static org.junit.jupiter.api.Assertions.assertEquals;
private static File testFile; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DiskUtilsTest {
private static final String TMP_PATH = EnvUtils.getNacosHome() + File.separator + "data" + File.separator + "tmp" + File.separator; private static final String TMP_PATH = EnvUtils.getNacosHome() + File.separator + "data" + File.separator + "tmp" + File.separator;
@BeforeClass private static File testFile;
public static void setup() throws IOException {
@BeforeAll
static void setup() throws IOException {
testFile = DiskUtils.createTmpFile("nacostmp", ".ut"); testFile = DiskUtils.createTmpFile("nacostmp", ".ut");
} }
@AfterClass @AfterAll
public static void tearDown() throws IOException { static void tearDown() throws IOException {
testFile.deleteOnExit(); testFile.deleteOnExit();
} }
@Test @Test
public void testTouch() throws IOException { void testTouch() throws IOException {
File file = Paths.get(TMP_PATH, "touch.ut").toFile(); File file = Paths.get(TMP_PATH, "touch.ut").toFile();
Assert.assertFalse(file.exists()); assertFalse(file.exists());
DiskUtils.touch(file); DiskUtils.touch(file);
Assert.assertTrue(file.exists()); assertTrue(file.exists());
file.deleteOnExit(); file.deleteOnExit();
} }
@Test @Test
public void testTouchWithFileName() throws IOException { void testTouchWithFileName() throws IOException {
File file = Paths.get(TMP_PATH, UUID.randomUUID().toString()).toFile(); File file = Paths.get(TMP_PATH, UUID.randomUUID().toString()).toFile();
Assert.assertFalse(file.exists()); assertFalse(file.exists());
DiskUtils.touch(file.getParent(), file.getName()); DiskUtils.touch(file.getParent(), file.getName());
Assert.assertTrue(file.exists()); assertTrue(file.exists());
file.deleteOnExit(); file.deleteOnExit();
} }
@Test @Test
public void testCreateTmpFile() throws IOException { void testCreateTmpFile() throws IOException {
File tmpFile = null; File tmpFile = null;
try { try {
tmpFile = DiskUtils.createTmpFile("nacos1", ".ut"); tmpFile = DiskUtils.createTmpFile("nacos1", ".ut");
Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); assertTrue(tmpFile.getName().startsWith("nacos1"));
Assert.assertTrue(tmpFile.getName().endsWith(".ut")); assertTrue(tmpFile.getName().endsWith(".ut"));
} finally { } finally {
if (tmpFile != null) { if (tmpFile != null) {
tmpFile.deleteOnExit(); tmpFile.deleteOnExit();
@ -78,13 +83,13 @@ public class DiskUtilsTest {
} }
@Test @Test
public void testCreateTmpFileWithPath() throws IOException { void testCreateTmpFileWithPath() throws IOException {
File tmpFile = null; File tmpFile = null;
try { try {
tmpFile = DiskUtils.createTmpFile(TMP_PATH, "nacos1", ".ut"); tmpFile = DiskUtils.createTmpFile(TMP_PATH, "nacos1", ".ut");
Assert.assertEquals(TMP_PATH, tmpFile.getParent() + File.separator); assertEquals(TMP_PATH, tmpFile.getParent() + File.separator);
Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); assertTrue(tmpFile.getName().startsWith("nacos1"));
Assert.assertTrue(tmpFile.getName().endsWith(".ut")); assertTrue(tmpFile.getName().endsWith(".ut"));
} finally { } finally {
if (tmpFile != null) { if (tmpFile != null) {
tmpFile.deleteOnExit(); tmpFile.deleteOnExit();
@ -93,94 +98,93 @@ public class DiskUtilsTest {
} }
@Test @Test
public void testReadFile() { void testReadFile() {
Assert.assertNotNull(DiskUtils.readFile(testFile)); assertNotNull(DiskUtils.readFile(testFile));
} }
@Test @Test
public void testReadFileWithInputStream() throws FileNotFoundException { void testReadFileWithInputStream() throws FileNotFoundException {
Assert.assertNotNull(DiskUtils.readFile(new FileInputStream(testFile))); assertNotNull(DiskUtils.readFile(new FileInputStream(testFile)));
} }
@Test @Test
public void testReadFileWithPath() { void testReadFileWithPath() {
Assert.assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName()));
} }
@Test @Test
public void testReadFileBytes() { void testReadFileBytes() {
Assert.assertNotNull(DiskUtils.readFileBytes(testFile)); assertNotNull(DiskUtils.readFileBytes(testFile));
} }
@Test @Test
public void testReadFileBytesWithPath() { void testReadFileBytesWithPath() {
Assert.assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName()));
} }
@Test @Test
public void writeFile() { void writeFile() {
Assert.assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false)); assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false));
Assert.assertEquals("unit test", DiskUtils.readFile(testFile)); assertEquals("unit test", DiskUtils.readFile(testFile));
} }
@Test @Test
public void deleteQuietly() throws IOException { void deleteQuietly() throws IOException {
File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut");
DiskUtils.deleteQuietly(tmpFile); DiskUtils.deleteQuietly(tmpFile);
Assert.assertFalse(tmpFile.exists()); assertFalse(tmpFile.exists());
} }
@Test @Test
public void testDeleteQuietlyWithPath() throws IOException { void testDeleteQuietlyWithPath() throws IOException {
String dir = TMP_PATH + "/" + "diskutils"; String dir = TMP_PATH + "/" + "diskutils";
DiskUtils.forceMkdir(dir); DiskUtils.forceMkdir(dir);
DiskUtils.createTmpFile(dir, "nacos", ".ut"); DiskUtils.createTmpFile(dir, "nacos", ".ut");
Path path = Paths.get(dir); Path path = Paths.get(dir);
DiskUtils.deleteQuietly(path); DiskUtils.deleteQuietly(path);
Assert.assertFalse(path.toFile().exists()); assertFalse(path.toFile().exists());
} }
@Test @Test
public void testDeleteFile() throws IOException { void testDeleteFile() throws IOException {
File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut");
Assert.assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName()));
Assert.assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName()));
} }
@Test @Test
public void deleteDirectory() throws IOException { void deleteDirectory() throws IOException {
Path diskutils = Paths.get(TMP_PATH, "diskutils"); Path diskutils = Paths.get(TMP_PATH, "diskutils");
File file = diskutils.toFile(); File file = diskutils.toFile();
if (!file.exists()) { if (!file.exists()) {
file.mkdir(); file.mkdir();
} }
Assert.assertTrue(file.exists()); assertTrue(file.exists());
DiskUtils.deleteDirectory(diskutils.toString()); DiskUtils.deleteDirectory(diskutils.toString());
Assert.assertFalse(file.exists()); assertFalse(file.exists());
} }
@Test @Test
public void testForceMkdir() throws IOException { void testForceMkdir() throws IOException {
File dir = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()) File dir = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()).toFile();
.toFile();
DiskUtils.forceMkdir(dir); DiskUtils.forceMkdir(dir);
Assert.assertTrue(dir.exists()); assertTrue(dir.exists());
dir.deleteOnExit(); dir.deleteOnExit();
} }
@Test @Test
public void testForceMkdirWithPath() throws IOException { void testForceMkdirWithPath() throws IOException {
Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()); Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString());
DiskUtils.forceMkdir(path.toString()); DiskUtils.forceMkdir(path.toString());
File file = path.toFile(); File file = path.toFile();
Assert.assertTrue(file.exists()); assertTrue(file.exists());
file.deleteOnExit(); file.deleteOnExit();
} }
@Test @Test
public void deleteDirThenMkdir() throws IOException { void deleteDirThenMkdir() throws IOException {
Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString()); Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString());
DiskUtils.forceMkdir(path.toString()); DiskUtils.forceMkdir(path.toString());
@ -190,15 +194,15 @@ public class DiskUtilsTest {
DiskUtils.deleteDirThenMkdir(path.toString()); DiskUtils.deleteDirThenMkdir(path.toString());
File file = path.toFile(); File file = path.toFile();
Assert.assertTrue(file.exists()); assertTrue(file.exists());
Assert.assertTrue(file.isDirectory()); assertTrue(file.isDirectory());
Assert.assertTrue(file.list() == null || file.list().length == 0); assertTrue(file.list() == null || file.list().length == 0);
file.deleteOnExit(); file.deleteOnExit();
} }
@Test @Test
public void testCopyDirectory() throws IOException { void testCopyDirectory() throws IOException {
Path srcPath = Paths.get(TMP_PATH, UUID.randomUUID().toString()); Path srcPath = Paths.get(TMP_PATH, UUID.randomUUID().toString());
DiskUtils.forceMkdir(srcPath.toString()); DiskUtils.forceMkdir(srcPath.toString());
File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut"); File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut");
@ -207,36 +211,36 @@ public class DiskUtilsTest {
DiskUtils.copyDirectory(srcPath.toFile(), destPath.toFile()); DiskUtils.copyDirectory(srcPath.toFile(), destPath.toFile());
File file = Paths.get(destPath.toString(), nacos.getName()).toFile(); File file = Paths.get(destPath.toString(), nacos.getName()).toFile();
Assert.assertTrue(file.exists()); assertTrue(file.exists());
DiskUtils.deleteDirectory(srcPath.toString()); DiskUtils.deleteDirectory(srcPath.toString());
DiskUtils.deleteDirectory(destPath.toString()); DiskUtils.deleteDirectory(destPath.toString());
} }
@Test @Test
public void testCopyFile() throws IOException { void testCopyFile() throws IOException {
File nacos = DiskUtils.createTmpFile("nacos", ".ut"); File nacos = DiskUtils.createTmpFile("nacos", ".ut");
DiskUtils.copyFile(testFile, nacos); DiskUtils.copyFile(testFile, nacos);
Assert.assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos)); assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos));
nacos.deleteOnExit(); nacos.deleteOnExit();
} }
@Test @Test
public void openFile() { void openFile() {
File file = DiskUtils.openFile(testFile.getParent(), testFile.getName()); File file = DiskUtils.openFile(testFile.getParent(), testFile.getName());
Assert.assertNotNull(file); assertNotNull(file);
Assert.assertEquals(testFile.getPath(), file.getPath()); assertEquals(testFile.getPath(), file.getPath());
Assert.assertEquals(testFile.getName(), file.getName()); assertEquals(testFile.getName(), file.getName());
} }
@Test @Test
public void testOpenFileWithPath() { void testOpenFileWithPath() {
File file = DiskUtils.openFile(testFile.getParent(), testFile.getName(), false); File file = DiskUtils.openFile(testFile.getParent(), testFile.getName(), false);
Assert.assertNotNull(file); assertNotNull(file);
Assert.assertEquals(testFile.getPath(), file.getPath()); assertEquals(testFile.getPath(), file.getPath());
Assert.assertEquals(testFile.getName(), file.getName()); assertEquals(testFile.getName(), file.getName());
} }
} }

View File

@ -16,26 +16,27 @@
package com.alibaba.nacos.plugin.control.utils; package com.alibaba.nacos.plugin.control.utils;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.File; import java.io.File;
public class EnvUtilsTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class EnvUtilsTest {
@After @AfterEach
public void tearDown() throws Exception { void tearDown() throws Exception {
System.clearProperty("nacos.home"); System.clearProperty("nacos.home");
} }
@Test @Test
public void test() { void test() {
String nacosHome = EnvUtils.getNacosHome(); String nacosHome = EnvUtils.getNacosHome();
Assert.assertEquals(System.getProperty("user.home") + File.separator + "nacos", nacosHome); assertEquals(System.getProperty("user.home") + File.separator + "nacos", nacosHome);
System.setProperty("nacos.home", "test"); System.setProperty("nacos.home", "test");
String testHome = EnvUtils.getNacosHome(); String testHome = EnvUtils.getNacosHome();
Assert.assertEquals("test", testHome); assertEquals("test", testHome);
} }
} }

View File

@ -21,33 +21,35 @@ import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper;
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper;
import com.alibaba.nacos.plugin.datasource.mapper.Mapper; import com.alibaba.nacos.plugin.datasource.mapper.Mapper;
import com.alibaba.nacos.plugin.datasource.mapper.TestMapper; import com.alibaba.nacos.plugin.datasource.mapper.TestMapper;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Map; import java.util.Map;
public class MapperManagerTest { import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class MapperManagerTest {
@Test @Test
public void testInstance() { void testInstance() {
MapperManager instance = MapperManager.instance(false); MapperManager instance = MapperManager.instance(false);
Assert.assertNotNull(instance); assertNotNull(instance);
} }
@Test @Test
public void testLoadInitial() throws NoSuchFieldException, IllegalAccessException { void testLoadInitial() throws NoSuchFieldException, IllegalAccessException {
MapperManager instance = MapperManager.instance(false); MapperManager instance = MapperManager.instance(false);
instance.loadInitial(); instance.loadInitial();
Class<MapperManager> mapperManagerClass = MapperManager.class; Class<MapperManager> mapperManagerClass = MapperManager.class;
Field declaredField = mapperManagerClass.getDeclaredField("MAPPER_SPI_MAP"); Field declaredField = mapperManagerClass.getDeclaredField("MAPPER_SPI_MAP");
declaredField.setAccessible(true); declaredField.setAccessible(true);
Map<String, Map<String, Mapper>> map = (Map<String, Map<String, Mapper>>) declaredField.get(instance); Map<String, Map<String, Mapper>> map = (Map<String, Map<String, Mapper>>) declaredField.get(instance);
Assert.assertEquals(2, map.size()); assertEquals(2, map.size());
} }
@Test @Test
public void testJoin() { void testJoin() {
MapperManager.join(new AbstractMapper() { MapperManager.join(new AbstractMapper() {
@Override @Override
public String getTableName() { public String getTableName() {
@ -61,23 +63,23 @@ public class MapperManagerTest {
}); });
MapperManager instance = MapperManager.instance(false); MapperManager instance = MapperManager.instance(false);
Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test"); Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test");
Assert.assertNotNull(mapper); assertNotNull(mapper);
} }
@Test @Test
public void testFindMapper() { void testFindMapper() {
testJoin(); testJoin();
MapperManager instance = MapperManager.instance(false); MapperManager instance = MapperManager.instance(false);
Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test"); Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test");
Assert.assertNotNull(mapper); assertNotNull(mapper);
} }
@Test @Test
public void testEnableDataSourceLogJoin() { void testEnableDataSourceLogJoin() {
MapperManager.join(new TestMapper()); MapperManager.join(new TestMapper());
MapperManager instance = MapperManager.instance(true); MapperManager instance = MapperManager.instance(true);
ConfigInfoAggrMapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "enable_data_source_log_test"); ConfigInfoAggrMapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "enable_data_source_log_test");
Assert.assertNotNull(mapper); assertNotNull(mapper);
} }
} }

View File

@ -18,7 +18,9 @@ package com.alibaba.nacos.plugin.datasource.impl;
/** /**
* A custom interface. just for test * A custom interface. just for test
*
* @author mikolls * @author mikolls
**/ **/
public interface TestInterface { public interface TestInterface {
}
}

View File

@ -22,24 +22,25 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class ConfigInfoAggrMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class ConfigInfoAggrMapperByDerbyTest {
private ConfigInfoAggrMapperByDerby configInfoAggrMapperByDerby; private ConfigInfoAggrMapperByDerby configInfoAggrMapperByDerby;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
this.configInfoAggrMapperByDerby = new ConfigInfoAggrMapperByDerby(); this.configInfoAggrMapperByDerby = new ConfigInfoAggrMapperByDerby();
} }
@Test @Test
public void testBatchRemoveAggr() { void testBatchRemoveAggr() {
List<String> datumList = Arrays.asList("1", "2", "3", "4", "5"); List<String> datumList = Arrays.asList("1", "2", "3", "4", "5");
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
@ -57,13 +58,13 @@ public class ConfigInfoAggrMapperByDerbyTest {
String sql = result.getSql(); String sql = result.getSql();
List<Object> paramList = result.getParamList(); List<Object> paramList = result.getParamList();
Assert.assertEquals(sql, "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " assertEquals(sql,
+ "AND datum_id IN (?, ?, ?, ?, ?)"); "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)");
Assert.assertEquals(paramList, argList); assertEquals(paramList, argList);
} }
@Test @Test
public void testAggrConfigInfoCount() { void testAggrConfigInfoCount() {
List<String> datumIds = Arrays.asList("1", "2", "3", "4", "5"); List<String> datumIds = Arrays.asList("1", "2", "3", "4", "5");
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
@ -82,14 +83,13 @@ public class ConfigInfoAggrMapperByDerbyTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, assertEquals(sql, "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? "
"SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)");
+ "AND datum_id IN (?, ?, ?, ?, ?)"); assertEquals(paramList, argList);
Assert.assertEquals(paramList, argList);
} }
@Test @Test
public void testFindConfigInfoAggrIsOrdered() { void testFindConfigInfoAggrIsOrdered() {
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
String tenantId = "tenant-id"; String tenantId = "tenant-id";
@ -103,13 +103,13 @@ public class ConfigInfoAggrMapperByDerbyTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM "
+ "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id"); + "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id");
Assert.assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId)); assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId));
} }
@Test @Test
public void testFindConfigInfoAggrByPageFetchRows() { void testFindConfigInfoAggrByPageFetchRows() {
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
String tenantId = "tenant-id"; String tenantId = "tenant-id";
@ -126,27 +126,26 @@ public class ConfigInfoAggrMapperByDerbyTest {
MapperResult mapperResult = configInfoAggrMapperByDerby.findConfigInfoAggrByPageFetchRows(context); MapperResult mapperResult = configInfoAggrMapperByDerby.findConfigInfoAggrByPageFetchRows(context);
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE "
"SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " + "data_id=? AND group_id=? AND tenant_id=? ORDER BY datum_id OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY");
+ "data_id=? AND group_id=? AND tenant_id=? ORDER BY datum_id OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId));
Assert.assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId));
} }
@Test @Test
public void testFindAllAggrGroupByDistinct() { void testFindAllAggrGroupByDistinct() {
MapperResult sql = configInfoAggrMapperByDerby.findAllAggrGroupByDistinct(null); MapperResult sql = configInfoAggrMapperByDerby.findAllAggrGroupByDistinct(null);
Assert.assertEquals(sql.getSql(), "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr"); assertEquals("SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr", sql.getSql());
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoAggrMapperByDerby.getTableName(); String tableName = configInfoAggrMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_AGGR); assertEquals(TableConstant.CONFIG_INFO_AGGR, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoAggrMapperByDerby.getDataSource(); String dataSource = configInfoAggrMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -22,17 +22,17 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class ConfigInfoBetaMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoBetaMapperByDerby configInfoBetaMapperByDerby;
class ConfigInfoBetaMapperByDerbyTest {
int startRow = 0; int startRow = 0;
@ -52,8 +52,10 @@ public class ConfigInfoBetaMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoBetaMapperByDerby configInfoBetaMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoBetaMapperByDerby = new ConfigInfoBetaMapperByDerby(); configInfoBetaMapperByDerby = new ConfigInfoBetaMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -67,7 +69,7 @@ public class ConfigInfoBetaMapperByDerbyTest {
} }
@Test @Test
public void testUpdateConfigInfo4BetaCas() { void testUpdateConfigInfo4BetaCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -106,35 +108,33 @@ public class ConfigInfoBetaMapperByDerbyTest {
MapperResult mapperResult = configInfoBetaMapperByDerby.updateConfigInfo4BetaCas(context); MapperResult mapperResult = configInfoBetaMapperByDerby.updateConfigInfo4BetaCas(context);
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
Assert.assertEquals(sql, "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?," assertEquals(sql, "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,"
+ "gmt_modified = ?,app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND " + "gmt_modified = ?,app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND "
+ "(md5 = ? OR md5 is null OR md5 = '')"); + "(md5 = ? OR md5 is null OR md5 = '')");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, md5},
new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, mapperResult.getParamList().toArray());
md5});
} }
@Test @Test
public void testFindAllConfigInfoBetaForDumpAllFetchRows() { void testFindAllConfigInfoBetaForDumpAllFetchRows() {
MapperResult result = configInfoBetaMapperByDerby.findAllConfigInfoBetaForDumpAllFetchRows(context); MapperResult result = configInfoBetaMapperByDerby.findAllConfigInfoBetaForDumpAllFetchRows(context);
String sql = result.getSql(); String sql = result.getSql();
List<Object> paramList = result.getParamList(); List<Object> paramList = result.getParamList();
Assert.assertEquals(sql, assertEquals(sql, "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips FROM "
"SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips FROM " + "( SELECT id FROM config_info_beta ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, "
+ "( SELECT id FROM config_info_beta ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + "config_info_beta t WHERE g.id = t.id");
+ pageSize + " ROWS ONLY ) g, " + "config_info_beta t WHERE g.id = t.id"); assertEquals(paramList, Arrays.asList(startRow, pageSize));
Assert.assertEquals(paramList, Arrays.asList(startRow, pageSize));
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoBetaMapperByDerby.getTableName(); String tableName = configInfoBetaMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_BETA); assertEquals(TableConstant.CONFIG_INFO_BETA, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoBetaMapperByDerby.getDataSource(); String dataSource = configInfoBetaMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -23,16 +23,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
public class ConfigInfoMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoMapperByDerby configInfoMapperByDerby;
class ConfigInfoMapperByDerbyTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -58,8 +58,10 @@ public class ConfigInfoMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoMapperByDerby configInfoMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoMapperByDerby = new ConfigInfoMapperByDerby(); configInfoMapperByDerby = new ConfigInfoMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -74,256 +76,243 @@ public class ConfigInfoMapperByDerbyTest {
} }
@Test @Test
public void testFindConfigMaxId() { void testFindConfigMaxId() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigMaxId(null); MapperResult mapperResult = configInfoMapperByDerby.findConfigMaxId(null);
Assert.assertEquals(mapperResult.getSql(), "SELECT MAX(id) FROM config_info"); assertEquals("SELECT MAX(id) FROM config_info", mapperResult.getSql());
} }
@Test @Test
public void testFindAllDataIdAndGroup() { void testFindAllDataIdAndGroup() {
MapperResult mapperResult = configInfoMapperByDerby.findAllDataIdAndGroup(null); MapperResult mapperResult = configInfoMapperByDerby.findAllDataIdAndGroup(null);
Assert.assertEquals(mapperResult.getSql(), "SELECT DISTINCT data_id, group_id FROM config_info"); assertEquals("SELECT DISTINCT data_id, group_id FROM config_info", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfoByAppCountRows() { void testFindConfigInfoByAppCountRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppCountRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?"); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfoByAppFetchRows() { void testFindConfigInfoByAppFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE"
"SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE" + " ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
+ " ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testConfigInfoLikeTenantCount() { void testConfigInfoLikeTenantCount() {
MapperResult mapperResult = configInfoMapperByDerby.configInfoLikeTenantCount(context); MapperResult mapperResult = configInfoMapperByDerby.configInfoLikeTenantCount(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE tenant_id LIKE ?"); assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testGetTenantIdList() { void testGetTenantIdList() {
MapperResult mapperResult = configInfoMapperByDerby.getTenantIdList(context); MapperResult mapperResult = configInfoMapperByDerby.getTenantIdList(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id OFFSET " + startRow "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id OFFSET " + startRow + " ROWS FETCH NEXT "
+ " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + pageSize + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testGetGroupIdList() { void testGetGroupIdList() {
MapperResult mapperResult = configInfoMapperByDerby.getGroupIdList(context); MapperResult mapperResult = configInfoMapperByDerby.getGroupIdList(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id OFFSET " + startRow "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize
+ " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigKey() { void testFindAllConfigKey() {
MapperResult mapperResult = configInfoMapperByDerby.findAllConfigKey(context); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigKey(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
" SELECT data_id,group_id,app_name FROM ( SELECT id FROM config_info WHERE tenant_id LIKE" " SELECT data_id,group_id,app_name FROM ( SELECT id FROM config_info WHERE tenant_id LIKE" + " ? ORDER BY id OFFSET "
+ " ? ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, config_info t WHERE g.id = t.id ");
+ " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId});
} }
@Test @Test
public void testFindAllConfigInfoBaseFetchRows() { void testFindAllConfigInfoBaseFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoBaseFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoBaseFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY " + "id OFFSET " "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY " + "id OFFSET " + startRow
+ startRow + " ROWS FETCH NEXT " + pageSize + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, config_info t WHERE g.id = t.id ");
+ " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigInfoFragment() { void testFindAllConfigInfoFragment() {
//with content //with content
context.putContextParameter(ContextConstant.NEED_CONTENT, "true"); context.putContextParameter(ContextConstant.NEED_CONTENT, "true");
MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFragment(context); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFragment(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type FROM config_info " + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
+ "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray());
+ " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id});
//with out content //with out content
context.putContextParameter(ContextConstant.NEED_CONTENT, "false"); context.putContextParameter(ContextConstant.NEED_CONTENT, "false");
MapperResult mapperResult2 = configInfoMapperByDerby.findAllConfigInfoFragment(context); MapperResult mapperResult2 = configInfoMapperByDerby.findAllConfigInfoFragment(context);
Assert.assertEquals(mapperResult2.getSql(), assertEquals(mapperResult2.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type FROM config_info " + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
+ "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize assertArrayEquals(new Object[] {id}, mapperResult2.getParamList().toArray());
+ " ROWS ONLY");
Assert.assertArrayEquals(mapperResult2.getParamList().toArray(), new Object[] {id});
} }
@Test @Test
public void testFindChangeConfig() { void testFindChangeConfig() {
MapperResult mapperResult = configInfoMapperByDerby.findChangeConfig(context); MapperResult mapperResult = configInfoMapperByDerby.findChangeConfig(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id, data_id, group_id, tenant_id, app_name, content, gmt_modified, encrypted_data_key FROM config_info " "SELECT id, data_id, group_id, tenant_id, app_name, content, gmt_modified, encrypted_data_key FROM config_info "
+ "WHERE gmt_modified >= ? and id > ? order by id OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); + "WHERE gmt_modified >= ? and id > ? order by id OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindChangeConfigCountRows() { void testFindChangeConfigCountRows() {
MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigCountRows(context); MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? ",
"SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? "); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime}); assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindChangeConfigFetchRows() { void testFindChangeConfigFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info " + "WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? OFFSET " + startRow + " ROWS FETCH NEXT "
+ "WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? OFFSET " + startRow + pageSize + " ROWS ONLY");
+ " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime});
} }
@Test @Test
public void testListGroupKeyMd5ByPageFetchRows() { void testListGroupKeyMd5ByPageFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.listGroupKeyMd5ByPageFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.listGroupKeyMd5ByPageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
" SELECT t.id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM ( SELECT id FROM config_info " " SELECT t.id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM ( SELECT id FROM config_info "
+ "ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + "ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize
+ " ROWS ONLY ) g, config_info t WHERE g.id = t.id"); + " ROWS ONLY ) g, config_info t WHERE g.id = t.id");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigInfo4Export() { void testFindAllConfigInfo4Export() {
MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user,"
+ "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
context.putWhereParameter(FieldConstant.IDS, null); context.putWhereParameter(FieldConstant.IDS, null);
mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context); mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user,"
+ "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? "); + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfoBaseLikeCountRows() { void testFindConfigInfoBaseLikeCountRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeCountRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeCountRows(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' "); assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' ", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfoBaseLikeFetchRows() { void testFindConfigInfoBaseLikeFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " + "OFFSET " + startRow
+ "OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfo4PageCountRows() { void testFindConfigInfo4PageCountRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageCountRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? ", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? "); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfo4PageFetchRows() { void testFindConfigInfo4PageFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content,type FROM config_info WHERE tenant_id=? AND app_name=? " "SELECT id,data_id,group_id,tenant_id,app_name,content,type FROM config_info WHERE tenant_id=? AND app_name=? "
+ " OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + " OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfoBaseByGroupFetchRows() { void testFindConfigInfoBaseByGroupFetchRows() {
context.putWhereParameter(FieldConstant.GROUP_ID, groupId); context.putWhereParameter(FieldConstant.GROUP_ID, groupId);
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseByGroupFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseByGroupFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? " + "OFFSET " "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? " + "OFFSET " + startRow
+ startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, tenantId}); assertArrayEquals(new Object[] {groupId, tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfoLike4PageCountRows() { void testFindConfigInfoLike4PageCountRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? ", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? "); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfoLike4PageFetchRows() { void testFindConfigInfoLike4PageFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info " + "WHERE tenant_id LIKE ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
+ "WHERE tenant_id LIKE ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
+ pageSize + " ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindAllConfigInfoFetchRows() { void testFindAllConfigInfoFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFetchRows(context); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
" SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info " " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info "
+ "WHERE tenant_id LIKE ? ORDER BY id OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ) g, config_info t WHERE g.id = t.id "); + "WHERE tenant_id LIKE ? ORDER BY id OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ) g, config_info t WHERE g.id = t.id ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, startRow, pageSize}); assertArrayEquals(new Object[] {tenantId, startRow, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfosByIds() { void testFindConfigInfosByIds() {
MapperResult mapperResult = configInfoMapperByDerby.findConfigInfosByIds(context); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfosByIds(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) ",
"SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
} }
@Test @Test
public void testRemoveConfigInfoByIdsAtomic() { void testRemoveConfigInfoByIdsAtomic() {
MapperResult mapperResult = configInfoMapperByDerby.removeConfigInfoByIdsAtomic(context); MapperResult mapperResult = configInfoMapperByDerby.removeConfigInfoByIdsAtomic(context);
Assert.assertEquals(mapperResult.getSql(), "DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); assertEquals("DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String sql = configInfoMapperByDerby.getTableName(); String sql = configInfoMapperByDerby.getTableName();
Assert.assertEquals(sql, TableConstant.CONFIG_INFO); assertEquals(TableConstant.CONFIG_INFO, sql);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String sql = configInfoMapperByDerby.getDataSource(); String sql = configInfoMapperByDerby.getDataSource();
Assert.assertEquals(sql, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, sql);
} }
@Test @Test
public void testUpdateConfigInfoAtomicCas() { void testUpdateConfigInfoAtomicCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -358,12 +347,12 @@ public class ConfigInfoMapperByDerbyTest {
context.putWhereParameter(FieldConstant.MD5, md5); context.putWhereParameter(FieldConstant.MD5, md5);
MapperResult mapperResult = configInfoMapperByDerby.updateConfigInfoAtomicCas(context); MapperResult mapperResult = configInfoMapperByDerby.updateConfigInfoAtomicCas(context);
Assert.assertEquals(mapperResult.getSql(), "UPDATE config_info SET " assertEquals(mapperResult.getSql(),
+ "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?,c_use=?," "UPDATE config_info SET " + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?,c_use=?,"
+ "effect=?,type=?,c_schema=?,encrypted_data_key=? " + "effect=?,type=?,c_schema=?,encrypted_data_key=? "
+ "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(
new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, encrypedDataKey,
encrypedDataKey, dataId, group, tenantId, md5}); dataId, group, tenantId, md5}, mapperResult.getParamList().toArray());
} }
} }

View File

@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
public class ConfigInfoTagMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoTagMapperByDerby configInfoTagMapperByDerby;
class ConfigInfoTagMapperByDerbyTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -53,8 +53,10 @@ public class ConfigInfoTagMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoTagMapperByDerby configInfoTagMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoTagMapperByDerby = new ConfigInfoTagMapperByDerby(); configInfoTagMapperByDerby = new ConfigInfoTagMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -68,7 +70,7 @@ public class ConfigInfoTagMapperByDerbyTest {
} }
@Test @Test
public void testUpdateConfigInfo4TagCas() { void testUpdateConfigInfo4TagCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -106,34 +108,31 @@ public class ConfigInfoTagMapperByDerbyTest {
MapperResult mapperResult = configInfoTagMapperByDerby.updateConfigInfo4TagCas(context); MapperResult mapperResult = configInfoTagMapperByDerby.updateConfigInfo4TagCas(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?,"
"UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND "
+ "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " + "(md5 = ? OR md5 IS NULL OR md5 = '')");
+ "(md5 = ? OR md5 IS NULL OR md5 = '')"); assertArrayEquals(new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, md5},
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), mapperResult.getParamList().toArray());
new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId,
md5});
} }
@Test @Test
public void testFindAllConfigInfoTagForDumpAllFetchRows() { void testFindAllConfigInfoTagForDumpAllFetchRows() {
MapperResult mapperResult = configInfoTagMapperByDerby.findAllConfigInfoTagForDumpAllFetchRows(context); MapperResult mapperResult = configInfoTagMapperByDerby.findAllConfigInfoTagForDumpAllFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM "
"SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM " + "( SELECT id FROM config_info_tag ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, "
+ "( SELECT id FROM config_info_tag ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + "config_info_tag t WHERE g.id = t.id");
+ pageSize + " ROWS ONLY ) g, " + "config_info_tag t WHERE g.id = t.id"); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoTagMapperByDerby.getTableName(); String tableName = configInfoTagMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_TAG); assertEquals(TableConstant.CONFIG_INFO_TAG, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoTagMapperByDerby.getDataSource(); String dataSource = configInfoTagMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class ConfigInfoTagsRelationMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoTagsRelationMapperByDerby configInfoTagsRelationMapperByDerby;
class ConfigInfoTagsRelationMapperByDerbyTest {
int startRow = 0; int startRow = 0;
@ -43,8 +43,10 @@ public class ConfigInfoTagsRelationMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoTagsRelationMapperByDerby configInfoTagsRelationMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
this.configInfoTagsRelationMapperByDerby = new ConfigInfoTagsRelationMapperByDerby(); this.configInfoTagsRelationMapperByDerby = new ConfigInfoTagsRelationMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
@ -52,60 +54,57 @@ public class ConfigInfoTagsRelationMapperByDerbyTest {
} }
@Test @Test
public void testFindConfigInfo4PageCountRows() { void testFindConfigInfo4PageCountRows() {
MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE "
"SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
+ "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testFindConfigInfo4PageFetchRows() { void testFindConfigInfo4PageFetchRows() {
MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfo4PageFetchRows(context); MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfo4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN "
+ "config_tags_relation b ON a.id=b.id WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) " + "config_tags_relation b ON a.id=b.id WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) "
+ "OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); + "OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testFindConfigInfoLike4PageCountRows() { void testFindConfigInfoLike4PageCountRows() {
MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "
"SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " + "WHERE a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
+ "WHERE a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void tsetFindConfigInfoLike4PageFetchRows() { void tsetFindConfigInfoLike4PageFetchRows() {
MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageFetchRows(context); MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a "
"SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a " + "LEFT JOIN config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND b.tag_name "
+ "LEFT JOIN config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND b.tag_name " + "IN (?, ?, ?, ?, ?) OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY");
+ "IN (?, ?, ?, ?, ?) OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoTagsRelationMapperByDerby.getTableName(); String tableName = configInfoTagsRelationMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_TAGS_RELATION); assertEquals(TableConstant.CONFIG_TAGS_RELATION, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoTagsRelationMapperByDerby.getDataSource(); String dataSource = configInfoTagsRelationMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class GroupCapacityMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private GroupCapacityMapperByDerby groupCapacityMapperByDerby;
class GroupCapacityMapperByDerbyTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -45,8 +45,10 @@ public class GroupCapacityMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private GroupCapacityMapperByDerby groupCapacityMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
this.groupCapacityMapperByDerby = new GroupCapacityMapperByDerby(); this.groupCapacityMapperByDerby = new GroupCapacityMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
@ -56,19 +58,19 @@ public class GroupCapacityMapperByDerbyTest {
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = groupCapacityMapperByDerby.getTableName(); String tableName = groupCapacityMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.GROUP_CAPACITY); assertEquals(TableConstant.GROUP_CAPACITY, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = groupCapacityMapperByDerby.getDataSource(); String dataSource = groupCapacityMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
@Test @Test
public void testInsertIntoSelect() { void testInsertIntoSelect() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -85,16 +87,16 @@ public class GroupCapacityMapperByDerbyTest {
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelect(context); MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelect(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create," "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create,"
+ " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info"); + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified},
new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}); mapperResult.getParamList().toArray());
} }
@Test @Test
public void testInsertIntoSelectByWhere() { void testInsertIntoSelectByWhere() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -112,74 +114,72 @@ public class GroupCapacityMapperByDerbyTest {
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelectByWhere(context); MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelectByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create," "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create,"
+ " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''"); + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group},
new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}); mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhereQuotaEqualZero() { void testIncrementUsageByWhereQuotaEqualZero() {
Object usage = 1; Object usage = 1;
context.putWhereParameter(FieldConstant.USAGE, usage); context.putWhereParameter(FieldConstant.USAGE, usage);
MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaEqualZero(context); MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaEqualZero(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0",
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId, usage}); assertArrayEquals(new Object[] {modified, groupId, usage}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhereQuotaNotEqualZero() { void testIncrementUsageByWhereQuotaNotEqualZero() {
MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaNotEqualZero(context); MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaNotEqualZero(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0",
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhere() { void testIncrementUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?", mapperResult.getSql());
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?"); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId});
} }
@Test @Test
public void testDecrementUsageByWhere() { void testDecrementUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByDerby.decrementUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByDerby.decrementUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0",
"UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testUpdateUsage() { void testUpdateUsage() {
MapperResult mapperResult = groupCapacityMapperByDerby.updateUsage(context); MapperResult mapperResult = groupCapacityMapperByDerby.updateUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?",
"UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testUpdateUsageByWhere() { void testUpdateUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByDerby.updateUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByDerby.updateUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = '')," "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = ''),"
+ " gmt_modified = ? WHERE group_id= ?"); + " gmt_modified = ? WHERE group_id= ?");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, modified, groupId}); assertArrayEquals(new Object[] {groupId, modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testSelectGroupInfoBySize() { void testSelectGroupInfoBySize() {
Object id = 1; Object id = 1;
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
MapperResult mapperResult = groupCapacityMapperByDerby.selectGroupInfoBySize(context); MapperResult mapperResult = groupCapacityMapperByDerby.selectGroupInfoBySize(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY", mapperResult.getSql());
"SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY");
context.putWhereParameter(FieldConstant.GMT_CREATE, createTime); context.putWhereParameter(FieldConstant.GMT_CREATE, createTime);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, pageSize}); assertArrayEquals(new Object[] {id, pageSize}, mapperResult.getParamList().toArray());
} }
} }

View File

@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class HistoryConfigInfoMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private HistoryConfigInfoMapperByDerby historyConfigInfoMapperByDerby;
class HistoryConfigInfoMapperByDerbyTest {
int startRow = 0; int startRow = 0;
@ -45,8 +45,10 @@ public class HistoryConfigInfoMapperByDerbyTest {
MapperContext context; MapperContext context;
@Before private HistoryConfigInfoMapperByDerby historyConfigInfoMapperByDerby;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
historyConfigInfoMapperByDerby = new HistoryConfigInfoMapperByDerby(); historyConfigInfoMapperByDerby = new HistoryConfigInfoMapperByDerby();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putWhereParameter(FieldConstant.START_TIME, startTime); context.putWhereParameter(FieldConstant.START_TIME, startTime);
@ -58,33 +60,32 @@ public class HistoryConfigInfoMapperByDerbyTest {
} }
@Test @Test
public void testRemoveConfigHistory() { void testRemoveConfigHistory() {
MapperResult mapperResult = historyConfigInfoMapperByDerby.removeConfigHistory(context); MapperResult mapperResult = historyConfigInfoMapperByDerby.removeConfigHistory(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"DELETE FROM his_config_info WHERE id IN( SELECT id FROM his_config_info WHERE gmt_modified < ? " "DELETE FROM his_config_info WHERE id IN( SELECT id FROM his_config_info WHERE gmt_modified < ? "
+ "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY)"); + "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY)");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, limitSize}); assertArrayEquals(new Object[] {startTime, limitSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigHistoryCountByTime() { void testFindConfigHistoryCountByTime() {
MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryCountByTime(context); MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryCountByTime(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM his_config_info WHERE gmt_modified < ?"); assertEquals("SELECT count(*) FROM his_config_info WHERE gmt_modified < ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime}); assertArrayEquals(new Object[] {startTime}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindDeletedConfig() { void testFindDeletedConfig() {
MapperResult mapperResult = historyConfigInfoMapperByDerby.findDeletedConfig(context); MapperResult mapperResult = historyConfigInfoMapperByDerby.findDeletedConfig(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' "
"SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' " + "AND gmt_modified >= ? and nid > ? order by nid OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY");
+ "AND gmt_modified >= ? and nid > ? order by nid OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigHistoryFetchRows() { void testFindConfigHistoryFetchRows() {
Object dataId = "dataId"; Object dataId = "dataId";
Object groupId = "groupId"; Object groupId = "groupId";
Object tenantId = "tenantId"; Object tenantId = "tenantId";
@ -94,32 +95,31 @@ public class HistoryConfigInfoMapperByDerbyTest {
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
context.putWhereParameter(FieldConstant.DATA_ID, dataId); context.putWhereParameter(FieldConstant.DATA_ID, dataId);
MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryFetchRows(context); MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info " "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info "
+ "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC"); + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {dataId, groupId, tenantId}); assertArrayEquals(new Object[] {dataId, groupId, tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testDetailPreviousConfigHistory() { void testDetailPreviousConfigHistory() {
Object id = "1"; Object id = "1";
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
MapperResult mapperResult = historyConfigInfoMapperByDerby.detailPreviousConfigHistory(context); MapperResult mapperResult = historyConfigInfoMapperByDerby.detailPreviousConfigHistory(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create,"
"SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)");
+ "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id});
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = historyConfigInfoMapperByDerby.getTableName(); String tableName = historyConfigInfoMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.HIS_CONFIG_INFO); assertEquals(TableConstant.HIS_CONFIG_INFO, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = historyConfigInfoMapperByDerby.getDataSource(); String dataSource = historyConfigInfoMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -21,28 +21,30 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class TenantCapacityMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private TenantCapacityMapperByDerby tenantCapacityMapperByDerby;
class TenantCapacityMapperByDerbyTest {
String tenantId = "tenantId"; String tenantId = "tenantId";
MapperContext context; MapperContext context;
private TenantCapacityMapperByDerby tenantCapacityMapperByDerby;
private Object modified = new Timestamp(System.currentTimeMillis()); private Object modified = new Timestamp(System.currentTimeMillis());
private Object oldModified = new Timestamp(System.currentTimeMillis()); private Object oldModified = new Timestamp(System.currentTimeMillis());
private Object usage = 1; private Object usage = 1;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
tenantCapacityMapperByDerby = new TenantCapacityMapperByDerby(); tenantCapacityMapperByDerby = new TenantCapacityMapperByDerby();
context = new MapperContext(); context = new MapperContext();
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
@ -53,75 +55,70 @@ public class TenantCapacityMapperByDerbyTest {
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = tenantCapacityMapperByDerby.getTableName(); String tableName = tenantCapacityMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.TENANT_CAPACITY); assertEquals(TableConstant.TENANT_CAPACITY, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = tenantCapacityMapperByDerby.getDataSource(); String dataSource = tenantCapacityMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
@Test @Test
public void testIncrementUsageWithDefaultQuotaLimit() { void testIncrementUsageWithDefaultQuotaLimit() {
MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithDefaultQuotaLimit(context); MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithDefaultQuotaLimit(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" + " ? AND quota = 0");
+ " ? AND quota = 0"); assertArrayEquals(new Object[] {modified, tenantId, usage}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId, usage});
} }
@Test @Test
public void testIncrementUsageWithQuotaLimit() { void testIncrementUsageWithQuotaLimit() {
MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithQuotaLimit(context); MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithQuotaLimit(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " + "quota AND quota != 0");
+ "quota AND quota != 0"); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId});
} }
@Test @Test
public void testIncrementUsage() { void testIncrementUsage() {
MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsage(context); MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?", mapperResult.getSql());
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?"); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId});
} }
@Test @Test
public void testDecrementUsage() { void testDecrementUsage() {
MapperResult mapperResult = tenantCapacityMapperByDerby.decrementUsage(context); MapperResult mapperResult = tenantCapacityMapperByDerby.decrementUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0",
"UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testCorrectUsage() { void testCorrectUsage() {
MapperResult mapperResult = tenantCapacityMapperByDerby.correctUsage(context); MapperResult mapperResult = tenantCapacityMapperByDerby.correctUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), "
"UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " + "gmt_modified = ? WHERE tenant_id = ?");
+ "gmt_modified = ? WHERE tenant_id = ?"); assertArrayEquals(new Object[] {tenantId, modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, modified, tenantId});
} }
@Test @Test
public void testGetCapacityList4CorrectUsage() { void testGetCapacityList4CorrectUsage() {
Object id = 1; Object id = 1;
Object limit = 10; Object limit = 10;
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit);
MapperResult mapperResult = tenantCapacityMapperByDerby.getCapacityList4CorrectUsage(context); MapperResult mapperResult = tenantCapacityMapperByDerby.getCapacityList4CorrectUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY", mapperResult.getSql());
"SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); assertArrayEquals(new Object[] {id, limit}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, limit});
} }
@Test @Test
public void testInsertTenantCapacity() { void testInsertTenantCapacity() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -142,10 +139,10 @@ public class TenantCapacityMapperByDerbyTest {
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
MapperResult mapperResult = tenantCapacityMapperByDerby.insertTenantCapacity(context); MapperResult mapperResult = tenantCapacityMapperByDerby.insertTenantCapacity(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, " "INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;"); + "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId},
new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}); mapperResult.getParamList().toArray());
} }
} }

View File

@ -18,28 +18,29 @@ package com.alibaba.nacos.plugin.datasource.impl.derby;
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
public class TenantInfoMapperByDerbyTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class TenantInfoMapperByDerbyTest {
private TenantInfoMapperByDerby tenantInfoMapperByDerby; private TenantInfoMapperByDerby tenantInfoMapperByDerby;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
tenantInfoMapperByDerby = new TenantInfoMapperByDerby(); tenantInfoMapperByDerby = new TenantInfoMapperByDerby();
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = tenantInfoMapperByDerby.getTableName(); String tableName = tenantInfoMapperByDerby.getTableName();
Assert.assertEquals(tableName, TableConstant.TENANT_INFO); assertEquals(TableConstant.TENANT_INFO, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = tenantInfoMapperByDerby.getDataSource(); String dataSource = tenantInfoMapperByDerby.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.DERBY); assertEquals(DataSourceConstant.DERBY, dataSource);
} }
} }

View File

@ -22,27 +22,25 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@RunWith(JUnit4.class) import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConfigInfoAggrMapperByMySqlTest {
class ConfigInfoAggrMapperByMySqlTest {
private ConfigInfoAggrMapperByMySql configInfoAggrMapperByMySql; private ConfigInfoAggrMapperByMySql configInfoAggrMapperByMySql;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
configInfoAggrMapperByMySql = new ConfigInfoAggrMapperByMySql(); configInfoAggrMapperByMySql = new ConfigInfoAggrMapperByMySql();
} }
@Test @Test
public void testBatchRemoveAggr() { void testBatchRemoveAggr() {
List<String> datumList = Arrays.asList("1", "2", "3", "4", "5"); List<String> datumList = Arrays.asList("1", "2", "3", "4", "5");
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
@ -61,14 +59,14 @@ public class ConfigInfoAggrMapperByMySqlTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " assertEquals(sql,
+ "AND datum_id IN (?, ?, ?, ?, ?)"); "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)");
Assert.assertEquals(paramList, argList); assertEquals(paramList, argList);
} }
@Test @Test
public void testAggrConfigInfoCount() { void testAggrConfigInfoCount() {
List<String> datumIds = Arrays.asList("1", "2", "3", "4", "5"); List<String> datumIds = Arrays.asList("1", "2", "3", "4", "5");
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
@ -87,14 +85,13 @@ public class ConfigInfoAggrMapperByMySqlTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, assertEquals(sql, "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? "
"SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)");
+ "AND datum_id IN (?, ?, ?, ?, ?)"); assertEquals(paramList, argList);
Assert.assertEquals(paramList, argList);
} }
@Test @Test
public void testFindConfigInfoAggrIsOrdered() { void testFindConfigInfoAggrIsOrdered() {
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
String tenantId = "tenant-id"; String tenantId = "tenant-id";
@ -108,13 +105,13 @@ public class ConfigInfoAggrMapperByMySqlTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM "
+ "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id"); + "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id");
Assert.assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId)); assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId));
} }
@Test @Test
public void testFindConfigInfoAggrByPageFetchRows() { void testFindConfigInfoAggrByPageFetchRows() {
String dataId = "data-id"; String dataId = "data-id";
String groupId = "group-id"; String groupId = "group-id";
String tenantId = "tenant-id"; String tenantId = "tenant-id";
@ -132,28 +129,26 @@ public class ConfigInfoAggrMapperByMySqlTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE "
"SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " + "data_id= ? AND group_id= ? AND tenant_id= ? ORDER BY datum_id LIMIT 0,5");
+ "data_id= ? AND group_id= ? AND tenant_id= ? ORDER BY datum_id LIMIT 0,5"); assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId));
Assert.assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId));
} }
@Test @Test
public void testFindAllAggrGroupByDistinct() { void testFindAllAggrGroupByDistinct() {
MapperResult mapperResult = configInfoAggrMapperByMySql.findAllAggrGroupByDistinct(null); MapperResult mapperResult = configInfoAggrMapperByMySql.findAllAggrGroupByDistinct(null);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr", mapperResult.getSql());
"SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr");
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoAggrMapperByMySql.getTableName(); String tableName = configInfoAggrMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_AGGR); assertEquals(TableConstant.CONFIG_INFO_AGGR, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoAggrMapperByMySql.getDataSource(); String dataSource = configInfoAggrMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -22,17 +22,17 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class ConfigInfoBetaMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoBetaMapperByMySql configInfoBetaMapperByMySql;
class ConfigInfoBetaMapperByMySqlTest {
int startRow = 0; int startRow = 0;
@ -52,8 +52,10 @@ public class ConfigInfoBetaMapperByMySqlTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoBetaMapperByMySql configInfoBetaMapperByMySql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoBetaMapperByMySql = new ConfigInfoBetaMapperByMySql(); configInfoBetaMapperByMySql = new ConfigInfoBetaMapperByMySql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -67,7 +69,7 @@ public class ConfigInfoBetaMapperByMySqlTest {
} }
@Test @Test
public void testUpdateConfigInfo4BetaCas() { void testUpdateConfigInfo4BetaCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -107,35 +109,33 @@ public class ConfigInfoBetaMapperByMySqlTest {
String sql = mapperResult.getSql(); String sql = mapperResult.getSql();
List<Object> paramList = mapperResult.getParamList(); List<Object> paramList = mapperResult.getParamList();
Assert.assertEquals(sql, assertEquals(sql,
"UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? " "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? "
+ "WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND (md5 = ? OR md5 is null OR md5 = '')"); + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND (md5 = ? OR md5 is null OR md5 = '')");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, md5},
new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, mapperResult.getParamList().toArray());
md5});
} }
@Test @Test
public void testFindAllConfigInfoBetaForDumpAllFetchRows() { void testFindAllConfigInfoBetaForDumpAllFetchRows() {
MapperResult result = configInfoBetaMapperByMySql.findAllConfigInfoBetaForDumpAllFetchRows(context); MapperResult result = configInfoBetaMapperByMySql.findAllConfigInfoBetaForDumpAllFetchRows(context);
String sql = result.getSql(); String sql = result.getSql();
List<Object> paramList = result.getParamList(); List<Object> paramList = result.getParamList();
Assert.assertEquals(sql, assertEquals(sql, " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key "
" SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key " + " FROM ( SELECT id FROM config_info_beta ORDER BY id LIMIT " + startRow + "," + pageSize + " )"
+ " FROM ( SELECT id FROM config_info_beta ORDER BY id LIMIT " + startRow + "," + pageSize + " g, config_info_beta t WHERE g.id = t.id ");
+ " )" + " g, config_info_beta t WHERE g.id = t.id "); assertEquals(paramList, Arrays.asList(startRow, pageSize));
Assert.assertEquals(paramList, Arrays.asList(startRow, pageSize));
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoBetaMapperByMySql.getTableName(); String tableName = configInfoBetaMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_BETA); assertEquals(TableConstant.CONFIG_INFO_BETA, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoBetaMapperByMySql.getDataSource(); String dataSource = configInfoBetaMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -24,16 +24,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
public class ConfigInfoMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoMapperByMySql configInfoMapperByMySql;
class ConfigInfoMapperByMySqlTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -59,8 +59,10 @@ public class ConfigInfoMapperByMySqlTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoMapperByMySql configInfoMapperByMySql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoMapperByMySql = new ConfigInfoMapperByMySql(); configInfoMapperByMySql = new ConfigInfoMapperByMySql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -76,253 +78,239 @@ public class ConfigInfoMapperByMySqlTest {
} }
@Test @Test
public void testFindConfigMaxId() { void testFindConfigMaxId() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigMaxId(null); MapperResult mapperResult = configInfoMapperByMySql.findConfigMaxId(null);
Assert.assertEquals(mapperResult.getSql(), "SELECT MAX(id) FROM config_info"); assertEquals("SELECT MAX(id) FROM config_info", mapperResult.getSql());
} }
@Test @Test
public void testFindAllDataIdAndGroup() { void testFindAllDataIdAndGroup() {
MapperResult mapperResult = configInfoMapperByMySql.findAllDataIdAndGroup(null); MapperResult mapperResult = configInfoMapperByMySql.findAllDataIdAndGroup(null);
Assert.assertEquals(mapperResult.getSql(), "SELECT DISTINCT data_id, group_id FROM config_info"); assertEquals("SELECT DISTINCT data_id, group_id FROM config_info", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfoByAppCountRows() { void testFindConfigInfoByAppCountRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppCountRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?"); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfoByAppFetchRows() { void testFindConfigInfoByAppFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name= ? LIMIT " "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name= ? LIMIT "
+ startRow + "," + pageSize); + startRow + "," + pageSize);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testConfigInfoLikeTenantCount() { void testConfigInfoLikeTenantCount() {
MapperResult mapperResult = configInfoMapperByMySql.configInfoLikeTenantCount(context); MapperResult mapperResult = configInfoMapperByMySql.configInfoLikeTenantCount(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE tenant_id LIKE ?"); assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testGetTenantIdList() { void testGetTenantIdList() {
MapperResult mapperResult = configInfoMapperByMySql.getTenantIdList(context); MapperResult mapperResult = configInfoMapperByMySql.getTenantIdList(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId()
"SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize);
+ "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testGetGroupIdList() { void testGetGroupIdList() {
MapperResult mapperResult = configInfoMapperByMySql.getGroupIdList(context); MapperResult mapperResult = configInfoMapperByMySql.getGroupIdList(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT " + startRow + "," "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT " + startRow + "," + pageSize);
+ pageSize); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigKey() { void testFindAllConfigKey() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigKey(context); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigKey(context);
Assert.assertEquals(mapperResult.getSql(), " SELECT data_id,group_id,app_name FROM ( " assertEquals(mapperResult.getSql(),
+ " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + context.getStartRow() + "," " SELECT data_id,group_id,app_name FROM ( " + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT "
+ context.getPageSize() + " )" + " g, config_info t WHERE g.id = t.id "); + context.getStartRow() + "," + context.getPageSize() + " )" + " g, config_info t WHERE g.id = t.id ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindAllConfigInfoBaseFetchRows() { void testFindAllConfigInfoBaseFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoBaseFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoBaseFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + context.getStartRow() + "," "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + context.getStartRow()
+ context.getPageSize() + " ) g, config_info t WHERE g.id = t.id "); + "," + context.getPageSize() + " ) g, config_info t WHERE g.id = t.id ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigInfoFragment() { void testFindAllConfigInfoFragment() {
//with content //with content
context.putContextParameter(ContextConstant.NEED_CONTENT, "true"); context.putContextParameter(ContextConstant.NEED_CONTENT, "true");
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFragment(context); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFragment(context);
Assert.assertEquals( assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key "
"SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key " + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, mapperResult.getSql());
+ "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray());
mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id});
context.putContextParameter(ContextConstant.NEED_CONTENT, "false"); context.putContextParameter(ContextConstant.NEED_CONTENT, "false");
MapperResult mapperResult2 = configInfoMapperByMySql.findAllConfigInfoFragment(context); MapperResult mapperResult2 = configInfoMapperByMySql.findAllConfigInfoFragment(context);
Assert.assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type,encrypted_data_key " assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type,encrypted_data_key "
+ "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, mapperResult2.getSql());
mapperResult2.getSql()); assertArrayEquals(new Object[] {id}, mapperResult2.getParamList().toArray());
Assert.assertArrayEquals(mapperResult2.getParamList().toArray(), new Object[] {id});
} }
@Test @Test
public void testFindChangeConfig() { void testFindChangeConfig() {
MapperResult mapperResult = configInfoMapperByMySql.findChangeConfig(context); MapperResult mapperResult = configInfoMapperByMySql.findChangeConfig(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id, data_id, group_id, tenant_id, app_name,md5, gmt_modified, encrypted_data_key FROM config_info" "SELECT id, data_id, group_id, tenant_id, app_name,md5, gmt_modified, encrypted_data_key FROM config_info"
+ " WHERE gmt_modified >= ? and id > ? order by id limit ? "); + " WHERE gmt_modified >= ? and id > ? order by id limit ? ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindChangeConfigCountRows() { void testFindChangeConfigCountRows() {
MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigCountRows(context); MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? ",
"SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? "); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime}); assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindChangeConfigFetchRows() { void testFindChangeConfigFetchRows() {
Object lastMaxId = 100; Object lastMaxId = 100;
context.putWhereParameter(FieldConstant.LAST_MAX_ID, lastMaxId); context.putWhereParameter(FieldConstant.LAST_MAX_ID, lastMaxId);
MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM config_info " + "WHERE 1=1 AND tenant_id = ? AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? AND id > " + lastMaxId
+ "WHERE 1=1 AND tenant_id = ? AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? AND id > " + " ORDER BY id ASC LIMIT " + startRow + "," + pageSize);
+ lastMaxId + " ORDER BY id ASC LIMIT " + startRow + "," + pageSize); assertArrayEquals(new Object[] {tenantId, appName, startTime, endTime}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(),
new Object[] {tenantId, appName, startTime, endTime});
} }
@Test @Test
public void testListGroupKeyMd5ByPageFetchRows() { void testListGroupKeyMd5ByPageFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.listGroupKeyMd5ByPageFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.listGroupKeyMd5ByPageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM "
"SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM " + "( SELECT id FROM config_info ORDER BY id LIMIT 0,5 ) g, config_info t WHERE g.id = t.id");
+ "( SELECT id FROM config_info ORDER BY id LIMIT 0,5 ) g, config_info t WHERE g.id = t.id"); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindAllConfigInfo4Export() { void testFindAllConfigInfo4Export() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user,"
+ "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
context.putWhereParameter(FieldConstant.IDS, null); context.putWhereParameter(FieldConstant.IDS, null);
mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context); mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user,"
+ "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? "); + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfoBaseLikeCountRows() { void testFindConfigInfoBaseLikeCountRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeCountRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeCountRows(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' "); assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' ", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfoBaseLikeFetchRows() { void testFindConfigInfoBaseLikeFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' LIMIT " "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' LIMIT " + startRow + ","
+ startRow + "," + pageSize); + pageSize);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testFindConfigInfo4PageCountRows() { void testFindConfigInfo4PageCountRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageCountRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? ", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? "); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfo4PageFetchRows() { void testFindConfigInfo4PageFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info"
"SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info" + " WHERE tenant_id=? AND app_name=? LIMIT " + startRow + "," + pageSize);
+ " WHERE tenant_id=? AND app_name=? LIMIT " + startRow + "," + pageSize); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfoBaseByGroupFetchRows() { void testFindConfigInfoBaseByGroupFetchRows() {
context.putWhereParameter(FieldConstant.GROUP_ID, groupId); context.putWhereParameter(FieldConstant.GROUP_ID, groupId);
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseByGroupFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseByGroupFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? LIMIT " + startRow "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? LIMIT " + startRow + "," + pageSize);
+ "," + pageSize); assertArrayEquals(new Object[] {groupId, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, tenantId});
} }
@Test @Test
public void testFindConfigInfoLike4PageCountRows() { void testFindConfigInfoLike4PageCountRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? ", mapperResult.getSql());
"SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? "); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindConfigInfoLike4PageFetchRows() { void testFindConfigInfoLike4PageFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info "
"SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info " + "WHERE tenant_id LIKE ? AND app_name = ? LIMIT " + startRow + "," + pageSize);
+ "WHERE tenant_id LIKE ? AND app_name = ? LIMIT " + startRow + "," + pageSize); assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName});
} }
@Test @Test
public void testFindAllConfigInfoFetchRows() { void testFindAllConfigInfoFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFetchRows(context); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info " "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info "
+ "WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? ) g, config_info t WHERE g.id = t.id "); + "WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? ) g, config_info t WHERE g.id = t.id ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, startRow, pageSize}); assertArrayEquals(new Object[] {tenantId, startRow, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigInfosByIds() { void testFindConfigInfosByIds() {
MapperResult mapperResult = configInfoMapperByMySql.findConfigInfosByIds(context); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfosByIds(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) ",
"SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
} }
@Test @Test
public void testRemoveConfigInfoByIdsAtomic() { void testRemoveConfigInfoByIdsAtomic() {
MapperResult mapperResult = configInfoMapperByMySql.removeConfigInfoByIdsAtomic(context); MapperResult mapperResult = configInfoMapperByMySql.removeConfigInfoByIdsAtomic(context);
Assert.assertEquals(mapperResult.getSql(), "DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); assertEquals("DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray());
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String sql = configInfoMapperByMySql.getTableName(); String sql = configInfoMapperByMySql.getTableName();
Assert.assertEquals(sql, TableConstant.CONFIG_INFO); assertEquals(TableConstant.CONFIG_INFO, sql);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String sql = configInfoMapperByMySql.getDataSource(); String sql = configInfoMapperByMySql.getDataSource();
Assert.assertEquals(sql, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, sql);
} }
@Test @Test
public void testUpdateConfigInfoAtomicCas() { void testUpdateConfigInfoAtomicCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -357,12 +345,12 @@ public class ConfigInfoMapperByMySqlTest {
context.putWhereParameter(FieldConstant.MD5, md5); context.putWhereParameter(FieldConstant.MD5, md5);
MapperResult mapperResult = configInfoMapperByMySql.updateConfigInfoAtomicCas(context); MapperResult mapperResult = configInfoMapperByMySql.updateConfigInfoAtomicCas(context);
Assert.assertEquals(mapperResult.getSql(), "UPDATE config_info SET " assertEquals(mapperResult.getSql(),
+ "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?," "UPDATE config_info SET " + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?,"
+ "c_use=?,effect=?,type=?,c_schema=?,encrypted_data_key=? " + "c_use=?,effect=?,type=?,c_schema=?,encrypted_data_key=? "
+ "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(
new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, encryptedDataKey,
encryptedDataKey, dataId, group, tenantId, md5}); dataId, group, tenantId, md5}, mapperResult.getParamList().toArray());
} }
} }

View File

@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
public class ConfigInfoTagMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigInfoTagMapperByMySql configInfoTagMapperByMySql;
class ConfigInfoTagMapperByMySqlTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -53,8 +53,10 @@ public class ConfigInfoTagMapperByMySqlTest {
MapperContext context; MapperContext context;
@Before private ConfigInfoTagMapperByMySql configInfoTagMapperByMySql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configInfoTagMapperByMySql = new ConfigInfoTagMapperByMySql(); configInfoTagMapperByMySql = new ConfigInfoTagMapperByMySql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
@ -68,7 +70,7 @@ public class ConfigInfoTagMapperByMySqlTest {
} }
@Test @Test
public void testUpdateConfigInfo4TagCas() { void testUpdateConfigInfo4TagCas() {
String newContent = "new Content"; String newContent = "new Content";
String newMD5 = "newMD5"; String newMD5 = "newMD5";
String srcIp = "1.1.1.1"; String srcIp = "1.1.1.1";
@ -106,34 +108,31 @@ public class ConfigInfoTagMapperByMySqlTest {
MapperResult mapperResult = configInfoTagMapperByMySql.updateConfigInfo4TagCas(context); MapperResult mapperResult = configInfoTagMapperByMySql.updateConfigInfo4TagCas(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?,"
"UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND "
+ "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " + "(md5 = ? OR md5 IS NULL OR md5 = '')");
+ "(md5 = ? OR md5 IS NULL OR md5 = '')"); assertArrayEquals(new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, md5},
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), mapperResult.getParamList().toArray());
new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId,
md5});
} }
@Test @Test
public void testFindAllConfigInfoTagForDumpAllFetchRows() { void testFindAllConfigInfoTagForDumpAllFetchRows() {
MapperResult mapperResult = configInfoTagMapperByMySql.findAllConfigInfoTagForDumpAllFetchRows(context); MapperResult mapperResult = configInfoTagMapperByMySql.findAllConfigInfoTagForDumpAllFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), " SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM ( "
" SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM ( " + "SELECT id FROM config_info_tag ORDER BY id LIMIT " + startRow + "," + pageSize
+ "SELECT id FROM config_info_tag ORDER BY id LIMIT " + startRow + "," + pageSize + " ) g, config_info_tag t WHERE g.id = t.id ");
+ " ) g, config_info_tag t WHERE g.id = t.id "); assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs);
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configInfoTagMapperByMySql.getTableName(); String tableName = configInfoTagMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_TAG); assertEquals(TableConstant.CONFIG_INFO_TAG, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configInfoTagMapperByMySql.getDataSource(); String dataSource = configInfoTagMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class ConfigTagsRelationMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private ConfigTagsRelationMapperByMySql configTagsRelationMapperByMySql;
class ConfigTagsRelationMapperByMySqlTest {
int startRow = 0; int startRow = 0;
@ -43,8 +43,10 @@ public class ConfigTagsRelationMapperByMySqlTest {
MapperContext context; MapperContext context;
@Before private ConfigTagsRelationMapperByMySql configTagsRelationMapperByMySql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
configTagsRelationMapperByMySql = new ConfigTagsRelationMapperByMySql(); configTagsRelationMapperByMySql = new ConfigTagsRelationMapperByMySql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
@ -52,58 +54,54 @@ public class ConfigTagsRelationMapperByMySqlTest {
} }
@Test @Test
public void testFindConfigInfoLike4PageCountRows() { void testFindConfigInfoLike4PageCountRows() {
MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE "
"SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
+ "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testFindConfigInfo4PageCountRows() { void testFindConfigInfo4PageCountRows() {
MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageCountRows(context); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageCountRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "
"SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " + "WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) ");
+ "WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) ");
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testFindConfigInfo4PageFetchRows() { void testFindConfigInfo4PageFetchRows() {
context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.DATA_ID, "dataID1");
context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1");
context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1");
context.putWhereParameter(FieldConstant.CONTENT, "Content1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1");
MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageFetchRows(context); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageFetchRows(context);
Assert.assertEquals( assertEquals("SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info "
"SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info " + "a LEFT JOIN config_tags_relation b ON a.id=b.id "
+ "a LEFT JOIN config_tags_relation b ON a.id=b.id " + "WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND a.content LIKE ? "
+ "WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND a.content LIKE ? " + " AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + startRow + "," + pageSize, mapperResult.getSql());
+ " AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT "
+ startRow + "," + pageSize, mapperResult.getSql());
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.add("dataID1"); list.add("dataID1");
list.add("groupID1"); list.add("groupID1");
list.add("AppName1"); list.add("AppName1");
list.add("Content1"); list.add("Content1");
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testFindConfigInfoLike4PageCountRowss() { void testFindConfigInfoLike4PageCountRowss() {
context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.DATA_ID, "dataID1");
context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1");
context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1");
context.putWhereParameter(FieldConstant.CONTENT, "Content1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1");
MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context);
Assert.assertEquals("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " assertEquals("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "
+ "WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? AND a.group_id LIKE ? AND a.app_name = ? " + "WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? AND a.group_id LIKE ? AND a.app_name = ? "
+ "AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ", mapperResult.getSql()); + "AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ", mapperResult.getSql());
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
@ -112,39 +110,38 @@ public class ConfigTagsRelationMapperByMySqlTest {
list.add("AppName1"); list.add("AppName1");
list.add("Content1"); list.add("Content1");
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void tsetFindConfigInfoLike4PageFetchRows() { void tsetFindConfigInfoLike4PageFetchRows() {
context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.DATA_ID, "dataID1");
context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1");
context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1");
context.putWhereParameter(FieldConstant.CONTENT, "Content1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1");
MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageFetchRows(context); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN"
"SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN" + " config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? "
+ " config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? " + "AND a.group_id LIKE ? AND a.app_name = ? AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + startRow
+ "AND a.group_id LIKE ? AND a.app_name = ? AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + "," + pageSize);
+ startRow + "," + pageSize);
List<Object> list = CollectionUtils.list(tenantId); List<Object> list = CollectionUtils.list(tenantId);
list.add("dataID1"); list.add("dataID1");
list.add("groupID1"); list.add("groupID1");
list.add("AppName1"); list.add("AppName1");
list.add("Content1"); list.add("Content1");
list.addAll(Arrays.asList(tagArr)); list.addAll(Arrays.asList(tagArr));
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray());
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = configTagsRelationMapperByMySql.getTableName(); String tableName = configTagsRelationMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.CONFIG_TAGS_RELATION); assertEquals(TableConstant.CONFIG_TAGS_RELATION, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = configTagsRelationMapperByMySql.getDataSource(); String dataSource = configTagsRelationMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class GroupCapacityMapperByMysqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private GroupCapacityMapperByMysql groupCapacityMapperByMysql;
class GroupCapacityMapperByMysqlTest {
private final Object[] emptyObjs = new Object[] {}; private final Object[] emptyObjs = new Object[] {};
@ -45,8 +45,10 @@ public class GroupCapacityMapperByMysqlTest {
MapperContext context; MapperContext context;
@Before private GroupCapacityMapperByMysql groupCapacityMapperByMysql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
groupCapacityMapperByMysql = new GroupCapacityMapperByMysql(); groupCapacityMapperByMysql = new GroupCapacityMapperByMysql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
@ -56,19 +58,19 @@ public class GroupCapacityMapperByMysqlTest {
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = groupCapacityMapperByMysql.getTableName(); String tableName = groupCapacityMapperByMysql.getTableName();
Assert.assertEquals(tableName, TableConstant.GROUP_CAPACITY); assertEquals(TableConstant.GROUP_CAPACITY, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = groupCapacityMapperByMysql.getDataSource(); String dataSource = groupCapacityMapperByMysql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
@Test @Test
public void testInsertIntoSelect() { void testInsertIntoSelect() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -80,21 +82,21 @@ public class GroupCapacityMapperByMysqlTest {
context.putUpdateParameter(FieldConstant.MAX_SIZE, maxSize); context.putUpdateParameter(FieldConstant.MAX_SIZE, maxSize);
context.putUpdateParameter(FieldConstant.MAX_AGGR_SIZE, maxAggrSize); context.putUpdateParameter(FieldConstant.MAX_AGGR_SIZE, maxAggrSize);
context.putUpdateParameter(FieldConstant.MAX_AGGR_COUNT, maxAggrCount); context.putUpdateParameter(FieldConstant.MAX_AGGR_COUNT, maxAggrCount);
context.putUpdateParameter(FieldConstant.GMT_CREATE, createTime); context.putUpdateParameter(FieldConstant.GMT_CREATE, createTime);
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelect(context); MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelect(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create," "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create,"
+ " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info"); + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified},
new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}); mapperResult.getParamList().toArray());
} }
@Test @Test
public void testInsertIntoSelectByWhere() { void testInsertIntoSelectByWhere() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -112,72 +114,71 @@ public class GroupCapacityMapperByMysqlTest {
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelectByWhere(context); MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelectByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create," "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create,"
+ " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''"); + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group},
new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}); mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhereQuotaEqualZero() { void testIncrementUsageByWhereQuotaEqualZero() {
Object usage = 1; Object usage = 1;
context.putWhereParameter(FieldConstant.USAGE, usage); context.putWhereParameter(FieldConstant.USAGE, usage);
MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaEqualZero(context); MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaEqualZero(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0",
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId, usage}); assertArrayEquals(new Object[] {modified, groupId, usage}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhereQuotaNotEqualZero() { void testIncrementUsageByWhereQuotaNotEqualZero() {
MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaNotEqualZero(context); MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaNotEqualZero(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0",
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testIncrementUsageByWhere() { void testIncrementUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?", mapperResult.getSql());
"UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?"); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId});
} }
@Test @Test
public void testDecrementUsageByWhere() { void testDecrementUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByMysql.decrementUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByMysql.decrementUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0",
"UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testUpdateUsage() { void testUpdateUsage() {
MapperResult mapperResult = groupCapacityMapperByMysql.updateUsage(context); MapperResult mapperResult = groupCapacityMapperByMysql.updateUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?",
"UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testUpdateUsageByWhere() { void testUpdateUsageByWhere() {
MapperResult mapperResult = groupCapacityMapperByMysql.updateUsageByWhere(context); MapperResult mapperResult = groupCapacityMapperByMysql.updateUsageByWhere(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = '')," "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = ''),"
+ " gmt_modified = ? WHERE group_id= ?"); + " gmt_modified = ? WHERE group_id= ?");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, modified, groupId}); assertArrayEquals(new Object[] {groupId, modified, groupId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testSelectGroupInfoBySize() { void testSelectGroupInfoBySize() {
Object id = 1; Object id = 1;
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
MapperResult mapperResult = groupCapacityMapperByMysql.selectGroupInfoBySize(context); MapperResult mapperResult = groupCapacityMapperByMysql.selectGroupInfoBySize(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT id, group_id FROM group_capacity WHERE id > ? LIMIT ?"); assertEquals("SELECT id, group_id FROM group_capacity WHERE id > ? LIMIT ?", mapperResult.getSql());
context.putWhereParameter(FieldConstant.GMT_CREATE, createTime); context.putWhereParameter(FieldConstant.GMT_CREATE, createTime);
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, pageSize}); assertArrayEquals(new Object[] {id, pageSize}, mapperResult.getParamList().toArray());
} }
} }

View File

@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class HistoryConfigInfoMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private HistoryConfigInfoMapperByMySql historyConfigInfoMapperByMySql;
class HistoryConfigInfoMapperByMySqlTest {
int startRow = 0; int startRow = 0;
@ -45,8 +45,10 @@ public class HistoryConfigInfoMapperByMySqlTest {
MapperContext context; MapperContext context;
@Before private HistoryConfigInfoMapperByMySql historyConfigInfoMapperByMySql;
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
historyConfigInfoMapperByMySql = new HistoryConfigInfoMapperByMySql(); historyConfigInfoMapperByMySql = new HistoryConfigInfoMapperByMySql();
context = new MapperContext(startRow, pageSize); context = new MapperContext(startRow, pageSize);
context.putWhereParameter(FieldConstant.START_TIME, startTime); context.putWhereParameter(FieldConstant.START_TIME, startTime);
@ -57,31 +59,30 @@ public class HistoryConfigInfoMapperByMySqlTest {
} }
@Test @Test
public void testRemoveConfigHistory() { void testRemoveConfigHistory() {
MapperResult mapperResult = historyConfigInfoMapperByMySql.removeConfigHistory(context); MapperResult mapperResult = historyConfigInfoMapperByMySql.removeConfigHistory(context);
Assert.assertEquals(mapperResult.getSql(), "DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?"); assertEquals("DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, limitSize}); assertArrayEquals(new Object[] {startTime, limitSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigHistoryCountByTime() { void testFindConfigHistoryCountByTime() {
MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryCountByTime(context); MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryCountByTime(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM his_config_info WHERE gmt_modified < ?"); assertEquals("SELECT count(*) FROM his_config_info WHERE gmt_modified < ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime}); assertArrayEquals(new Object[] {startTime}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindDeletedConfig() { void testFindDeletedConfig() {
MapperResult mapperResult = historyConfigInfoMapperByMySql.findDeletedConfig(context); MapperResult mapperResult = historyConfigInfoMapperByMySql.findDeletedConfig(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info "
"SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info " + "WHERE op_type = 'D' AND gmt_modified >= ? and nid > ? order by nid limit ? ");
+ "WHERE op_type = 'D' AND gmt_modified >= ? and nid > ? order by nid limit ? ");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testFindConfigHistoryFetchRows() { void testFindConfigHistoryFetchRows() {
Object dataId = "dataId"; Object dataId = "dataId";
Object groupId = "groupId"; Object groupId = "groupId";
Object tenantId = "tenantId"; Object tenantId = "tenantId";
@ -91,32 +92,31 @@ public class HistoryConfigInfoMapperByMySqlTest {
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
context.putWhereParameter(FieldConstant.DATA_ID, dataId); context.putWhereParameter(FieldConstant.DATA_ID, dataId);
MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryFetchRows(context); MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryFetchRows(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info " "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info "
+ "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC"); + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {dataId, groupId, tenantId}); assertArrayEquals(new Object[] {dataId, groupId, tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testDetailPreviousConfigHistory() { void testDetailPreviousConfigHistory() {
Object id = "1"; Object id = "1";
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
MapperResult mapperResult = historyConfigInfoMapperByMySql.detailPreviousConfigHistory(context); MapperResult mapperResult = historyConfigInfoMapperByMySql.detailPreviousConfigHistory(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create,"
"SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)");
+ "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id});
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = historyConfigInfoMapperByMySql.getTableName(); String tableName = historyConfigInfoMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.HIS_CONFIG_INFO); assertEquals(TableConstant.HIS_CONFIG_INFO, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = historyConfigInfoMapperByMySql.getDataSource(); String dataSource = historyConfigInfoMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -21,28 +21,30 @@ import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.alibaba.nacos.plugin.datasource.model.MapperResult;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
public class TenantCapacityMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
private TenantCapacityMapperByMySql tenantCapacityMapperByMySql;
class TenantCapacityMapperByMySqlTest {
String tenantId = "tenantId"; String tenantId = "tenantId";
MapperContext context; MapperContext context;
private TenantCapacityMapperByMySql tenantCapacityMapperByMySql;
private Object modified = new Timestamp(System.currentTimeMillis()); private Object modified = new Timestamp(System.currentTimeMillis());
private Object oldModified = new Timestamp(System.currentTimeMillis()); private Object oldModified = new Timestamp(System.currentTimeMillis());
private Object usage = 1; private Object usage = 1;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
tenantCapacityMapperByMySql = new TenantCapacityMapperByMySql(); tenantCapacityMapperByMySql = new TenantCapacityMapperByMySql();
context = new MapperContext(); context = new MapperContext();
context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified);
@ -53,74 +55,70 @@ public class TenantCapacityMapperByMySqlTest {
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = tenantCapacityMapperByMySql.getTableName(); String tableName = tenantCapacityMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.TENANT_CAPACITY); assertEquals(TableConstant.TENANT_CAPACITY, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = tenantCapacityMapperByMySql.getDataSource(); String dataSource = tenantCapacityMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
@Test @Test
public void testIncrementUsageWithDefaultQuotaLimit() { void testIncrementUsageWithDefaultQuotaLimit() {
MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithDefaultQuotaLimit(context); MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithDefaultQuotaLimit(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" + " ? AND quota = 0");
+ " ? AND quota = 0"); assertArrayEquals(new Object[] {modified, tenantId, usage}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId, usage});
} }
@Test @Test
public void testIncrementUsageWithQuotaLimit() { void testIncrementUsageWithQuotaLimit() {
MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithQuotaLimit(context); MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithQuotaLimit(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " + "quota AND quota != 0");
+ "quota AND quota != 0"); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId});
} }
@Test @Test
public void testIncrementUsage() { void testIncrementUsage() {
MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsage(context); MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?", mapperResult.getSql());
"UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?"); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId});
} }
@Test @Test
public void testDecrementUsage() { void testDecrementUsage() {
MapperResult mapperResult = tenantCapacityMapperByMySql.decrementUsage(context); MapperResult mapperResult = tenantCapacityMapperByMySql.decrementUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals("UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0",
"UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0"); mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testCorrectUsage() { void testCorrectUsage() {
MapperResult mapperResult = tenantCapacityMapperByMySql.correctUsage(context); MapperResult mapperResult = tenantCapacityMapperByMySql.correctUsage(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(), "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), "
"UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " + "gmt_modified = ? WHERE tenant_id = ?");
+ "gmt_modified = ? WHERE tenant_id = ?"); assertArrayEquals(new Object[] {tenantId, modified, tenantId}, mapperResult.getParamList().toArray());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, modified, tenantId});
} }
@Test @Test
public void testGetCapacityList4CorrectUsage() { void testGetCapacityList4CorrectUsage() {
Object id = 1; Object id = 1;
Object limit = 10; Object limit = 10;
context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.ID, id);
context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit);
MapperResult mapperResult = tenantCapacityMapperByMySql.getCapacityList4CorrectUsage(context); MapperResult mapperResult = tenantCapacityMapperByMySql.getCapacityList4CorrectUsage(context);
Assert.assertEquals(mapperResult.getSql(), "SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?"); assertEquals("SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?", mapperResult.getSql());
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, limit}); assertArrayEquals(new Object[] {id, limit}, mapperResult.getParamList().toArray());
} }
@Test @Test
public void testInsertTenantCapacity() { void testInsertTenantCapacity() {
Object group = "group"; Object group = "group";
Object quota = "quota"; Object quota = "quota";
Object maxAggrSize = 10; Object maxAggrSize = 10;
@ -141,10 +139,10 @@ public class TenantCapacityMapperByMySqlTest {
context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId);
MapperResult mapperResult = tenantCapacityMapperByMySql.insertTenantCapacity(context); MapperResult mapperResult = tenantCapacityMapperByMySql.insertTenantCapacity(context);
Assert.assertEquals(mapperResult.getSql(), assertEquals(mapperResult.getSql(),
"INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, " "INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;"); + "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;");
Assert.assertArrayEquals(mapperResult.getParamList().toArray(), assertArrayEquals(new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId},
new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}); mapperResult.getParamList().toArray());
} }
} }

View File

@ -18,28 +18,29 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql;
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
public class TenantInfoMapperByMySqlTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class TenantInfoMapperByMySqlTest {
private TenantInfoMapperByMySql tenantInfoMapperByMySql; private TenantInfoMapperByMySql tenantInfoMapperByMySql;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
tenantInfoMapperByMySql = new TenantInfoMapperByMySql(); tenantInfoMapperByMySql = new TenantInfoMapperByMySql();
} }
@Test @Test
public void testGetTableName() { void testGetTableName() {
String tableName = tenantInfoMapperByMySql.getTableName(); String tableName = tenantInfoMapperByMySql.getTableName();
Assert.assertEquals(tableName, TableConstant.TENANT_INFO); assertEquals(TableConstant.TENANT_INFO, tableName);
} }
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
String dataSource = tenantInfoMapperByMySql.getDataSource(); String dataSource = tenantInfoMapperByMySql.getDataSource();
Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); assertEquals(DataSourceConstant.MYSQL, dataSource);
} }
} }

View File

@ -17,66 +17,67 @@
package com.alibaba.nacos.plugin.datasource.mapper; package com.alibaba.nacos.plugin.datasource.mapper;
import com.alibaba.nacos.plugin.datasource.impl.mysql.TenantInfoMapperByMySql; import com.alibaba.nacos.plugin.datasource.impl.mysql.TenantInfoMapperByMySql;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
public class AbstractMapperTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class AbstractMapperTest {
private AbstractMapper abstractMapper; private AbstractMapper abstractMapper;
@Before @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
abstractMapper = new TenantInfoMapperByMySql(); abstractMapper = new TenantInfoMapperByMySql();
} }
@Test @Test
public void testSelect() { void testSelect() {
String sql = abstractMapper.select(Arrays.asList("id", "name"), Arrays.asList("id")); String sql = abstractMapper.select(Arrays.asList("id", "name"), Arrays.asList("id"));
Assert.assertEquals(sql, "SELECT id,name FROM tenant_info WHERE id = ?"); assertEquals("SELECT id,name FROM tenant_info WHERE id = ?", sql);
} }
@Test @Test
public void testInsert() { void testInsert() {
String sql = abstractMapper.insert(Arrays.asList("id", "name")); String sql = abstractMapper.insert(Arrays.asList("id", "name"));
Assert.assertEquals(sql, "INSERT INTO tenant_info(id, name) VALUES(?,?)"); assertEquals("INSERT INTO tenant_info(id, name) VALUES(?,?)", sql);
} }
@Test @Test
public void testUpdate() { void testUpdate() {
String sql = abstractMapper.update(Arrays.asList("id", "name"), Arrays.asList("id")); String sql = abstractMapper.update(Arrays.asList("id", "name"), Arrays.asList("id"));
Assert.assertEquals(sql, "UPDATE tenant_info SET id = ?,name = ? WHERE id = ?"); assertEquals("UPDATE tenant_info SET id = ?,name = ? WHERE id = ?", sql);
} }
@Test @Test
public void testDelete() { void testDelete() {
String sql = abstractMapper.delete(Arrays.asList("id")); String sql = abstractMapper.delete(Arrays.asList("id"));
Assert.assertEquals(sql, "DELETE FROM tenant_info WHERE id = ? "); assertEquals("DELETE FROM tenant_info WHERE id = ? ", sql);
} }
@Test @Test
public void testCount() { void testCount() {
String sql = abstractMapper.count(Arrays.asList("id")); String sql = abstractMapper.count(Arrays.asList("id"));
Assert.assertEquals(sql, "SELECT COUNT(*) FROM tenant_info WHERE id = ?"); assertEquals("SELECT COUNT(*) FROM tenant_info WHERE id = ?", sql);
} }
@Test @Test
public void testGetPrimaryKeyGeneratedKeys() { void testGetPrimaryKeyGeneratedKeys() {
String[] keys = abstractMapper.getPrimaryKeyGeneratedKeys(); String[] keys = abstractMapper.getPrimaryKeyGeneratedKeys();
Assert.assertEquals(keys[0], "id"); assertEquals("id", keys[0]);
} }
@Test @Test
public void testSelectAll() { void testSelectAll() {
String sql = abstractMapper.select(Arrays.asList("id", "name"), null); String sql = abstractMapper.select(Arrays.asList("id", "name"), null);
Assert.assertEquals(sql, "SELECT id,name FROM tenant_info "); assertEquals("SELECT id,name FROM tenant_info ", sql);
} }
@Test @Test
public void testCountAll() { void testCountAll() {
String sql = abstractMapper.count(null); String sql = abstractMapper.count(null);
Assert.assertEquals(sql, "SELECT COUNT(*) FROM tenant_info "); assertEquals("SELECT COUNT(*) FROM tenant_info ", sql);
} }
} }

View File

@ -22,18 +22,19 @@ import com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoAggrMapperByMySq
/** /**
* Implement interfaces other than Mapper. just for test * Implement interfaces other than Mapper. just for test
*
* @author mikolls * @author mikolls
**/ **/
public class TestMapper extends ConfigInfoAggrMapperByMySql implements TestInterface { public class TestMapper extends ConfigInfoAggrMapperByMySql implements TestInterface {
@Override @Override
public String getTableName() { public String getTableName() {
return "enable_data_source_log_test"; return "enable_data_source_log_test";
} }
@Override @Override
public String getDataSource() { public String getDataSource() {
return DataSourceConstant.MYSQL; return DataSourceConstant.MYSQL;
} }
} }

View File

@ -17,60 +17,61 @@
package com.alibaba.nacos.plugin.datasource.proxy; package com.alibaba.nacos.plugin.datasource.proxy;
import com.alibaba.nacos.plugin.datasource.mapper.Mapper; import com.alibaba.nacos.plugin.datasource.mapper.Mapper;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.List; import java.util.List;
public class MapperProxyTest { import static org.junit.jupiter.api.Assertions.assertEquals;
class MapperProxyTest {
private MapperProxy mapperProxy; private MapperProxy mapperProxy;
@Before @BeforeEach
public void setup() { void setup() {
this.mapperProxy = new MapperProxy(); this.mapperProxy = new MapperProxy();
} }
@Test @Test
public void testCreateProxy() { void testCreateProxy() {
Mapper mapper = new Mapper() { Mapper mapper = new Mapper() {
@Override @Override
public String select(List<String> columns, List<String> where) { public String select(List<String> columns, List<String> where) {
return "select-test"; return "select-test";
} }
@Override @Override
public String insert(List<String> columns) { public String insert(List<String> columns) {
return "insert-test"; return "insert-test";
} }
@Override @Override
public String update(List<String> columns, List<String> where) { public String update(List<String> columns, List<String> where) {
return "update-test"; return "update-test";
} }
@Override @Override
public String delete(List<String> params) { public String delete(List<String> params) {
return "delete-test"; return "delete-test";
} }
@Override @Override
public String count(List<String> where) { public String count(List<String> where) {
return "count-test"; return "count-test";
} }
@Override @Override
public String getTableName() { public String getTableName() {
return "test"; return "test";
} }
@Override @Override
public String getDataSource() { public String getDataSource() {
return "test"; return "test";
} }
@Override @Override
public String[] getPrimaryKeyGeneratedKeys() { public String[] getPrimaryKeyGeneratedKeys() {
return new String[0]; return new String[0];
@ -84,7 +85,7 @@ public class MapperProxyTest {
Field mapperField = mapperProxy.getClass().getDeclaredField("mapper"); Field mapperField = mapperProxy.getClass().getDeclaredField("mapper");
mapperField.setAccessible(true); mapperField.setAccessible(true);
Class<?> clazz = mapperField.getDeclaringClass(); Class<?> clazz = mapperField.getDeclaringClass();
Assert.assertEquals(MapperProxy.class, clazz); assertEquals(MapperProxy.class, clazz);
} catch (NoSuchFieldException | IllegalAccessException e) { } catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -17,26 +17,28 @@
package com.alibaba.nacos.plugin.encryption; package com.alibaba.nacos.plugin.encryption;
import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.Optional; import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* EncryptionPluginManagerTest. * EncryptionPluginManagerTest.
* *
* @author lixiaoshuang * @author lixiaoshuang
*/ */
public class EncryptionPluginManagerTest { class EncryptionPluginManagerTest {
@Test @Test
public void testInstance() { void testInstance() {
EncryptionPluginManager instance = EncryptionPluginManager.instance(); EncryptionPluginManager instance = EncryptionPluginManager.instance();
Assert.assertNotNull(instance); assertNotNull(instance);
} }
@Test @Test
public void testJoin() { void testJoin() {
EncryptionPluginManager.join(new EncryptionPluginService() { EncryptionPluginManager.join(new EncryptionPluginService() {
@Override @Override
public String encrypt(String secretKey, String content) { public String encrypt(String secretKey, String content) {
@ -57,25 +59,25 @@ public class EncryptionPluginManagerTest {
public String algorithmName() { public String algorithmName() {
return "aes"; return "aes";
} }
@Override @Override
public String encryptSecretKey(String secretKey) { public String encryptSecretKey(String secretKey) {
return secretKey; return secretKey;
} }
@Override @Override
public String decryptSecretKey(String secretKey) { public String decryptSecretKey(String secretKey) {
return secretKey; return secretKey;
} }
}); });
Assert.assertNotNull(EncryptionPluginManager.instance().findEncryptionService("aes")); assertNotNull(EncryptionPluginManager.instance().findEncryptionService("aes"));
} }
@Test @Test
public void testFindEncryptionService() { void testFindEncryptionService() {
EncryptionPluginManager instance = EncryptionPluginManager.instance(); EncryptionPluginManager instance = EncryptionPluginManager.instance();
Optional<EncryptionPluginService> optional = instance.findEncryptionService("aes"); Optional<EncryptionPluginService> optional = instance.findEncryptionService("aes");
Assert.assertTrue(optional.isPresent()); assertTrue(optional.isPresent());
} }
} }

View File

@ -20,19 +20,20 @@ import com.alibaba.nacos.common.utils.Pair;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager;
import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService;
import org.apache.commons.codec.binary.Base64;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Base64; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.Before;
import org.junit.Test;
/** /**
* AES encryption algorithm testing dataId with prefix cipher. * AES encryption algorithm testing dataId with prefix cipher.
@ -41,12 +42,12 @@ import org.junit.Test;
* @Date 2023/12/22 6:07 PM * @Date 2023/12/22 6:07 PM
* @Version 1.0 * @Version 1.0
*/ */
public class EncryptionAesHandlerTest { class EncryptionAesHandlerTest {
private EncryptionPluginService mockEncryptionPluginService; private EncryptionPluginService mockEncryptionPluginService;
@Before @BeforeEach
public void setUp() { void setUp() {
mockEncryptionPluginService = new EncryptionPluginService() { mockEncryptionPluginService = new EncryptionPluginService() {
private static final String ALGORITHM = "AES"; private static final String ALGORITHM = "AES";
@ -138,18 +139,18 @@ public class EncryptionAesHandlerTest {
} }
@Test @Test
public void testEncrypt() { void testEncrypt() {
String content = "content"; String content = "content";
String contentKey = mockEncryptionPluginService.generateSecretKey(); String contentKey = mockEncryptionPluginService.generateSecretKey();
Pair<String, String> pair = EncryptionHandler.encryptHandler("cipher-aes-dataId", content); Pair<String, String> pair = EncryptionHandler.encryptHandler("cipher-aes-dataId", content);
Assert.assertEquals("should return the encryption secret key if algorithm defined.", mockEncryptionPluginService.encryptSecretKey(contentKey), assertEquals(mockEncryptionPluginService.encryptSecretKey(contentKey), pair.getFirst(),
pair.getFirst()); "should return the encryption secret key if algorithm defined.");
Assert.assertEquals("should return the encryption content if algorithm defined.", mockEncryptionPluginService.encrypt(contentKey, content), assertEquals(mockEncryptionPluginService.encrypt(contentKey, content), pair.getSecond(),
pair.getSecond()); "should return the encryption content if algorithm defined.");
} }
@Test @Test
public void testDecrypt() { void testDecrypt() {
String content = "content"; String content = "content";
String contentKey = mockEncryptionPluginService.generateSecretKey(); String contentKey = mockEncryptionPluginService.generateSecretKey();
String encryptionSecretKey = mockEncryptionPluginService.encryptSecretKey(contentKey); String encryptionSecretKey = mockEncryptionPluginService.encryptSecretKey(contentKey);
@ -157,14 +158,14 @@ public class EncryptionAesHandlerTest {
Pair<String, String> pair = EncryptionHandler.decryptHandler("cipher-aes-dataId", encryptionSecretKey, encryptionContent); Pair<String, String> pair = EncryptionHandler.decryptHandler("cipher-aes-dataId", encryptionSecretKey, encryptionContent);
Assert.assertEquals("should return the original secret key if algorithm defined.", mockEncryptionPluginService.generateSecretKey(), assertEquals(mockEncryptionPluginService.generateSecretKey(), pair.getFirst(),
pair.getFirst()); "should return the original secret key if algorithm defined.");
Assert.assertEquals("should return the original content if algorithm defined.", content, pair.getSecond()); assertEquals(content, pair.getSecond(), "should return the original content if algorithm defined.");
} }
@Test @Test
public void testEncryptAndDecrypt() { void testEncryptAndDecrypt() {
String dataId = "cipher-aes-dataId"; String dataId = "cipher-aes-dataId";
String content = "content"; String content = "content";
String contentKey = mockEncryptionPluginService.generateSecretKey(); String contentKey = mockEncryptionPluginService.generateSecretKey();
@ -172,64 +173,64 @@ public class EncryptionAesHandlerTest {
Pair<String, String> encryptPair = EncryptionHandler.encryptHandler(dataId, content); Pair<String, String> encryptPair = EncryptionHandler.encryptHandler(dataId, content);
String encryptionSecretKey = encryptPair.getFirst(); String encryptionSecretKey = encryptPair.getFirst();
String encryptionContent = encryptPair.getSecond(); String encryptionContent = encryptPair.getSecond();
Assert.assertNotNull(encryptPair); assertNotNull(encryptPair);
Assert.assertEquals("should return the encryption secret key if algorithm defined.", mockEncryptionPluginService.encryptSecretKey(contentKey), assertEquals(mockEncryptionPluginService.encryptSecretKey(contentKey), encryptionSecretKey,
encryptionSecretKey); "should return the encryption secret key if algorithm defined.");
Assert.assertEquals("should return the encryption content if algorithm defined.", mockEncryptionPluginService.encrypt(contentKey, content), assertEquals(mockEncryptionPluginService.encrypt(contentKey, content), encryptionContent,
encryptionContent); "should return the encryption content if algorithm defined.");
Pair<String, String> decryptPair = EncryptionHandler.decryptHandler(dataId, encryptionSecretKey, encryptionContent); Pair<String, String> decryptPair = EncryptionHandler.decryptHandler(dataId, encryptionSecretKey, encryptionContent);
Assert.assertNotNull(decryptPair); assertNotNull(decryptPair);
Assert.assertEquals("should return the original secret key if algorithm defined.", mockEncryptionPluginService.generateSecretKey(), assertEquals(mockEncryptionPluginService.generateSecretKey(), decryptPair.getFirst(),
decryptPair.getFirst()); "should return the original secret key if algorithm defined.");
Assert.assertEquals("should return the original content if algorithm defined.", content, decryptPair.getSecond()); assertEquals(content, decryptPair.getSecond(), "should return the original content if algorithm defined.");
} }
@Test @Test
public void testPrefixNotCipherEncrypt() { void testPrefixNotCipherEncrypt() {
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.encryptHandler("test-dataId", content); Pair<String, String> pair = EncryptionHandler.encryptHandler("test-dataId", content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals(pair.getFirst(), ""); assertEquals("", pair.getFirst());
Assert.assertEquals(pair.getSecond(), content); assertEquals(pair.getSecond(), content);
} }
@Test @Test
public void testPrefixNotCipherDecrypt() { void testPrefixNotCipherDecrypt() {
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.decryptHandler("test-dataId", "", content); Pair<String, String> pair = EncryptionHandler.decryptHandler("test-dataId", "", content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals(pair.getFirst(), ""); assertEquals("", pair.getFirst());
Assert.assertEquals(pair.getSecond(), content); assertEquals(pair.getSecond(), content);
} }
@Test @Test
public void testAlgorithmEmpty() { void testAlgorithmEmpty() {
String dataId = "cipher-"; String dataId = "cipher-";
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content); Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
Assert.assertNotNull("should not throw exception when parsing enc algo for dataId '" + dataId + "'", pair); assertNotNull(pair, "should not throw exception when parsing enc algo for dataId '" + dataId + "'");
Assert.assertEquals(pair.getFirst(), ""); assertEquals("", pair.getFirst());
Assert.assertEquals(pair.getSecond(), content); assertEquals(pair.getSecond(), content);
} }
@Test @Test
public void testUnknownAlgorithmNameEncrypt() { void testUnknownAlgorithmNameEncrypt() {
String dataId = "cipher-mySM4-application"; String dataId = "cipher-mySM4-application";
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content); Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals(pair.getFirst(), ""); assertEquals("", pair.getFirst());
Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined.");
} }
@Test @Test
public void testUnknownAlgorithmNameDecrypt() { void testUnknownAlgorithmNameDecrypt() {
String dataId = "cipher-mySM4-application"; String dataId = "cipher-mySM4-application";
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, "", content); Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, "", content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals(pair.getFirst(), ""); assertEquals("", pair.getFirst());
Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined.");
} }
} }

View File

@ -19,21 +19,23 @@ package com.alibaba.nacos.plugin.encryption.handler;
import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.common.utils.Pair;
import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager;
import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* EncryptionHandlerTest. * EncryptionHandlerTest.
* *
* @author lixiaoshuang * @author lixiaoshuang
*/ */
public class EncryptionHandlerTest { class EncryptionHandlerTest {
private EncryptionPluginService mockEncryptionPluginService; private EncryptionPluginService mockEncryptionPluginService;
@Before @BeforeEach
public void setUp() { void setUp() {
mockEncryptionPluginService = new EncryptionPluginService() { mockEncryptionPluginService = new EncryptionPluginService() {
@Override @Override
public String encrypt(String secretKey, String content) { public String encrypt(String secretKey, String content) {
@ -69,65 +71,63 @@ public class EncryptionHandlerTest {
} }
@Test @Test
public void testEncryptHandler() { void testEncryptHandler() {
Pair<String, String> pair = EncryptionHandler.encryptHandler("test-dataId", "content"); Pair<String, String> pair = EncryptionHandler.encryptHandler("test-dataId", "content");
Assert.assertNotNull(pair); assertNotNull(pair);
} }
@Test @Test
public void testDecryptHandler() { void testDecryptHandler() {
Pair<String, String> pair = EncryptionHandler.decryptHandler("test-dataId", "12345678", "content"); Pair<String, String> pair = EncryptionHandler.decryptHandler("test-dataId", "12345678", "content");
Assert.assertNotNull(pair); assertNotNull(pair);
} }
@Test @Test
public void testCornerCaseDataIdAlgoParse() { void testCornerCaseDataIdAlgoParse() {
String dataId = "cipher-"; String dataId = "cipher-";
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, "content"); Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, "content");
Assert.assertNotNull("should not throw exception when parsing enc algo for dataId '" + dataId + "'", pair); assertNotNull(pair, "should not throw exception when parsing enc algo for dataId '" + dataId + "'");
} }
@Test @Test
public void testUnknownAlgorithmNameEnc() { void testUnknownAlgorithmNameEnc() {
String dataId = "cipher-mySM4-application"; String dataId = "cipher-mySM4-application";
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content); Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined.");
} }
@Test @Test
public void testUnknownAlgorithmNameDecrypt() { void testUnknownAlgorithmNameDecrypt() {
String dataId = "cipher-mySM4-application"; String dataId = "cipher-mySM4-application";
String content = "content"; String content = "content";
Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, "", content); Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, "", content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined.");
} }
@Test @Test
public void testEncrypt() { void testEncrypt() {
String dataId = "cipher-mockAlgo-application"; String dataId = "cipher-mockAlgo-application";
String content = "content"; String content = "content";
String sec = mockEncryptionPluginService.generateSecretKey(); String sec = mockEncryptionPluginService.generateSecretKey();
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content); Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals("should return encrypted content.", assertEquals(mockEncryptionPluginService.encrypt(sec, content), pair.getSecond(), "should return encrypted content.");
mockEncryptionPluginService.encrypt(sec, content), pair.getSecond()); assertEquals(mockEncryptionPluginService.encryptSecretKey(sec), pair.getFirst(), "should return encrypted secret key.");
Assert.assertEquals("should return encrypted secret key.",
mockEncryptionPluginService.encryptSecretKey(sec), pair.getFirst());
} }
@Test @Test
public void testDecrypt() { void testDecrypt() {
String dataId = "cipher-mockAlgo-application"; String dataId = "cipher-mockAlgo-application";
String oContent = "content"; String oContent = "content";
String oSec = mockEncryptionPluginService.generateSecretKey(); String oSec = mockEncryptionPluginService.generateSecretKey();
String content = mockEncryptionPluginService.encrypt(oSec, oContent); String content = mockEncryptionPluginService.encrypt(oSec, oContent);
String sec = mockEncryptionPluginService.encryptSecretKey(oSec); String sec = mockEncryptionPluginService.encryptSecretKey(oSec);
Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, sec, content); Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, sec, content);
Assert.assertNotNull(pair); assertNotNull(pair);
Assert.assertEquals("should return original content.", oContent, pair.getSecond()); assertEquals(oContent, pair.getSecond(), "should return original content.");
Assert.assertEquals("should return original secret key.", oSec, pair.getFirst()); assertEquals(oSec, pair.getFirst(), "should return original secret key.");
} }
} }

View File

@ -17,28 +17,30 @@
package com.alibaba.nacos.plugin.environment; package com.alibaba.nacos.plugin.environment;
import com.alibaba.nacos.plugin.environment.spi.CustomEnvironmentPluginService; import com.alibaba.nacos.plugin.environment.spi.CustomEnvironmentPluginService;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* CustomEnvironment Plugin Test. * CustomEnvironment Plugin Test.
* *
* @author : huangtianhui * @author : huangtianhui
*/ */
public class CustomEnvironmentPluginManagerTest { class CustomEnvironmentPluginManagerTest {
@Test @Test
public void testInstance() { void testInstance() {
CustomEnvironmentPluginManager instance = CustomEnvironmentPluginManager.getInstance(); CustomEnvironmentPluginManager instance = CustomEnvironmentPluginManager.getInstance();
Assert.assertNotNull(instance); assertNotNull(instance);
} }
@Test @Test
public void testJoin() { void testJoin() {
CustomEnvironmentPluginManager.join(new CustomEnvironmentPluginService() { CustomEnvironmentPluginManager.join(new CustomEnvironmentPluginService() {
@Override @Override
public Map<String, Object> customValue(Map<String, Object> property) { public Map<String, Object> customValue(Map<String, Object> property) {
@ -46,27 +48,27 @@ public class CustomEnvironmentPluginManagerTest {
property.put("db.password.0", "test" + pwd); property.put("db.password.0", "test" + pwd);
return property; return property;
} }
@Override @Override
public Set<String> propertyKey() { public Set<String> propertyKey() {
Set<String> propertyKey = new HashSet<>(); Set<String> propertyKey = new HashSet<>();
propertyKey.add("db.password.0"); propertyKey.add("db.password.0");
return propertyKey; return propertyKey;
} }
@Override @Override
public Integer order() { public Integer order() {
return 0; return 0;
} }
@Override @Override
public String pluginName() { public String pluginName() {
return "test"; return "test";
} }
}); });
Assert.assertNotNull(CustomEnvironmentPluginManager.getInstance().getPropertyKeys()); assertNotNull(CustomEnvironmentPluginManager.getInstance().getPropertyKeys());
Map<String, Object> sourcePropertyMap = new HashMap<>(); Map<String, Object> sourcePropertyMap = new HashMap<>();
sourcePropertyMap.put("db.password.0", "nacos"); sourcePropertyMap.put("db.password.0", "nacos");
Assert.assertNotNull(CustomEnvironmentPluginManager.getInstance().getCustomValues(sourcePropertyMap)); assertNotNull(CustomEnvironmentPluginManager.getInstance().getCustomValues(sourcePropertyMap));
} }
} }

View File

@ -17,21 +17,21 @@
package com.alibaba.nacos.plugin.trace; package com.alibaba.nacos.plugin.trace;
import com.alibaba.nacos.plugin.trace.spi.NacosTraceSubscriber; import com.alibaba.nacos.plugin.trace.spi.NacosTraceSubscriber;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
public class NacosTracePluginManagerTest { class NacosTracePluginManagerTest {
@BeforeClass @BeforeAll
public static void setUp() { static void setUp() {
NacosTracePluginManager.getInstance(); NacosTracePluginManager.getInstance();
} }
@Test @Test
public void testGetAllTraceSubscribers() { void testGetAllTraceSubscribers() {
assertFalse(NacosTracePluginManager.getInstance().getAllTraceSubscribers().isEmpty()); assertFalse(NacosTracePluginManager.getInstance().getAllTraceSubscribers().isEmpty());
assertContainsTestPlugin(); assertContainsTestPlugin();
} }
@ -42,6 +42,6 @@ public class NacosTracePluginManagerTest {
return; return;
} }
} }
Assert.fail("No found plugin named 'trace-plugin-mock'"); fail("No found plugin named 'trace-plugin-mock'");
} }
} }