Skip to content

Commit

Permalink
Use Plugins.getMemberAccessor() instead of field reflect on test cases (
Browse files Browse the repository at this point in the history
  • Loading branch information
terrymanu authored Dec 23, 2022
1 parent e3170a5 commit 6e5f964
Show file tree
Hide file tree
Showing 82 changed files with 349 additions and 354 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import org.apache.shardingsphere.agent.core.path.AgentPathBuilder;
import org.junit.Test;
import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.internal.configuration.plugins.Plugins;

import java.io.File;
import java.io.IOException;
Expand All @@ -34,8 +34,8 @@ public final class PluginConfigurationLoaderTest {
private static final String DEFAULT_CONFIG_PATH = "/conf/agent.yaml";

@Test
public void assertLoad() throws IOException, NoSuchFieldException {
new InstanceField(AgentPathBuilder.class.getDeclaredField("agentPath"), AgentPathBuilder.class).set(new File(getResourceUrl()));
public void assertLoad() throws IOException, ReflectiveOperationException {
Plugins.getMemberAccessor().set(AgentPathBuilder.class.getDeclaredField("agentPath"), AgentPathBuilder.class, new File(getResourceUrl()));
assertNotNull(PluginConfigurationLoader.load());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@
import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutionUnit;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;
import org.junit.runner.RunWith;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.internal.configuration.plugins.Plugins;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
Expand Down Expand Up @@ -82,12 +81,12 @@ public void prepare() {
return invocation.callRealMethod();
}
});
Map<String, DataSourceMetaData> cachedDatasourceMetaData =
(Map<String, DataSourceMetaData>) new FieldReader(mockedJDBCExecutorCallback, JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA")).read();
Map<String, DataSourceMetaData> cachedDatasourceMetaData = (Map<String, DataSourceMetaData>) Plugins.getMemberAccessor()
.get(JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA"), mockedJDBCExecutorCallback);
cachedDatasourceMetaData.put("mock_url", new MockDataSourceMetaData());
Map<String, DatabaseType> storageTypes = new LinkedHashMap<>(1, 1);
storageTypes.put("mock.db", new MySQLDatabaseType());
new InstanceField(JDBCExecutorCallback.class.getDeclaredField("storageTypes"), mockedJDBCExecutorCallback).set(storageTypes);
Plugins.getMemberAccessor().set(JDBCExecutorCallback.class.getDeclaredField("storageTypes"), mockedJDBCExecutorCallback, storageTypes);
targetObject = (TargetAdviceObject) mockedJDBCExecutorCallback;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.Properties;

Expand All @@ -33,9 +33,9 @@ public final class JaegerTracingPluginBootServiceTest {
private final JaegerTracingPluginBootService pluginBootService = new JaegerTracingPluginBootService();

@After
public void close() throws NoSuchFieldException {
public void close() throws ReflectiveOperationException {
pluginBootService.close();
new InstanceField(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.class).set(NoopTracerFactory.create());
Plugins.getMemberAccessor().set(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.class, NoopTracerFactory.create());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
import lombok.SneakyThrows;
import org.apache.shardingsphere.agent.plugin.tracing.rule.CollectorRule;
import org.junit.rules.ExternalResource;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.List;

public class JaegerCollector extends ExternalResource implements CollectorRule {
public final class JaegerCollector extends ExternalResource implements CollectorRule {

private MockTracer tracer;

Expand All @@ -37,8 +37,7 @@ protected void before() {
if (!GlobalTracer.isRegistered()) {
GlobalTracer.register(new MockTracer());
}
FieldReader fieldReader = new FieldReader(GlobalTracer.get(), GlobalTracer.class.getDeclaredField("tracer"));
tracer = (MockTracer) fieldReader.read();
tracer = (MockTracer) Plugins.getMemberAccessor().get(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.get());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public final class CommandExecutorTaskAdviceTest {
Expand All @@ -53,8 +53,7 @@ public static void setup() throws ReflectiveOperationException {
if (!GlobalTracer.isRegistered()) {
GlobalTracer.register(new MockTracer());
}
FieldReader fieldReader = new FieldReader(GlobalTracer.get(), GlobalTracer.class.getDeclaredField("tracer"));
tracer = (MockTracer) fieldReader.read();
tracer = (MockTracer) Plugins.getMemberAccessor().get(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.get());
executeCommandMethod = CommandExecutorTask.class.getDeclaredMethod("executeCommand", ChannelHandlerContext.class, PacketPayload.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.io.IOException;
import java.lang.reflect.Method;
Expand All @@ -56,8 +56,7 @@ public static void setup() throws ReflectiveOperationException {
if (!GlobalTracer.isRegistered()) {
GlobalTracer.register(new MockTracer());
}
FieldReader fieldReader = new FieldReader(GlobalTracer.get(), GlobalTracer.class.getDeclaredField("tracer"));
tracer = (MockTracer) fieldReader.read();
tracer = (MockTracer) Plugins.getMemberAccessor().get(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.get());
executeMethod = JDBCExecutorCallback.class.getDeclaredMethod("execute", JDBCExecutionUnit.class, boolean.class, Map.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.io.IOException;
import java.lang.reflect.Method;
Expand All @@ -46,12 +46,11 @@ public final class SQLParserEngineAdviceTest {
private static Method parserMethod;

@BeforeClass
public static void setup() throws NoSuchMethodException, NoSuchFieldException {
public static void setup() throws ReflectiveOperationException {
if (!GlobalTracer.isRegistered()) {
GlobalTracer.register(new MockTracer());
}
FieldReader fieldReader = new FieldReader(GlobalTracer.get(), GlobalTracer.class.getDeclaredField("tracer"));
tracer = (MockTracer) fieldReader.read();
tracer = (MockTracer) Plugins.getMemberAccessor().get(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.get());
parserMethod = ShardingSphereSQLParserEngine.class.getDeclaredMethod("parse", String.class, boolean.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.Properties;

Expand All @@ -39,7 +39,7 @@ public void close() {
@Test
public void assertStart() throws ReflectiveOperationException {
pluginBootService.start(new PluginConfiguration("localhost", 9441, "", new Properties()), true);
Tracing tracing = (Tracing) new FieldReader(pluginBootService, ZipkinTracingPluginBootService.class.getDeclaredField("tracing")).read();
Tracing tracing = (Tracing) Plugins.getMemberAccessor().get(ZipkinTracingPluginBootService.class.getDeclaredField("tracing"), pluginBootService);
assertNotNull(tracing.tracer());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.shardingsphere.encrypt.rewrite.token;

import lombok.SneakyThrows;
import org.apache.shardingsphere.encrypt.rewrite.aware.EncryptRuleAware;
import org.apache.shardingsphere.encrypt.rewrite.token.generator.EncryptOrderByItemTokenGenerator;
import org.apache.shardingsphere.encrypt.rewrite.token.generator.EncryptProjectionTokenGenerator;
Expand All @@ -30,7 +31,7 @@
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Field;
Expand Down Expand Up @@ -83,8 +84,9 @@ private void assertSQLTokenGenerator(final SQLTokenGenerator sqlTokenGenerator)
}
}

@SneakyThrows(ReflectiveOperationException.class)
private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) {
assertThat(new FieldReader(sqlTokenGenerator, findField(sqlTokenGenerator.getClass(), fieldName, filedInstance.getClass())).read(), is(filedInstance));
assertThat(Plugins.getMemberAccessor().get(findField(sqlTokenGenerator.getClass(), fieldName, filedInstance.getClass()), sqlTokenGenerator), is(filedInstance));
}

private Field findField(final Class<?> clazz, final String fieldName, final Class<?> fieldType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.Arrays;
import java.util.Collections;
Expand All @@ -41,7 +41,8 @@ public final class FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest {
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
((Map<?, ?>) new FieldReader(FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class, FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
((Map<?, ?>) Plugins.getMemberAccessor().get(
FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP"), FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class)).clear();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.Arrays;
import java.util.Collections;
Expand All @@ -41,7 +41,8 @@ public final class TransactionWeightReadQueryLoadBalanceAlgorithmTest {
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
((Map<?, ?>) new FieldReader(TransactionWeightReadQueryLoadBalanceAlgorithm.class, TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
((Map<?, ?>) Plugins.getMemberAccessor()
.get(TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP"), TransactionWeightReadQueryLoadBalanceAlgorithm.class)).clear();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@
import org.apache.shardingsphere.sharding.factory.KeyGenerateAlgorithmFactory;
import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -190,14 +189,14 @@ public void assertGenerateKeyBeyondMaxSequencePerMilliSecond() {
assertThat(actual, is(expected));
}

@SneakyThrows(NoSuchFieldException.class)
@SneakyThrows(ReflectiveOperationException.class)
private void setLastMilliseconds(final KeyGenerateAlgorithm algorithm, final Number value) {
new InstanceField(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("lastMilliseconds"), algorithm).set(value);
Plugins.getMemberAccessor().set(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("lastMilliseconds"), algorithm, value);
}

@SneakyThrows(NoSuchFieldException.class)
@SneakyThrows(ReflectiveOperationException.class)
private void setSequence(final KeyGenerateAlgorithm algorithm, final Number value) {
new InstanceField(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("sequence"), algorithm).set(value);
Plugins.getMemberAccessor().set(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("sequence"), algorithm, value);
}

@Test(expected = IllegalArgumentException.class)
Expand Down Expand Up @@ -233,10 +232,10 @@ public void assertSetMaxVibrationOffsetFailureWhenOutOfRange() {
}

@Test
public void assertSetMaxTolerateTimeDifferenceMilliseconds() throws NoSuchFieldException {
public void assertSetMaxTolerateTimeDifferenceMilliseconds() throws ReflectiveOperationException {
Properties props = new Properties();
props.setProperty("max-tolerate-time-difference-milliseconds", String.valueOf(1));
KeyGenerateAlgorithm algorithm = KeyGenerateAlgorithmFactory.newInstance(new AlgorithmConfiguration("SNOWFLAKE", props));
assertThat(((Properties) new FieldReader(algorithm, algorithm.getClass().getDeclaredField("props")).read()).getProperty("max-tolerate-time-difference-milliseconds"), is("1"));
assertThat(((Properties) Plugins.getMemberAccessor().get(algorithm.getClass().getDeclaredField("props"), algorithm)).getProperty("max-tolerate-time-difference-milliseconds"), is("1"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import org.apache.shardingsphere.sharding.rule.aware.ShardingRuleAware;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.Collection;
import java.util.Iterator;
Expand Down Expand Up @@ -86,6 +86,6 @@ private void assertSqlTokenGenerator(final SQLTokenGenerator sqlTokenGenerator)
}

private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) throws Exception {
assertThat(new FieldReader(sqlTokenGenerator, sqlTokenGenerator.getClass().getDeclaredField(fieldName)).read(), is(filedInstance));
assertThat(Plugins.getMemberAccessor().get(sqlTokenGenerator.getClass().getDeclaredField(fieldName), sqlTokenGenerator), is(filedInstance));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;
import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -60,8 +60,8 @@ private Properties createJdbcUrlProperties() {
return result;
}

@SneakyThrows(NoSuchFieldException.class)
@SneakyThrows(ReflectiveOperationException.class)
private Properties getConnectionProperties(final BasicDataSource actual) {
return (Properties) new FieldReader(actual, BasicDataSource.class.getDeclaredField("connectionProperties")).read();
return (Properties) Plugins.getMemberAccessor().get(BasicDataSource.class.getDeclaredField("connectionProperties"), actual);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import org.junit.After;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;

import java.sql.SQLException;

Expand All @@ -30,7 +30,7 @@ public final class ExecutorExceptionHandlerTest {

@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
((ThreadLocal<?>) new FieldReader(SQLExecutorExceptionHandler.class, SQLExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN")).read()).remove();
((ThreadLocal<?>) Plugins.getMemberAccessor().get(SQLExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN"), SQLExecutorExceptionHandler.class)).remove();
}

@Test(expected = SQLException.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.junit.MockitoJUnitRunner;

import java.sql.Connection;
Expand Down Expand Up @@ -92,8 +92,8 @@ protected Optional<Integer> getSaneResult(final SQLStatement sqlStatement, final
return Optional.empty();
}
};
Map<String, DataSourceMetaData> cachedDataSourceMetaData = (Map<String, DataSourceMetaData>) new FieldReader(
jdbcExecutorCallback, JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA")).read();
Map<String, DataSourceMetaData> cachedDataSourceMetaData = (Map<String, DataSourceMetaData>) Plugins.getMemberAccessor()
.get(JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA"), jdbcExecutorCallback);
jdbcExecutorCallback.execute(units, true, Collections.emptyMap());
assertThat(cachedDataSourceMetaData.size(), is(1));
jdbcExecutorCallback.execute(units, true, Collections.emptyMap());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import org.apache.shardingsphere.sql.parser.api.CacheOption;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.junit.Test;
import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.internal.configuration.plugins.Plugins;

import static org.hamcrest.CoreMatchers.isA;
import static org.hamcrest.MatcherAssert.assertThat;
Expand All @@ -36,7 +36,7 @@ public final class SQLStatementCacheLoaderTest {
public void assertSQLStatementCacheLoad() throws ReflectiveOperationException {
SQLStatementCacheLoader sqlStatementCacheLoader = new SQLStatementCacheLoader("MySQL", new CacheOption(128, 1024L), false);
SQLStatementParserExecutor executor = mock(SQLStatementParserExecutor.class, RETURNS_DEEP_STUBS);
new InstanceField(sqlStatementCacheLoader.getClass().getDeclaredField("sqlStatementParserExecutor"), sqlStatementCacheLoader).set(executor);
Plugins.getMemberAccessor().set(sqlStatementCacheLoader.getClass().getDeclaredField("sqlStatementParserExecutor"), sqlStatementCacheLoader, executor);
assertThat(sqlStatementCacheLoader.load(SQL), isA(SQLStatement.class));
}
}
Loading

0 comments on commit 6e5f964

Please sign in to comment.