Skip to content

Commit

Permalink
Use FieldReader and InstanceField instead of reflection api in test c…
Browse files Browse the repository at this point in the history
…ases (apache#23022)

* webfont

* Refactor ExecutorExceptionHandlerTest

* Refactor PluginBootServiceTest

* Refactor PipelineContextUtil

* Refactor FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest

* Refactor ConnectionIdGeneratorTest

* Refactor DBCPDataSourcePoolCreatorTest

* Refactor TransactionWeightReadQueryLoadBalanceAlgorithmTest

* Refactor RunnerParameters

* Refactor ShardingTokenGenerateBuilderTest

* Refactor SnowflakeKeyGenerateAlgorithmTest

* Refactor MySQLFrontendEngineTest

* Refactor EncryptTokenGenerateBuilderTest

* Refactor SQLStatementCacheLoaderTest

* Refactor StatementAdapterTest

* Refactor ImportDatabaseConfigurationHandlerTest

* Refactor SeataATShardingSphereTransactionManagerTest

* Refactor YamlShardingSphereDataSourceFactoryTest
  • Loading branch information
terrymanu authored Dec 22, 2022
1 parent 93f304c commit 47916c3
Show file tree
Hide file tree
Showing 35 changed files with 161 additions and 242 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.junit.AfterClass;
import org.junit.After;
import org.junit.Test;

import java.io.IOException;
Expand All @@ -42,11 +42,11 @@

public final class PrometheusPluginBootServiceTest extends ProxyContextRestorer {

private static final PrometheusPluginBootService PROMETHEUS_PLUGIN_BOOT_SERVICE = new PrometheusPluginBootService();
private final PrometheusPluginBootService pluginBootService = new PrometheusPluginBootService();

@AfterClass
public static void close() {
PROMETHEUS_PLUGIN_BOOT_SERVICE.close();
@After
public void close() {
pluginBootService.close();
}

@Test
Expand All @@ -56,7 +56,7 @@ public void assertStart() throws IOException {
new ComputeNodeInstance(mock(InstanceMetaData.class)), new StandaloneWorkerIdGenerator(), new ModeConfiguration("Standalone", null), mock(LockContext.class),
new EventBusContext());
ProxyContext.init(new ContextManager(metaDataContexts, instanceContext));
PROMETHEUS_PLUGIN_BOOT_SERVICE.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
pluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
new Socket().connect(new InetSocketAddress("localhost", 8090));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,25 @@
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
import org.mockito.internal.util.reflection.InstanceField;

import java.lang.reflect.Field;
import java.util.Properties;

import static org.junit.Assert.assertTrue;

public final class JaegerTracingPluginBootServiceTest {

private final JaegerTracingPluginBootService jaegerTracingPluginBootService = new JaegerTracingPluginBootService();
private final JaegerTracingPluginBootService pluginBootService = new JaegerTracingPluginBootService();

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

@Test
public void assertStart() {
jaegerTracingPluginBootService.start(new PluginConfiguration("localhost", 5775, "", createProperties()), true);
pluginBootService.start(new PluginConfiguration("localhost", 5775, "", createProperties()), true);
assertTrue(GlobalTracer.isRegistered());
}

Expand All @@ -46,12 +52,4 @@ private Properties createProperties() {
result.setProperty("JAEGER_REPORTER_FLUSH_INTERVAL", "1");
return result;
}

@After
public void close() throws ReflectiveOperationException {
jaegerTracingPluginBootService.close();
Field field = GlobalTracer.class.getDeclaredField("tracer");
field.setAccessible(true);
field.set(null, NoopTracerFactory.create());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@

public final class OpenTelemetryTracingPluginBootServiceTest {

private final OpenTelemetryTracingPluginBootService pluginBootService = new OpenTelemetryTracingPluginBootService();

@Test
public void assertStart() {
new OpenTelemetryTracingPluginBootService().start(new PluginConfiguration(null, 0, null, createProperties()), true);
pluginBootService.start(new PluginConfiguration(null, 0, null, createProperties()), true);
assertNotNull(GlobalOpenTelemetry.getTracerProvider());
assertNotNull(GlobalOpenTelemetry.getTracer("shardingsphere-agent"));
}
Expand All @@ -44,7 +46,7 @@ private Properties createProperties() {

@After
public void close() {
new OpenTelemetryTracingPluginBootService().close();
pluginBootService.close();
GlobalOpenTelemetry.resetForTest();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,16 @@

public final class OpenTracingPluginBootServiceTest {

private final OpenTracingPluginBootService openTracingPluginBootService = new OpenTracingPluginBootService();
private final OpenTracingPluginBootService pluginBootService = new OpenTracingPluginBootService();

@After
public void close() {
pluginBootService.close();
}

@Test
public void assertStart() {
openTracingPluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
pluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
assertTrue(GlobalTracer.isRegistered());
}

Expand All @@ -41,9 +46,4 @@ private Properties createProperties() {
result.setProperty("opentracing-tracer-class-name", "io.opentracing.mock.MockTracer");
return result;
}

@After
public void close() {
openTracingPluginBootService.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,25 @@
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;

import java.lang.reflect.Field;
import java.util.Properties;

import static org.junit.Assert.assertNotNull;

public final class ZipkinTracingPluginBootServiceTest {

private final ZipkinTracingPluginBootService zipkinTracingPluginBootService = new ZipkinTracingPluginBootService();
private final ZipkinTracingPluginBootService pluginBootService = new ZipkinTracingPluginBootService();

@After
public void close() {
pluginBootService.close();
}

@Test
public void assertStart() throws ReflectiveOperationException {
zipkinTracingPluginBootService.start(new PluginConfiguration("localhost", 9441, "", new Properties()), true);
Field field = ZipkinTracingPluginBootService.class.getDeclaredField("tracing");
field.setAccessible(true);
Tracing tracing = (Tracing) field.get(zipkinTracingPluginBootService);
pluginBootService.start(new PluginConfiguration("localhost", 9441, "", new Properties()), true);
Tracing tracing = (Tracing) new FieldReader(pluginBootService, ZipkinTracingPluginBootService.class.getDeclaredField("tracing")).read();
assertNotNull(tracing.tracer());
}

@After
public void close() {
zipkinTracingPluginBootService.close();
}
}
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@

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

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;
import org.apache.shardingsphere.encrypt.rule.EncryptRule;
import org.apache.shardingsphere.encrypt.rewrite.aware.EncryptRuleAware;
import org.apache.shardingsphere.infra.binder.segment.select.orderby.OrderByItem;
import org.apache.shardingsphere.infra.binder.statement.dml.SelectStatementContext;
import org.apache.shardingsphere.infra.database.DefaultDatabase;
Expand All @@ -30,6 +30,7 @@
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Field;
Expand Down Expand Up @@ -57,36 +58,33 @@ public void setup() {
}

@Test
public void assertGetSQLTokenGenerators() throws IllegalAccessException {
public void assertGetSQLTokenGenerators() {
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(selectStatementContext.getAllTables().isEmpty()).thenReturn(false);
when(selectStatementContext.getTablesContext().getTableNames()).thenReturn(Collections.singletonList("table"));
when(selectStatementContext.getOrderByContext().getItems()).thenReturn(Collections.singletonList(mock(OrderByItem.class)));
when(selectStatementContext.getGroupByContext().getItems()).thenReturn(Collections.emptyList());
when(selectStatementContext.getWhereSegments()).thenReturn(Collections.emptyList());
EncryptTokenGenerateBuilder encryptTokenGenerateBuilder = new EncryptTokenGenerateBuilder(
encryptRule, selectStatementContext, Collections.emptyList(), DefaultDatabase.LOGIC_NAME);
EncryptTokenGenerateBuilder encryptTokenGenerateBuilder = new EncryptTokenGenerateBuilder(encryptRule, selectStatementContext, Collections.emptyList(), DefaultDatabase.LOGIC_NAME);
Collection<SQLTokenGenerator> sqlTokenGenerators = encryptTokenGenerateBuilder.getSQLTokenGenerators();
assertThat(sqlTokenGenerators.size(), is(2));
Iterator<SQLTokenGenerator> iterator = sqlTokenGenerators.iterator();
SQLTokenGenerator item1 = iterator.next();
assertThat(item1, instanceOf(EncryptProjectionTokenGenerator.class));
assertSqlTokenGenerator(item1);
assertSQLTokenGenerator(item1);
SQLTokenGenerator item2 = iterator.next();
assertThat(item2, instanceOf(EncryptOrderByItemTokenGenerator.class));
assertSqlTokenGenerator(item2);
assertSQLTokenGenerator(item2);
}

private void assertSqlTokenGenerator(final SQLTokenGenerator sqlTokenGenerator) throws IllegalAccessException {
private void assertSQLTokenGenerator(final SQLTokenGenerator sqlTokenGenerator) {
if (sqlTokenGenerator instanceof EncryptRuleAware) {
assertField(sqlTokenGenerator, encryptRule, "encryptRule");
}
}

private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) throws IllegalAccessException {
Field field = findField(sqlTokenGenerator.getClass(), fieldName, filedInstance.getClass());
field.setAccessible(true);
assertThat(field.get(sqlTokenGenerator), is(filedInstance));
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));
}

private Field findField(final Class<?> clazz, final String fieldName, final Class<?> fieldType) {
Expand All @@ -99,6 +97,6 @@ private Field findField(final Class<?> clazz, final String fieldName, final Clas
}
searchClass = searchClass.getSuperclass();
}
throw new IllegalStateException("No such field in class");
throw new IllegalStateException("No such field in class.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldReader;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
Expand All @@ -38,13 +38,10 @@

public final class FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest {

@SuppressWarnings("rawtypes")
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
Field accuracyThresholdField = FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP");
accuracyThresholdField.setAccessible(true);
((Map) accuracyThresholdField.get(FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class)).clear();
((Map<?, ?>) new FieldReader(FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class, FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
}

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

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Expand All @@ -38,13 +38,10 @@

public final class TransactionWeightReadQueryLoadBalanceAlgorithmTest {

@SuppressWarnings("rawtypes")
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
Field accuracyThresholdField = TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP");
accuracyThresholdField.setAccessible(true);
((Map) accuracyThresholdField.get(TransactionWeightReadQueryLoadBalanceAlgorithm.class)).clear();
((Map<?, ?>) new FieldReader(TransactionWeightReadQueryLoadBalanceAlgorithm.class, TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,21 @@

import lombok.SneakyThrows;
import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
import org.apache.shardingsphere.infra.instance.InstanceContextAware;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.infra.instance.ComputeNodeInstance;
import org.apache.shardingsphere.infra.instance.InstanceContext;
import org.apache.shardingsphere.infra.instance.InstanceContextAware;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.lock.LockContext;
import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.sharding.algorithm.keygen.fixture.FixedTimeService;
import org.apache.shardingsphere.sharding.algorithm.keygen.fixture.WorkerIdGeneratorFixture;
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 java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
Expand Down Expand Up @@ -180,7 +181,7 @@ public void assertGenerateKeyBeyondMaxSequencePerMilliSecond() {
((InstanceContextAware) algorithm).setInstanceContext(INSTANCE);
}
setLastMilliseconds(algorithm, timeService.getCurrentMillis());
setSequence(algorithm, (1 << DEFAULT_SEQUENCE_BITS) - 1);
setSequence(algorithm, (1 << DEFAULT_SEQUENCE_BITS) - 1L);
List<Comparable<?>> expected = Arrays.asList(4194304L, 4194305L, 4194306L, 8388608L, 8388609L, 8388610L, 12582913L, 12582914L, 12582915L, 16777216L);
List<Comparable<?>> actual = new ArrayList<>(DEFAULT_KEY_AMOUNT);
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
Expand All @@ -189,18 +190,14 @@ public void assertGenerateKeyBeyondMaxSequencePerMilliSecond() {
assertThat(actual, is(expected));
}

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

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

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

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

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Iterator;

Expand Down Expand Up @@ -86,8 +86,6 @@ private void assertSqlTokenGenerator(final SQLTokenGenerator sqlTokenGenerator)
}

private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) throws Exception {
Field field = sqlTokenGenerator.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
assertThat(field.get(sqlTokenGenerator), is(filedInstance));
assertThat(new FieldReader(sqlTokenGenerator, sqlTokenGenerator.getClass().getDeclaredField(fieldName)).read(), is(filedInstance));
}
}
Loading

0 comments on commit 47916c3

Please sign in to comment.