You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by pa...@apache.org on 2022/06/20 04:29:35 UTC

[shardingsphere] branch master updated: Add more test cases for ExportDatabaseConfigurationHandler (#18435)

This is an automated email from the ASF dual-hosted git repository.

panjuan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new 60db6430478 Add more test cases for ExportDatabaseConfigurationHandler (#18435)
60db6430478 is described below

commit 60db643047837b0102166e5604540c43e85add42
Author: Liang Zhang <zh...@apache.org>
AuthorDate: Mon Jun 20 12:29:26 2022 +0800

    Add more test cases for ExportDatabaseConfigurationHandler (#18435)
    
    * Add more test cases for ExportDatabaseConfigurationHandler
    
    * Fix checkstyle
---
 .../ExportDatabaseConfigurationHandlerTest.java    | 171 ++++++++++++++++-----
 .../expected/export-database-configuration.yaml    |  59 +++++++
 2 files changed, 190 insertions(+), 40 deletions(-)

diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/queryable/ExportDatabaseConfigurationHandlerTest.java b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/queryable/ExportDatabaseConfigurationHandlerTest.java
index 4595c0e02cf..d470ca4dce7 100644
--- a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/queryable/ExportDatabaseConfigurationHandlerTest.java
+++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/queryable/ExportDatabaseConfigurationHandlerTest.java
@@ -17,9 +17,10 @@
 
 package org.apache.shardingsphere.proxy.backend.text.distsql.ral.common.queryable;
 
-import com.zaxxer.hikari.HikariDataSource;
+import lombok.SneakyThrows;
 import org.apache.shardingsphere.distsql.parser.statement.ral.common.queryable.ExportDatabaseConfigurationStatement;
 import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
+import org.apache.shardingsphere.infra.exception.DatabaseNotExistedException;
 import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
 import org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereColumn;
 import org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereIndex;
@@ -27,6 +28,9 @@ import org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.
 import org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereTable;
 import org.apache.shardingsphere.mode.manager.ContextManager;
 import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
+import org.apache.shardingsphere.proxy.backend.exception.NoDatabaseSelectedException;
+import org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeader;
+import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
 import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
 import org.apache.shardingsphere.proxy.backend.util.ProxyContextRestorer;
 import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
@@ -36,20 +40,27 @@ import org.apache.shardingsphere.sharding.api.config.strategy.sharding.NoneShard
 import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
 import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.DatabaseSegment;
 import org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue;
+import org.apache.shardingsphere.test.mock.MockedDataSource;
 import org.junit.Before;
 import org.junit.Test;
 
 import javax.sql.DataSource;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
 import java.sql.SQLException;
-import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Properties;
 
 import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -59,22 +70,41 @@ public final class ExportDatabaseConfigurationHandlerTest extends ProxyContextRe
     @Before
     public void init() {
         ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
-        ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
-        when(database.getSchemas().get("sharding_db")).thenReturn(new ShardingSphereSchema(createTableMap()));
-        when(database.getResource().getDataSources()).thenReturn(createDataSourceMap());
-        when(database.getRuleMetaData().getConfigurations()).thenReturn(Collections.singleton(createShardingRuleConfiguration()));
-        when(contextManager.getMetaDataContexts().getMetaData().getDatabases()).thenReturn(Collections.singletonMap("sharding_db", database));
+        Map<String, ShardingSphereDatabase> databases = createDatabases();
+        when(contextManager.getMetaDataContexts().getMetaData().getDatabases()).thenReturn(databases);
         ProxyContext.init(contextManager);
     }
     
-    @Test
-    public void assertExportDatabaseExecutor() throws SQLException {
-        ExportDatabaseConfigurationHandler handler = new ExportDatabaseConfigurationHandler();
-        handler.init(createSQLStatement(), mock(ConnectionSession.class));
-        handler.execute();
-        handler.next();
-        Collection<Object> data = new ArrayList<>(handler.getRowData());
-        assertThat(data.size(), is(1));
+    private Map<String, ShardingSphereDatabase> createDatabases() {
+        Map<String, ShardingSphereDatabase> result = new HashMap<>(2, 1);
+        result.put("normal_db", createNormalDatabase());
+        result.put("empty_db", createEmptyDatabase());
+        return result;
+    }
+    
+    private ShardingSphereDatabase createNormalDatabase() {
+        ShardingSphereDatabase result = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
+        when(result.getResource().getDataSources()).thenReturn(createDataSourceMap());
+        when(result.getRuleMetaData().getConfigurations()).thenReturn(Collections.singleton(createShardingRuleConfiguration()));
+        when(result.getSchemas().get("normal_db")).thenReturn(new ShardingSphereSchema(createTables()));
+        return result;
+    }
+    
+    private Map<String, DataSource> createDataSourceMap() {
+        Map<String, DataSource> result = new LinkedHashMap<>(2, 1);
+        result.put("ds_0", createDataSource("demo_ds_0"));
+        result.put("ds_1", createDataSource("demo_ds_1"));
+        return result;
+    }
+    
+    private DataSource createDataSource(final String name) {
+        MockedDataSource result = new MockedDataSource();
+        result.setUrl(String.format("jdbc:mock://127.0.0.1/%s", name));
+        result.setUsername("root");
+        result.setPassword("");
+        result.setMaxPoolSize(50);
+        result.setMinPoolSize(1);
+        return result;
     }
     
     private ShardingRuleConfiguration createShardingRuleConfiguration() {
@@ -90,45 +120,106 @@ public final class ExportDatabaseConfigurationHandlerTest extends ProxyContextRe
         return result;
     }
     
+    private ShardingTableRuleConfiguration createTableRuleConfiguration() {
+        ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order", "ds_${0..1}.t_order_${0..1}");
+        result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_id", "snowflake"));
+        return result;
+    }
+    
     private Properties createProperties() {
         Properties result = new Properties();
         result.setProperty("algorithm-expression", "ds_${order_id % 2}");
         return result;
     }
     
-    private Map<String, DataSource> createDataSourceMap() {
-        Map<String, DataSource> result = new LinkedHashMap<>(2, 1);
-        result.put("ds_0", createDataSource("demo_ds_0"));
-        result.put("ds_1", createDataSource("demo_ds_1"));
-        return result;
+    private Map<String, ShardingSphereTable> createTables() {
+        Collection<ShardingSphereColumn> columns = Collections.singleton(new ShardingSphereColumn("order_id", 0, false, false, false));
+        Collection<ShardingSphereIndex> indexes = Collections.singleton(new ShardingSphereIndex("primary"));
+        return Collections.singletonMap("t_order", new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList()));
     }
     
-    private DataSource createDataSource(final String dbName) {
-        HikariDataSource result = new HikariDataSource();
-        result.setJdbcUrl(String.format("jdbc:mysql://127.0.0.1:3306/%s?serverTimezone=UTC&useSSL=false", dbName));
-        result.setUsername("root");
-        result.setPassword("");
-        result.setConnectionTimeout(30000L);
-        result.setIdleTimeout(60000L);
-        result.setMaxLifetime(1800000L);
-        result.setMaximumPoolSize(50);
-        result.setMinimumIdle(1);
+    private ShardingSphereDatabase createEmptyDatabase() {
+        ShardingSphereDatabase result = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
+        when(result.getResource().getDataSources()).thenReturn(Collections.emptyMap());
+        when(result.getRuleMetaData().getConfigurations()).thenReturn(Collections.emptyList());
         return result;
     }
     
-    private Map<String, ShardingSphereTable> createTableMap() {
-        Collection<ShardingSphereColumn> columns = Collections.singleton(new ShardingSphereColumn("order_id", 0, false, false, false));
-        Collection<ShardingSphereIndex> indexes = Collections.singleton(new ShardingSphereIndex("primary"));
-        return Collections.singletonMap("t_order", new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList()));
+    @Test
+    public void assertExecute() throws SQLException {
+        ExportDatabaseConfigurationHandler handler = new ExportDatabaseConfigurationHandler();
+        handler.init(new ExportDatabaseConfigurationStatement(new DatabaseSegment(0, 0, new IdentifierValue("normal_db")), null), mock(ConnectionSession.class));
+        assertQueryResponseHeader((QueryResponseHeader) handler.execute());
+        assertTrue(handler.next());
+        assertRowData(handler.getRowData());
+        assertFalse(handler.next());
     }
     
-    private ShardingTableRuleConfiguration createTableRuleConfiguration() {
-        ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order", "ds_${0..1}.t_order_${0..1}");
-        result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_id", "snowflake"));
-        return result;
+    private void assertQueryResponseHeader(final QueryResponseHeader actual) {
+        assertThat(actual.getQueryHeaders().size(), is(1));
+        assertQueryHeader(actual.getQueryHeaders().get(0));
+    }
+    
+    private void assertQueryHeader(final QueryHeader actual) {
+        assertThat(actual.getSchema(), is(""));
+        assertThat(actual.getTable(), is(""));
+        assertThat(actual.getColumnLabel(), is("result"));
+        assertThat(actual.getColumnName(), is("result"));
+        assertThat(actual.getColumnType(), is(1));
+        assertThat(actual.getColumnTypeName(), is("CHAR"));
+        assertThat(actual.getColumnLength(), is(255));
+        assertThat(actual.getDecimals(), is(0));
+        assertFalse(actual.isSigned());
+        assertFalse(actual.isPrimaryKey());
+        assertFalse(actual.isNotNull());
+        assertFalse(actual.isAutoIncrement());
+    }
+    
+    private void assertRowData(final Collection<Object> actual) {
+        assertThat(actual.size(), is(1));
+        assertThat(actual.iterator().next(), is(loadExpectedRow()));
+    }
+    
+    @SneakyThrows(IOException.class)
+    private String loadExpectedRow() {
+        StringBuilder result = new StringBuilder();
+        String fileName = Objects.requireNonNull(ExportDatabaseConfigurationHandlerTest.class.getResource("/expected/export-database-configuration.yaml")).getFile();
+        try (
+                FileReader fileReader = new FileReader(fileName);
+                BufferedReader reader = new BufferedReader(fileReader)) {
+            String line;
+            while (null != (line = reader.readLine())) {
+                if (!line.startsWith("#") && !"".equals(line.trim())) {
+                    result.append(line).append(System.lineSeparator());
+                }
+            }
+        }
+        return result.toString();
     }
     
-    private ExportDatabaseConfigurationStatement createSQLStatement() {
-        return new ExportDatabaseConfigurationStatement(new DatabaseSegment(0, 0, new IdentifierValue("sharding_db")), null);
+    @Test
+    public void assertExecuteWithEmptyDatabase() throws SQLException {
+        ExportDatabaseConfigurationHandler handler = new ExportDatabaseConfigurationHandler();
+        handler.init(new ExportDatabaseConfigurationStatement(new DatabaseSegment(0, 0, new IdentifierValue("empty_db")), null), mock(ConnectionSession.class));
+        assertQueryResponseHeader((QueryResponseHeader) handler.execute());
+        assertTrue(handler.next());
+        Collection<Object> rowData = handler.getRowData();
+        assertThat(rowData.size(), is(1));
+        assertThat(rowData.iterator().next(), is("databaseName: empty_db\n"));
+        assertFalse(handler.next());
+    }
+    
+    @Test(expected = DatabaseNotExistedException.class)
+    public void assertExecuteWithNotExistedDatabase() throws SQLException {
+        ExportDatabaseConfigurationHandler handler = new ExportDatabaseConfigurationHandler();
+        handler.init(new ExportDatabaseConfigurationStatement(new DatabaseSegment(0, 0, new IdentifierValue("not_exist_db")), null), mock(ConnectionSession.class));
+        handler.execute();
+    }
+    
+    @Test(expected = NoDatabaseSelectedException.class)
+    public void assertExecuteWithNoDatabaseSelected() throws SQLException {
+        ExportDatabaseConfigurationHandler handler = new ExportDatabaseConfigurationHandler();
+        handler.init(new ExportDatabaseConfigurationStatement(null, null), mock(ConnectionSession.class));
+        handler.execute();
     }
 }
diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/resources/expected/export-database-configuration.yaml b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/resources/expected/export-database-configuration.yaml
new file mode 100644
index 00000000000..1a25aa4550b
--- /dev/null
+++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/resources/expected/export-database-configuration.yaml
@@ -0,0 +1,59 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+databaseName: normal_db
+dataSources:
+  ds_0:
+    password: 
+    url: jdbc:mock://127.0.0.1/demo_ds_0
+    username: root
+    minPoolSize: 1
+    maxPoolSize: 50
+  ds_1:
+    password: 
+    url: jdbc:mock://127.0.0.1/demo_ds_1
+    username: root
+    minPoolSize: 1
+    maxPoolSize: 50
+rules:
+!!set
+? !SHARDING
+  defaultDatabaseStrategy:
+    standard:
+      shardingAlgorithmName: ds_inline
+      shardingColumn: order_id
+  defaultTableStrategy:
+    none: ''
+  keyGenerators:
+    snowflake:
+      type: SNOWFLAKE
+  scaling:
+    default_scaling: null
+  scalingName: default_scaling
+  shardingAlgorithms:
+    ds_inline:
+      props:
+        algorithm-expression: ds_${order_id % 2}
+      type: INLINE
+  tables:
+    t_order:
+      actualDataNodes: ds_${0..1}.t_order_${0..1}
+      keyGenerateStrategy:
+        column: order_id
+        keyGeneratorName: snowflake
+      logicTable: t_order
+: null