This is an automated email from the ASF dual-hosted git repository.
terrymanu 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 a3b395c7a39 Refine test assertions and fixtures (#40331)
a3b395c7a39 is described below
commit a3b395c7a393a65b7de2c547c51b398a576ec824
Author: Liang Zhang <[email protected]>
AuthorDate: Thu Oct 22 17:06:58 2026 +0800
Refine test assertions and fixtures (#40331)
---
.../type/InstanceMethodAdviceExecutorTest.java | 4 +-
.../type/StaticMethodAdviceExecutorTest.java | 4 +-
.../FirebirdBinaryProtocolValueFactoryTest.java | 11 +-
.../complex/ShardingComplexRouteEngineTest.java | 3 +-
.../dal/AnalyzeTableStatementBinderTest.java | 5 +-
.../statement/ddl/CommentStatementBinderTest.java | 21 +-
.../statement/ddl/PrepareStatementBinderTest.java | 11 +-
.../infra/checker/SupportedSQLCheckEngineTest.java | 3 +-
.../builder/database/DatabaseRulesBuilderTest.java | 2 +-
.../pool/creator/DataSourcePoolReflectionTest.java | 13 +-
...ordTableInventoryCheckCalculatedResultTest.java | 6 +-
.../incremental/client/MySQLBinlogClientTest.java | 61 ++----
.../incremental/client/PasswordEncryptionTest.java | 20 +-
.../client/netty/MySQLNegotiateHandlerTest.java | 10 +-
.../PostgreSQLColumnPropertiesAppenderTest.java | 29 +--
...ostgreSQLConstraintsPropertiesAppenderTest.java | 13 +-
.../ddl/index/PostgreSQLIndexSQLGeneratorTest.java | 2 +-
.../table/PostgreSQLTablePropertiesLoaderTest.java | 6 +-
.../PostgreSQLPipelineFreemarkerManagerTest.java | 2 +-
.../builder/SQLFederationPlannerBuilderTest.java | 2 +-
.../impl/LiteralExpressionConverterTest.java | 2 +-
.../calcite/CalciteSQLFederationExecutorTest.java | 3 +-
.../processor/SQLFederationProcessorTest.java | 78 +++++---
.../transaction/rule/TransactionRuleTest.java | 15 +-
.../dialect/FirebirdXAConnectionWrapperTest.java | 14 +-
.../YamlMCPLaunchConfigurationSwapperTest.java | 221 +++++++++++++--------
.../AbstractMCPToolSpecificationFactoryTest.java | 2 +-
.../constraint/OriginHeaderConstraintTest.java | 31 ++-
.../metadata/SearchMetadataToolHandlerTest.java | 3 +-
.../workflow/WorkflowExecutionToolHandlerTest.java | 5 +-
.../WorkflowValidationToolHandlerTest.java | 3 +-
.../broadcast/TestWorkflowSessionContext.java | 5 +-
.../encrypt/TestWorkflowSessionContext.java | 5 +-
.../feature/mask/TestWorkflowSessionContext.java | 5 +-
.../TestWorkflowSessionContext.java | 5 +-
.../ReadwriteSplittingInspectionServiceTest.java | 7 +-
.../feature/shadow/TestWorkflowSessionContext.java | 5 +-
.../sharding/ShardingMCPHandlerProviderTest.java | 8 +-
.../sharding/TestWorkflowSessionContext.java | 5 +-
.../service/TestWorkflowSessionContext.java | 5 +-
.../WorkflowSynchronizationSupportTest.java | 8 +-
.../FederationMetaDataRefreshEngineTest.java | 2 +
.../refresher/util/TableRefreshUtilsTest.java | 35 +---
.../ClusterExclusiveOperatorContextTest.java | 3 +-
.../SelectInformationSchemataExecutorTest.java | 3 +-
.../PostgreSQLAuthenticationEngineTest.java | 24 +--
.../cases/cursor/OpenGaussCursorTestCase.java | 4 +-
.../engine/command/CursorSQLCommand.java | 2 +-
.../sql/binder/dialect/oracle/OracleBinderIT.java | 89 +++------
49 files changed, 393 insertions(+), 432 deletions(-)
diff --git
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/InstanceMethodAdviceExecutorTest.java
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/InstanceMethodAdviceExecutorTest.java
index 3699e09a723..2c7b6410524 100644
---
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/InstanceMethodAdviceExecutorTest.java
+++
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/InstanceMethodAdviceExecutorTest.java
@@ -203,8 +203,8 @@ class InstanceMethodAdviceExecutorTest {
private final List<LogRecord> records;
@Override
- public void publish(final LogRecord record) {
- records.add(record);
+ public void publish(final LogRecord logRecord) {
+ records.add(logRecord);
}
@Override
diff --git
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/StaticMethodAdviceExecutorTest.java
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/StaticMethodAdviceExecutorTest.java
index 917cae21ad9..5ec4fccad51 100644
---
a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/StaticMethodAdviceExecutorTest.java
+++
b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/advisor/executor/type/StaticMethodAdviceExecutorTest.java
@@ -227,8 +227,8 @@ class StaticMethodAdviceExecutorTest {
private final List<LogRecord> records;
@Override
- public void publish(final LogRecord record) {
- records.add(record);
+ public void publish(final LogRecord logRecord) {
+ records.add(logRecord);
}
@Override
diff --git
a/database/protocol/dialect/firebird/src/test/java/org/apache/shardingsphere/database/protocol/firebird/packet/command/query/statement/execute/protocol/FirebirdBinaryProtocolValueFactoryTest.java
b/database/protocol/dialect/firebird/src/test/java/org/apache/shardingsphere/database/protocol/firebird/packet/command/query/statement/execute/protocol/FirebirdBinaryProtocolValueFactoryTest.java
index 6130ac08199..901ea0c7ca6 100644
---
a/database/protocol/dialect/firebird/src/test/java/org/apache/shardingsphere/database/protocol/firebird/packet/command/query/statement/execute/protocol/FirebirdBinaryProtocolValueFactoryTest.java
+++
b/database/protocol/dialect/firebird/src/test/java/org/apache/shardingsphere/database/protocol/firebird/packet/command/query/statement/execute/protocol/FirebirdBinaryProtocolValueFactoryTest.java
@@ -32,12 +32,11 @@ class FirebirdBinaryProtocolValueFactoryTest {
assertThat(actual, isA(FirebirdStringBinaryProtocolValue.class));
}
- // TODO Uncomment when a specific handler is required; currently BLOB is
handled by StringBinaryProtocolValue
- // @Test
- // void assertGetByteBinaryProtocolValue() {
- // FirebirdBinaryProtocolValue actual =
FirebirdBinaryProtocolValueFactory.getBinaryProtocolValue(FirebirdBinaryColumnType.BLOB);
- // assertThat(actual, isA(FirebirdByteBinaryProtocolValue.class));
- // }
+ @Test
+ void assertGetBlobBinaryProtocolValue() {
+ FirebirdBinaryProtocolValue actual =
FirebirdBinaryProtocolValueFactory.getBinaryProtocolValue(FirebirdBinaryColumnType.BLOB);
+ assertThat(actual, isA(FirebirdBlobBinaryProtocolValue.class));
+ }
@Test
void assertGetInt16BinaryProtocolValue() {
diff --git
a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/complex/ShardingComplexRouteEngineTest.java
b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/complex/ShardingComplexRouteEngineTest.java
index 3eca1f2b003..3cd0777d3a1 100644
---
a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/complex/ShardingComplexRouteEngineTest.java
+++
b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/complex/ShardingComplexRouteEngineTest.java
@@ -21,6 +21,7 @@ import
org.apache.shardingsphere.infra.binder.context.statement.SQLStatementCont
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.infra.hint.HintValueContext;
import org.apache.shardingsphere.infra.route.context.RouteContext;
+import org.apache.shardingsphere.infra.route.context.RouteMapper;
import org.apache.shardingsphere.infra.route.context.RouteUnit;
import
org.apache.shardingsphere.sharding.exception.metadata.ShardingTableRuleNotFoundException;
import
org.apache.shardingsphere.sharding.route.engine.condition.ShardingCondition;
@@ -84,7 +85,7 @@ class ShardingComplexRouteEngineTest {
List<RouteUnit> routeUnits = new
ArrayList<>(routeContext.getRouteUnits());
assertThat(routeUnits.size(), is(1));
assertThat(routeUnits.get(0).getDataSourceMapper().getActualName(),
is("ds_1"));
- Map<String, String> actualTableNames =
routeUnits.get(0).getTableMappers().stream().collect(Collectors.toMap(each ->
each.getLogicName(), each -> each.getActualName()));
+ Map<String, String> actualTableNames =
routeUnits.get(0).getTableMappers().stream().collect(Collectors.toMap(RouteMapper::getLogicName,
RouteMapper::getActualName));
assertThat(actualTableNames.size(), is(2));
assertThat(actualTableNames.get("t_order"), is("t_order_1"));
assertThat(actualTableNames.get("t_user"), is("t_user_1"));
diff --git
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dal/AnalyzeTableStatementBinderTest.java
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dal/AnalyzeTableStatementBinderTest.java
index eeda398eacd..800e5074187 100644
---
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dal/AnalyzeTableStatementBinderTest.java
+++
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dal/AnalyzeTableStatementBinderTest.java
@@ -39,7 +39,6 @@ import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -61,9 +60,9 @@ class AnalyzeTableStatementBinderTest {
IdentifierValue databaseName = new IdentifierValue("foo_db");
when(metaData.containsDatabase(databaseName)).thenReturn(true);
when(metaData.getDatabase(databaseName.getValue())).thenReturn(database);
- when(metaData.getDatabase(eq(databaseName))).thenReturn(database);
+ when(metaData.getDatabase(databaseName)).thenReturn(database);
when(database.getDefaultSchemaName()).thenReturn(databaseName.getValue());
- when(database.getSchema(eq(databaseName))).thenReturn(schema);
+ when(database.getSchema(databaseName)).thenReturn(schema);
AnalyzeTableStatement actual = getAnalyzeTableStatement();
Collection<SimpleTableSegment> actualTables = actual.getTables();
assertThat(actualTables.size(), is(1));
diff --git
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/CommentStatementBinderTest.java
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/CommentStatementBinderTest.java
index dee5e77a856..f90f5efea99 100644
---
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/CommentStatementBinderTest.java
+++
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/CommentStatementBinderTest.java
@@ -39,7 +39,6 @@ import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -63,13 +62,13 @@ class CommentStatementBinderTest {
void assertBindWithTable() {
IdentifierValue databaseName = new IdentifierValue("foo_db_1");
IdentifierValue tableName = new IdentifierValue("t_order");
- when(metaData.containsDatabase(eq(databaseName))).thenReturn(true);
+ when(metaData.containsDatabase(databaseName)).thenReturn(true);
when(metaData.getDatabase(databaseName.getValue())).thenReturn(database);
- when(metaData.getDatabase(eq(databaseName))).thenReturn(database);
+ when(metaData.getDatabase(databaseName)).thenReturn(database);
when(database.getDefaultSchemaName()).thenReturn(databaseName.getValue());
- when(database.getSchema(eq(databaseName))).thenReturn(schema);
- when(schema.containsTable(eq(tableName))).thenReturn(true);
- when(schema.getTable(eq(tableName))).thenReturn(table);
+ when(database.getSchema(databaseName)).thenReturn(schema);
+ when(schema.containsTable(tableName)).thenReturn(true);
+ when(schema.getTable(tableName)).thenReturn(table);
when(table.getAllColumns()).thenReturn(Collections.emptyList());
HintValueContext hintValueContext = new HintValueContext();
hintValueContext.setSkipMetadataValidate(true);
@@ -96,13 +95,13 @@ class CommentStatementBinderTest {
void assertBindWithColumn() {
IdentifierValue databaseName = new IdentifierValue("foo_db_1");
IdentifierValue tableName = new IdentifierValue("t_order");
- when(metaData.containsDatabase(eq(databaseName))).thenReturn(true);
+ when(metaData.containsDatabase(databaseName)).thenReturn(true);
when(metaData.getDatabase(databaseName.getValue())).thenReturn(database);
- when(metaData.getDatabase(eq(databaseName))).thenReturn(database);
+ when(metaData.getDatabase(databaseName)).thenReturn(database);
when(database.getDefaultSchemaName()).thenReturn(databaseName.getValue());
- when(database.getSchema(eq(databaseName))).thenReturn(schema);
- when(schema.containsTable(eq(tableName))).thenReturn(true);
- when(schema.getTable(eq(tableName))).thenReturn(table);
+ when(database.getSchema(databaseName)).thenReturn(schema);
+ when(schema.containsTable(tableName)).thenReturn(true);
+ when(schema.getTable(tableName)).thenReturn(table);
when(table.getAllColumns()).thenReturn(Collections.emptyList());
HintValueContext hintValueContext = new HintValueContext();
hintValueContext.setSkipMetadataValidate(true);
diff --git
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/PrepareStatementBinderTest.java
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/PrepareStatementBinderTest.java
index 4e4eb3796e9..7fa086756a4 100644
---
a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/PrepareStatementBinderTest.java
+++
b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/ddl/PrepareStatementBinderTest.java
@@ -48,7 +48,6 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@@ -72,13 +71,13 @@ class PrepareStatementBinderTest {
void assertBindWithSelect() {
IdentifierValue databaseName = new IdentifierValue("foo_db_1");
IdentifierValue tableName = new IdentifierValue("t_order");
- when(metaData.containsDatabase(eq(databaseName))).thenReturn(true);
+ when(metaData.containsDatabase(databaseName)).thenReturn(true);
when(metaData.getDatabase(databaseName.getValue())).thenReturn(database);
- when(metaData.getDatabase(eq(databaseName))).thenReturn(database);
+ when(metaData.getDatabase(databaseName)).thenReturn(database);
when(database.getDefaultSchemaName()).thenReturn(databaseName.getValue());
- when(database.getSchema(eq(databaseName))).thenReturn(schema);
- when(schema.containsTable(eq(tableName))).thenReturn(true);
- when(schema.getTable(eq(tableName))).thenReturn(table);
+ when(database.getSchema(databaseName)).thenReturn(schema);
+ when(schema.containsTable(tableName)).thenReturn(true);
+ when(schema.getTable(tableName)).thenReturn(table);
when(table.getAllColumns()).thenReturn(Collections.emptyList());
HintValueContext hintValueContext = new HintValueContext();
hintValueContext.setSkipMetadataValidate(true);
diff --git
a/infra/checker/src/test/java/org/apache/shardingsphere/infra/checker/SupportedSQLCheckEngineTest.java
b/infra/checker/src/test/java/org/apache/shardingsphere/infra/checker/SupportedSQLCheckEngineTest.java
index 9fbce9891f2..af8686ae1f8 100644
---
a/infra/checker/src/test/java/org/apache/shardingsphere/infra/checker/SupportedSQLCheckEngineTest.java
+++
b/infra/checker/src/test/java/org/apache/shardingsphere/infra/checker/SupportedSQLCheckEngineTest.java
@@ -34,7 +34,6 @@ import java.util.Collections;
import java.util.Map;
import java.util.Optional;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -63,7 +62,7 @@ class SupportedSQLCheckEngineTest {
when(database.findDefaultSchema()).thenReturn(Optional.of(defaultSchema));
new SupportedSQLCheckEngine().checkSQL(Collections.singleton(rule),
sqlStatementContext, database);
verify(supportedSQLChecker).check(rule, database, defaultSchema,
sqlStatementContext);
- verify(unsupportedSQLChecker, never()).check(eq(rule), eq(database),
eq(defaultSchema), eq(sqlStatementContext));
+ verify(unsupportedSQLChecker, never()).check(rule, database,
defaultSchema, sqlStatementContext);
}
@SuppressWarnings({"rawtypes", "unchecked"})
diff --git
a/infra/common/src/test/java/org/apache/shardingsphere/infra/rule/builder/database/DatabaseRulesBuilderTest.java
b/infra/common/src/test/java/org/apache/shardingsphere/infra/rule/builder/database/DatabaseRulesBuilderTest.java
index f2f3c650ee6..8a49304408b 100644
---
a/infra/common/src/test/java/org/apache/shardingsphere/infra/rule/builder/database/DatabaseRulesBuilderTest.java
+++
b/infra/common/src/test/java/org/apache/shardingsphere/infra/rule/builder/database/DatabaseRulesBuilderTest.java
@@ -176,7 +176,7 @@ class DatabaseRulesBuilderTest {
mockedLoader.when(() ->
OrderedSPILoader.getServicesByClass(DatabaseRuleConfigurationChecker.class,
Collections.singleton(FixtureDatabaseRuleConfiguration.class))).thenReturn(Collections.singletonMap(FixtureDatabaseRuleConfiguration.class,
checker));
assertThat(DatabaseRulesBuilder.build("foo_db", null, rules,
ruleConfig, null, EMPTY_RESOURCE_META_DATA), isA(FixtureRule.class));
- verify(checker).check(eq("foo_db"), eq(ruleConfig),
eq(EMPTY_RESOURCE_META_DATA.getDataSourceMap()), eq(rules));
+ verify(checker).check("foo_db", ruleConfig,
EMPTY_RESOURCE_META_DATA.getDataSourceMap(), rules);
}
}
diff --git
a/infra/data-source-pool/core/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolReflectionTest.java
b/infra/data-source-pool/core/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolReflectionTest.java
index 2ff7b4d46d8..d0d37d8c9f2 100644
---
a/infra/data-source-pool/core/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolReflectionTest.java
+++
b/infra/data-source-pool/core/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolReflectionTest.java
@@ -84,17 +84,8 @@ class DataSourcePoolReflectionTest {
}
@ParameterizedTest(name = "{0}")
- @MethodSource("setFieldWithConvertedValues")
- void assertSetFieldWithConvertedValues(final String name, final String
fieldName, final Object fieldValue, final String actualFieldName, final Object
expectedFieldValue) {
- DataSourcePoolReflectionFixture dataSource = new
DataSourcePoolReflectionFixture();
- new DataSourcePoolReflection(dataSource).setField(fieldName,
fieldValue);
- Object actualFieldValue = getFieldValue(dataSource, actualFieldName);
- assertThat(actualFieldValue, is(expectedFieldValue));
- }
-
- @ParameterizedTest(name = "{0}")
- @MethodSource("setFieldWithIgnoredValues")
- void assertSetFieldWithIgnoredValues(final String name, final String
fieldName, final Object fieldValue, final String actualFieldName, final Object
expectedFieldValue) {
+ @MethodSource({"setFieldWithConvertedValues", "setFieldWithIgnoredValues"})
+ void assertSetField(final String name, final String fieldName, final
Object fieldValue, final String actualFieldName, final Object
expectedFieldValue) {
DataSourcePoolReflectionFixture dataSource = new
DataSourcePoolReflectionFixture();
new DataSourcePoolReflection(dataSource).setField(fieldName,
fieldValue);
Object actualFieldValue = getFieldValue(dataSource, actualFieldName);
diff --git
a/kernel/data-pipeline/core/src/test/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/result/RecordTableInventoryCheckCalculatedResultTest.java
b/kernel/data-pipeline/core/src/test/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/result/RecordTableInventoryCheckCalculatedResultTest.java
index daf85ccc83e..f9d7c334ee1 100644
---
a/kernel/data-pipeline/core/src/test/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/result/RecordTableInventoryCheckCalculatedResultTest.java
+++
b/kernel/data-pipeline/core/src/test/java/org/apache/shardingsphere/data/pipeline/core/consistencycheck/result/RecordTableInventoryCheckCalculatedResultTest.java
@@ -87,9 +87,9 @@ class RecordTableInventoryCheckCalculatedResultTest {
@Test
void assertNotEqualsWithDifferentRandomColumnValue() {
- Map<String, Object> record = buildFixedFullTypeRecord();
- RecordTableInventoryCheckCalculatedResult result1 = new
RecordTableInventoryCheckCalculatedResult(1000,
Collections.singletonList(record));
- record.forEach((key, value) -> {
+ Map<String, Object> recordMap = buildFixedFullTypeRecord();
+ RecordTableInventoryCheckCalculatedResult result1 = new
RecordTableInventoryCheckCalculatedResult(1000,
Collections.singletonList(recordMap));
+ recordMap.forEach((key, value) -> {
RecordTableInventoryCheckCalculatedResult result2 = new
RecordTableInventoryCheckCalculatedResult(
1000,
Collections.singletonList(ConsistencyCheckDataBuilder.modifyColumnValueRandomly(buildFixedFullTypeRecord(),
key)));
assertThat(result1, not(result2));
diff --git
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/MySQLBinlogClientTest.java
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/MySQLBinlogClientTest.java
index da8e7d72665..794dfa1f574 100644
---
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/MySQLBinlogClientTest.java
+++
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/MySQLBinlogClientTest.java
@@ -59,7 +59,9 @@ import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
+import org.mockito.stubbing.Answer;
+import javax.annotation.Nullable;
import java.net.InetSocketAddress;
import java.sql.SQLException;
import java.util.Arrays;
@@ -138,7 +140,6 @@ class MySQLBinlogClientTest {
void assertConnect() throws Exception {
MySQLServerVersion expected = new MySQLServerVersion("5.5.0-log");
AtomicReference<ChannelInitializer<SocketChannel>> initializer = new
AtomicReference<>();
- mockChannelResponse(expected);
try (MockedConstruction<Bootstrap> ignored =
mockConstruction(Bootstrap.class, (mock, context) -> {
when(mock.group(any())).thenReturn(mock);
when(mock.channel(any())).thenReturn(mock);
@@ -147,7 +148,7 @@ class MySQLBinlogClientTest {
initializer.set(invocation.getArgument(0));
return mock;
});
- when(mock.connect(anyString(),
anyInt())).thenReturn(channelFuture);
+ when(mock.connect(anyString(),
anyInt())).thenAnswer(mockChannelResponse(expected));
})) {
client.connect();
}
@@ -160,10 +161,19 @@ class MySQLBinlogClientTest {
client.closeChannel(true);
}
+ private Answer<ChannelFuture> mockChannelResponse(@Nullable final Object
response) {
+ return invocation -> {
+ @SuppressWarnings("unchecked")
+ Promise<Object> callback = (Promise<Object>)
Plugins.getMemberAccessor().get(MySQLBinlogClient.class.getDeclaredField("responseCallback"),
client);
+ callback.setSuccess(response);
+ return channelFuture;
+ };
+ }
+
@Test
void assertExecuteSuccess() {
prepareClientChannel();
- mockChannelResponse(new MySQLOKPacket(0));
+ doAnswer(mockChannelResponse(new
MySQLOKPacket(0))).when(channel).writeAndFlush(any(MySQLComQueryPacket.class));
assertTrue(client.execute("sql"));
verify(channel).writeAndFlush(any(MySQLComQueryPacket.class));
}
@@ -171,7 +181,7 @@ class MySQLBinlogClientTest {
@Test
void assertNullResponseHandling() {
prepareClientChannel();
- mockChannelResponse(null);
+
doAnswer(mockChannelResponse(null)).when(channel).writeAndFlush(any(MySQLComQueryPacket.class));
assertFalse(client.execute("sql"));
PipelineInternalException updateException =
assertThrows(PipelineInternalException.class, () ->
client.executeUpdate("update"));
assertThat(updateException.getMessage(), is("Could not get MySQL OK
packet"));
@@ -182,7 +192,7 @@ class MySQLBinlogClientTest {
@Test
void assertExecuteThrowsWhenErrorResponse() {
prepareClientChannel();
- mockChannelResponse(new MySQLErrPacket(new SQLException("err",
"state", 1)));
+ doAnswer(mockChannelResponse(new MySQLErrPacket(new
SQLException("err", "state",
1)))).when(channel).writeAndFlush(any(MySQLComQueryPacket.class));
PipelineInternalException ex =
assertThrows(PipelineInternalException.class, () -> client.execute("sql"));
assertThat(ex.getMessage(), is("err"));
}
@@ -190,7 +200,7 @@ class MySQLBinlogClientTest {
@Test
void assertExecuteQueryThrowsWhenUnexpectedResponse() {
prepareClientChannel();
- mockChannelResponse(new Object());
+ doAnswer(mockChannelResponse(new
Object())).when(channel).writeAndFlush(any(MySQLComQueryPacket.class));
PipelineInternalException ex =
assertThrows(PipelineInternalException.class, () ->
client.executeQuery("query"));
assertThat(ex.getMessage(), is("unexpected response type"));
}
@@ -264,9 +274,7 @@ class MySQLBinlogClientTest {
client.subscribe("binlog-000002", 8L);
ArgumentCaptor<ChannelHandler> captor =
ArgumentCaptor.forClass(ChannelHandler.class);
verify(pipeline, times(4)).addLast(captor.capture());
- List<Integer> checksumLengths = captor.getAllValues().stream()
- .filter(each -> each instanceof MySQLBinlogEventPacketDecoder)
- .map(each -> getChecksumLength((MySQLBinlogEventPacketDecoder)
each))
+ List<Integer> checksumLengths =
captor.getAllValues().stream().filter(MySQLBinlogEventPacketDecoder.class::isInstance).map(each
-> getChecksumLength((MySQLBinlogEventPacketDecoder) each))
.collect(Collectors.toList());
assertThat(checksumLengths, is(Arrays.asList(0, 4)));
}
@@ -303,9 +311,8 @@ class MySQLBinlogClientTest {
client.subscribe("binlog-000004", 16L);
ArgumentCaptor<ChannelHandler> captor =
ArgumentCaptor.forClass(ChannelHandler.class);
verify(pipeline, times(2)).addLast(captor.capture());
- MySQLBinlogEventPacketDecoder decoder = captor.getAllValues().stream()
- .filter(each -> each instanceof MySQLBinlogEventPacketDecoder)
-
.map(MySQLBinlogEventPacketDecoder.class::cast).findFirst().orElseThrow(IllegalStateException::new);
+ MySQLBinlogEventPacketDecoder decoder =
captor.getAllValues().stream().filter(MySQLBinlogEventPacketDecoder.class::isInstance).map(MySQLBinlogEventPacketDecoder.class::cast).findFirst()
+ .orElseThrow(IllegalStateException::new);
assertThat(getChecksumLength(decoder), is(0));
}
@@ -359,7 +366,6 @@ class MySQLBinlogClientTest {
SocketChannel socketChannel = mock(SocketChannel.class,
RETURNS_DEEP_STUBS);
when(socketChannel.pipeline()).thenReturn(pipeline);
when(channelFuture.channel()).thenReturn(channel);
- mockChannelResponse(new MySQLServerVersion("5.5.0-log"));
try (MockedConstruction<Bootstrap> ignored =
mockConstruction(Bootstrap.class, (mock, context) -> {
when(mock.group(any())).thenReturn(mock);
when(mock.channel(any())).thenReturn(mock);
@@ -368,7 +374,7 @@ class MySQLBinlogClientTest {
initializer.set(invocation.getArgument(0));
return mock;
});
- when(mock.connect(anyString(),
anyInt())).thenReturn(channelFuture);
+ when(mock.connect(anyString(),
anyInt())).thenAnswer(mockChannelResponse(new MySQLServerVersion("5.5.0-log")));
})) {
client.connect();
}
@@ -379,9 +385,8 @@ class MySQLBinlogClientTest {
initializer.get().channelRegistered(context);
ArgumentCaptor<ChannelHandler> captor =
ArgumentCaptor.forClass(ChannelHandler.class);
verify(pipeline, times(7)).addLast(captor.capture());
- ChannelInboundHandlerAdapter handler = captor.getAllValues().stream()
- .filter(each ->
"MySQLCommandResponseHandler".equals(each.getClass().getSimpleName()))
- .map(each -> (ChannelInboundHandlerAdapter)
each).findFirst().orElseThrow(IllegalStateException::new);
+ ChannelInboundHandlerAdapter handler =
captor.getAllValues().stream().filter(each ->
"MySQLCommandResponseHandler".equals(each.getClass().getSimpleName()))
+
.map(ChannelInboundHandlerAdapter.class::cast).findFirst().orElseThrow(IllegalStateException::new);
Promise<Object> callback = new DefaultPromise<>(eventLoopGroup.next());
setResponseCallback(callback);
handler.channelRead(mock(ChannelHandlerContext.class), new Object());
@@ -439,26 +444,4 @@ class MySQLBinlogClientTest {
MySQLBinlogContext binlogContext = (MySQLBinlogContext)
Plugins.getMemberAccessor().get(MySQLBinlogEventPacketDecoder.class.getDeclaredField("binlogContext"),
decoder);
return binlogContext.getChecksumLength();
}
-
- private void mockChannelResponse(final Object response) {
- new Thread(() -> mockChannelResponseInThread(response)).start();
- }
-
- @SneakyThrows(InterruptedException.class)
- @SuppressWarnings("unchecked")
- private void mockChannelResponseInThread(final Object response) {
- long startMillis = System.currentTimeMillis();
- do {
- Promise<Object> callback;
- try {
- callback = (Promise<Object>)
Plugins.getMemberAccessor().get(MySQLBinlogClient.class.getDeclaredField("responseCallback"),
client);
- } catch (final ReflectiveOperationException ex) {
- throw new RuntimeException(ex);
- }
- if (null != callback && !callback.isDone()) {
- callback.setSuccess(response);
- }
- TimeUnit.MILLISECONDS.sleep(100L);
- } while (System.currentTimeMillis() - startMillis <=
TimeUnit.SECONDS.toMillis(20L));
- }
}
diff --git
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/PasswordEncryptionTest.java
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/PasswordEncryptionTest.java
index 252d44edba8..a64896d188c 100644
---
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/PasswordEncryptionTest.java
+++
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/PasswordEncryptionTest.java
@@ -68,14 +68,16 @@ class PasswordEncryptionTest {
}
private String mockPublicKey() {
- return "-----BEGIN PUBLIC KEY-----\n"
- +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1ealW/qDdArgzCMnE5Cz\n"
- +
"6FHskcTTweMncG6A124rn2DFBZvmZNyTBiFLM7Scp3jFSyqpw2xg6aaKcM9eCaCf\n"
- +
"nJg4A18HgpAxrFnijVADgsNrHlSniNe2AsN+/uLpEtWezVLr823WvPLgMKQMRWfy\n"
- +
"UD24rpoC2Leir+rvyG8xbDHX65NPGxPFGrlwo7kbUqrgQlYOC3x64C4/S/6K6EZQ\n"
- +
"XaUZwZHdXjEme0/D8p8KBXdMipanZXwHdL+LOBSACj3/FwHn+6oZO2k02g80uofs\n"
- +
"zFdWMjpPVqVCqe85GRFzEY73wDYEItl0d+9a9OV3FFZqVgC2FLk3cD5qajPtyo6v\n"
- + "UQIDAQAB\n"
- + "-----END PUBLIC KEY-----\n";
+ return """
+ -----BEGIN PUBLIC KEY-----
+
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1ealW/qDdArgzCMnE5Cz
+
6FHskcTTweMncG6A124rn2DFBZvmZNyTBiFLM7Scp3jFSyqpw2xg6aaKcM9eCaCf
+
nJg4A18HgpAxrFnijVADgsNrHlSniNe2AsN+/uLpEtWezVLr823WvPLgMKQMRWfy
+
UD24rpoC2Leir+rvyG8xbDHX65NPGxPFGrlwo7kbUqrgQlYOC3x64C4/S/6K6EZQ
+
XaUZwZHdXjEme0/D8p8KBXdMipanZXwHdL+LOBSACj3/FwHn+6oZO2k02g80uofs
+
zFdWMjpPVqVCqe85GRFzEY73wDYEItl0d+9a9OV3FFZqVgC2FLk3cD5qajPtyo6v
+ UQIDAQAB
+ -----END PUBLIC KEY-----
+ """;
}
}
diff --git
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLNegotiateHandlerTest.java
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLNegotiateHandlerTest.java
index 2351f4c23d8..c5257344207 100644
---
a/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLNegotiateHandlerTest.java
+++
b/kernel/data-pipeline/dialect/mysql/src/test/java/org/apache/shardingsphere/data/pipeline/mysql/ingest/incremental/client/netty/MySQLNegotiateHandlerTest.java
@@ -172,10 +172,12 @@ class MySQLNegotiateHandlerTest {
}
private String publicKey() {
- return "-----BEGIN PUBLIC KEY-----\n"
- +
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eq+i+GtqR4344d18PT9bjK5YfX/8r\n"
- +
"O8uRAZ3kKQEiC5EvhczHxVn9Yx8RJWb1x1oGf4bm/FYnGV8eK3opg+cCAwEAAQ==\n"
- + "-----END PUBLIC KEY-----";
+ return """
+ -----BEGIN PUBLIC KEY-----
+
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eq+i+GtqR4344d18PT9bjK5YfX/8r
+
O8uRAZ3kKQEiC5EvhczHxVn9Yx8RJWb1x1oGf4bm/FYnGV8eK3opg+cCAwEAAQ==
+ -----END PUBLIC KEY-----\
+ """;
}
private MySQLAuthSwitchResponsePacket captureAuthSwitchResponse() {
diff --git
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/column/PostgreSQLColumnPropertiesAppenderTest.java
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/column/PostgreSQLColumnPropertiesAppenderTest.java
index 314bb7cf7ff..42915600859 100644
---
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/column/PostgreSQLColumnPropertiesAppenderTest.java
+++
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/column/PostgreSQLColumnPropertiesAppenderTest.java
@@ -22,6 +22,8 @@ import
org.apache.shardingsphere.data.pipeline.postgresql.sqlbuilder.ddl.Postgre
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -281,32 +283,13 @@ class PostgreSQLColumnPropertiesAppenderTest {
assertNull(singleColumn.get("seqmax"));
}
- @Test
- void assertNormalizeSequenceValuesRemovesInvalidFormat() {
- Map<String, Object> column = createTextColumnWithName("id");
- column.put("attidentity", "a");
- column.put("colconstype", "i");
- column.put("seqmax", ", ,");
- Map<String, Object> singleColumn = appendWithSingleColumn(column);
- assertFalse(singleColumn.containsKey("seqmax"));
- }
-
- @Test
- void assertNormalizeSequenceValuesRemovesMultipleSigns() {
- Map<String, Object> column = createTextColumnWithName("id");
- column.put("attidentity", "a");
- column.put("colconstype", "i");
- column.put("seqmax", "+-123");
- Map<String, Object> singleColumn = appendWithSingleColumn(column);
- assertFalse(singleColumn.containsKey("seqmax"));
- }
-
- @Test
- void assertNormalizeSequenceValuesRemovesOverflowValue() {
+ @ParameterizedTest(name = "{0}")
+ @ValueSource(strings = {", ,", "+-123", "999999999999999999999999"})
+ void assertNormalizeSequenceValuesRemovesInvalidValues(final String value)
{
Map<String, Object> column = createTextColumnWithName("id");
column.put("attidentity", "a");
column.put("colconstype", "i");
- column.put("seqmax", "999999999999999999999999");
+ column.put("seqmax", value);
Map<String, Object> singleColumn = appendWithSingleColumn(column);
assertFalse(singleColumn.containsKey("seqmax"));
}
diff --git
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/constraints/PostgreSQLConstraintsPropertiesAppenderTest.java
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/constraints/PostgreSQLConstraintsPropertiesAppenderTest.java
index 332539def5b..2c392b41276 100644
---
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/constraints/PostgreSQLConstraintsPropertiesAppenderTest.java
+++
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/constraints/PostgreSQLConstraintsPropertiesAppenderTest.java
@@ -31,7 +31,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -59,8 +58,8 @@ class PostgreSQLConstraintsPropertiesAppenderTest {
Collection<Map<String, Object>> primaryKeys = (Collection<Map<String,
Object>>) context.get("primary_key");
assertThat(primaryKeys.size(), is(1));
Map<String, Object> primaryKey = primaryKeys.iterator().next();
- List<String> primaryColumns = ((Collection<Map<String, Object>>)
primaryKey.get("columns")).stream().map(each -> (String)
each.get("column")).collect(Collectors.toList());
- assertThat(primaryColumns, is(Arrays.asList("id", "name")));
+ Collection<String> actualPrimaryColumns = ((Collection<Map<String,
Object>>) primaryKey.get("columns")).stream().map(each -> (String)
each.get("column")).toList();
+ assertThat(actualPrimaryColumns, is(Arrays.asList("id", "name")));
assertThat(primaryKey.get("include"),
is(Collections.singletonList("include_col")));
Collection<Map<String, Object>> uniqueConstraints =
(Collection<Map<String, Object>>) context.get("unique_constraint");
assertThat(uniqueConstraints.size(), is(1));
@@ -86,10 +85,10 @@ class PostgreSQLConstraintsPropertiesAppenderTest {
Collection<Map<String, Object>> exclusionConstraints =
(Collection<Map<String, Object>>) context.get("exclude_constraint");
assertThat(exclusionConstraints.size(), is(1));
Map<String, Object> exclusionConstraint =
exclusionConstraints.iterator().next();
- List<Boolean> orders = ((Collection<Map<String, Object>>)
exclusionConstraint.get("columns")).stream().map(each -> (Boolean)
each.get("order")).collect(Collectors.toList());
- List<Boolean> nullsOrders = ((Collection<Map<String, Object>>)
exclusionConstraint.get("columns")).stream().map(each -> (Boolean)
each.get("nulls_order")).collect(Collectors.toList());
- assertThat(orders, is(Arrays.asList(true, false)));
- assertThat(nullsOrders, is(Arrays.asList(false, true)));
+ Collection<Boolean> actualOrders = ((Collection<Map<String, Object>>)
exclusionConstraint.get("columns")).stream().map(each -> (Boolean)
each.get("order")).toList();
+ Collection<Boolean> actualNullsOrders = ((Collection<Map<String,
Object>>) exclusionConstraint.get("columns")).stream().map(each -> (Boolean)
each.get("nulls_order")).toList();
+ assertThat(actualOrders, is(Arrays.asList(true, false)));
+ assertThat(actualNullsOrders, is(Arrays.asList(false, true)));
assertThat(exclusionConstraint.get("include"),
is(Collections.singletonList("excl_inc")));
}
diff --git
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/index/PostgreSQLIndexSQLGeneratorTest.java
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/index/PostgreSQLIndexSQLGeneratorTest.java
index 6dabec87e54..fe3561f3ad7 100644
---
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/index/PostgreSQLIndexSQLGeneratorTest.java
+++
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/index/PostgreSQLIndexSQLGeneratorTest.java
@@ -64,7 +64,7 @@ class PostgreSQLIndexSQLGeneratorTest {
when(templateExecutor.getMajorVersion()).thenReturn(10);
when(templateExecutor.executeByTemplate(anyMap(),
eq("component/indexes/%s/nodes.ftl"))).thenReturn(Collections.singletonList(createIndexNode(2L,
false)));
when(templateExecutor.executeByTemplate(anyMap(),
eq("component/indexes/%s/properties.ftl"))).thenReturn(Collections.singletonList(createNonBtreeIndexProps()));
-
when(templateExecutor.executeByTemplate(eq(Collections.singletonMap("idx",
2L)), eq("component/indexes/%s/column_details.ftl")))
+
when(templateExecutor.executeByTemplate(Collections.singletonMap("idx", 2L),
"component/indexes/%s/column_details.ftl"))
.thenReturn(Collections.singletonList(createColumnDetail("foo_col",
"foo_collation", "foo_op_class", null)));
PostgreSQLIndexSQLGenerator generator = new
PostgreSQLIndexSQLGenerator(mock(Connection.class), 10, 0);
Plugins.getMemberAccessor().set(PostgreSQLIndexSQLGenerator.class.getDeclaredField("templateExecutor"),
generator, templateExecutor);
diff --git
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/table/PostgreSQLTablePropertiesLoaderTest.java
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/table/PostgreSQLTablePropertiesLoaderTest.java
index a84a7053e0c..935a9ef8221 100644
---
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/table/PostgreSQLTablePropertiesLoaderTest.java
+++
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/ddl/table/PostgreSQLTablePropertiesLoaderTest.java
@@ -38,11 +38,9 @@ class PostgreSQLTablePropertiesLoaderTest {
Connection connection = mock(Connection.class, RETURNS_DEEP_STUBS);
when(connection.getCatalog()).thenReturn("foo_db");
ResultSet fetchDatabaseIdResultSet = mockFetchDatabaseIdResultSet();
- when(connection.createStatement().executeQuery("\n" + "SELECT oid AS
did, datlastsysoid FROM pg_catalog.pg_database WHERE datname = 'foo_db';" +
"\n"))
- .thenReturn(fetchDatabaseIdResultSet);
+ when(connection.createStatement().executeQuery("\nSELECT oid AS did,
datlastsysoid FROM pg_catalog.pg_database WHERE datname =
'foo_db';\n")).thenReturn(fetchDatabaseIdResultSet);
ResultSet fetchSchemaIdResultSet = mockFetchSchemaIdResultSet();
- when(connection.createStatement().executeQuery("\n" + "SELECT oid AS
scid FROM pg_catalog.pg_namespace WHERE nspname = 'foo_schema';" + "\n"))
- .thenReturn(fetchSchemaIdResultSet);
+ when(connection.createStatement().executeQuery("\nSELECT oid AS scid
FROM pg_catalog.pg_namespace WHERE nspname =
'foo_schema';\n")).thenReturn(fetchSchemaIdResultSet);
Map<String, Object> actual = new
PostgreSQLTablePropertiesLoader(connection, "foo_tbl", "foo_schema", 12,
0).load();
assertThat(actual.size(), is(7));
assertThat(actual.get("did"), is(1));
diff --git
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/template/PostgreSQLPipelineFreemarkerManagerTest.java
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/template/PostgreSQLPipelineFreemarkerManagerTest.java
index 7d8d53c34d8..845d75367d4 100644
---
a/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/template/PostgreSQLPipelineFreemarkerManagerTest.java
+++
b/kernel/data-pipeline/dialect/postgresql/src/test/java/org/apache/shardingsphere/data/pipeline/postgresql/sqlbuilder/template/PostgreSQLPipelineFreemarkerManagerTest.java
@@ -36,7 +36,7 @@ class PostgreSQLPipelineFreemarkerManagerTest {
@Test
void assertGetSQLByDefaultVersion() {
String actual =
PostgreSQLPipelineFreemarkerManager.getSQLByVersion(Collections.singletonMap("databaseName",
"foo_db"), "component/table/%s/get_database_id.ftl", 10, 0);
- String expected = "\n" + "SELECT oid AS did, datlastsysoid FROM
pg_catalog.pg_database WHERE datname = 'foo_db';" + "\n";
+ String expected = "\nSELECT oid AS did, datlastsysoid FROM
pg_catalog.pg_database WHERE datname = 'foo_db';\n";
assertThat(actual, is(expected));
}
diff --git
a/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/planner/builder/SQLFederationPlannerBuilderTest.java
b/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/planner/builder/SQLFederationPlannerBuilderTest.java
index bb5903bbb83..2edcd2d44b9 100644
---
a/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/planner/builder/SQLFederationPlannerBuilderTest.java
+++
b/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/planner/builder/SQLFederationPlannerBuilderTest.java
@@ -50,7 +50,7 @@ class SQLFederationPlannerBuilderTest {
assertThat(actual.getRelTraitDefs(),
hasItem(ConventionTraitDef.INSTANCE));
assertThat(actual.getRelTraitDefs(),
hasItem(RelCollationTraitDef.INSTANCE));
assertTrue(actual.getRules().contains(EnumerableRules.ENUMERABLE_JOIN_RULE));
- assertTrue(actual.getRules().stream().anyMatch(each -> each instanceof
ConverterRule));
+
assertTrue(actual.getRules().stream().anyMatch(ConverterRule.class::isInstance));
}
@Test
diff --git
a/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/sql/ast/converter/segment/expression/impl/LiteralExpressionConverterTest.java
b/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/sql/ast/converter/segment/expression/impl/LiteralExpressionConverterTest.java
index 42c0befb03d..7d43d8c701c 100644
---
a/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/sql/ast/converter/segment/expression/impl/LiteralExpressionConverterTest.java
+++
b/kernel/sql-federation/compiler/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/sql/ast/converter/segment/expression/impl/LiteralExpressionConverterTest.java
@@ -78,7 +78,7 @@ class LiteralExpressionConverterTest {
@Test
void assertConvertApproximateNumber() {
- SqlNumericLiteral actual = (SqlNumericLiteral)
LiteralExpressionConverter.convert(new LiteralExpressionSegment(0, 0, new
Float("1.5")), null).orElse(null);
+ SqlNumericLiteral actual = (SqlNumericLiteral)
LiteralExpressionConverter.convert(new LiteralExpressionSegment(0, 0,
Float.valueOf("1.5")), null).orElse(null);
assertNotNull(actual);
assertFalse(actual.isExact());
}
diff --git
a/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/CalciteSQLFederationExecutorTest.java
b/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/CalciteSQLFederationExecutorTest.java
index 1101fcc3684..eaa7825dd18 100644
---
a/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/CalciteSQLFederationExecutorTest.java
+++
b/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/CalciteSQLFederationExecutorTest.java
@@ -88,6 +88,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -312,7 +313,7 @@ class CalciteSQLFederationExecutorTest {
(mock, context) ->
when(mock.compile(any(ExecutionPlanCacheKey.class),
eq(false))).thenReturn(executionPlan));
MockedStatic<RelOptUtil> relOptUtil =
mockStatic(RelOptUtil.class)) {
relOptUtil.when(() -> RelOptUtil.toString(any(RelNode.class),
eq(SqlExplainLevel.ALL_ATTRIBUTES))).thenReturn("plan");
- executor.executeQuery(prepareEngine, callback, federationContext);
+ assertThat(executor.executeQuery(prepareEngine, callback,
federationContext), sameInstance(resultSet));
}
}
diff --git
a/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/processor/SQLFederationProcessorTest.java
b/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/processor/SQLFederationProcessorTest.java
index 5d5fe424a91..7ab7ae41761 100644
---
a/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/processor/SQLFederationProcessorTest.java
+++
b/kernel/sql-federation/provider/calcite/src/test/java/org/apache/shardingsphere/sqlfederation/provider/calcite/processor/SQLFederationProcessorTest.java
@@ -65,6 +65,7 @@ import
org.apache.shardingsphere.sqlfederation.compiler.metadata.schema.SQLFeder
import
org.apache.shardingsphere.sqlfederation.compiler.rel.converter.SQLFederationRelConverter;
import org.apache.shardingsphere.sqlfederation.context.SQLFederationContext;
import
org.apache.shardingsphere.sqlfederation.executor.context.ExecutorBindContext;
+import
org.apache.shardingsphere.sqlfederation.executor.context.ExecutorContext;
import
org.apache.shardingsphere.sqlfederation.provider.calcite.resultset.SQLFederationResultSet;
import
org.apache.shardingsphere.sqlfederation.resultset.converter.DialectSQLFederationColumnTypeConverter;
import org.junit.jupiter.api.BeforeEach;
@@ -79,7 +80,6 @@ import org.mockito.MockedStatic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -88,9 +88,11 @@ import java.util.Optional;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -246,15 +248,18 @@ class SQLFederationProcessorTest {
Enumerable<Object> enumerable = mock(Enumerable.class);
when(enumerable.enumerator()).thenReturn(enumerator);
when(bindable.bind(any())).thenReturn(enumerable);
+ ArgumentCaptor<DataContext> dataContextCaptor =
ArgumentCaptor.forClass(DataContext.class);
try (
MockedStatic<SQLFederationExecutionPlan> mockedExecutionPlan =
mockStatic(SQLFederationExecutionPlan.class);
MockedStatic<DatabaseTypedSPILoader> mockedSpiLoader =
mockStatic(DatabaseTypedSPILoader.class)) {
mockedExecutionPlan.when(() ->
SQLFederationExecutionPlan.toBindable(physicalPlan, Collections.emptyMap(),
null, Prefer.ARRAY)).thenReturn(bindable);
mockedSpiLoader.when(() -> DatabaseTypedSPILoader
.getService(eq(DialectSQLFederationColumnTypeConverter.class),
any(DatabaseType.class))).thenReturn(mock(DialectSQLFederationColumnTypeConverter.class));
- ResultSet result = processor.executePlan(executionPlan, converter,
federationContext, rootSchema);
- ((SQLFederationResultSet) result).close();
+ ResultSet actual = processor.executePlan(executionPlan, converter,
federationContext, rootSchema);
+ ((SQLFederationResultSet) actual).close();
}
+ verify(bindable).bind(dataContextCaptor.capture());
+ assertTrue(((ExecutorBindContext)
dataContextCaptor.getValue()).getParameters().isEmpty());
}
@ParameterizedTest(name = "{0}")
@@ -335,47 +340,64 @@ class SQLFederationProcessorTest {
}
}
- @SuppressWarnings("unchecked")
@Test
- void assertExecutePlanPreviewAndNonPreview() {
- DriverExecutionPrepareEngine<JDBCExecutionUnit, Connection>
prepareEngine = mock(DriverExecutionPrepareEngine.class);
- JDBCExecutorCallback<? extends ExecuteResult> callback =
mock(JDBCExecutorCallback.class);
- SQLFederationContext federationContext =
createFederationContext(false, null);
- Collection<ExecutionUnit> previewExecutionUnits =
federationContext.getPreviewExecutionUnits();
- previewExecutionUnits.clear();
- CompilerContext compilerContext = mock(CompilerContext.class);
+ void assertExecutePlanWithPreview() {
+ SQLFederationContext federationContext = createFederationContext(true,
null);
SchemaPlus rootSchema = mockSchemaTreeWithTable();
DialectSchemaOption schemaOption = mock(DialectSchemaOption.class);
when(schemaOption.getDefaultSchema()).thenReturn(Optional.of(schemaName));
+ SQLFederationExecutionPlan executionPlan = createExecutionPlan();
+ SQLFederationRelConverter converter =
mock(SQLFederationRelConverter.class);
+ Bindable<Object> bindable = mockBindable();
+ ExecutionUnit expected = mock(ExecutionUnit.class);
try (
- MockedConstruction<DatabaseTypeRegistry> ignored =
mockConstruction(DatabaseTypeRegistry.class, (constructed, context) -> {
+ MockedConstruction<ExecutorContext> ignoredExecutorContext =
mockConstruction(ExecutorContext.class,
+ (constructed, context) ->
when(constructed.getPreviewExecutionUnits()).thenReturn(Collections.singleton(expected)));
+ MockedConstruction<DatabaseTypeRegistry> ignoredRegistry =
mockConstruction(DatabaseTypeRegistry.class, (constructed, context) -> {
DialectDatabaseMetaData dialectMeta =
mock(DialectDatabaseMetaData.class);
when(dialectMeta.getSchemaOption()).thenReturn(schemaOption);
when(constructed.getDialectDatabaseMetaData()).thenReturn(dialectMeta);
- })) {
- processor.prepare(prepareEngine, callback, databaseName,
schemaName, federationContext, compilerContext, rootSchema);
+ });
+ MockedStatic<SQLFederationExecutionPlan> mockedExecutionPlan =
mockStatic(SQLFederationExecutionPlan.class);
+ MockedStatic<DatabaseTypedSPILoader> mockedSpiLoader =
mockStatic(DatabaseTypedSPILoader.class)) {
+ processor.prepare(mock(), mock(), databaseName, schemaName,
federationContext, mock(CompilerContext.class), rootSchema);
+ mockedExecutionPlan.when(() ->
SQLFederationExecutionPlan.toBindable(executionPlan.getPhysicalPlan(),
Collections.emptyMap(), null, Prefer.ARRAY)).thenReturn(bindable);
+ mockedSpiLoader.when(() -> DatabaseTypedSPILoader
+
.getService(eq(DialectSQLFederationColumnTypeConverter.class),
any(DatabaseType.class))).thenReturn(mock(DialectSQLFederationColumnTypeConverter.class));
+ ResultSet actual = processor.executePlan(executionPlan, converter,
federationContext, rootSchema);
+ ((SQLFederationResultSet) actual).close();
}
- SQLFederationExecutionPlan executionPlan =
mock(SQLFederationExecutionPlan.class);
- EnumerableRel physicalPlan = mock(EnumerableRel.class);
- when(executionPlan.getPhysicalPlan()).thenReturn(physicalPlan);
-
when(executionPlan.getResultColumnType()).thenReturn(mock(RelDataType.class));
+ assertThat(federationContext.getPreviewExecutionUnits(),
contains(expected));
+ }
+
+ @Test
+ void assertExecutePlanWithoutPreview() {
+ SQLFederationContext federationContext =
createFederationContext(false, null);
+ SchemaPlus rootSchema = mockSchemaTreeWithTable();
+ DialectSchemaOption schemaOption = mock(DialectSchemaOption.class);
+
when(schemaOption.getDefaultSchema()).thenReturn(Optional.of(schemaName));
+ SQLFederationExecutionPlan executionPlan = createExecutionPlan();
SQLFederationRelConverter converter =
mock(SQLFederationRelConverter.class);
- Bindable<Object> bindable = mock(Bindable.class);
- Enumerator<Object> enumerator = mock(Enumerator.class);
- Enumerable<Object> enumerable = mock(Enumerable.class);
- when(enumerable.enumerator()).thenReturn(enumerator);
- when(bindable.bind(any())).thenReturn(enumerable);
+ Bindable<Object> bindable = mockBindable();
+ ExecutionUnit expected = mock(ExecutionUnit.class);
try (
+ MockedConstruction<ExecutorContext> ignoredExecutorContext =
mockConstruction(ExecutorContext.class,
+ (constructed, context) ->
when(constructed.getPreviewExecutionUnits()).thenReturn(Collections.singleton(expected)));
+ MockedConstruction<DatabaseTypeRegistry> ignoredRegistry =
mockConstruction(DatabaseTypeRegistry.class, (constructed, context) -> {
+ DialectDatabaseMetaData dialectMeta =
mock(DialectDatabaseMetaData.class);
+
when(dialectMeta.getSchemaOption()).thenReturn(schemaOption);
+
when(constructed.getDialectDatabaseMetaData()).thenReturn(dialectMeta);
+ });
MockedStatic<SQLFederationExecutionPlan> mockedExecutionPlan =
mockStatic(SQLFederationExecutionPlan.class);
MockedStatic<DatabaseTypedSPILoader> mockedSpiLoader =
mockStatic(DatabaseTypedSPILoader.class)) {
- mockedExecutionPlan.when(() ->
SQLFederationExecutionPlan.toBindable(physicalPlan, Collections.emptyMap(),
null, Prefer.ARRAY)).thenReturn(bindable);
+ processor.prepare(mock(), mock(), databaseName, schemaName,
federationContext, mock(CompilerContext.class), rootSchema);
+ mockedExecutionPlan.when(() ->
SQLFederationExecutionPlan.toBindable(executionPlan.getPhysicalPlan(),
Collections.emptyMap(), null, Prefer.ARRAY)).thenReturn(bindable);
mockedSpiLoader.when(() -> DatabaseTypedSPILoader
.getService(eq(DialectSQLFederationColumnTypeConverter.class),
any(DatabaseType.class))).thenReturn(mock(DialectSQLFederationColumnTypeConverter.class));
- ResultSet previewResult = processor.executePlan(executionPlan,
converter, federationContext, rootSchema);
- ((SQLFederationResultSet) previewResult).close();
- ResultSet normalResult = processor.executePlan(executionPlan,
converter, federationContext, rootSchema);
- ((SQLFederationResultSet) normalResult).close();
+ ResultSet actual = processor.executePlan(executionPlan, converter,
federationContext, rootSchema);
+ ((SQLFederationResultSet) actual).close();
}
+ assertTrue(federationContext.getPreviewExecutionUnits().isEmpty());
}
@Test
diff --git
a/kernel/transaction/core/src/test/java/org/apache/shardingsphere/transaction/rule/TransactionRuleTest.java
b/kernel/transaction/core/src/test/java/org/apache/shardingsphere/transaction/rule/TransactionRuleTest.java
index e77530dc245..0b5923c5e24 100644
---
a/kernel/transaction/core/src/test/java/org/apache/shardingsphere/transaction/rule/TransactionRuleTest.java
+++
b/kernel/transaction/core/src/test/java/org/apache/shardingsphere/transaction/rule/TransactionRuleTest.java
@@ -148,22 +148,9 @@ class TransactionRuleTest {
private ShardingSphereDatabase createAddDatabase() {
ShardingSphereDatabase result = mock(ShardingSphereDatabase.class);
- ResourceMetaData resourceMetaData = createAddResourceMetaData();
+ ResourceMetaData resourceMetaData = createResourceMetaData();
when(result.getResourceMetaData()).thenReturn(resourceMetaData);
when(result.getName()).thenReturn(BAR_DB);
return result;
}
-
- private ResourceMetaData createAddResourceMetaData() {
- Map<String, StorageUnit> storageUnits = new HashMap<>(2, 1F);
- DataSourcePoolProperties dataSourcePoolProps0 =
mock(DataSourcePoolProperties.class, RETURNS_DEEP_STUBS);
-
when(dataSourcePoolProps0.getConnectionPropertySynonyms().getStandardProperties()).thenReturn(ImmutableMap.of("url",
"jdbc:mock://127.0.0.1/ds_0", "username", "test"));
- storageUnits.put("ds_0", new StorageUnit(mock(StorageNode.class),
dataSourcePoolProps0, new MockedDataSource()));
- DataSourcePoolProperties dataSourcePoolProps1 =
mock(DataSourcePoolProperties.class, RETURNS_DEEP_STUBS);
-
when(dataSourcePoolProps1.getConnectionPropertySynonyms().getStandardProperties()).thenReturn(ImmutableMap.of("url",
"jdbc:mock://127.0.0.1/ds_1", "username", "test"));
- storageUnits.put("ds_1", new StorageUnit(mock(StorageNode.class),
dataSourcePoolProps1, new MockedDataSource()));
- ResourceMetaData result = mock(ResourceMetaData.class,
RETURNS_DEEP_STUBS);
- when(result.getStorageUnits()).thenReturn(storageUnits);
- return result;
- }
}
diff --git
a/kernel/transaction/type/xa/core/src/test/java/org/apache/shardingsphere/transaction/xa/jta/connection/dialect/FirebirdXAConnectionWrapperTest.java
b/kernel/transaction/type/xa/core/src/test/java/org/apache/shardingsphere/transaction/xa/jta/connection/dialect/FirebirdXAConnectionWrapperTest.java
index cdc10605145..737b1e4843b 100644
---
a/kernel/transaction/type/xa/core/src/test/java/org/apache/shardingsphere/transaction/xa/jta/connection/dialect/FirebirdXAConnectionWrapperTest.java
+++
b/kernel/transaction/type/xa/core/src/test/java/org/apache/shardingsphere/transaction/xa/jta/connection/dialect/FirebirdXAConnectionWrapperTest.java
@@ -33,11 +33,14 @@ import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
+import javax.transaction.xa.XAResource;
import java.sql.Connection;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isA;
+import static org.hamcrest.Matchers.sameInstance;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -47,10 +50,13 @@ class FirebirdXAConnectionWrapperTest {
@Test
void assertWrap() throws SQLException {
- XAConnection actual =
DatabaseTypedSPILoader.getService(XAConnectionWrapper.class,
databaseType).wrap(createXADataSource(), mockConnection());
+ Connection connection = mockConnection();
+ FBConnection firebirdConnection =
connection.unwrap(FBConnection.class);
+ XAResource expected = mock(XAResource.class);
+
when(firebirdConnection.getManagedConnection().getXAResource()).thenReturn(expected);
+ XAConnection actual =
DatabaseTypedSPILoader.getService(XAConnectionWrapper.class,
databaseType).wrap(createXADataSource(), connection);
assertThat(actual, isA(FBXAConnection.class));
- // TODO Fix the error with getting XAResource
- // assertThat(actual.getXAResource(), isA(FBXAConnection.class));
+ assertThat(actual.getXAResource(), sameInstance(expected));
}
private XADataSource createXADataSource() {
@@ -61,7 +67,7 @@ class FirebirdXAConnectionWrapperTest {
private Connection mockConnection() throws SQLException {
Connection result = mock(Connection.class);
-
when(result.unwrap(FBConnection.class)).thenReturn(mock(FBConnection.class));
+
when(result.unwrap(FBConnection.class)).thenReturn(mock(FBConnection.class,
RETURNS_DEEP_STUBS));
return result;
}
}
diff --git
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/config/yaml/swapper/YamlMCPLaunchConfigurationSwapperTest.java
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/config/yaml/swapper/YamlMCPLaunchConfigurationSwapperTest.java
index e54cda6a4cc..68308024221 100644
---
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/config/yaml/swapper/YamlMCPLaunchConfigurationSwapperTest.java
+++
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/config/yaml/swapper/YamlMCPLaunchConfigurationSwapperTest.java
@@ -44,18 +44,20 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObject() {
- String yamlContent = "transport:\n"
- + " type: HTTP\n"
- + " http:\n"
- + " bindHost: 127.0.0.1\n"
- + " port: 9090\n"
- + " endpointPath: /gateway\n"
- + "runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: secret\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: HTTP
+ http:
+ bindHost: 127.0.0.1
+ port: 9090
+ endpointPath: /gateway
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: secret
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class));
assertThat(actual.getTransportType(), is(MCPTransportType.HTTP));
assertThat(actual.getHttpTransport().getBindHost(), is("127.0.0.1"));
@@ -66,26 +68,30 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObjectWithPasswordMissing() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class));
assertThat(actual.getDatabases().get("logic_db").getPassword(),
is(""));
}
@Test
void assertSwapToObjectWithBlankDriverClassName() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " driverClassName: ''\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ driverClassName: ''
+ """;
IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), is("MCP launch configuration property
`runtimeDatabases[logic_db].driverClassName` is required."));
}
@@ -104,28 +110,32 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObjectWithMissingTransportSection() {
- IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal("runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n",
YamlMCPLaunchConfiguration.class)));
+ IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal("""
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """, YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), is("MCP launch configuration property
`transport` is required."));
}
@Test
void assertSwapToObjectWithoutRuntimeDatabasesSection() {
- MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal(
- "transport:\n" + " type: STDIO\n",
- YamlMCPLaunchConfiguration.class));
+ MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal("""
+ transport:
+ type: STDIO
+ """, YamlMCPLaunchConfiguration.class));
assertThat(actual.getDatabases(), is(Collections.emptyMap()));
}
@Test
void assertSwapToObjectWithNullRuntimeDatabases() {
- YamlMCPLaunchConfiguration yamlConfig = YamlEngine.unmarshal(
- "transport:\n" + " type: STDIO\n",
- YamlMCPLaunchConfiguration.class);
+ YamlMCPLaunchConfiguration yamlConfig = YamlEngine.unmarshal("""
+ transport:
+ type: STDIO
+ """, YamlMCPLaunchConfiguration.class);
yamlConfig.setRuntimeDatabases(null);
IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(yamlConfig));
assertThat(actual.getMessage(), is("MCP launch configuration property
`runtimeDatabases` is required."));
@@ -133,9 +143,11 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObjectWithEmptyRuntimeDatabases() {
- MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal(
- "transport:\n" + " type: STDIO\n" + "runtimeDatabases: {}\n",
- YamlMCPLaunchConfiguration.class));
+ MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal("""
+ transport:
+ type: STDIO
+ runtimeDatabases: {}
+ """, YamlMCPLaunchConfiguration.class));
assertThat(actual.getDatabases(), is(Collections.emptyMap()));
}
@@ -185,80 +197,103 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObjectWithUnsupportedRootProperty() {
- ConstructorException actual = assertThrows(ConstructorException.class,
() -> swapper.swapToObject(YamlEngine.unmarshal("runtime:\n"
- + " props:\n"
- + " databaseName: logic_db\n",
YamlMCPLaunchConfiguration.class)));
+ ConstructorException actual = assertThrows(ConstructorException.class,
() -> swapper.swapToObject(YamlEngine.unmarshal("""
+ runtime:
+ props:
+ databaseName: logic_db
+ """, YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), containsString("Unable to find
property 'runtime'"));
}
@Test
void assertSwapToObjectWithNumericRuntimeDatabaseName() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " 1:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ 1:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
MCPLaunchConfiguration actual =
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class));
assertThat(actual.getDatabases().get("1").getJdbcUrl(),
is("jdbc:mysql://localhost:3306/logic_db"));
}
@Test
void assertSwapToObjectWithBlankRuntimeDatabaseName() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " '':\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ '':
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
ConstructorException actual = assertThrows(ConstructorException.class,
() -> swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), containsString("YAML map key cannot be
blank."));
}
@Test
void assertSwapToObjectWithNullRuntimeDatabaseName() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " null:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ null:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
ConstructorException actual = assertThrows(ConstructorException.class,
() -> swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), containsString("YAML map key cannot be
null."));
}
@Test
void assertSwapToObjectWithNullRuntimeDatabaseConfiguration() {
- String yamlContent = "transport:\n" + " type: STDIO\n" +
"runtimeDatabases:\n" + " foo_{message}:\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ foo_{message}:
+ """;
IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), is("MCP launch configuration property
`runtimeDatabases` contains null database configuration."));
}
@Test
void assertSwapToObjectWithUnsupportedRuntimeDatabaseProperty() {
- String yamlContent = "transport:\n"
- + " type: STDIO\n"
- + "runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n"
- + " unsupported: true\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ unsupported: true
+ """;
ConstructorException actual = assertThrows(ConstructorException.class,
() -> swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), containsString("Unable to find
property 'unsupported'"));
}
@Test
void assertSwapToObjectWithPlaceholderRuntimeDatabaseName() {
- String yamlContent = "transport:\n" + " type: STDIO\n" +
"runtimeDatabases:\n" + " <foo_{message}>:\n" + " jdbcUrl:
jdbc:mysql://localhost:3306/logic_db\n" + " username: demo\n"
- + " password: ''\n" + " driverClassName:
com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ <foo_{message}>:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), is("MCP launch configuration property
`runtimeDatabases` contains placeholder database name."));
}
@@ -278,8 +313,16 @@ class YamlMCPLaunchConfigurationSwapperTest {
@Test
void assertSwapToObjectWithPlaceholderPassword() {
- String yamlContent = "transport:\n" + " type: STDIO\n" +
"runtimeDatabases:\n" + " foo_{message}:\n" + " jdbcUrl:
jdbc:mysql://localhost:3306/logic_db\n" + " username: demo\n"
- + " password: <unresolved-password>\n" + "
driverClassName: com.mysql.cj.jdbc.Driver\n";
+ String yamlContent = """
+ transport:
+ type: STDIO
+ runtimeDatabases:
+ foo_{message}:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: <unresolved-password>
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
IllegalArgumentException actual =
assertThrows(IllegalArgumentException.class, () ->
swapper.swapToObject(YamlEngine.unmarshal(yamlContent,
YamlMCPLaunchConfiguration.class)));
assertThat(actual.getMessage(), is("MCP launch configuration property
`runtimeDatabases` contains placeholder database property `password`."));
}
@@ -304,11 +347,13 @@ class YamlMCPLaunchConfigurationSwapperTest {
}
private String createRuntimeDatabasesYaml() {
- return "runtimeDatabases:\n"
- + " logic_db:\n"
- + " jdbcUrl: jdbc:mysql://localhost:3306/logic_db\n"
- + " username: demo\n"
- + " password: ''\n"
- + " driverClassName: com.mysql.cj.jdbc.Driver\n";
+ return """
+ runtimeDatabases:
+ logic_db:
+ jdbcUrl: jdbc:mysql://localhost:3306/logic_db
+ username: demo
+ password: ''
+ driverClassName: com.mysql.cj.jdbc.Driver
+ """;
}
}
diff --git
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/capability/tool/AbstractMCPToolSpecificationFactoryTest.java
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/capability/tool/AbstractMCPToolSpecificationFactoryTest.java
index 4493e3533f0..2df6c764925 100644
---
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/capability/tool/AbstractMCPToolSpecificationFactoryTest.java
+++
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/capability/tool/AbstractMCPToolSpecificationFactoryTest.java
@@ -163,7 +163,7 @@ abstract class AbstractMCPToolSpecificationFactoryTest {
assertFalse(actualQuestions.isEmpty());
Map<?, ?> actualQuestion = (Map<?, ?>) actualQuestions.get(0);
assertThat(actualQuestion.get("input_type"), is("secret"));
- assertTrue(Boolean.TRUE.equals(actualQuestion.get("secret")));
+ assertTrue((Boolean) actualQuestion.get("secret"));
assertTrue(actualQuestion.containsKey("message"));
assertFalse(actualQuestion.containsKey("display_message"));
List<?> actualNextActions = (List<?>)
actualPayload.get("next_actions");
diff --git
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/server/http/validator/constraint/OriginHeaderConstraintTest.java
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/server/http/validator/constraint/OriginHeaderConstraintTest.java
index 3b90c5ebd1a..79b6443d9fb 100644
---
a/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/server/http/validator/constraint/OriginHeaderConstraintTest.java
+++
b/mcp/bootstrap/src/test/java/org/apache/shardingsphere/mcp/bootstrap/transport/server/http/validator/constraint/OriginHeaderConstraintTest.java
@@ -20,6 +20,11 @@ package
org.apache.shardingsphere.mcp.bootstrap.transport.server.http.validator.
import
io.modelcontextprotocol.server.transport.ServerTransportSecurityException;
import
org.apache.shardingsphere.mcp.bootstrap.transport.server.http.validator.MCPTransportSecurityException;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -48,27 +53,19 @@ class OriginHeaderConstraintTest {
assertDoesNotThrow(() -> new
OriginHeaderConstraint(true).validate("http://[::1]:8080"));
}
- @Test
- void assertValidateWithRemoteOriginOnLoopbackBinding() {
- ServerTransportSecurityException actual =
assertThrows(ServerTransportSecurityException.class, () -> new
OriginHeaderConstraint(true).validate("http://example.com:8080"));
- assertThat(actual.getStatusCode(), is(403));
- assertThat(actual.getMessage(), is("Origin is not allowed by MCP HTTP
transport policy."));
- assertThat(((MCPTransportSecurityException) actual).getCategory(),
is("origin_not_allowed"));
- }
-
- @Test
- void assertValidateWithLoopbackOriginOnNonLoopbackBinding() {
- ServerTransportSecurityException actual =
assertThrows(ServerTransportSecurityException.class, () -> new
OriginHeaderConstraint(false).validate("http://127.0.0.1:8080"));
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("getDeniedOrigins")
+ void assertValidateWithDeniedOrigin(final String name, final boolean
loopbackBinding, final String origin) {
+ ServerTransportSecurityException actual =
assertThrows(ServerTransportSecurityException.class, () -> new
OriginHeaderConstraint(loopbackBinding).validate(origin));
assertThat(actual.getStatusCode(), is(403));
assertThat(actual.getMessage(), is("Origin is not allowed by MCP HTTP
transport policy."));
assertThat(((MCPTransportSecurityException) actual).getCategory(),
is("origin_not_allowed"));
}
- @Test
- void assertValidateWithInvalidOrigin() {
- ServerTransportSecurityException actual =
assertThrows(ServerTransportSecurityException.class, () -> new
OriginHeaderConstraint(true).validate("://bad-origin"));
- assertThat(actual.getStatusCode(), is(403));
- assertThat(actual.getMessage(), is("Origin is not allowed by MCP HTTP
transport policy."));
- assertThat(((MCPTransportSecurityException) actual).getCategory(),
is("origin_not_allowed"));
+ private static Stream<Arguments> getDeniedOrigins() {
+ return Stream.of(
+ Arguments.of("remote origin on loopback binding", true,
"http://example.com:8080"),
+ Arguments.of("loopback origin on non-loopback binding", false,
"http://127.0.0.1:8080"),
+ Arguments.of("invalid origin", true, "://bad-origin"));
}
}
diff --git
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/metadata/SearchMetadataToolHandlerTest.java
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/metadata/SearchMetadataToolHandlerTest.java
index c38f97e4484..42ed5290926 100644
---
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/metadata/SearchMetadataToolHandlerTest.java
+++
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/metadata/SearchMetadataToolHandlerTest.java
@@ -39,7 +39,6 @@ import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -386,7 +385,7 @@ class SearchMetadataToolHandlerTest {
}
private List<DatabaseMetadataFixture> createLargeDatabaseMetadata() {
- List<TableMetadataFixture> tables = IntStream.range(0,
101).mapToObj(index -> ResourceTestDataFactory.createTable("table_" + index,
List.of(), List.of())).collect(Collectors.toList());
+ List<TableMetadataFixture> tables = IntStream.range(0,
101).mapToObj(index -> ResourceTestDataFactory.createTable("table_" + index,
List.of(), List.of())).toList();
return List.of(ResourceTestDataFactory.createDatabase("large_db",
"MySQL", "", List.of(ResourceTestDataFactory.createSchema("public", tables,
List.of(), List.of()))));
}
diff --git
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowExecutionToolHandlerTest.java
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowExecutionToolHandlerTest.java
index ea442dd7dc9..df3fe27ddb7 100644
---
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowExecutionToolHandlerTest.java
+++
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowExecutionToolHandlerTest.java
@@ -37,7 +37,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstruction;
import static org.mockito.Mockito.verify;
@@ -66,8 +65,8 @@ class WorkflowExecutionToolHandlerTest {
MCPSuccessPayload actual =
handler.handle(fixture.requestContext(), Map.of(WorkflowFieldNames.PLAN_ID,
"plan-1",
WorkflowFieldNames.APPROVED_STEPS,
List.of("rule_distsql"), WorkflowFieldNames.EXECUTION_MODE, "manual-only"));
WorkflowExecutionService executionService =
mockedExecutionServices.constructed().getFirst();
-
verify(executionService).apply(eq(fixture.workflowSessionContext()),
eq(fixture.queryFacade()), eq(fixture.executionFacade()),
- eq(workflowRuntimeHandler),
eq(workflowApplyArtifactValidator), eq("session-1"), eq(snapshot),
eq(List.of("rule_distsql")), eq("manual-only"));
+ verify(executionService).apply(fixture.workflowSessionContext(),
fixture.queryFacade(), fixture.executionFacade(),
+ workflowRuntimeHandler, workflowApplyArtifactValidator,
"session-1", snapshot, List.of("rule_distsql"), "manual-only");
assertThat(actual.toPayload().get("status"), is("completed"));
}
}
diff --git
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowValidationToolHandlerTest.java
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowValidationToolHandlerTest.java
index 32d5c3e09aa..ce55d9fc351 100644
---
a/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowValidationToolHandlerTest.java
+++
b/mcp/core/src/test/java/org/apache/shardingsphere/mcp/core/tool/handler/workflow/WorkflowValidationToolHandlerTest.java
@@ -35,7 +35,6 @@ import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -62,7 +61,7 @@ class WorkflowValidationToolHandlerTest {
WorkflowValidationToolHandler handler = new
WorkflowValidationToolHandler(new WorkflowRuntimeDefinitionRegistry(List.of(
WorkflowHandlerTestFixture.createDefinition("encrypt.rule",
workflowRuntimeHandler, MCPWorkflowApplyArtifactValidator.NO_OP))));
MCPSuccessPayload actual = handler.handle(fixture.requestContext(),
Map.of("plan_id", "plan-1"));
- verify(workflowRuntimeHandler).validate(eq(snapshot),
eq(fixture.queryFacade()));
+ verify(workflowRuntimeHandler).validate(snapshot,
fixture.queryFacade());
assertThat(actual.toPayload().get("status"), is("validated"));
}
diff --git
a/mcp/features/broadcast/src/test/java/org/apache/shardingsphere/mcp/feature/broadcast/TestWorkflowSessionContext.java
b/mcp/features/broadcast/src/test/java/org/apache/shardingsphere/mcp/feature/broadcast/TestWorkflowSessionContext.java
index 4152383eb10..3eceb490680 100644
---
a/mcp/features/broadcast/src/test/java/org/apache/shardingsphere/mcp/feature/broadcast/TestWorkflowSessionContext.java
+++
b/mcp/features/broadcast/src/test/java/org/apache/shardingsphere/mcp/feature/broadcast/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/features/encrypt/src/test/java/org/apache/shardingsphere/mcp/feature/encrypt/TestWorkflowSessionContext.java
b/mcp/features/encrypt/src/test/java/org/apache/shardingsphere/mcp/feature/encrypt/TestWorkflowSessionContext.java
index 8559df58777..0cf21bf0345 100644
---
a/mcp/features/encrypt/src/test/java/org/apache/shardingsphere/mcp/feature/encrypt/TestWorkflowSessionContext.java
+++
b/mcp/features/encrypt/src/test/java/org/apache/shardingsphere/mcp/feature/encrypt/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/features/mask/src/test/java/org/apache/shardingsphere/mcp/feature/mask/TestWorkflowSessionContext.java
b/mcp/features/mask/src/test/java/org/apache/shardingsphere/mcp/feature/mask/TestWorkflowSessionContext.java
index aa936579982..16b9bc7f11b 100644
---
a/mcp/features/mask/src/test/java/org/apache/shardingsphere/mcp/feature/mask/TestWorkflowSessionContext.java
+++
b/mcp/features/mask/src/test/java/org/apache/shardingsphere/mcp/feature/mask/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/TestWorkflowSessionContext.java
b/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/TestWorkflowSessionContext.java
index 8200c42a09b..31155d4fe39 100644
---
a/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/TestWorkflowSessionContext.java
+++
b/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/tool/service/ReadwriteSplittingInspectionServiceTest.java
b/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/tool/service/ReadwriteSplittingInspectionServiceTest.java
index 18f3de1bfea..62b19732c79 100644
---
a/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/tool/service/ReadwriteSplittingInspectionServiceTest.java
+++
b/mcp/features/readwrite-splitting/src/test/java/org/apache/shardingsphere/mcp/feature/readwritesplitting/tool/service/ReadwriteSplittingInspectionServiceTest.java
@@ -29,7 +29,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -54,14 +53,14 @@ class ReadwriteSplittingInspectionServiceTest {
void assertQueryRules() {
MCPFeatureQueryFacade queryFacade = mock(MCPFeatureQueryFacade.class);
new ReadwriteSplittingInspectionService().queryRules(queryFacade,
"logic_db");
- verify(queryFacade).query(eq("logic_db"), eq("SHOW READWRITE_SPLITTING
RULES FROM logic_db"));
+ verify(queryFacade).query("logic_db", "SHOW READWRITE_SPLITTING RULES
FROM logic_db");
}
@Test
void assertQueryRuleStatus() {
MCPFeatureQueryFacade queryFacade = mock(MCPFeatureQueryFacade.class);
new ReadwriteSplittingInspectionService().queryRuleStatus(queryFacade,
"logic_db", "readwrite_ds");
- verify(queryFacade).query(eq("logic_db"), eq("SHOW STATUS FROM
READWRITE_SPLITTING RULE readwrite_ds FROM logic_db"));
+ verify(queryFacade).query("logic_db", "SHOW STATUS FROM
READWRITE_SPLITTING RULE readwrite_ds FROM logic_db");
}
@Test
@@ -86,7 +85,7 @@ class ReadwriteSplittingInspectionServiceTest {
@Test
void assertQueryRuleCount() {
MCPFeatureQueryFacade queryFacade = mock(MCPFeatureQueryFacade.class);
- when(queryFacade.query(eq("logic_db"), eq("COUNT READWRITE_SPLITTING
RULE FROM logic_db"))).thenReturn(List.of(Map.of("count", 1)));
+ when(queryFacade.query("logic_db", "COUNT READWRITE_SPLITTING RULE
FROM logic_db")).thenReturn(List.of(Map.of("count", 1)));
assertThat(new
ReadwriteSplittingInspectionService().queryRuleCount(queryFacade, "logic_db"),
is(List.of(Map.of("count", 1))));
}
diff --git
a/mcp/features/shadow/src/test/java/org/apache/shardingsphere/mcp/feature/shadow/TestWorkflowSessionContext.java
b/mcp/features/shadow/src/test/java/org/apache/shardingsphere/mcp/feature/shadow/TestWorkflowSessionContext.java
index d5a3977f698..9bf0a26baf0 100644
---
a/mcp/features/shadow/src/test/java/org/apache/shardingsphere/mcp/feature/shadow/TestWorkflowSessionContext.java
+++
b/mcp/features/shadow/src/test/java/org/apache/shardingsphere/mcp/feature/shadow/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/ShardingMCPHandlerProviderTest.java
b/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/ShardingMCPHandlerProviderTest.java
index a69679c564c..62fec8a52ce 100644
---
a/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/ShardingMCPHandlerProviderTest.java
+++
b/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/ShardingMCPHandlerProviderTest.java
@@ -48,10 +48,10 @@ class ShardingMCPHandlerProviderTest {
assertThat(actual.size(), is(22));
assertTrue(actual.stream().map(MCPResourceHandler::getResourceUriTemplate).toList().contains(ShardingFeatureDefinition.TABLE_RULES_RESOURCE_URI));
assertTrue(actual.stream().map(MCPResourceHandler::getResourceUriTemplate).toList().contains(ShardingFeatureDefinition.UNUSED_AUDITORS_RESOURCE_URI));
- assertTrue(actual.stream().anyMatch(each -> each instanceof
ShardingAlgorithmResourceHandler));
- assertTrue(actual.stream().anyMatch(each -> each instanceof
ShardingTableResourceHandler));
- assertTrue(actual.stream().anyMatch(each -> each instanceof
ShardingStrategyResourceHandler));
- assertTrue(actual.stream().anyMatch(each -> each instanceof
ShardingGovernanceResourceHandler));
+
assertTrue(actual.stream().anyMatch(ShardingAlgorithmResourceHandler.class::isInstance));
+
assertTrue(actual.stream().anyMatch(ShardingTableResourceHandler.class::isInstance));
+
assertTrue(actual.stream().anyMatch(ShardingStrategyResourceHandler.class::isInstance));
+
assertTrue(actual.stream().anyMatch(ShardingGovernanceResourceHandler.class::isInstance));
}
@Test
diff --git
a/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/TestWorkflowSessionContext.java
b/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/TestWorkflowSessionContext.java
index 697385e4a39..3bc71d0bf31 100644
---
a/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/TestWorkflowSessionContext.java
+++
b/mcp/features/sharding/src/test/java/org/apache/shardingsphere/mcp/feature/sharding/TestWorkflowSessionContext.java
@@ -24,7 +24,6 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TestWorkflowSessionContext implements
WorkflowSessionContext {
@@ -33,13 +32,15 @@ public final class TestWorkflowSessionContext implements
WorkflowSessionContext
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setSessionId(SESSION_ID);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
diff --git
a/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/TestWorkflowSessionContext.java
b/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/TestWorkflowSessionContext.java
index 6ce098ae464..ce9f0920c50 100644
---
a/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/TestWorkflowSessionContext.java
+++
b/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/TestWorkflowSessionContext.java
@@ -25,20 +25,21 @@ import
org.apache.shardingsphere.mcp.support.workflow.model.WorkflowLifecycle;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
final class TestWorkflowSessionContext implements WorkflowSessionContext {
private final Map<String, WorkflowContextSnapshot> contexts = new
ConcurrentHashMap<>();
+ private int planIdSequence;
+
@Override
public WorkflowContextSnapshot getOrCreate(final String planId) {
if (null != planId && !planId.isBlank()) {
return getRequired(planId);
}
WorkflowContextSnapshot result = new WorkflowContextSnapshot();
- result.setPlanId("plan-" + UUID.randomUUID());
+ result.setPlanId("plan-test-" + ++planIdSequence);
result.setStatus(WorkflowLifecycle.STATUS_CLARIFYING);
return result;
}
diff --git
a/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/WorkflowSynchronizationSupportTest.java
b/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/WorkflowSynchronizationSupportTest.java
index 62911daacf9..c4505ed74b1 100644
---
a/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/WorkflowSynchronizationSupportTest.java
+++
b/mcp/support/src/test/java/org/apache/shardingsphere/mcp/support/workflow/service/WorkflowSynchronizationSupportTest.java
@@ -36,8 +36,12 @@ class WorkflowSynchronizationSupportTest {
@Test
void assertSynchronize() {
- new WorkflowSynchronizationSupport(Duration.ofMillis(1L),
Duration.ofMillis(1L))
- .synchronize(() ->
createValidationReport(WorkflowLifecycle.STATUS_PASSED));
+ AtomicInteger attempts = new AtomicInteger();
+ new WorkflowSynchronizationSupport(Duration.ofMillis(1L),
Duration.ofMillis(1L)).synchronize(() -> {
+ attempts.incrementAndGet();
+ return createValidationReport(WorkflowLifecycle.STATUS_PASSED);
+ });
+ assertThat(attempts.get(), is(1));
}
@Test
diff --git
a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/federation/FederationMetaDataRefreshEngineTest.java
b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/federation/FederationMetaDataRefreshEngineTest.java
index 913039636ea..14af89f1c40 100644
---
a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/federation/FederationMetaDataRefreshEngineTest.java
+++
b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/federation/FederationMetaDataRefreshEngineTest.java
@@ -41,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(AutoMockExtension.class)
@@ -109,6 +110,7 @@ class FederationMetaDataRefreshEngineTest {
when(sqlStatementContext.getSqlStatement()).thenReturn(UpdateStatement.builder().databaseType(databaseType).build());
FederationMetaDataRefreshEngine engine = new
FederationMetaDataRefreshEngine(sqlStatementContext);
engine.refresh(metaDataManagerPersistService, database);
+ verifyNoInteractions(metaDataManagerPersistService, database);
}
@Test
diff --git
a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/util/TableRefreshUtilsTest.java
b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/util/TableRefreshUtilsTest.java
index 3bdbf14959d..c247173c294 100644
---
a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/util/TableRefreshUtilsTest.java
+++
b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/refresher/util/TableRefreshUtilsTest.java
@@ -42,6 +42,8 @@ import
org.apache.shardingsphere.sql.parser.statement.core.value.identifier.Iden
import
org.apache.shardingsphere.test.infra.framework.extension.mock.AutoMockExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import java.util.Arrays;
import java.util.Collections;
@@ -196,13 +198,14 @@ class TableRefreshUtilsTest {
assertFalse(TableRefreshUtils.isNeedRefresh(new
RuleMetaData(Collections.singleton(rule)), "foo_schema", "foo_tbl"));
}
- @Test
- void assertIsNeedRefreshBlockedByDataSourceWildcard() {
+ @ParameterizedTest(name = "{0}")
+ @ValueSource(strings = {"foo_ds.*", "foo_ds.*.*", "foo_ds.foo_schema.*"})
+ void assertIsNeedRefreshBlockedByWildcard(final String tablePattern) {
MutableDataNodeRuleAttribute mutableDataNodeRuleAttribute =
mock(MutableDataNodeRuleAttribute.class);
DataNode dataNode = new DataNode("foo_ds", "foo_schema", "foo_tbl");
when(mutableDataNodeRuleAttribute.findTableDataNode("foo_schema",
"foo_tbl")).thenReturn(Optional.of(dataNode));
SingleRuleConfiguration ruleConfig = new SingleRuleConfiguration();
- ruleConfig.setTables(Collections.singletonList("foo_ds.*"));
+ ruleConfig.setTables(Collections.singletonList(tablePattern));
ShardingSphereRule rule = mock(ShardingSphereRule.class);
when(rule.getConfiguration()).thenReturn(ruleConfig);
when(rule.getAttributes()).thenReturn(new
RuleAttributes(mutableDataNodeRuleAttribute));
@@ -234,32 +237,6 @@ class TableRefreshUtilsTest {
assertTrue(TableRefreshUtils.isNeedRefresh(new
RuleMetaData(Collections.singleton(rule)), "foo_schema",
Arrays.asList("bar_tbl", "foo_tbl")));
}
- @Test
- void assertIsNeedRefreshBlockedByDataSourceSchemaWildcard() {
- MutableDataNodeRuleAttribute mutableDataNodeRuleAttribute =
mock(MutableDataNodeRuleAttribute.class);
- DataNode dataNode = new DataNode("foo_ds", "foo_schema", "foo_tbl");
- when(mutableDataNodeRuleAttribute.findTableDataNode("foo_schema",
"foo_tbl")).thenReturn(Optional.of(dataNode));
- SingleRuleConfiguration ruleConfig = new SingleRuleConfiguration();
- ruleConfig.setTables(Collections.singletonList("foo_ds.*.*"));
- ShardingSphereRule rule = mock(ShardingSphereRule.class);
- when(rule.getConfiguration()).thenReturn(ruleConfig);
- when(rule.getAttributes()).thenReturn(new
RuleAttributes(mutableDataNodeRuleAttribute));
- assertFalse(TableRefreshUtils.isNeedRefresh(new
RuleMetaData(Collections.singleton(rule)), "foo_schema", "foo_tbl"));
- }
-
- @Test
- void assertIsNeedRefreshBlockedBySchemaSpecificWildcard() {
- MutableDataNodeRuleAttribute mutableDataNodeRuleAttribute =
mock(MutableDataNodeRuleAttribute.class);
- DataNode dataNode = new DataNode("foo_ds", "foo_schema", "foo_tbl");
- when(mutableDataNodeRuleAttribute.findTableDataNode("foo_schema",
"foo_tbl")).thenReturn(Optional.of(dataNode));
- SingleRuleConfiguration ruleConfig = new SingleRuleConfiguration();
- ruleConfig.setTables(Collections.singletonList("foo_ds.foo_schema.*"));
- ShardingSphereRule rule = mock(ShardingSphereRule.class);
- when(rule.getConfiguration()).thenReturn(ruleConfig);
- when(rule.getAttributes()).thenReturn(new
RuleAttributes(mutableDataNodeRuleAttribute));
- assertFalse(TableRefreshUtils.isNeedRefresh(new
RuleMetaData(Collections.singleton(rule)), "foo_schema", "foo_tbl"));
- }
-
@Test
void assertIsNeedRefreshWithTableCollectionWhenNoTableNeedsRefresh() {
ShardingSphereRule rule = mock(ShardingSphereRule.class);
diff --git
a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/exclusive/ClusterExclusiveOperatorContextTest.java
b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/exclusive/ClusterExclusiveOperatorContextTest.java
index 4d7f29762bb..69ba6171d96 100644
---
a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/exclusive/ClusterExclusiveOperatorContextTest.java
+++
b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/exclusive/ClusterExclusiveOperatorContextTest.java
@@ -80,8 +80,7 @@ class ClusterExclusiveOperatorContextTest {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
Future<Optional<ExclusiveLockHandle>> future =
executorService.submit(() -> context.start("op", 500L));
- TimeUnit.MILLISECONDS.sleep(100L);
- assertFalse(future.isDone());
+ assertThrows(TimeoutException.class, () -> future.get(100L,
TimeUnit.MILLISECONDS));
assertThat(sharedState.tryLockCallCount.get(), is(1));
lockHandle.close();
Optional<ExclusiveLockHandle> actual = future.get(1L,
TimeUnit.SECONDS);
diff --git
a/proxy/backend/dialect/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/select/SelectInformationSchemataExecutorTest.java
b/proxy/backend/dialect/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/select/SelectInformationSchemataExecutorTest.java
index 0319bdfd2d7..623cfb74c09 100644
---
a/proxy/backend/dialect/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/select/SelectInformationSchemataExecutorTest.java
+++
b/proxy/backend/dialect/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/select/SelectInformationSchemataExecutorTest.java
@@ -69,7 +69,6 @@ import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstruction;
@@ -194,7 +193,7 @@ class SelectInformationSchemataExecutorTest {
when(lowerCasePreparedStatement.executeQuery()).thenReturn(lowerCaseResultSet);
when(queryPreparedStatement.executeQuery()).thenReturn(resultSet);
when(result.prepareStatement(any(String.class))).thenReturn(queryPreparedStatement);
- when(result.prepareStatement(eq("SELECT
@@lower_case_table_names"))).thenReturn(lowerCasePreparedStatement);
+ when(result.prepareStatement("SELECT
@@lower_case_table_names")).thenReturn(lowerCasePreparedStatement);
return result;
}
diff --git
a/proxy/frontend/dialect/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
b/proxy/frontend/dialect/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
index 69710c61e82..345f38845c5 100644
---
a/proxy/frontend/dialect/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
+++
b/proxy/frontend/dialect/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/authentication/PostgreSQLAuthenticationEngineTest.java
@@ -69,11 +69,15 @@ import
org.apache.shardingsphere.test.infra.framework.extension.mock.StaticMockS
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.internal.configuration.plugins.Plugins;
+import javax.annotation.Nullable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -85,6 +89,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
+import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -313,22 +318,15 @@ class PostgreSQLAuthenticationEngineTest {
assertTrue(actual.isFinished());
}
- @Test
- void assertStartupUsesDefaultClientEncoding() throws
ReflectiveOperationException {
- assertAuthenticateAndClientEncodingParameterStatus(USERNAME,
DATABASE_NAME, null);
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("getClientEncodings")
+ void assertStartupNormalizesClientEncoding(final String name, @Nullable
final String clientEncoding) throws ReflectiveOperationException {
+ assertAuthenticateAndClientEncodingParameterStatus(USERNAME,
DATABASE_NAME, clientEncoding);
verify(charsetAttribute).set(StandardCharsets.UTF_8);
}
- @Test
- void assertStartupNormalizesUtf8DashAlias() throws
ReflectiveOperationException {
- assertAuthenticateAndClientEncodingParameterStatus(USERNAME,
DATABASE_NAME, "UTF-8");
- verify(charsetAttribute).set(StandardCharsets.UTF_8);
- }
-
- @Test
- void assertStartupNormalizesUnicodeAlias() throws
ReflectiveOperationException {
- assertAuthenticateAndClientEncodingParameterStatus(USERNAME,
DATABASE_NAME, "UNICODE");
- verify(charsetAttribute).set(StandardCharsets.UTF_8);
+ private static Stream<Arguments> getClientEncodings() {
+ return Stream.of(Arguments.of("default encoding", null),
Arguments.of("UTF-8 alias", "UTF-8"), Arguments.of("UNICODE alias", "UNICODE"));
}
@Test
diff --git
a/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/cases/cursor/OpenGaussCursorTestCase.java
b/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/cases/cursor/OpenGaussCursorTestCase.java
index 1b834323720..d9a43d528b0 100644
---
a/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/cases/cursor/OpenGaussCursorTestCase.java
+++
b/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/cases/cursor/OpenGaussCursorTestCase.java
@@ -156,8 +156,8 @@ public final class OpenGaussCursorTestCase extends
BaseTransactionTestCase {
}
private void broadcastAndSingleTablesCursorTest2(final Connection
connection) throws SQLException {
- String cursorName =
cursorSQLCommand.getBroadcastTablesCursor2().getCursorName();
- String sql = cursorSQLCommand.getBroadcastTablesCursor2().getSql();
+ String cursorName =
cursorSQLCommand.getBroadcastAndSingleTablesCursor2().getCursorName();
+ String sql =
cursorSQLCommand.getBroadcastAndSingleTablesCursor2().getSql();
executeWithLog(connection, "start transaction;");
executeWithLog(connection, sql);
executeWithLog(connection, String.format("close %s;", cursorName));
diff --git
a/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/engine/command/CursorSQLCommand.java
b/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/engine/command/CursorSQLCommand.java
index ba7f5e6caee..f7c0dae03c5 100644
---
a/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/engine/command/CursorSQLCommand.java
+++
b/test/e2e/operation/transaction/src/test/java/org/apache/shardingsphere/test/e2e/operation/transaction/engine/command/CursorSQLCommand.java
@@ -50,7 +50,7 @@ public final class CursorSQLCommand {
private CursorSQL broadcastAndSingleTablesCursor;
@XmlElement(name = "broadcast-and-single-tables-cursor2")
- private String broadcastAndSingleTablesCursor2;
+ private CursorSQL broadcastAndSingleTablesCursor2;
@XmlElement(name = "view-cursor")
private CursorSQL viewCursor;
diff --git
a/test/it/binder/src/test/java/org/apache/shardingsphere/test/it/sql/binder/dialect/oracle/OracleBinderIT.java
b/test/it/binder/src/test/java/org/apache/shardingsphere/test/it/sql/binder/dialect/oracle/OracleBinderIT.java
index a5082a0b56e..0603957c7d9 100644
---
a/test/it/binder/src/test/java/org/apache/shardingsphere/test/it/sql/binder/dialect/oracle/OracleBinderIT.java
+++
b/test/it/binder/src/test/java/org/apache/shardingsphere/test/it/sql/binder/dialect/oracle/OracleBinderIT.java
@@ -27,8 +27,12 @@ import
org.apache.shardingsphere.sql.parser.statement.core.statement.type.dml.Se
import org.apache.shardingsphere.test.it.sql.binder.SQLBinderIT;
import org.apache.shardingsphere.test.it.sql.binder.SQLBinderITSettings;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
+import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -78,70 +82,33 @@ class OracleBinderIT extends SQLBinderIT {
assertThat(actualTable.getAt().get().getValue(), is("@"));
}
- @Test
- void assertBindBlockWithLocalRecordFieldTypeAttribute() {
- String sql = "DECLARE TYPE foo_rec IS RECORD (order_id NUMBER);
t_order foo_rec; foo_copy t_order.order_id%TYPE; BEGIN NULL; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindBlockWithLocalCursorRowtypeAttribute() {
- String sql = "DECLARE CURSOR foo_cursor IS SELECT 1 foo_id FROM dual;
TYPE foo_ref IS REF CURSOR RETURN foo_cursor%ROWTYPE; BEGIN NULL; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindPackageWithLocalRecordFieldTypeAttribute() {
- String sql = "CREATE PACKAGE foo_pkg AS TYPE foo_rec IS RECORD (foo_id
NUMBER); foo_record foo_rec; foo_copy foo_pkg.foo_record.foo_id%TYPE; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindPackageWithSchemaQualifiedCursorRowtypeAttribute() {
- String sql = "CREATE PACKAGE foo_schema.foo_pkg AS TYPE foo_rec IS
RECORD (foo_id NUMBER); CURSOR foo_cursor RETURN foo_rec;"
- + " TYPE foo_ref IS REF CURSOR RETURN
foo_schema.foo_pkg.foo_cursor%ROWTYPE; END;";
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("getTypeAttributeStatements")
+ void assertBindWithTypeAttribute(final String name, final String sql) {
SQLStatement actual = bindSQLStatement("Oracle", sql);
assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
}
- @Test
- void assertBindPackageWithNestedLocalCursorRowtypeAttribute() {
- String sql = "CREATE PACKAGE BODY foo_pkg AS PROCEDURE foo_proc IS
CURSOR foo_cursor IS SELECT 1 foo_id FROM dual;"
- + " TYPE foo_ref IS REF CURSOR RETURN
foo_pkg.foo_proc.foo_cursor%ROWTYPE; BEGIN NULL; END; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindBlockWithNestedLocalCursorRowtypeAttribute() {
- String sql = "<<foo_block>> DECLARE PROCEDURE foo_proc IS CURSOR
foo_cursor IS SELECT 1 foo_id FROM dual;"
- + " TYPE foo_ref IS REF CURSOR RETURN
foo_block.foo_proc.foo_cursor%ROWTYPE; BEGIN NULL; END; BEGIN NULL; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindPackageWithSchemaQualifiedScalarTypeAttribute() {
- String sql = "CREATE PACKAGE foo_schema.foo_pkg AS foo_var NUMBER;
foo_copy foo_schema.foo_pkg.foo_var%TYPE; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindPackageWithNestedScalarTypeAttribute() {
- String sql = "CREATE PACKAGE BODY foo_pkg AS PROCEDURE foo_proc IS
foo_var NUMBER; foo_copy foo_pkg.foo_proc.foo_var%TYPE; BEGIN NULL; END; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
- }
-
- @Test
- void assertBindFunctionWithSchemaQualifiedCursorRowtypeAttribute() {
- String sql = "CREATE FUNCTION foo_schema.foo_func RETURN NUMBER AS
CURSOR foo_cursor IS SELECT 1 foo_id FROM dual;"
- + " TYPE foo_ref IS REF CURSOR RETURN
foo_schema.foo_func.foo_cursor%ROWTYPE; BEGIN RETURN 1; END;";
- SQLStatement actual = bindSQLStatement("Oracle", sql);
- assertTrue(new
CommonSQLStatementContext(actual).getTablesContext().getTableNames().isEmpty());
+ private static Stream<Arguments> getTypeAttributeStatements() {
+ return Stream.of(
+ Arguments.of("BlockWithLocalRecordFieldTypeAttribute",
"DECLARE TYPE foo_rec IS RECORD (order_id NUMBER); t_order foo_rec; foo_copy
t_order.order_id%TYPE; BEGIN NULL; END;"),
+ Arguments.of("BlockWithLocalCursorRowtypeAttribute", "DECLARE
CURSOR foo_cursor IS SELECT 1 foo_id FROM dual; TYPE foo_ref IS REF CURSOR
RETURN foo_cursor%ROWTYPE; BEGIN NULL; END;"),
+ Arguments.of("PackageWithLocalRecordFieldTypeAttribute",
+ "CREATE PACKAGE foo_pkg AS TYPE foo_rec IS RECORD
(foo_id NUMBER); foo_record foo_rec; foo_copy foo_pkg.foo_record.foo_id%TYPE;
END;"),
+
Arguments.of("PackageWithSchemaQualifiedCursorRowtypeAttribute",
+ "CREATE PACKAGE foo_schema.foo_pkg AS TYPE foo_rec IS
RECORD (foo_id NUMBER); CURSOR foo_cursor RETURN foo_rec;"
+ + " TYPE foo_ref IS REF CURSOR RETURN
foo_schema.foo_pkg.foo_cursor%ROWTYPE; END;"),
+ Arguments.of("PackageWithNestedLocalCursorRowtypeAttribute",
+ "CREATE PACKAGE BODY foo_pkg AS PROCEDURE foo_proc IS
CURSOR foo_cursor IS SELECT 1 foo_id FROM dual;"
+ + " TYPE foo_ref IS REF CURSOR RETURN
foo_pkg.foo_proc.foo_cursor%ROWTYPE; BEGIN NULL; END; END;"),
+ Arguments.of("BlockWithNestedLocalCursorRowtypeAttribute",
+ "<<foo_block>> DECLARE PROCEDURE foo_proc IS CURSOR
foo_cursor IS SELECT 1 foo_id FROM dual;"
+ + " TYPE foo_ref IS REF CURSOR RETURN
foo_block.foo_proc.foo_cursor%ROWTYPE; BEGIN NULL; END; BEGIN NULL; END;"),
+ Arguments.of("PackageWithSchemaQualifiedScalarTypeAttribute",
"CREATE PACKAGE foo_schema.foo_pkg AS foo_var NUMBER; foo_copy
foo_schema.foo_pkg.foo_var%TYPE; END;"),
+ Arguments.of("PackageWithNestedScalarTypeAttribute",
+ "CREATE PACKAGE BODY foo_pkg AS PROCEDURE foo_proc IS
foo_var NUMBER; foo_copy foo_pkg.foo_proc.foo_var%TYPE; BEGIN NULL; END; END;"),
+
Arguments.of("FunctionWithSchemaQualifiedCursorRowtypeAttribute",
+ "CREATE FUNCTION foo_schema.foo_func RETURN NUMBER AS
CURSOR foo_cursor IS SELECT 1 foo_id FROM dual;"
+ + " TYPE foo_ref IS REF CURSOR RETURN
foo_schema.foo_func.foo_cursor%ROWTYPE; BEGIN RETURN 1; END;"));
}
}