From d35ae4bc58fe24679c8e7adc0ebcad3270edd509 Mon Sep 17 00:00:00 2001 From: Liang Zhang Date: Thu, 5 Dec 2024 00:01:15 +0800 Subject: [PATCH] Simplify usages of mock ShardingSphereDatabase (#33917) * Simplify usages of mock ShardingSphereDatabase --- .../jdbc/JDBCMetaDataInfoExporterTest.java | 13 +++--- .../impl/jdbc/JDBCStateExporterTest.java | 6 +-- .../merge/dql/EncryptMergedResultTest.java | 40 +++++++----------- ...EncryptInsertValuesTokenGeneratorTest.java | 12 +----- ...PredicateRightValueTokenGeneratorTest.java | 13 ++---- .../update/AlterEncryptRuleExecutorTest.java | 5 +-- .../update/DropEncryptRuleExecutorTest.java | 4 +- .../update/DropMaskRuleExecutorTest.java | 4 +- .../pagination/PaginationContextTest.java | 15 ++----- .../engine/ProjectionsContextEngineTest.java | 10 +---- .../dml/InsertStatementContextTest.java | 24 ++++++----- .../engine/GenericSQLRewriteEngineTest.java | 6 +-- .../mode/manager/ContextManagerTest.java | 4 +- .../mode/metadata/MetaDataContextsTest.java | 5 +-- .../backend/context/ProxyContextTest.java | 15 ++----- .../DatabaseAdminQueryBackendHandlerTest.java | 17 ++------ .../UnicastDatabaseBackendHandlerTest.java | 42 ++++++------------- .../DistSQLQueryBackendHandlerTest.java | 8 ++-- .../DistSQLUpdateBackendHandlerTest.java | 23 ++++------ .../ShowCreateDatabaseExecutorTest.java | 25 ++++------- .../executor/ShowDatabasesExecutorTest.java | 28 ++++--------- .../ShowFunctionStatusExecutorTest.java | 32 +++++--------- .../ShowProcedureStatusExecutorTest.java | 32 +++++--------- .../executor/ShowTablesExecutorTest.java | 28 ++++++------- .../executor/UseDatabaseExecutorTest.java | 26 +++++------- .../MySQLAuthenticationEngineTest.java | 18 +++----- 26 files changed, 154 insertions(+), 301 deletions(-) diff --git a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java index 96d6ca5eb5d5c..70200da65cfe0 100644 --- a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java +++ b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCMetaDataInfoExporterTest.java @@ -25,6 +25,7 @@ import org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration; import org.apache.shardingsphere.agent.plugin.metrics.core.fixture.collector.MetricsCollectorFixture; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; +import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit; import org.apache.shardingsphere.mode.manager.ContextManager; import org.junit.jupiter.api.AfterEach; @@ -52,17 +53,16 @@ class JDBCMetaDataInfoExporterTest { @BeforeEach void setUp() { instanceId = UUID.randomUUID().toString(); - databaseName = "sharding_db"; + databaseName = "foo_db"; ContextManager contextManager = mockContextManager(instanceId, databaseName); ShardingSphereDataSourceContextHolder.put(instanceId, new ShardingSphereDataSourceContext(databaseName, contextManager)); } private ContextManager mockContextManager(final String instanceId, final String databaseName) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(databaseName); - when(database.getResourceMetaData().getStorageUnits()).thenReturn(Collections.singletonMap("ds_0", mock(StorageUnit.class))); + ResourceMetaData resourceMetaData = mock(ResourceMetaData.class); + when(resourceMetaData.getStorageUnits()).thenReturn(Collections.singletonMap("ds_0", mock(StorageUnit.class))); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - when(result.getDatabase(databaseName)).thenReturn(database); + when(result.getDatabase(databaseName)).thenReturn(new ShardingSphereDatabase(databaseName, mock(), resourceMetaData, mock(), Collections.emptyList())); when(result.getComputeNodeInstanceContext().getInstance().getMetaData().getId()).thenReturn(instanceId); return result; } @@ -70,8 +70,7 @@ private ContextManager mockContextManager(final String instanceId, final String @AfterEach void clean() { MetricConfiguration config = new MetricConfiguration("jdbc_meta_data_info", - MetricCollectorType.GAUGE_METRIC_FAMILY, "Meta data information of ShardingSphere-JDBC", - Arrays.asList("driver_instance", "database", "type"), Collections.emptyMap()); + MetricCollectorType.GAUGE_METRIC_FAMILY, "Meta data information of ShardingSphere-JDBC", Arrays.asList("driver_instance", "database", "type"), Collections.emptyMap()); ((MetricsCollectorFixture) MetricsCollectorRegistry.get(config, "FIXTURE")).reset(); ShardingSphereDataSourceContextHolder.remove(instanceId); } diff --git a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java index c6fbee962252c..dfb9a24706abc 100644 --- a/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java +++ b/agent/plugins/metrics/core/src/test/java/org/apache/shardingsphere/agent/plugin/metrics/core/exporter/impl/jdbc/JDBCStateExporterTest.java @@ -31,6 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.Collections; import java.util.Optional; import java.util.UUID; @@ -50,15 +51,14 @@ class JDBCStateExporterTest { @BeforeEach void setUp() { instanceId = UUID.randomUUID().toString(); - databaseName = "sharding_db"; + databaseName = "foo_db"; ContextManager contextManager = mockContextManager(instanceId, databaseName); ShardingSphereDataSourceContextHolder.put(instanceId, new ShardingSphereDataSourceContext(databaseName, contextManager)); } private ContextManager mockContextManager(final String instanceId, final String databaseName) { ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn(databaseName); + ShardingSphereDatabase database = new ShardingSphereDatabase(databaseName, mock(), mock(), mock(), Collections.emptyList()); when(result.getDatabase(databaseName)).thenReturn(database); when(result.getComputeNodeInstanceContext().getInstance().getMetaData().getId()).thenReturn(instanceId); when(result.getComputeNodeInstanceContext().getInstance().getState().getCurrentState().ordinal()).thenReturn(InstanceState.OK.ordinal()); diff --git a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/merge/dql/EncryptMergedResultTest.java b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/merge/dql/EncryptMergedResultTest.java index 2858dac0e90c5..755a38a13e7da 100644 --- a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/merge/dql/EncryptMergedResultTest.java +++ b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/merge/dql/EncryptMergedResultTest.java @@ -65,12 +65,6 @@ class EncryptMergedResultTest { private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); - @Mock - private ShardingSphereDatabase database; - - @Mock - private ShardingSphereMetaData metaData; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private SelectStatementContext selectStatementContext; @@ -79,14 +73,14 @@ class EncryptMergedResultTest { @Test void assertNext() throws SQLException { - assertFalse(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).next()); + assertFalse(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).next()); } @Test void assertGetValueWithoutColumnProjection() throws SQLException { when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.empty()); when(mergedResult.getValue(1, String.class)).thenReturn("foo_value"); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); + assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); } @Test @@ -95,9 +89,9 @@ void assertGetValueWithoutEncryptTable() throws SQLException { null, null, new ColumnSegmentBoundInfo(new IdentifierValue("foo_col"))); when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.of(columnProjection)); EncryptRule rule = mockRule(mock(EncryptAlgorithm.class)); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); when(mergedResult.getValue(1, String.class)).thenReturn("foo_value"); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); + assertThat(new EncryptMergedResult(database, mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); } @Test @@ -106,9 +100,9 @@ void assertGetValueWithoutEncryptColumn() throws SQLException { null, null, new ColumnSegmentBoundInfo(new IdentifierValue("bar_col"))); when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.of(columnProjection)); EncryptRule rule = mockRule(mock(EncryptAlgorithm.class)); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); when(mergedResult.getValue(1, String.class)).thenReturn("foo_value"); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); + assertThat(new EncryptMergedResult(database, mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value")); } @Test @@ -120,11 +114,8 @@ void assertGetValueWithEncryptColumn() throws SQLException { EncryptAlgorithm encryptAlgorithm = mock(EncryptAlgorithm.class); when(encryptAlgorithm.decrypt(eq("foo_value"), deepEq(new AlgorithmSQLContext("foo_db", "foo_schema", "foo_tbl", "foo_col")))).thenReturn("foo_decrypted_value"); EncryptRule rule = mockRule(encryptAlgorithm); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); - when(metaData.containsDatabase("foo_db")).thenReturn(true); - when(metaData.getDatabase("foo_db")).thenReturn(database); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()); when(mergedResult.getValue(1, Object.class)).thenReturn("foo_value"); assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_decrypted_value")); } @@ -138,11 +129,8 @@ void assertGetValueFailed() throws SQLException { EncryptAlgorithm encryptAlgorithm = mock(EncryptAlgorithm.class); when(encryptAlgorithm.decrypt(eq("foo_value"), deepEq(new AlgorithmSQLContext("foo_db", "foo_schema", "foo_tbl", "foo_col")))).thenThrow(new RuntimeException("Test failed")); EncryptRule rule = mockRule(encryptAlgorithm); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); - when(metaData.containsDatabase("foo_db")).thenReturn(true); - when(metaData.getDatabase("foo_db")).thenReturn(database); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()); when(mergedResult.getValue(1, Object.class)).thenReturn("foo_value"); assertThrows(DecryptFailedException.class, () -> new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class)); } @@ -162,25 +150,25 @@ private EncryptRule mockRule(final EncryptAlgorithm encryptAlgorithm) { void assertGetCalendarValue() throws SQLException { Calendar calendar = Calendar.getInstance(); when(mergedResult.getCalendarValue(1, Date.class, calendar)).thenReturn(new Date(0L)); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getCalendarValue(1, Date.class, calendar), is(new Date(0L))); + assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getCalendarValue(1, Date.class, calendar), is(new Date(0L))); } @Test void assertGetInputStream() throws SQLException { InputStream inputStream = mock(InputStream.class); when(mergedResult.getInputStream(1, "asc")).thenReturn(inputStream); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getInputStream(1, "asc"), is(inputStream)); + assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getInputStream(1, "asc"), is(inputStream)); } @Test void assertGetCharacterStream() throws SQLException { Reader reader = mock(Reader.class); when(mergedResult.getCharacterStream(1)).thenReturn(reader); - assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getCharacterStream(1), is(reader)); + assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getCharacterStream(1), is(reader)); } @Test void assertWasNull() throws SQLException { - assertFalse(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).wasNull()); + assertFalse(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).wasNull()); } } diff --git a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/insert/EncryptInsertValuesTokenGeneratorTest.java b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/insert/EncryptInsertValuesTokenGeneratorTest.java index a1437d6caca78..93e2c434d8b53 100644 --- a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/insert/EncryptInsertValuesTokenGeneratorTest.java +++ b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/insert/EncryptInsertValuesTokenGeneratorTest.java @@ -29,7 +29,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class EncryptInsertValuesTokenGeneratorTest { @@ -48,21 +47,14 @@ void assertIsGenerateSQLToken() { @Test void assertGenerateSQLTokenFromGenerateNewSQLToken() { generator.setPreviousSQLTokens(Collections.emptyList()); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("db_schema"); - generator.setDatabase(database); + generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList())); assertThat(generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Arrays.asList(1, "Tom", 0, "123456"))).toString(), is("(?, ?, ?, ?, ?, ?)")); } @Test void assertGenerateSQLTokenFromPreviousSQLTokens() { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("db-001"); - generator.setDatabase(database); generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens()); - database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("db_schema"); - generator.setDatabase(database); + generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList())); assertThat(generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Arrays.asList(1, "Tom", 0, "123456"))).toString(), is("(?, ?, ?, ?, ?, ?)")); } } diff --git a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/predicate/EncryptPredicateRightValueTokenGeneratorTest.java b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/predicate/EncryptPredicateRightValueTokenGeneratorTest.java index 3e9e3d648bc75..d37fea852b784 100644 --- a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/predicate/EncryptPredicateRightValueTokenGeneratorTest.java +++ b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/generator/predicate/EncryptPredicateRightValueTokenGeneratorTest.java @@ -28,12 +28,12 @@ import org.junit.jupiter.api.Test; import java.util.Collection; +import java.util.Collections; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class EncryptPredicateRightValueTokenGeneratorTest { @@ -46,18 +46,14 @@ void setup() { @Test void assertIsGenerateSQLToken() { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - generator.setDatabase(database); + generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList())); assertTrue(generator.isGenerateSQLToken(EncryptGeneratorFixtureBuilder.createUpdateStatementContext())); } @Test void assertGenerateSQLTokenFromGenerateNewSQLToken() { UpdateStatementContext updateStatementContext = EncryptGeneratorFixtureBuilder.createUpdateStatementContext(); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - generator.setDatabase(database); + generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList())); generator.setEncryptConditions(getEncryptConditions(updateStatementContext)); Collection sqlTokens = generator.generateSQLTokens(updateStatementContext); assertThat(sqlTokens.size(), is(1)); @@ -65,8 +61,7 @@ void assertGenerateSQLTokenFromGenerateNewSQLToken() { } private Collection getEncryptConditions(final UpdateStatementContext updateStatementContext) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getSchema("foo_db")).thenReturn(mock(ShardingSphereSchema.class)); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.singleton(new ShardingSphereSchema("foo_db"))); return new EncryptConditionEngine(EncryptGeneratorFixtureBuilder.createEncryptRule(), database) .createEncryptConditions(updateStatementContext.getWhereSegments(), updateStatementContext.getColumnSegments(), updateStatementContext, "foo_db"); } diff --git a/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/AlterEncryptRuleExecutorTest.java b/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/AlterEncryptRuleExecutorTest.java index ae485ffb488ec..1580fd1b48e04 100644 --- a/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/AlterEncryptRuleExecutorTest.java +++ b/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/AlterEncryptRuleExecutorTest.java @@ -107,11 +107,8 @@ void assertExecuteUpdateWithoutAssistQueryAndLikeColumns() throws SQLException { } private ContextManager mockContextManager(final EncryptRule rule) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - when(result.getDatabase("foo_db")).thenReturn(database); + when(result.getDatabase("foo_db")).thenReturn(new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList())); return result; } diff --git a/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/DropEncryptRuleExecutorTest.java b/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/DropEncryptRuleExecutorTest.java index 7584a26af271b..981a1a9ea3350 100644 --- a/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/DropEncryptRuleExecutorTest.java +++ b/features/encrypt/distsql/handler/src/test/java/org/apache/shardingsphere/encrypt/distsql/handler/update/DropEncryptRuleExecutorTest.java @@ -137,10 +137,8 @@ private EncryptRuleConfiguration createCurrentRuleConfigurationWithMultipleTable } private ContextManager mockContextManager(final EncryptRule rule) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); when(result.getDatabase("foo_db")).thenReturn(database); return result; } diff --git a/features/mask/distsql/handler/src/test/java/org/apache/shardingsphere/mask/distsql/handler/update/DropMaskRuleExecutorTest.java b/features/mask/distsql/handler/src/test/java/org/apache/shardingsphere/mask/distsql/handler/update/DropMaskRuleExecutorTest.java index 6cd1db5b9cf2b..daa0b18fd595a 100644 --- a/features/mask/distsql/handler/src/test/java/org/apache/shardingsphere/mask/distsql/handler/update/DropMaskRuleExecutorTest.java +++ b/features/mask/distsql/handler/src/test/java/org/apache/shardingsphere/mask/distsql/handler/update/DropMaskRuleExecutorTest.java @@ -99,9 +99,7 @@ private boolean assertRuleConfigurationWithIfExists(final MaskRuleConfiguration } private ContextManager mockContextManager(final MaskRule rule) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(result.getDatabase("foo_db")).thenReturn(database); return result; diff --git a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/pagination/PaginationContextTest.java b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/pagination/PaginationContextTest.java index 76c30b4ac62ba..b76e01fb5b23a 100644 --- a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/pagination/PaginationContextTest.java +++ b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/pagination/PaginationContextTest.java @@ -18,12 +18,9 @@ package org.apache.shardingsphere.infra.binder.context.segment.select.pagination; import org.apache.shardingsphere.infra.binder.context.statement.dml.SelectStatementContext; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.metadata.database.enums.NullsOrderType; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.sql.parser.statement.core.enums.OrderDirection; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.item.ProjectionsSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.order.GroupBySegment; @@ -48,9 +45,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class PaginationContextTest { @@ -166,9 +161,8 @@ void assertGetRevisedRowCountForSQLServer() { private void getRevisedRowCount(final SelectStatement selectStatement) { selectStatement.setProjections(new ProjectionsSegment(0, 0)); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(ResourceMetaData.class), mock(RuleMetaData.class), mock(ConfigurationProperties.class)); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()); SelectStatementContext selectStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), selectStatement, "foo_db", Collections.emptyList()); assertThat(new PaginationContext(getOffsetSegment(), getRowCountSegment(), getParameters()).getRevisedRowCount(selectStatementContext), is(50L)); } @@ -202,9 +196,8 @@ private void getRevisedRowCountWithMax(final SelectStatement selectStatement) { selectStatement.setProjections(new ProjectionsSegment(0, 0)); selectStatement.setGroupBy(new GroupBySegment(0, 0, Collections.singletonList(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, NullsOrderType.LAST)))); selectStatement.setOrderBy(new OrderBySegment(0, 0, Collections.singletonList(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, NullsOrderType.LAST)))); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(ResourceMetaData.class), mock(RuleMetaData.class), mock(ConfigurationProperties.class)); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()); SelectStatementContext selectStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), selectStatement, "foo_db", Collections.emptyList()); assertThat(new PaginationContext(getOffsetSegment(), getRowCountSegment(), getParameters()).getRevisedRowCount(selectStatementContext), is((long) Integer.MAX_VALUE)); } diff --git a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/projection/engine/ProjectionsContextEngineTest.java b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/projection/engine/ProjectionsContextEngineTest.java index 4b43dabf43d18..3abaf2d0df173 100644 --- a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/projection/engine/ProjectionsContextEngineTest.java +++ b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/select/projection/engine/ProjectionsContextEngineTest.java @@ -22,12 +22,9 @@ import org.apache.shardingsphere.infra.binder.context.segment.select.orderby.OrderByItem; import org.apache.shardingsphere.infra.binder.context.segment.select.projection.ProjectionsContext; import org.apache.shardingsphere.infra.binder.context.statement.dml.SelectStatementContext; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.metadata.database.enums.NullsOrderType; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.sql.parser.statement.core.enums.OrderDirection; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.column.ColumnSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.expr.subquery.SubquerySegment; @@ -59,9 +56,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ProjectionsContextEngineTest { @@ -220,9 +215,8 @@ private void assertCreateProjectionsContextWithoutIndexOrderByItemSegment(final } private SelectStatementContext createSelectStatementContext(final SelectStatement selectStatement) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(ResourceMetaData.class), mock(RuleMetaData.class), mock(ConfigurationProperties.class)); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()); return new SelectStatementContext(metaData, Collections.emptyList(), selectStatement, "foo_db", Collections.emptyList()); } diff --git a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/statement/dml/InsertStatementContextTest.java b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/statement/dml/InsertStatementContextTest.java index 93e6a1f6a58cd..0665b71acfe55 100644 --- a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/statement/dml/InsertStatementContextTest.java +++ b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/statement/dml/InsertStatementContextTest.java @@ -17,11 +17,8 @@ package org.apache.shardingsphere.infra.binder.context.statement.dml; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; import org.apache.shardingsphere.sql.parser.statement.core.enums.ParameterMarkerType; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.assignment.ColumnAssignmentSegment; @@ -47,6 +44,7 @@ import org.apache.shardingsphere.sql.parser.statement.postgresql.PostgreSQLStatement; import org.apache.shardingsphere.sql.parser.statement.postgresql.dml.PostgreSQLInsertStatement; import org.apache.shardingsphere.sql.parser.statement.sql92.dml.SQL92InsertStatement; +import org.apache.shardingsphere.sql.parser.statement.sqlserver.SQLServerStatement; import org.apache.shardingsphere.sql.parser.statement.sqlserver.dml.SQLServerInsertStatement; import org.junit.jupiter.api.Test; @@ -63,7 +61,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -108,14 +105,21 @@ private void assertInsertStatementContextWithColumnNames(final InsertStatement i } private InsertStatementContext createInsertStatementContext(final List params, final InsertStatement insertStatement) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); ShardingSphereSchema schema = mock(ShardingSphereSchema.class); - String defaultSchemaName = insertStatement instanceof PostgreSQLStatement || insertStatement instanceof OpenGaussStatement ? "public" : "foo_db"; - when(database.getSchema(defaultSchemaName)).thenReturn(schema); + when(schema.getName()).thenReturn(getSchemaName(insertStatement)); when(schema.getVisibleColumnNames("tbl")).thenReturn(Arrays.asList("id", "name", "status")); - return new InsertStatementContext(new ShardingSphereMetaData(Collections.singleton(database), mock(ResourceMetaData.class), mock(RuleMetaData.class), mock(ConfigurationProperties.class)), - params, insertStatement, "foo_db"); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.singleton(schema)); + return new InsertStatementContext(new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock()), params, insertStatement, "foo_db"); + } + + private String getSchemaName(final InsertStatement insertStatement) { + if (insertStatement instanceof PostgreSQLStatement || insertStatement instanceof OpenGaussStatement) { + return "public"; + } + if (insertStatement instanceof SQLServerStatement) { + return "dbo"; + } + return "foo_db"; } @Test diff --git a/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/engine/GenericSQLRewriteEngineTest.java b/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/engine/GenericSQLRewriteEngineTest.java index a411749e5cd53..2f8258bf02007 100644 --- a/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/engine/GenericSQLRewriteEngineTest.java +++ b/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/engine/GenericSQLRewriteEngineTest.java @@ -21,6 +21,7 @@ import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; +import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; @@ -70,10 +71,7 @@ private QueryContext mockQueryContext(final CommonSQLStatementContext sqlStateme @Test void assertRewriteStorageTypeIsEmpty() { SQLTranslatorRule rule = new SQLTranslatorRule(new DefaultSQLTranslatorRuleConfigurationBuilder().build()); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - when(database.getAllSchemas()).thenReturn(Collections.singleton(new ShardingSphereSchema("test"))); - when(database.getResourceMetaData().getStorageUnits()).thenReturn(Collections.emptyMap()); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), new ResourceMetaData(Collections.emptyMap()), mock(), Collections.singleton(new ShardingSphereSchema("test"))); CommonSQLStatementContext sqlStatementContext = mock(CommonSQLStatementContext.class); DatabaseType databaseType = mock(DatabaseType.class); when(sqlStatementContext.getDatabaseType()).thenReturn(databaseType); diff --git a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java index 4c8fa8cfc5491..d06f2292f89e8 100644 --- a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java +++ b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java @@ -173,9 +173,7 @@ void assertReloadTableWithDataSourceName() throws SQLException { @Test void assertGetPreSelectedDatabaseNameWithJDBC() { when(computeNodeInstanceContext.getInstance()).thenReturn(new ComputeNodeInstance(new JDBCInstanceMetaData("foo_id", "foo_db"), Collections.emptyList())); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(metaDataContexts.getMetaData().getAllDatabases()).thenReturn(Collections.singleton(database)); + when(metaDataContexts.getMetaData().getAllDatabases()).thenReturn(Collections.singleton(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()))); assertThat(contextManager.getPreSelectedDatabaseName(), is("foo_db")); } diff --git a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsTest.java b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsTest.java index b37698d249471..009ecd01255ce 100644 --- a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsTest.java +++ b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsTest.java @@ -31,15 +31,12 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class MetaDataContextsTest { @Test void assertGetDefaultMetaData() { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", TypedSPILoader.getService(DatabaseType.class, "FIXTURE"), mock(), mock(), Collections.emptyList()); ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), new ConfigurationProperties(new Properties())); assertThat(MetaDataContextsFactory.create(mock(MetaDataPersistService.class), metaData).getMetaData().getDatabase("foo_db"), is(database)); } diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java index 8828252b96248..de91f84566bb1 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/context/ProxyContextTest.java @@ -38,9 +38,9 @@ import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.LinkedList; import java.util.Properties; import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -94,23 +94,14 @@ void assertDatabaseExists() { void assertGetAllDatabaseNames() { Collection databases = createDatabases(); ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(mock(MetaDataPersistService.class), - new ShardingSphereMetaData(databases, mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(mock(), new ShardingSphereMetaData(databases, mock(), mock(), new ConfigurationProperties(new Properties()))); when(contextManager.getMetaDataContexts()).thenReturn(metaDataContexts); ProxyContext.init(contextManager); assertThat(new HashSet<>(ProxyContext.getInstance().getAllDatabaseNames()), is(databases.stream().map(ShardingSphereDatabase::getName).collect(Collectors.toSet()))); } private Collection createDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - String databaseName = String.format(SCHEMA_PATTERN, i); - when(database.getName()).thenReturn(databaseName); - when(database.getProtocolType()).thenReturn(databaseType); - result.add(database); - } - return result; + return IntStream.range(0, 10).mapToObj(i -> new ShardingSphereDatabase(String.format(SCHEMA_PATTERN, i), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } private ShardingSphereDatabase mockDatabase() { diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/admin/DatabaseAdminQueryBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/admin/DatabaseAdminQueryBackendHandlerTest.java index 1a56346ec3625..5531dde2f9a40 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/admin/DatabaseAdminQueryBackendHandlerTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/admin/DatabaseAdminQueryBackendHandlerTest.java @@ -17,7 +17,6 @@ package org.apache.shardingsphere.proxy.backend.handler.admin; -import org.apache.shardingsphere.infra.config.mode.ModeConfiguration; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.spi.DatabaseTypedSPILoader; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; @@ -26,13 +25,9 @@ import org.apache.shardingsphere.infra.merge.result.impl.local.LocalDataQueryResultRow; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; -import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; -import org.apache.shardingsphere.mode.spi.PersistRepository; import org.apache.shardingsphere.proxy.backend.context.ProxyContext; import org.apache.shardingsphere.proxy.backend.handler.admin.executor.DatabaseAdminQueryExecutor; import org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeaderBuilder; @@ -111,14 +106,10 @@ void assertGetRowData() throws SQLException { } private ContextManager mockContextManager() { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getProtocolType()).thenReturn(databaseType); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", databaseType, mock(), mock(), Collections.emptyList()); when(ProxyContext.getInstance().getContextManager().getDatabase("foo_db")).thenReturn(database); - ShardingSphereMetaData metaData = new ShardingSphereMetaData( - Collections.singleton(database), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties())); - ComputeNodeInstanceContext computeNodeInstanceContext = mock(ComputeNodeInstanceContext.class); - when(computeNodeInstanceContext.getModeConfiguration()).thenReturn(mock(ModeConfiguration.class)); - return new ContextManager(MetaDataContextsFactory.create(mock(MetaDataPersistService.class), metaData), computeNodeInstanceContext, mock(PersistRepository.class)); + ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), new ConfigurationProperties(new Properties())); + ComputeNodeInstanceContext computeNodeInstanceContext = mock(ComputeNodeInstanceContext.class, RETURNS_DEEP_STUBS); + return new ContextManager(MetaDataContextsFactory.create(mock(), metaData), computeNodeInstanceContext, mock()); } } diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/data/impl/UnicastDatabaseBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/data/impl/UnicastDatabaseBackendHandlerTest.java index b5a346687ea42..bd10f1e26fd77 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/data/impl/UnicastDatabaseBackendHandlerTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/data/impl/UnicastDatabaseBackendHandlerTest.java @@ -18,18 +18,14 @@ package org.apache.shardingsphere.proxy.backend.handler.data.impl; import lombok.SneakyThrows; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.session.connection.ConnectionContext; import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; -import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContexts; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; @@ -41,23 +37,21 @@ import org.apache.shardingsphere.proxy.backend.response.header.ResponseHeader; import org.apache.shardingsphere.proxy.backend.response.header.update.UpdateResponseHeader; import org.apache.shardingsphere.proxy.backend.session.ConnectionSession; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; import org.apache.shardingsphere.test.mock.AutoMockExtension; import org.apache.shardingsphere.test.mock.StaticMockSettings; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Answers; import org.mockito.Mock; import org.mockito.internal.configuration.plugins.Plugins; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.Optional; -import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -70,16 +64,17 @@ @ExtendWith(AutoMockExtension.class) @StaticMockSettings(ProxyContext.class) -@MockitoSettings(strictness = Strictness.LENIENT) class UnicastDatabaseBackendHandlerTest { private static final String EXECUTE_SQL = "SELECT 1 FROM user WHERE id = 1"; private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); + private UnicastDatabaseBackendHandler unicastDatabaseBackendHandler; - @Mock + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ConnectionSession connectionSession; @Mock @@ -91,11 +86,9 @@ class UnicastDatabaseBackendHandlerTest { @BeforeEach void setUp() throws SQLException { when(connectionSession.getCurrentDatabaseName()).thenReturn(String.format(DATABASE_PATTERN, 0)); - when(connectionSession.getDatabaseConnectionManager()).thenReturn(mock(ProxyDatabaseConnectionManager.class)); - mockDatabaseConnector(new UpdateResponseHeader(mock(SQLStatement.class))); - unicastDatabaseBackendHandler = - new UnicastDatabaseBackendHandler(new QueryContext(mock(SQLStatementContext.class), EXECUTE_SQL, Collections.emptyList(), new HintValueContext(), mockConnectionContext(), - mock(ShardingSphereMetaData.class)), connectionSession); + mockDatabaseConnector(new UpdateResponseHeader(mock())); + unicastDatabaseBackendHandler = new UnicastDatabaseBackendHandler( + new QueryContext(mock(), EXECUTE_SQL, Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock()), connectionSession); setBackendHandlerFactory(unicastDatabaseBackendHandler); } @@ -112,8 +105,7 @@ private void mockDatabaseConnector(final ResponseHeader responseHeader) throws S @SneakyThrows(ReflectiveOperationException.class) private void setBackendHandlerFactory(final DatabaseBackendHandler schemaDatabaseBackendHandler) { - Plugins.getMemberAccessor() - .set(schemaDatabaseBackendHandler.getClass().getDeclaredField("databaseConnectorFactory"), schemaDatabaseBackendHandler, databaseConnectorFactory); + Plugins.getMemberAccessor().set(schemaDatabaseBackendHandler.getClass().getDeclaredField("databaseConnectorFactory"), schemaDatabaseBackendHandler, databaseConnectorFactory); } @Test @@ -140,21 +132,13 @@ void assertDatabaseUsingStream() throws SQLException { private ContextManager mockContextManager() { ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(mock(MetaDataPersistService.class), - new ShardingSphereMetaData(createDatabases(), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(mock(), new ShardingSphereMetaData(createDatabases(), mock(), mock(), mock())); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } private Collection createDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.containsDataSource()).thenReturn(true); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); - result.add(database); - } - return result; + return IntStream.range(0, 10).mapToObj(each -> new ShardingSphereDatabase( + String.format(DATABASE_PATTERN, each), databaseType, mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), mock(), Collections.emptyList())).collect(Collectors.toList()); } } diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java index 76178be6cd684..428fb9066734c 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java @@ -60,6 +60,8 @@ @StaticMockSettings(ProxyContext.class) class DistSQLQueryBackendHandlerTest { + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); + @Test void assertExecuteWithNoDatabase() { assertThrows(NoDatabaseSelectedException.class, @@ -86,10 +88,8 @@ void assertExecuteWithAbstractStatement() { @Test void assertExecute() { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn("foo_db"); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); - when(database.getSchema("foo_db")).thenReturn(new ShardingSphereSchema("foo_db", createTables(), Collections.emptyList())); + ShardingSphereDatabase database = new ShardingSphereDatabase( + "foo_db", databaseType, mock(), mock(), Collections.singleton(new ShardingSphereSchema("foo_db", createTables(), Collections.emptyList()))); when(ProxyContext.getInstance().getContextManager().getDatabase("foo_db")).thenReturn(database); assertDoesNotThrow(() -> new DistSQLQueryBackendHandler(createSqlStatement(), mock(ConnectionSession.class, RETURNS_DEEP_STUBS)).execute()); } diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLUpdateBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLUpdateBackendHandlerTest.java index 24522f507f674..0e6a9d9bb364b 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLUpdateBackendHandlerTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLUpdateBackendHandlerTest.java @@ -17,10 +17,10 @@ package org.apache.shardingsphere.proxy.backend.handler.distsql; -import org.apache.shardingsphere.infra.exception.kernel.metadata.resource.storageunit.EmptyStorageUnitException; -import org.apache.shardingsphere.infra.exception.kernel.metadata.resource.storageunit.MissingRequiredStorageUnitsException; import org.apache.shardingsphere.distsql.statement.ral.updatable.RefreshTableMetaDataStatement; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; +import org.apache.shardingsphere.infra.exception.kernel.metadata.resource.storageunit.EmptyStorageUnitException; +import org.apache.shardingsphere.infra.exception.kernel.metadata.resource.storageunit.MissingRequiredStorageUnitsException; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.mode.manager.ContextManager; @@ -32,8 +32,6 @@ import org.apache.shardingsphere.test.mock.StaticMockSettings; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; import java.sql.SQLException; import java.util.Collections; @@ -47,17 +45,16 @@ @ExtendWith(AutoMockExtension.class) @StaticMockSettings(ProxyContext.class) -@MockitoSettings(strictness = Strictness.LENIENT) class DistSQLUpdateBackendHandlerTest { + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); + @Test void assertEmptyResource() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); when(contextManager.getStorageUnits("foo_db")).thenReturn(Collections.emptyMap()); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(contextManager.getDatabase("foo_db")).thenReturn(database); + when(contextManager.getDatabase("foo_db")).thenReturn(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList())); DistSQLUpdateBackendHandler backendHandler = new DistSQLUpdateBackendHandler(new RefreshTableMetaDataStatement(), mockConnectionSession("foo_db")); assertThrows(EmptyStorageUnitException.class, backendHandler::execute); } @@ -66,7 +63,6 @@ void assertEmptyResource() { void assertMissingRequiredResources() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); - when(ProxyContext.getInstance().databaseExists("foo_db")).thenReturn(true); DistSQLUpdateBackendHandler backendHandler = new DistSQLUpdateBackendHandler(new RefreshTableMetaDataStatement("t_order", "ds_1", null), mockConnectionSession("foo_db")); assertThrows(MissingRequiredStorageUnitsException.class, backendHandler::execute); } @@ -75,19 +71,14 @@ void assertMissingRequiredResources() { void assertUpdate() throws SQLException { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); - when(contextManager.getDatabase("foo_db")).thenReturn(database); - DistSQLUpdateBackendHandler backendHandler = new DistSQLUpdateBackendHandler(new RefreshTableMetaDataStatement(), mockConnectionSession("foo_db")); - ResponseHeader actual = backendHandler.execute(); + when(contextManager.getDatabase("foo_db")).thenReturn(new ShardingSphereDatabase("foo_db", databaseType, mock(), mock(), Collections.emptyList())); + ResponseHeader actual = new DistSQLUpdateBackendHandler(new RefreshTableMetaDataStatement(), mockConnectionSession("foo_db")).execute(); assertThat(actual, instanceOf(UpdateResponseHeader.class)); } private ConnectionSession mockConnectionSession(final String databaseName) { ConnectionSession result = mock(ConnectionSession.class); when(result.getUsedDatabaseName()).thenReturn(databaseName); - when(result.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); return result; } } diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowCreateDatabaseExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowCreateDatabaseExecutorTest.java index 38f217ab44d37..92573f3eb2a56 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowCreateDatabaseExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowCreateDatabaseExecutorTest.java @@ -17,12 +17,9 @@ package org.apache.shardingsphere.proxy.backend.mysql.handler.admin.executor; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; import org.apache.shardingsphere.metadata.persist.data.ShardingSphereDataPersistService; @@ -39,9 +36,10 @@ import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedList; +import java.util.Collections; import java.util.Optional; -import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -56,6 +54,8 @@ class ShowCreateDatabaseExecutorTest { private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); + @Test void assertExecute() throws SQLException { MySQLShowCreateDatabaseStatement statement = new MySQLShowCreateDatabaseStatement(); @@ -78,21 +78,14 @@ private ContextManager mockContextManager() { ShardingSphereDataPersistService shardingSphereDataPersistService = mock(ShardingSphereDataPersistService.class); when(shardingSphereDataPersistService.load(any())).thenReturn(Optional.empty()); when(metaDataPersistService.getShardingSphereDataPersistService()).thenReturn(shardingSphereDataPersistService); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, - new ShardingSphereMetaData(mockDatabases(), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, new ShardingSphereMetaData(createDatabases(), mock(), mock(), mock())); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } - private Collection mockDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - result.add(database); - } - return result; + private Collection createDatabases() { + return IntStream.range(0, 10) + .mapToObj(each -> new ShardingSphereDatabase(String.format(DATABASE_PATTERN, each), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } } diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowDatabasesExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowDatabasesExecutorTest.java index 5007ffe98215c..21e74375f3d1b 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowDatabasesExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowDatabasesExecutorTest.java @@ -19,17 +19,14 @@ import org.apache.shardingsphere.authority.model.ShardingSpherePrivileges; import org.apache.shardingsphere.authority.rule.AuthorityRule; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.metadata.user.Grantee; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; -import org.apache.shardingsphere.metadata.persist.data.ShardingSphereDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContexts; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; @@ -48,10 +45,8 @@ import java.sql.SQLException; import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.Map; import java.util.Optional; -import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -71,6 +66,8 @@ class ShowDatabasesExecutorTest { private static final String DATABASE_PATTERN = "database_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); + @Test void assertExecute() throws SQLException { ContextManager contextManager = mockContextManager(); @@ -185,12 +182,9 @@ void assertExecuteWithLikeMatchNone() throws SQLException { private ContextManager mockContextManager() { ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); RuleMetaData globalRuleMetaData = new RuleMetaData(Collections.singleton(mockAuthorityRule())); - MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class); - ShardingSphereDataPersistService shardingSphereDataPersistService = mock(ShardingSphereDataPersistService.class); - when(shardingSphereDataPersistService.load(any())).thenReturn(Optional.empty()); - when(metaDataPersistService.getShardingSphereDataPersistService()).thenReturn(shardingSphereDataPersistService); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, - new ShardingSphereMetaData(mockDatabases(), mock(ResourceMetaData.class), globalRuleMetaData, new ConfigurationProperties(new Properties()))); + MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class, RETURNS_DEEP_STUBS); + when(metaDataPersistService.getShardingSphereDataPersistService().load(any())).thenReturn(Optional.empty()); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, new ShardingSphereMetaData(createDatabases(), mock(), globalRuleMetaData, mock())); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } @@ -208,15 +202,9 @@ private ShardingSpherePrivileges mockPrivileges() { return result; } - private Collection mockDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - result.add(database); - } - return result; + private Collection createDatabases() { + return IntStream.range(0, 10) + .mapToObj(each -> new ShardingSphereDatabase(String.format(DATABASE_PATTERN, each), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } private ConnectionSession mockConnectionSession() { diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowFunctionStatusExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowFunctionStatusExecutorTest.java index 1a66cdb2ed2a8..717ae24389cf6 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowFunctionStatusExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowFunctionStatusExecutorTest.java @@ -17,15 +17,11 @@ package org.apache.shardingsphere.proxy.backend.mysql.handler.admin.executor; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; -import org.apache.shardingsphere.metadata.persist.data.ShardingSphereDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContexts; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; @@ -39,9 +35,10 @@ import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedList; +import java.util.Collections; import java.util.Optional; -import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -56,6 +53,8 @@ class ShowFunctionStatusExecutorTest { private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); + @Test void assertExecute() throws SQLException { ShowFunctionStatusExecutor executor = new ShowFunctionStatusExecutor(new MySQLShowFunctionStatusStatement()); @@ -66,25 +65,16 @@ void assertExecute() throws SQLException { } private ContextManager mockContextManager() { - MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class); - ShardingSphereDataPersistService shardingSphereDataPersistService = mock(ShardingSphereDataPersistService.class); - when(shardingSphereDataPersistService.load(any())).thenReturn(Optional.empty()); - when(metaDataPersistService.getShardingSphereDataPersistService()).thenReturn(shardingSphereDataPersistService); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, - new ShardingSphereMetaData(mockDatabases(), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class, RETURNS_DEEP_STUBS); + when(metaDataPersistService.getShardingSphereDataPersistService().load(any())).thenReturn(Optional.empty()); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, new ShardingSphereMetaData(createDatabases(), mock(), mock(), mock())); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } - private Collection mockDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - result.add(database); - } - return result; + private Collection createDatabases() { + return IntStream.range(0, 10) + .mapToObj(each -> new ShardingSphereDatabase(String.format(DATABASE_PATTERN, each), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } } diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowProcedureStatusExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowProcedureStatusExecutorTest.java index d74dd78c28c83..c2127ceb7601f 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowProcedureStatusExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowProcedureStatusExecutorTest.java @@ -17,15 +17,11 @@ package org.apache.shardingsphere.proxy.backend.mysql.handler.admin.executor; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; -import org.apache.shardingsphere.metadata.persist.data.ShardingSphereDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContexts; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; @@ -39,9 +35,10 @@ import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedList; +import java.util.Collections; import java.util.Optional; -import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -56,6 +53,8 @@ class ShowProcedureStatusExecutorTest { private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); + @Test void assertExecute() throws SQLException { ShowProcedureStatusExecutor executor = new ShowProcedureStatusExecutor(new MySQLShowProcedureStatusStatement()); @@ -66,25 +65,16 @@ void assertExecute() throws SQLException { } private ContextManager mockContextManager() { - MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class); - ShardingSphereDataPersistService shardingSphereDataPersistService = mock(ShardingSphereDataPersistService.class); - when(shardingSphereDataPersistService.load(any())).thenReturn(Optional.empty()); - when(metaDataPersistService.getShardingSphereDataPersistService()).thenReturn(shardingSphereDataPersistService); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, - new ShardingSphereMetaData(mockDatabases(), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class, RETURNS_DEEP_STUBS); + when(metaDataPersistService.getShardingSphereDataPersistService().load(any())).thenReturn(Optional.empty()); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, new ShardingSphereMetaData(createDatabases(), mock(), mock(), mock())); ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } - private Collection mockDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - result.add(database); - } - return result; + private Collection createDatabases() { + return IntStream.range(0, 10) + .mapToObj(each -> new ShardingSphereDatabase(String.format(DATABASE_PATTERN, each), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } } diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java index 0c8a781bfef7d..30be8e59dd2a4 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java @@ -50,6 +50,7 @@ import org.mockito.quality.Strictness; import java.sql.SQLException; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; @@ -71,9 +72,11 @@ class ShowTablesExecutorTest { private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL"); + @Test void assertShowTablesExecutorWithoutFilter() throws SQLException { - ShowTablesExecutor executor = new ShowTablesExecutor(new MySQLShowTablesStatement(), TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(new MySQLShowTablesStatement(), databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -94,7 +97,7 @@ void assertShowTablesExecutorWithoutFilter() throws SQLException { void assertShowTablesExecutorWithFull() throws SQLException { MySQLShowTablesStatement showTablesStatement = mock(MySQLShowTablesStatement.class); when(showTablesStatement.isContainsFull()).thenReturn(true); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -108,7 +111,7 @@ void assertShowTablesExecutorWithLikeFilter() throws SQLException { ShowFilterSegment showFilterSegment = mock(ShowFilterSegment.class); when(showFilterSegment.getLike()).thenReturn(Optional.of(new ShowLikeSegment(0, 10, "t_account%"))); showTablesStatement.setFilter(showFilterSegment); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -129,7 +132,7 @@ void assertShowTablesExecutorWithSpecificTable() throws SQLException { ShowFilterSegment showFilterSegment = mock(ShowFilterSegment.class); when(showFilterSegment.getLike()).thenReturn(Optional.of(new ShowLikeSegment(0, 10, "t_account"))); showTablesStatement.setFilter(showFilterSegment); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -146,7 +149,7 @@ void assertShowTablesExecutorWithUpperCase() throws SQLException { ShowFilterSegment showFilterSegment = mock(ShowFilterSegment.class); when(showFilterSegment.getLike()).thenReturn(Optional.of(new ShowLikeSegment(0, 10, "T_TEST"))); showTablesStatement.setFilter(showFilterSegment); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -163,7 +166,7 @@ void assertShowTablesExecutorWithLowerCase() throws SQLException { ShowFilterSegment showFilterSegment = mock(ShowFilterSegment.class); when(showFilterSegment.getLike()).thenReturn(Optional.of(new ShowLikeSegment(0, 10, "t_test"))); showTablesStatement.setFilter(showFilterSegment); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); Collection databases = mockDatabases(); ContextManager contextManager = mockContextManager(databases); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); @@ -178,7 +181,7 @@ void assertShowTablesExecutorWithLowerCase() throws SQLException { void assertShowTableFromUncompletedDatabase() throws SQLException { MySQLShowTablesStatement showTablesStatement = new MySQLShowTablesStatement(); showTablesStatement.setFromDatabase(new FromDatabaseSegment(0, 0, new DatabaseSegment(0, 0, new IdentifierValue("uncompleted")))); - ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, TypedSPILoader.getService(DatabaseType.class, "MySQL")); + ShowTablesExecutor executor = new ShowTablesExecutor(showTablesStatement, databaseType); ContextManager contextManager = mockContextManager(mockDatabases()); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); executor.execute(mockConnectionSession()); @@ -211,15 +214,10 @@ private Collection mockDatabases() { ShardingSphereSchema schema = new ShardingSphereSchema("foo_db", tables, Collections.emptyList()); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, 0)); - when(database.getSchema(String.format(DATABASE_PATTERN, 0))).thenReturn(schema); + when(database.getProtocolType()).thenReturn(databaseType); when(database.isComplete()).thenReturn(true); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - Collection result = new LinkedList<>(); - result.add(database); - ShardingSphereDatabase uncompletedDatabase = mock(ShardingSphereDatabase.class); - when(uncompletedDatabase.getName()).thenReturn("uncompleted"); - result.add(uncompletedDatabase); - return result; + when(database.getSchema(String.format(DATABASE_PATTERN, 0))).thenReturn(schema); + return Arrays.asList(database, new ShardingSphereDatabase("uncompleted", mock(), mock(), mock(), Collections.emptyList())); } private ConnectionSession mockConnectionSession() { diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/UseDatabaseExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/UseDatabaseExecutorTest.java index 0483a0eb7a035..98348e96c1f73 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/UseDatabaseExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/UseDatabaseExecutorTest.java @@ -17,13 +17,10 @@ package org.apache.shardingsphere.proxy.backend.mysql.handler.admin.executor; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.exception.dialect.exception.syntax.database.UnknownDatabaseException; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; @@ -40,8 +37,9 @@ import org.mockito.Mock; import java.util.Collection; -import java.util.LinkedList; -import java.util.Properties; +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; @@ -56,6 +54,8 @@ class UseDatabaseExecutorTest { private static final String DATABASE_PATTERN = "db_%s"; + private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ConnectionSession connectionSession; @@ -84,20 +84,14 @@ void assertExecuteUseStatementBackendHandlerWhenSchemaNotExist() { private ContextManager mockContextManager() { ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(mock(MetaDataPersistService.class), - new ShardingSphereMetaData(mockDatabases(), mock(ResourceMetaData.class), mock(RuleMetaData.class), new ConfigurationProperties(new Properties()))); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create( + mock(MetaDataPersistService.class, RETURNS_DEEP_STUBS), new ShardingSphereMetaData(createDatabases(), mock(), mock(), mock())); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; } - private Collection mockDatabases() { - Collection result = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getName()).thenReturn(String.format(DATABASE_PATTERN, i)); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); - result.add(database); - } - return result; + private Collection createDatabases() { + return IntStream.range(0, 10) + .mapToObj(each -> new ShardingSphereDatabase(String.format(DATABASE_PATTERN, each), databaseType, mock(), mock(), Collections.emptyList())).collect(Collectors.toList()); } } diff --git a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationEngineTest.java b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationEngineTest.java index 7495758d63be9..b3695be41957e 100644 --- a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationEngineTest.java +++ b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationEngineTest.java @@ -36,7 +36,6 @@ import org.apache.shardingsphere.db.protocol.mysql.packet.generic.MySQLOKPacket; import org.apache.shardingsphere.db.protocol.mysql.packet.handshake.MySQLHandshakePacket; import org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload; -import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.exception.dialect.exception.syntax.database.UnknownDatabaseException; import org.apache.shardingsphere.infra.exception.mysql.exception.AccessDeniedException; @@ -45,13 +44,11 @@ import org.apache.shardingsphere.infra.exception.mysql.vendor.MySQLVendorError; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.metadata.user.Grantee; import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.metadata.persist.MetaDataPersistService; -import org.apache.shardingsphere.metadata.persist.data.ShardingSphereDataPersistService; import org.apache.shardingsphere.mode.manager.ContextManager; import org.apache.shardingsphere.mode.metadata.MetaDataContexts; import org.apache.shardingsphere.mode.metadata.MetaDataContextsFactory; @@ -74,7 +71,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -287,15 +283,11 @@ void assertAuthenticateSuccess() { private ContextManager mockContextManager(final AuthorityRule rule) { ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS); - ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); - when(database.getName()).thenReturn("foo_db"); - when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "MySQL")); - MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class); - ShardingSphereDataPersistService shardingSphereDataPersistService = mock(ShardingSphereDataPersistService.class); - when(shardingSphereDataPersistService.load(any())).thenReturn(Optional.empty()); - when(metaDataPersistService.getShardingSphereDataPersistService()).thenReturn(shardingSphereDataPersistService); - MetaDataContexts metaDataContexts = MetaDataContextsFactory.create(metaDataPersistService, new ShardingSphereMetaData( - Collections.singleton(database), mock(ResourceMetaData.class), new RuleMetaData(Collections.singleton(rule)), new ConfigurationProperties(new Properties()))); + MetaDataPersistService metaDataPersistService = mock(MetaDataPersistService.class, RETURNS_DEEP_STUBS); + when(metaDataPersistService.getShardingSphereDataPersistService().load(any())).thenReturn(Optional.empty()); + ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", TypedSPILoader.getService(DatabaseType.class, "MySQL"), mock(), mock(), Collections.emptyList()); + MetaDataContexts metaDataContexts = MetaDataContextsFactory.create( + metaDataPersistService, new ShardingSphereMetaData(Collections.singleton(database), mock(), new RuleMetaData(Collections.singleton(rule)), mock())); when(result.getMetaDataContexts()).thenReturn(metaDataContexts); return result; }