Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

--other=add unit test for polaris routing module #44

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ public static ServiceId newServiceId() {
return serviceId;
}

public static ServiceId newTestServiceId() {
ServiceId serviceId = new ServiceId();
Map<String, Object> params = new HashMap<>();
serviceId.setParameters(params);
return serviceId;
}

public static ServiceInstance genServiceInstance(int i) {
Map<String, Object> map = new HashMap<>();
map.put(POLARIS_CMDBCAMPUS, "cmdbCampus");
Expand Down Expand Up @@ -170,6 +177,14 @@ private static PluginConfig createDiscoveryConfig() {
return new PluginConfig("polaris", PolarisSelector.class, extMap);
}

private static PluginConfig createDiscoveryConfig1() {
Map<String, Object> extMap = new HashMap<>();
extMap.put(PolarisConstant.POLARIS_RUNMODE_KEY, RunMode.ModeNoAgent.ordinal());
extMap.put(PolarisConstant.POLARIS_ADDRESSES_KEY, "http://10.235.25.499:8080");
extMap.put(PolarisConstant.POLARIS_ENABLE_TRANS_META, "true");
return new PluginConfig("polaris", PolarisSelector.class, extMap);
}


private static PluginConfig createWorkerPoolConfig() {
return WorkerPoolManager.newThreadWorkerPoolConfig("selector_pool1", 4, Boolean.FALSE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,27 @@
import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.APIFactory;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import com.tencent.polaris.plugins.loadbalancer.random.WeightedRandomBalance;
import com.tencent.polaris.plugins.loadbalancer.ringhash.ConsistentHashLoadBalance;
import com.tencent.trpc.core.common.ConfigManager;
import com.tencent.trpc.core.common.config.PluginConfig;
import com.tencent.trpc.core.rpc.Request;
import com.tencent.trpc.core.selector.ServiceId;
import com.tencent.trpc.core.selector.ServiceInstance;
import com.tencent.trpc.polaris.common.PolarisConstant;
import com.tencent.trpc.polaris.common.PolarisTrans;
import com.tencent.trpc.selector.polaris.PolarisSelector;
import com.tencent.trpc.selector.polaris.common.PolarisCommon;
import com.tencent.trpc.selector.polaris.common.pojo.PolarisServiceInstances;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.*;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不能引入”*“,import具体的类

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ObjectUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
Expand Down Expand Up @@ -152,9 +157,9 @@ public void testFallback() {
clusterNaming.init();
ServiceId serviceId = DataTest.newServiceId();
serviceId.setServiceName("fallback");

Request request = DataTest.request;
CompletionStage<ServiceInstance> future = clusterNaming
.asyncSelectOne(serviceId, DataTest.request);
.asyncSelectOne(serviceId, request);
AtomicReference<Throwable> errorRef = new AtomicReference<>();
CompletionStage<ServiceInstance> stage = future.whenComplete((res, err) -> {
if (err != null) {
Expand Down Expand Up @@ -307,6 +312,12 @@ public void toPolarisInstance() {
Assert.assertEquals("set.sz.1", polarisServiceInstance.getMetadata().get("set"));
}

@Test
public void testEmptyToPolarisInstance() {
List<ServiceInstance> serviceInstances = null;
Assert.assertNull(PolarisTrans.toPolarisInstance(serviceInstances));
}

@Test
public void testDestroy() {
PolarisSelector clusterNaming = new PolarisSelector();
Expand All @@ -327,4 +338,113 @@ public void testGetConsumerAPI() {
Assert.assertNotNull(polarisSelector.getPolarisAPI());
polarisSelector.destroy();
}

@Test
public void testExceptionInit() {
PolarisSelector polarisSelector = new PolarisSelector();
try {
polarisSelector.setPluginConfig(selectorConfig);
polarisSelector.init();
Assert.assertNull(polarisSelector.getPolarisAPI());
polarisSelector.destroy();
} catch (Exception e) {
return;
}
}

@Test
public void testExceptionWarmup() {
PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
clusterNaming.init();
ServiceId serviceId = DataTest.newTestServiceId();
try {
clusterNaming.warmup(serviceId);
} catch (Exception e) {
return;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

可以再这里断言一下,如果是测试异常情况,其他地方也是

}
}

@Test
public void testAsyncSelectOne() {
PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
clusterNaming.init();
ServiceId serviceId = DataTest.newServiceId();
serviceId.setServiceName("service-metadata-select-one");
clusterNaming.warmup(serviceId);
Request request = DataTest.mockServiceMetadataRequest();
CompletionStage<ServiceInstance> future = clusterNaming.asyncSelectOne(serviceId, request);
AtomicReference<Throwable> errorRef = new AtomicReference<>();
CompletionStage<ServiceInstance> stage = future.whenComplete((res, err) -> {
if (err != null) {
errorRef.set(err);
err.printStackTrace();
}
});
CompletableFuture.allOf(stage.toCompletableFuture()).join();
Assert.assertNull(errorRef.get());
}

@Test
public void testGetCriteria() {
PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
clusterNaming.init();
ServiceId serviceId = DataTest.newServiceId();
serviceId.setServiceName("service-metadata-select-one");
clusterNaming.warmup(serviceId);
Request request = DataTest.mockServiceMetadataRequest();
request.getMeta().setHashVal("123333");
CompletionStage<ServiceInstance> future = clusterNaming.asyncSelectOne(serviceId, request);
AtomicReference<Throwable> errorRef = new AtomicReference<>();
CompletionStage<ServiceInstance> stage = future.whenComplete((res, err) -> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

能正常获取到实例,就没有异常吧,也可以判断一下ServiceInstance

if (err != null) {
errorRef.set(err);
err.printStackTrace();
}
});
CompletableFuture.allOf(stage.toCompletableFuture()).join();
Assert.assertNull(errorRef.get());
}

@Test
public void testExceptionAsyncSelectOne() {
PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
ServiceId serviceId = DataTest.newServiceId();
serviceId.setServiceName("fallback");
Request request = DataTest.request;
try {
CompletionStage<ServiceInstance> future = clusterNaming
.asyncSelectOne(serviceId, request);
} catch (Exception e) {
return;
}
}

@Test
public void testExceptionReport() {
PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
clusterNaming.init();
try {
clusterNaming.report(null, 1, -1L);
} catch (Exception e) {
return;
}
}

@Test
public void testExceptionAsyncSelectAll() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

异常测试,需要断言一下,其他也是

PolarisSelector clusterNaming = new PolarisSelector();
clusterNaming.setPluginConfig(selectorConfig);
clusterNaming.init();
try {
ServiceId serviceId = Mockito.mock(ServiceId.class);
clusterNaming.asyncSelectAll(serviceId,DataTest.request);
} catch (Exception e) {
return;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,39 @@

package com.tencent.trpc.selector.open.polaris.common;

import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.factory.config.consumer.CircuitBreakerConfigImpl;
import com.tencent.trpc.core.common.config.PluginConfig;
import com.tencent.trpc.core.selector.SelectorManager;
import com.tencent.trpc.core.selector.spi.Selector;
import com.tencent.trpc.selector.open.polaris.DataTest;
import com.tencent.trpc.selector.polaris.PolarisSelector;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import com.google.common.collect.Maps;
import com.tencent.polaris.api.plugin.route.RouteResult;
import com.tencent.polaris.api.plugin.route.RouteResult.NextRouterInfo;
import com.tencent.polaris.api.plugin.route.RouteResult.State;
import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import com.tencent.polaris.factory.config.consumer.ConsumerConfigImpl;
import com.tencent.polaris.factory.config.consumer.LocalCacheConfigImpl;
import com.tencent.polaris.factory.config.global.APIConfigImpl;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import com.tencent.trpc.core.selector.ServiceInstance;
import com.tencent.trpc.polaris.common.PolarisConstant;
import com.tencent.trpc.polaris.common.PolarisTrans;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.tencent.trpc.selector.polaris.common.PolarisCommon;

public class PolarisTransTest {

Expand Down Expand Up @@ -143,4 +164,137 @@ public void testUpdateConsumerConfig() {
Assert.assertEquals(3, cacheConfig.getPersistMaxWriteRetry());
Assert.assertEquals("test_type", cacheConfig.getType());
}

@Test
public void testGetPolarisInstanceId() {
Instance instance = Mockito.mock(Instance.class);
when(instance.getHost()).thenReturn("127.0.0.1");
when(instance.getPort()).thenReturn(111);
when(instance.isHealthy()).thenReturn(true);
when(instance.getRevision()).thenReturn("1.0.0");
Map<String, String> metadata = new HashMap<>();
metadata.put("set", "set.sz.1");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这些字符串和魔数辛苦提取为常量

metadata.put(PolarisConstant.POLARIS_ID, "sz0001");
when(instance.getMetadata()).thenReturn(metadata);

InstancesResponse instancesResponse = Mockito.mock(InstancesResponse.class);
when(instancesResponse.getTotalWeight()).thenReturn(1000);
when(instancesResponse.getNamespace()).thenReturn("dev");
when(instancesResponse.getService()).thenReturn("trpc.test.test.1");
when(instancesResponse.getInstances()).thenReturn(new Instance[]{instance});

ServiceInstance serviceInstance = PolarisTrans
.toServiceInstance(instancesResponse, instance);
String instanceId = PolarisTrans.getPolarisInstanceId(serviceInstance);
Assert.assertEquals("sz0001",instanceId);
}

@Test
public void testParseRouterResult() {
Instance instance1 = Mockito.mock(Instance.class);
when(instance1.getId()).thenReturn("10001");
when(instance1.getHost()).thenReturn("10.0.0.1");
when(instance1.getPort()).thenReturn(2);
Map<String, String> metadata = new HashMap<>();
metadata.put("set", "set.sz.1");
metadata.put(PolarisConstant.POLARIS_ID, "sz0001");
when(instance1.getMetadata()).thenReturn(metadata);

Instance instance2 = Mockito.mock(Instance.class);
when(instance2.getId()).thenReturn("10002");
when(instance2.getHost()).thenReturn("10.0.0.1");
when(instance2.getPort()).thenReturn(1);
List<Instance> instances = new ArrayList<>();
instances.add(instance1);
instances.add(instance2);
InstancesResponse instancesResponse = Mockito.mock(InstancesResponse.class);
when(instancesResponse.getTotalWeight()).thenReturn(1000);
when(instancesResponse.getNamespace()).thenReturn("dev");
when(instancesResponse.getService()).thenReturn("trpc.test.test.1");
when(instancesResponse.getInstances()).thenReturn(instances.toArray(new Instance[0]));

RouteResult routeResult = Mockito.mock(RouteResult.class);
when(routeResult.getInstances()).thenReturn(instances);
when(routeResult.getNextRouterInfo()).thenReturn(new NextRouterInfo(State.Next));

List<ServiceInstance> serviceInstances = PolarisTrans.parseRouterResult(routeResult,instancesResponse);

ServiceInstances convertServiceIns = PolarisCommon.toServiceInstances(serviceInstances);

Assert.assertEquals(2,serviceInstances.size());
Assert.assertEquals("sz0001",serviceInstances.get(0).getParameter(PolarisConstant.POLARIS_ID));
Assert.assertEquals(2,convertServiceIns.getInstances().size());
}

@Test
public void testGenCircuitBreakerConfiguration() {
ConfigurationImpl configuration = new ConfigurationImpl();
configuration.setDefault();
Map<String, Object> extMap = new HashMap<>();
extMap.put(PolarisConstant.POLARIS_ID, "sz0001");
CircuitBreakerConfigImpl circuitBreakerConfig =
PolarisCommon.genCircuitBreakerConfiguration(configuration,extMap);
Assert.assertEquals(1,circuitBreakerConfig.getChain().size());
}

@Test
public void testEmptyGenCircuitBreakerConfiguration() {
ConfigurationImpl configuration = new ConfigurationImpl();
configuration.setDefault();
Map<String, Object> extMap = null;
CircuitBreakerConfigImpl circuitBreakerConfig =
PolarisCommon.genCircuitBreakerConfiguration(configuration,extMap);
Assert.assertEquals(1,circuitBreakerConfig.getChain().size());
}

@Test
public void testEmptyGenPolarisConfiguration() {
Assert.assertNotNull(PolarisCommon.genPolarisConfiguration(null));
}

@Test
public void testGetSetName() {
Instance instance = Mockito.mock(Instance.class);
when(instance.getHost()).thenReturn("127.0.0.1");
when(instance.getPort()).thenReturn(111);
when(instance.isHealthy()).thenReturn(true);
when(instance.getRevision()).thenReturn("1.0.0");
Map<String, String> metadata = new HashMap<>();
metadata.put(PolarisConstant.INTERNAL_SET_NAME_KEY, "set.sz.1");
metadata.put(PolarisConstant.INTERNAL_ENABLE_SET_KEY, "Y");
when(instance.getMetadata()).thenReturn(metadata);
Assert.assertEquals("set.sz.1",PolarisTrans.getSetName(instance));
}

@Test
public void testGetContainerName() {
Instance instance = Mockito.mock(Instance.class);
when(instance.getHost()).thenReturn("127.0.0.1");
when(instance.getPort()).thenReturn(111);
when(instance.isHealthy()).thenReturn(true);
when(instance.getRevision()).thenReturn("1.0.0");
Map<String, String> metadata = new HashMap<>();
metadata.put(PolarisConstant.CONTAINER_NAME, "xxx1");
when(instance.getMetadata()).thenReturn(metadata);
Assert.assertEquals("xxx1",PolarisTrans.getContainerName(instance));
}

@Test
public void testPickMetaData() {
Assert.assertNotNull(PolarisTrans.pickMetaData(new HashMap<>(),false,"sz11"));
}

@Test
public void testEmptyTransfer2ServiceInstance() {
Assert.assertEquals(0,PolarisTrans.transfer2ServiceInstance(null,null).size());
}

@Test
public void testExceptionParseRouterResult() {
try {
PolarisTrans.parseRouterResult(null,null);
} catch (Exception e) {
return;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

缺少断言

}
}
}
Loading