Skip to content

Commit

Permalink
Simplify usages of mock ShardingSphereDatabase (#33917)
Browse files Browse the repository at this point in the history
* Simplify usages of mock ShardingSphereDatabase
  • Loading branch information
terrymanu authored Dec 4, 2024
1 parent 702e00c commit d35ae4b
Show file tree
Hide file tree
Showing 26 changed files with 154 additions and 301 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.apache.shardingsphere.agent.plugin.metrics.core.config.MetricConfiguration;
import org.apache.shardingsphere.agent.plugin.metrics.core.fixture.collector.MetricsCollectorFixture;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData;
import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.junit.jupiter.api.AfterEach;
Expand Down Expand Up @@ -52,26 +53,24 @@ class JDBCMetaDataInfoExporterTest {
@BeforeEach
void setUp() {
instanceId = UUID.randomUUID().toString();
databaseName = "sharding_db";
databaseName = "foo_db";
ContextManager contextManager = mockContextManager(instanceId, databaseName);
ShardingSphereDataSourceContextHolder.put(instanceId, new ShardingSphereDataSourceContext(databaseName, contextManager));
}

private ContextManager mockContextManager(final String instanceId, final String databaseName) {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getName()).thenReturn(databaseName);
when(database.getResourceMetaData().getStorageUnits()).thenReturn(Collections.singletonMap("ds_0", mock(StorageUnit.class)));
ResourceMetaData resourceMetaData = mock(ResourceMetaData.class);
when(resourceMetaData.getStorageUnits()).thenReturn(Collections.singletonMap("ds_0", mock(StorageUnit.class)));
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(result.getDatabase(databaseName)).thenReturn(database);
when(result.getDatabase(databaseName)).thenReturn(new ShardingSphereDatabase(databaseName, mock(), resourceMetaData, mock(), Collections.emptyList()));
when(result.getComputeNodeInstanceContext().getInstance().getMetaData().getId()).thenReturn(instanceId);
return result;
}

@AfterEach
void clean() {
MetricConfiguration config = new MetricConfiguration("jdbc_meta_data_info",
MetricCollectorType.GAUGE_METRIC_FAMILY, "Meta data information of ShardingSphere-JDBC",
Arrays.asList("driver_instance", "database", "type"), Collections.emptyMap());
MetricCollectorType.GAUGE_METRIC_FAMILY, "Meta data information of ShardingSphere-JDBC", Arrays.asList("driver_instance", "database", "type"), Collections.emptyMap());
((MetricsCollectorFixture) MetricsCollectorRegistry.get(config, "FIXTURE")).reset();
ShardingSphereDataSourceContextHolder.remove(instanceId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.Optional;
import java.util.UUID;

Expand All @@ -50,15 +51,14 @@ class JDBCStateExporterTest {
@BeforeEach
void setUp() {
instanceId = UUID.randomUUID().toString();
databaseName = "sharding_db";
databaseName = "foo_db";
ContextManager contextManager = mockContextManager(instanceId, databaseName);
ShardingSphereDataSourceContextHolder.put(instanceId, new ShardingSphereDataSourceContext(databaseName, contextManager));
}

private ContextManager mockContextManager(final String instanceId, final String databaseName) {
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn(databaseName);
ShardingSphereDatabase database = new ShardingSphereDatabase(databaseName, mock(), mock(), mock(), Collections.emptyList());
when(result.getDatabase(databaseName)).thenReturn(database);
when(result.getComputeNodeInstanceContext().getInstance().getMetaData().getId()).thenReturn(instanceId);
when(result.getComputeNodeInstanceContext().getInstance().getState().getCurrentState().ordinal()).thenReturn(InstanceState.OK.ordinal());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,6 @@ class EncryptMergedResultTest {

private final DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE");

@Mock
private ShardingSphereDatabase database;

@Mock
private ShardingSphereMetaData metaData;

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private SelectStatementContext selectStatementContext;

Expand All @@ -79,14 +73,14 @@ class EncryptMergedResultTest {

@Test
void assertNext() throws SQLException {
assertFalse(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).next());
assertFalse(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).next());
}

@Test
void assertGetValueWithoutColumnProjection() throws SQLException {
when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.empty());
when(mergedResult.getValue(1, String.class)).thenReturn("foo_value");
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
}

@Test
Expand All @@ -95,9 +89,9 @@ void assertGetValueWithoutEncryptTable() throws SQLException {
null, null, new ColumnSegmentBoundInfo(new IdentifierValue("foo_col")));
when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.of(columnProjection));
EncryptRule rule = mockRule(mock(EncryptAlgorithm.class));
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
when(mergedResult.getValue(1, String.class)).thenReturn("foo_value");
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
assertThat(new EncryptMergedResult(database, mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
}

@Test
Expand All @@ -106,9 +100,9 @@ void assertGetValueWithoutEncryptColumn() throws SQLException {
null, null, new ColumnSegmentBoundInfo(new IdentifierValue("bar_col")));
when(selectStatementContext.findColumnProjection(1)).thenReturn(Optional.of(columnProjection));
EncryptRule rule = mockRule(mock(EncryptAlgorithm.class));
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
when(mergedResult.getValue(1, String.class)).thenReturn("foo_value");
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
assertThat(new EncryptMergedResult(database, mock(), selectStatementContext, mergedResult).getValue(1, String.class), is("foo_value"));
}

@Test
Expand All @@ -120,11 +114,8 @@ void assertGetValueWithEncryptColumn() throws SQLException {
EncryptAlgorithm encryptAlgorithm = mock(EncryptAlgorithm.class);
when(encryptAlgorithm.decrypt(eq("foo_value"), deepEq(new AlgorithmSQLContext("foo_db", "foo_schema", "foo_tbl", "foo_col")))).thenReturn("foo_decrypted_value");
EncryptRule rule = mockRule(encryptAlgorithm);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("foo_db");
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
when(metaData.containsDatabase("foo_db")).thenReturn(true);
when(metaData.getDatabase("foo_db")).thenReturn(database);
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock());
when(mergedResult.getValue(1, Object.class)).thenReturn("foo_value");
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class), is("foo_decrypted_value"));
}
Expand All @@ -138,11 +129,8 @@ void assertGetValueFailed() throws SQLException {
EncryptAlgorithm encryptAlgorithm = mock(EncryptAlgorithm.class);
when(encryptAlgorithm.decrypt(eq("foo_value"), deepEq(new AlgorithmSQLContext("foo_db", "foo_schema", "foo_tbl", "foo_col")))).thenThrow(new RuntimeException("Test failed"));
EncryptRule rule = mockRule(encryptAlgorithm);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("foo_db");
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
when(metaData.containsDatabase("foo_db")).thenReturn(true);
when(metaData.getDatabase("foo_db")).thenReturn(database);
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(), mock(), mock());
when(mergedResult.getValue(1, Object.class)).thenReturn("foo_value");
assertThrows(DecryptFailedException.class, () -> new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getValue(1, String.class));
}
Expand All @@ -162,25 +150,25 @@ private EncryptRule mockRule(final EncryptAlgorithm encryptAlgorithm) {
void assertGetCalendarValue() throws SQLException {
Calendar calendar = Calendar.getInstance();
when(mergedResult.getCalendarValue(1, Date.class, calendar)).thenReturn(new Date(0L));
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getCalendarValue(1, Date.class, calendar), is(new Date(0L)));
assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getCalendarValue(1, Date.class, calendar), is(new Date(0L)));
}

@Test
void assertGetInputStream() throws SQLException {
InputStream inputStream = mock(InputStream.class);
when(mergedResult.getInputStream(1, "asc")).thenReturn(inputStream);
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getInputStream(1, "asc"), is(inputStream));
assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getInputStream(1, "asc"), is(inputStream));
}

@Test
void assertGetCharacterStream() throws SQLException {
Reader reader = mock(Reader.class);
when(mergedResult.getCharacterStream(1)).thenReturn(reader);
assertThat(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).getCharacterStream(1), is(reader));
assertThat(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).getCharacterStream(1), is(reader));
}

@Test
void assertWasNull() throws SQLException {
assertFalse(new EncryptMergedResult(database, metaData, selectStatementContext, mergedResult).wasNull());
assertFalse(new EncryptMergedResult(mock(), mock(), selectStatementContext, mergedResult).wasNull());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class EncryptInsertValuesTokenGeneratorTest {

Expand All @@ -48,21 +47,14 @@ void assertIsGenerateSQLToken() {
@Test
void assertGenerateSQLTokenFromGenerateNewSQLToken() {
generator.setPreviousSQLTokens(Collections.emptyList());
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("db_schema");
generator.setDatabase(database);
generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()));
assertThat(generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Arrays.asList(1, "Tom", 0, "123456"))).toString(), is("(?, ?, ?, ?, ?, ?)"));
}

@Test
void assertGenerateSQLTokenFromPreviousSQLTokens() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("db-001");
generator.setDatabase(database);
generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens());
database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("db_schema");
generator.setDatabase(database);
generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()));
assertThat(generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Arrays.asList(1, "Tom", 0, "123456"))).toString(), is("(?, ?, ?, ?, ?, ?)"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
import org.junit.jupiter.api.Test;

import java.util.Collection;
import java.util.Collections;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class EncryptPredicateRightValueTokenGeneratorTest {

Expand All @@ -46,27 +46,22 @@ void setup() {

@Test
void assertIsGenerateSQLToken() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("foo_db");
generator.setDatabase(database);
generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()));
assertTrue(generator.isGenerateSQLToken(EncryptGeneratorFixtureBuilder.createUpdateStatementContext()));
}

@Test
void assertGenerateSQLTokenFromGenerateNewSQLToken() {
UpdateStatementContext updateStatementContext = EncryptGeneratorFixtureBuilder.createUpdateStatementContext();
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getName()).thenReturn("foo_db");
generator.setDatabase(database);
generator.setDatabase(new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.emptyList()));
generator.setEncryptConditions(getEncryptConditions(updateStatementContext));
Collection<SQLToken> sqlTokens = generator.generateSQLTokens(updateStatementContext);
assertThat(sqlTokens.size(), is(1));
assertThat(sqlTokens.iterator().next().toString(), is("'assistedEncryptValue'"));
}

private Collection<EncryptCondition> getEncryptConditions(final UpdateStatementContext updateStatementContext) {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
when(database.getSchema("foo_db")).thenReturn(mock(ShardingSphereSchema.class));
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), mock(), Collections.singleton(new ShardingSphereSchema("foo_db")));
return new EncryptConditionEngine(EncryptGeneratorFixtureBuilder.createEncryptRule(), database)
.createEncryptConditions(updateStatementContext.getWhereSegments(), updateStatementContext.getColumnSegments(), updateStatementContext, "foo_db");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,8 @@ void assertExecuteUpdateWithoutAssistQueryAndLikeColumns() throws SQLException {
}

private ContextManager mockContextManager(final EncryptRule rule) {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getName()).thenReturn("foo_db");
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(result.getDatabase("foo_db")).thenReturn(database);
when(result.getDatabase("foo_db")).thenReturn(new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList()));
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,8 @@ private EncryptRuleConfiguration createCurrentRuleConfigurationWithMultipleTable
}

private ContextManager mockContextManager(final EncryptRule rule) {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getName()).thenReturn("foo_db");
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
when(result.getDatabase("foo_db")).thenReturn(database);
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ private boolean assertRuleConfigurationWithIfExists(final MaskRuleConfiguration
}

private ContextManager mockContextManager(final MaskRule rule) {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getName()).thenReturn("foo_db");
when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule)));
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", mock(), mock(), new RuleMetaData(Collections.singleton(rule)), Collections.emptyList());
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(result.getDatabase("foo_db")).thenReturn(database);
return result;
Expand Down
Loading

0 comments on commit d35ae4b

Please sign in to comment.