diff --git a/jacoco.exec b/jacoco.exec new file mode 100644 index 0000000000..e69de29bb2 diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/TrpcGatewayApplicationTest.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/TrpcGatewayApplicationTest.java new file mode 100644 index 0000000000..e6a05bbea6 --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/TrpcGatewayApplicationTest.java @@ -0,0 +1,44 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway; + +import com.tencent.trpc.spring.cloud.gateway.service.MyService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TrpcGatewayApplication.class) +public class TrpcGatewayApplicationTest { + + @Autowired + private MyService myService; + + @Autowired + private ApplicationContext applicationContext; + + @Test + public void testContextLoads() { + // 测试上下文加载 + Assert.assertNotNull(applicationContext); + } + + @Test + public void testComponentBehavior() { + Assert.assertNotNull(myService); + Assert.assertTrue(myService.invoke()); + } +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/client/TrpcGatewayClientTest.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/client/TrpcGatewayClientTest.java new file mode 100644 index 0000000000..f069c1281f --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/client/TrpcGatewayClientTest.java @@ -0,0 +1,133 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.client; + +import com.tencent.trpc.core.rpc.CloseFuture; +import com.tencent.trpc.core.rpc.GenericClient; +import com.tencent.trpc.core.rpc.RpcClientContext; +import com.tencent.trpc.core.rpc.TRpcProxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletionStage; +import java.util.function.Predicate; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.cloud.gateway.filter.FilterDefinition; +import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.route.Route.Builder; +import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.server.ServerWebExchange; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(TRpcProxy.class) +@PowerMockIgnore({"javax.management.*", "javax.security.*", "javax.ws.*"}) +public class TrpcGatewayClientTest { + + private TrpcGatewayClient client; + + private Route route; + + private Builder builder; + + /** + * 初始化build. + * + * @throws URISyntaxException + */ + @Before + public void setUp() throws URISyntaxException { + PowerMockito.mockStatic(TRpcProxy.class); + RouteDefinition definition = initData(); + builder = Route.builder(definition); + Predicate predicate = serverWebExchange -> { + serverWebExchange.checkNotModified("test"); + return true; + }; + ReflectionTestUtils.setField(builder, "predicate", predicate); + Predicate predicate2 = serverWebExchange -> { + serverWebExchange.checkNotModified("test2"); + return true; + }; + builder.and(predicate2); + route = builder.build(); + Mockito.when(TRpcProxy.getProxy(Mockito.anyString())).thenReturn(new GenericClient() { + + @Override + public CompletionStage asyncInvoke(RpcClientContext context, byte[] body) { + return new CloseFuture<>(); + } + + @Override + public byte[] invoke(RpcClientContext context, byte[] body) { + return new byte[0]; + } + }); + + client = new TrpcGatewayClient(route); + } + + private static @NotNull RouteDefinition initData() throws URISyntaxException { + RouteDefinition definition = new RouteDefinition(); + definition.setId("1"); + List list = new ArrayList<>(); + list.add(new FilterDefinition()); + definition.setFilters(list); + URI uri = new URI("https://www.tencent.com/sayHello/nameParam"); + definition.setUri(uri); + Map metaData = new HashMap<>(); + metaData.put("k1", new Object()); + definition.setMetadata(metaData); + definition.setOrder(1024); + List predicates = new ArrayList<>(); + PredicateDefinition p = new PredicateDefinition(); + p.setName("trpc-Name"); + p.setArgs(new HashMap<>()); + predicates.add(p); + definition.setPredicates(predicates); + return definition; + } + + @Test + public void testOpen() throws URISyntaxException { + Object callInfo = ReflectionTestUtils.getField(client, "callInfo"); + Assert.assertNotNull(callInfo); + } + + @Test(expected = NullPointerException.class) + public void testParseCallInfoWithNull() { + TrpcGatewayClient.parseCallInfo(""); + } + + @Test + public void testParseCallInfoWithIllegalArgument() { + try { + TrpcGatewayClient.parseCallInfo("http://www.abc.com"); + } catch (Exception e) { + Assert.assertTrue( + e.getMessage().contains("Create RpcInvocation fail: URI does not meet path specification")); + } + } +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/TrpcGatewayFilterFactoryTest.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/TrpcGatewayFilterFactoryTest.java new file mode 100644 index 0000000000..51995e50b8 --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/TrpcGatewayFilterFactoryTest.java @@ -0,0 +1,126 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.filter; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.tencent.trpc.spring.cloud.gateway.filter.TrpcGatewayFilterFactory.Config; +import com.tencent.trpc.spring.cloud.gateway.filter.request.MyRequestRewriter; +import com.tencent.trpc.spring.cloud.gateway.filter.request.MyRequestRewriterTest; +import com.tencent.trpc.spring.cloud.gateway.filter.response.MyResponseRewriter; +import com.tencent.trpc.spring.cloud.gateway.filter.response.MyResponseRewriterTest; +import com.tencent.trpc.spring.cloud.gateway.rewriter.TrpcRequestRewriter; +import com.tencent.trpc.spring.cloud.gateway.rewriter.TrpcResponseRewriter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.test.util.ReflectionTestUtils; + +public class TrpcGatewayFilterFactoryTest { + + private TrpcGatewayFilterFactory factory; + + private TrpcGatewayFilterFactory.Config config; + + @Before + public void setUp() { + config = mock(Config.class); + factory = new TrpcGatewayFilterFactory(); + ReflectionTestUtils.setField(factory, "requestRewriter", mock(TrpcRequestRewriter.class)); + ReflectionTestUtils.setField(factory, "responseRewriter", mock(TrpcResponseRewriter.class)); + } + + @Test + public void testApply() { + when(config.isEnabled()).thenReturn(Boolean.TRUE); + GatewayFilter filter = factory.apply(config); + Assert.assertNotNull(filter); + Assert.assertTrue(filter instanceof TrpcRoutingFilter); + } + + @Test + public void testLoadRequestRewriter() { + setRequest(); + } + + @Test(expected = IllegalArgumentException.class) + public void testLoadRequestRewriterWithException() { + String className = "com.tencent.MyRequestRewriter"; + Mockito.when(config.getRequestRewriter()).thenReturn(className); + factory.apply(config); + } + + @Test + public void testLoadRequestRewriterWithNull() { + String className = "com.tencent.trpc.spring.cloud.gateway.filter.request.MyRequestRewriterTest"; + Mockito.when(config.getRequestRewriter()).thenReturn(className); + factory.apply(config); + Object requestRewriter = ReflectionTestUtils.getField(factory, "requestRewriter"); + Assert.assertFalse(requestRewriter instanceof MyRequestRewriterTest); + } + + @Test + public void testLoadResponseRewriter() { + setRequest(); + String respClassName = "com.tencent.trpc.spring.cloud.gateway.filter.response.MyResponseRewriter"; + Mockito.when(config.getResponseRewriter()).thenReturn(respClassName); + factory.apply(config); + Object requestRewriter = ReflectionTestUtils.getField(factory, "responseRewriter"); + Assert.assertTrue(requestRewriter instanceof MyResponseRewriter); + } + + + @Test(expected = IllegalArgumentException.class) + public void testLoadResponseRewriterWithException() { + setRequest(); + String className = "com.tencent.MyRequestRewriter"; + Mockito.when(config.getRequestRewriter()).thenReturn(className); + factory.apply(config); + } + + @Test + public void testLoadResponseRewriterWithNull() { + setRequest(); + String className = "com.tencent.trpc.spring.cloud.gateway.filter.response.MyResponseRewriterTest"; + Mockito.when(config.getResponseRewriter()).thenReturn(className); + factory.apply(config); + Object requestRewriter = ReflectionTestUtils.getField(factory, "responseRewriter"); + System.out.println(requestRewriter); + Assert.assertFalse(requestRewriter instanceof MyResponseRewriterTest); + } + + private void setRequest() { + String className = "com.tencent.trpc.spring.cloud.gateway.filter.request.MyRequestRewriter"; + Mockito.when(config.getRequestRewriter()).thenReturn(className); + factory.apply(config); + Object requestRewriter = ReflectionTestUtils.getField(factory, "requestRewriter"); + Assert.assertTrue(requestRewriter instanceof MyRequestRewriter); + } + + @Test + public void testConfig() { + TrpcGatewayFilterFactory.Config newConfig = new Config(); + newConfig.setEnabled(true); + Assert.assertTrue(newConfig.isEnabled()); + + String requestWriter = "com.tencent.trpc.spring.cloud.gateway.filter.request.MyRequestRewriter"; + newConfig.setRequestRewriter(requestWriter); + Assert.assertEquals(requestWriter, newConfig.getRequestRewriter()); + + String metaData = "k1:v1;k2:v2"; + newConfig.setMetadata(metaData); + Assert.assertEquals(metaData, newConfig.getMetadata()); + } +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriter.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriter.java new file mode 100644 index 0000000000..46ce8744ae --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriter.java @@ -0,0 +1,25 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.filter.request; + +import com.tencent.trpc.spring.cloud.gateway.rewriter.TrpcRequestRewriter; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.web.server.ServerWebExchange; + +public class MyRequestRewriter implements TrpcRequestRewriter { + + @Override + public DataBuffer resolver(ServerWebExchange exchange, Route route, DataBuffer body) { + return null; + } +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriterTest.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriterTest.java new file mode 100644 index 0000000000..0b5928a97a --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/request/MyRequestRewriterTest.java @@ -0,0 +1,16 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.filter.request; + +public class MyRequestRewriterTest extends Thread { + +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriter.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriter.java new file mode 100644 index 0000000000..a9d5bc6f23 --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriter.java @@ -0,0 +1,25 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.filter.response; + +import com.tencent.trpc.spring.cloud.gateway.rewriter.TrpcResponseRewriter; +import java.util.Map; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +public class MyResponseRewriter implements TrpcResponseRewriter { + + @Override + public Mono write(ServerWebExchange exchange, Map metaData, Mono result) { + return null; + } +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriterTest.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriterTest.java new file mode 100644 index 0000000000..ac66f420d1 --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/response/MyResponseRewriterTest.java @@ -0,0 +1,16 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.filter.response; + +public class MyResponseRewriterTest extends Thread{ + +} diff --git a/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/service/MyService.java b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/service/MyService.java new file mode 100644 index 0000000000..d0e53aa79d --- /dev/null +++ b/trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/service/MyService.java @@ -0,0 +1,22 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.cloud.gateway.service; + +import org.springframework.stereotype.Component; + +@Component +public class MyService { + + public boolean invoke() { + return true; + } +} diff --git a/trpc-spring-support/trpc-spring/src/main/java/com/tencent/trpc/spring/exception/support/DefaultExceptionResultTransformer.java b/trpc-spring-support/trpc-spring/src/main/java/com/tencent/trpc/spring/exception/support/DefaultExceptionResultTransformer.java index 5d081cd037..54f0f81761 100644 --- a/trpc-spring-support/trpc-spring/src/main/java/com/tencent/trpc/spring/exception/support/DefaultExceptionResultTransformer.java +++ b/trpc-spring-support/trpc-spring/src/main/java/com/tencent/trpc/spring/exception/support/DefaultExceptionResultTransformer.java @@ -18,7 +18,6 @@ import com.tencent.trpc.spring.exception.api.ExceptionResultTransformer; import java.util.Collection; import java.util.Map; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** @@ -32,17 +31,6 @@ public class DefaultExceptionResultTransformer implements ExceptionResultTransfo private static final Map, Builder> cache = new ConcurrentHashMap<>(); - private static Builder newBuilder(Class clazz) { - Objects.requireNonNull(clazz, "protobuf message class must not be null"); - return cache.computeIfAbsent(clazz, c -> { - try { - return (Builder) c.getMethod("newBuilder").invoke(null); - } catch (Exception e) { - throw new IllegalStateException("newBuilder for type '" + clazz + "' error", e); - } - }).getDefaultInstanceForType().newBuilderForType(); - } - @SuppressWarnings("unchecked") @Override public Object transform(Object result, Class targetType) { diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractExceptionHandlingMethodInterceptorTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractExceptionHandlingMethodInterceptorTest.java new file mode 100644 index 0000000000..bd5cca1954 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractExceptionHandlingMethodInterceptorTest.java @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.aop; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import com.tencent.trpc.spring.exception.api.ExceptionHandler; +import com.tencent.trpc.spring.exception.api.ExceptionHandlerResolver; +import com.tencent.trpc.spring.exception.api.ExceptionResultTransformer; +import org.aopalliance.intercept.MethodInvocation; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.Ordered; +import java.lang.reflect.Method; +import org.springframework.test.util.ReflectionTestUtils; + +public class AbstractExceptionHandlingMethodInterceptorTest { + + private AbstractExceptionHandlingMethodInterceptor interceptor; + + @Mock + private MethodInvocation mockMethodInvocation; + + @Mock + private ExceptionHandlerResolver mockExceptionHandlerResolver; + + @Mock + private ExceptionHandler mockExceptionHandler; + + @Mock + private ExceptionResultTransformer mockExceptionResultTransformer; + + /** + * 初始化interceptor测试. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + interceptor = new AbstractExceptionHandlingMethodInterceptor( + () -> mockExceptionHandlerResolver, + () -> mockExceptionResultTransformer) { + // 覆盖抽象方法 + @Override + protected boolean shouldHandleException(Throwable t, Method method, Object[] args) { + return true; + } + + @Override + protected ExceptionHandler determineExceptionHandler(Method method) { + return mockExceptionHandler; + } + + @Override + protected ExceptionResultTransformer determineExceptionResultTransform(Method method) { + return mockExceptionResultTransformer; + } + }; + } + + @Test + public void testConstructor() { + Assert.assertNotNull(ReflectionTestUtils.getField(interceptor, "defaultHandlerResolverSupplier")); + Assert.assertNotNull(ReflectionTestUtils.getField(interceptor, "defaultTransformSupplier")); + } + + @Test + public void testGetOrder() { + // 验证getOrder方法是否返回正确的顺序值 + Assert.assertEquals(Ordered.HIGHEST_PRECEDENCE, interceptor.getOrder()); + } + + @Test(expected = NullPointerException.class) + public void testInvokeException() throws Throwable { + // 模拟异常执行 + when(mockMethodInvocation.proceed()).thenThrow(new RuntimeException("test exception")); + when(mockExceptionHandler.handle(any(), any(), any())).thenReturn("exception result"); + Object result = interceptor.invoke(mockMethodInvocation); + Assert.assertEquals("exception result", result); + } + + @Test + public void testInvoke() throws Throwable { + // 模拟正常执行 + when(mockMethodInvocation.proceed()).thenReturn("normal result"); + Object result = interceptor.invoke(mockMethodInvocation); + Assert.assertEquals("normal result", result); + } +} \ No newline at end of file diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractTRpcServiceAdvisorTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractTRpcServiceAdvisorTest.java new file mode 100644 index 0000000000..c66a00815d --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/aop/AbstractTRpcServiceAdvisorTest.java @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.aop; + +import org.aopalliance.aop.Advice; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.springframework.aop.Pointcut; + +public class AbstractTRpcServiceAdvisorTest { + + private AbstractTRpcServiceAdvisor advisor; + + @Mock + private Pointcut extraPointcut; + + @Before + public void setUp() { + advisor = new AbstractTRpcServiceAdvisor() { + @Override + public Advice getAdvice() { + return new Advice() { + }; + } + + @Override + protected Pointcut getExtraPointcut() { + return extraPointcut; + } + }; + } + + @Test + public void testGetPointcut() { + Pointcut pointcut = advisor.getPointcut(); + Assert.assertNotNull(pointcut); + } +} \ No newline at end of file diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/AnnotationInjectedBeanPostProcessorTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/AnnotationInjectedBeanPostProcessorTest.java new file mode 100644 index 0000000000..a9ad13de07 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/AnnotationInjectedBeanPostProcessorTest.java @@ -0,0 +1,123 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context; + +import static org.junit.Assert.fail; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.annotation.InjectionMetadata.InjectedElement; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.env.Environment; +import org.springframework.core.io.DefaultResourceLoader; + +public class AnnotationInjectedBeanPostProcessorTest { + + @Mock + private ConfigurableListableBeanFactory mockBeanFactory; + @Mock + private Environment mockEnvironment; + + private ConcreteAnnotationInjectedBeanPostProcessor processor; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + processor = new ConcreteAnnotationInjectedBeanPostProcessor(); + processor.setBeanFactory(mockBeanFactory); + processor.setEnvironment(mockEnvironment); + processor.setBeanClassLoader(new DefaultResourceLoader().getClassLoader()); + } + + @Test + public void testPostProcessProperties() { + Object bean = new Object(); + PropertyValues pvs = new PropertyValues() { + @Override + public PropertyValue[] getPropertyValues() { + return new PropertyValue[0]; + } + + @Override + public PropertyValue getPropertyValue(String s) { + return new PropertyValue(s, "testValue"); + } + + @Override + public PropertyValues changesSince(PropertyValues propertyValues) { + return propertyValues; + } + + @Override + public boolean contains(String s) { + return false; + } + + @Override + public boolean isEmpty() { + return false; + } + }; + String beanName = "testBean"; + PropertyValues processedPvs = processor.postProcessProperties(pvs, bean, beanName); + Assert.assertNotNull(processedPvs); + } + + @Test + public void testPostProcessMergedBeanDefinition() { + RootBeanDefinition beanDefinition = new RootBeanDefinition(); + Class beanType = Object.class; + String beanName = "testBean"; + processor.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName); + Assert.assertNotNull(beanDefinition); + } + + @Test + public void testDestroy() { + try { + processor.destroy(); + } catch (Exception e) { + fail("Destroy method should not throw an exception"); + } + } + + static class ConcreteAnnotationInjectedBeanPostProcessor extends AnnotationInjectedBeanPostProcessor { + + public ConcreteAnnotationInjectedBeanPostProcessor() { + super(MyAnnotation.class); + } + + @Override + protected String buildInjectedObjectCacheKey(AnnotationAttributes attributes, Object bean, String beanName, + Class injectedType, InjectedElement injectedElement) { + return attributes.toString(); // 示例:使用注解属性的字符串表示作为缓存键 + } + + @Override + protected Object doGetInjectedBean(AnnotationAttributes attributes, Object bean, String beanName, + Class injectedType, InjectedElement injectedElement) throws Exception { + return Mockito.mock(injectedType); + } + } + + public @interface MyAnnotation { + + } +} \ No newline at end of file diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientAnnotationBeanPostProcessorTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientAnnotationBeanPostProcessorTest.java new file mode 100644 index 0000000000..2befafe50d --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientAnnotationBeanPostProcessorTest.java @@ -0,0 +1,89 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context; + +import static org.powermock.api.mockito.PowerMockito.when; + +import com.tencent.trpc.core.common.ConfigManager; +import com.tencent.trpc.core.common.config.BackendConfig; +import com.tencent.trpc.core.common.config.ClientConfig; +import com.tencent.trpc.core.utils.StringUtils; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.annotation.AnnotationAttributes; + +@PowerMockIgnore({"javax.management.*"}) +@RunWith(PowerMockRunner.class) +@PrepareForTest({ConfigManager.class}) +public class TRpcClientAnnotationBeanPostProcessorTest { + + private TRpcClientAnnotationBeanPostProcessor postProcessor; + + @Mock + private ConfigManager configManager; + + @Mock + private ClientConfig clientConfig; + + @Mock + private Map backendConfigMap; + + @Mock + private BackendConfig backendConfig; + + @Before + public void setUp() { + postProcessor = new TRpcClientAnnotationBeanPostProcessor(); + PowerMockito.mockStatic(ConfigManager.class); + backendConfig.setName("myName"); + } + + + @Test + public void testDoGetInjectedBean() { + when(ConfigManager.getInstance()).thenReturn(configManager); + when(configManager.getClientConfig()).thenReturn(clientConfig); + when(clientConfig.getBackendConfigMap()).thenReturn(backendConfigMap); + when(backendConfigMap.get(Mockito.anyString())).thenReturn(backendConfig); + AnnotationAttributes attributes = new AnnotationAttributes(); + attributes.put("id", "MmyAnnotationService"); + Object o = postProcessor.doGetInjectedBean(attributes, null, null, MyAnnotationService.class, null); + Assert.assertNull(o); + when(backendConfig.getDefaultProxy()).thenReturn(new Object()); + o = postProcessor.doGetInjectedBean(attributes, null, null, MyAnnotationService.class, null); + Assert.assertNotNull(o); + } + + @Test(expected = IllegalArgumentException.class) + public void testDoGetInjectedBeanWithException() { + when(ConfigManager.getInstance()).thenReturn(configManager); + when(configManager.getClientConfig()).thenReturn(clientConfig); + when(clientConfig.getBackendConfigMap()).thenReturn(backendConfigMap); + when(backendConfigMap.get(Mockito.anyString())).thenReturn(backendConfig); + AnnotationAttributes attributes = new AnnotationAttributes(); + attributes.put("id", StringUtils.EMPTY); + postProcessor.doGetInjectedBean(attributes, null, null, MyAnnotationService.class, null); + } + + static class MyAnnotationService { + + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientFactoryBeanTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientFactoryBeanTest.java new file mode 100644 index 0000000000..06c4ae087f --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcClientFactoryBeanTest.java @@ -0,0 +1,61 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; + +import com.tencent.trpc.core.rpc.TRpcProxy; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({TRpcProxy.class}) +public class TRpcClientFactoryBeanTest { + + private TRpcClientFactoryBean factoryBean; + + @Before + public void setUp() { + String name = "trpcService"; + MockitoAnnotations.initMocks(this); + factoryBean = new TRpcClientFactoryBean<>(name, MyTrpcService.class); + PowerMockito.mockStatic(TRpcProxy.class); + when(TRpcProxy.getProxy(name, MyTrpcService.class)).thenReturn(() -> 1024); + } + + @Test + public void testGetObject() { + assertNotNull(factoryBean); + MyTrpcService object = factoryBean.getObject(); + assertNotNull(object); + int result = object.doMethod(); + Assert.assertEquals(1024, result); + } + + @Test + public void testGetGetObjectType() { + Class objectType = factoryBean.getObjectType(); + Assert.assertEquals(objectType, MyTrpcService.class); + } + + public interface MyTrpcService { + + int doMethod(); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcLifecycleManagerTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcLifecycleManagerTest.java new file mode 100644 index 0000000000..21a5d438b2 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/TRpcLifecycleManagerTest.java @@ -0,0 +1,110 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; +import com.tencent.trpc.core.common.ConfigManager; +import com.tencent.trpc.core.common.config.ServerConfig; +import com.tencent.trpc.core.common.config.ServiceConfig; +import com.tencent.trpc.spring.util.TRpcSpringUtils; +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.event.ApplicationContextEvent; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.core.Ordered; + +@PowerMockIgnore({"javax.management.*"}) +@RunWith(PowerMockRunner.class) +@PrepareForTest({ConfigManager.class, TRpcSpringUtils.class}) +public class TRpcLifecycleManagerTest { + + @Mock + private ConfigManager mockConfigManager; + + @Mock + private ConfigurableApplicationContext context; + + TRpcLifecycleManager tRpcLifecycleManager; + + private static final String SERVICE_FILTER_THREE = "additional_server_filter"; + + private static final String SERVICE_FILTER_FOUR = "auto_inject_test_server_filter"; + + private static final String SERVICE_BACKEND_MAP_KEY = "service-backend"; + + private static final String SERVICE_CONFIG_NAME = "service_config_name"; + + @Before + public void setUp() { + tRpcLifecycleManager = new TRpcLifecycleManager(); + PowerMockito.mockStatic(ConfigManager.class); + when(ConfigManager.getInstance()).thenReturn(mockConfigManager); + context = mock(ConfigurableApplicationContext.class); + PowerMockito.mockStatic(TRpcSpringUtils.class); + } + + @Test + public void testSupportsEventType() { + Assert.assertTrue(tRpcLifecycleManager.supportsEventType(ContextRefreshedEvent.class)); + Assert.assertTrue(tRpcLifecycleManager.supportsEventType(ContextClosedEvent.class)); + Assert.assertFalse(tRpcLifecycleManager.supportsEventType(ApplicationContextEvent.class)); + } + + @Test + public void testOnContextRefreshedEvent() { + ContextRefreshedEvent contextRefreshedEvent = new ContextRefreshedEvent(context); + + // test ContextRefreshedEvent logic + when(TRpcSpringUtils.isAwareContext(context)).thenReturn(false); + tRpcLifecycleManager.onApplicationEvent(contextRefreshedEvent); + verify(mockConfigManager, times(0)).start(false); + verify(mockConfigManager, times(0)).start(true); + + when(TRpcSpringUtils.isAwareContext(context)).thenReturn(true); + ServerConfig serverConfig = new ServerConfig(); + ServiceConfig serviceConfig = new ServiceConfig(); + serviceConfig.setName(SERVICE_CONFIG_NAME); + serviceConfig.setFilters(Arrays.asList(SERVICE_FILTER_THREE, SERVICE_FILTER_FOUR)); + serverConfig.getServiceMap().put(SERVICE_BACKEND_MAP_KEY, serviceConfig); + when(mockConfigManager.getServerConfig()).thenReturn(serverConfig); + tRpcLifecycleManager.onApplicationEvent(contextRefreshedEvent); + verify(mockConfigManager, times(1)).start(false); + + // test ContextClosedEvent logic + ContextClosedEvent contextClosedEvent = new ContextClosedEvent(context); + verify(mockConfigManager, times(0)).stop(); + + when(TRpcSpringUtils.isAwareContext(context)).thenReturn(true); + tRpcLifecycleManager.onApplicationEvent(contextClosedEvent); + verify(mockConfigManager, times(1)).stop(); + + } + + @Test + public void testGetOrder() { + Assert.assertEquals(Ordered.HIGHEST_PRECEDENCE + 20000, tRpcLifecycleManager.getOrder()); + } + +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/AbstractProtocolSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/AbstractProtocolSchemaTest.java new file mode 100644 index 0000000000..d9ef599da4 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/AbstractProtocolSchemaTest.java @@ -0,0 +1,67 @@ +package com.tencent.trpc.spring.context.configuration.schema; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class AbstractProtocolSchemaTest { + + private AbstractProtocolSchema schema; + + @Before + public void setUp() { + schema = new AbstractProtocolSchema() { + + }; + } + + @Test + public void testProtocolSetterAndGetter() { + String testProtocol = "testProtocol"; + schema.setProtocol(testProtocol); + assertEquals(testProtocol, schema.getProtocol()); + } + + @Test + public void testExtMapSetterAndGetter() { + Map testMap = new HashMap<>(); + testMap.put("key", "value"); + schema.setExtMap(testMap); + assertEquals(testMap, schema.getExtMap()); + } + + @Test + public void testExtMapDefault() { + assertEquals(0, schema.getExtMap().size()); + } + + @Test + public void testBooleanSetterAndGetter() { + schema.setLazyinit(Boolean.FALSE); + assertFalse(schema.getLazyinit()); + } + + @Test + public void testIntegerSetterAndGetter() { + schema.setPayload(1024); + assertEquals(Integer.valueOf(1024), schema.getPayload()); + } + + @Test + public void testSetProtocolType() { + schema.setProtocolType("type1"); + String protocolType = schema.getProtocolType(); + assertEquals("type1", protocolType); + } + + @Test + public void setCompressMinBytes() { + schema.setCompressMinBytes(10); + Integer compressMinBytes = schema.getCompressMinBytes(); + assertEquals(10L, Long.parseLong(compressMinBytes + "")); + } +} \ No newline at end of file diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/GlobalSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/GlobalSchemaTest.java new file mode 100644 index 0000000000..51fabaa2d5 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/GlobalSchemaTest.java @@ -0,0 +1,59 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class GlobalSchemaTest { + + private GlobalSchema schema; + + @Before + public void stUp() { + schema = new GlobalSchema(); + } + + @Test + public void testSetEnableSet() { + schema.setEnableSet(YesOrNo.Y); + YesOrNo enableSet = schema.getEnableSet(); + Assert.assertEquals(YesOrNo.Y, enableSet); + } + + @Test + public void testSetFullSetName() { + String fullSetName = "myFullName"; + schema.setFullSetName(fullSetName); + String name = schema.getFullSetName(); + Assert.assertEquals(fullSetName, name); + } + + @Test + public void tesSetExt() { + Map extMap = new HashMap<>(); + extMap.put("k1", new Object()); + schema.setExt(extMap); + Map schemaExt = schema.getExt(); + Assert.assertEquals(extMap.size(), schemaExt.size()); + } + + @Test + public void testToString() { + schema.setFullSetName("fullName"); + String schemaString = schema.toString(); + Assert.assertTrue(schemaString.contains("fullSetName='fullName'")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientSchemaTest.java new file mode 100644 index 0000000000..db0280fabe --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientSchemaTest.java @@ -0,0 +1,82 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.client; + +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ClientSchemaTest { + + private ClientSchema schema; + + @Before + public void setUp() { + schema = new ClientSchema(); + } + + @Test + public void testSetNamespace() { + String ns = "ns-1"; + schema.setNamespace(ns); + Assert.assertEquals(ns, schema.getNamespace()); + } + + @Test + public void testSetRequestTimeout() { + Integer timeout = 2000; + schema.setRequestTimeout(timeout); + Assert.assertEquals(Long.parseLong(timeout + ""), Long.parseLong(schema.getRequestTimeout() + "")); + } + + @Test + public void testSetProxyType() { + String proxyType = "proxy-type"; + schema.setProxyType(proxyType); + Assert.assertEquals(proxyType, schema.getProxyType()); + } + + @Test + public void testSetFilters() { + List list = Arrays.asList("filter1", "filter2", "filter3"); + schema.setFilters(list); + Assert.assertEquals(list.size(), schema.getFilters().size()); + } + + @Test + public void setInterceptors() { + List list = Arrays.asList("incerceptor1", "incerceptor2", "incerceptor3"); + schema.setInterceptors(list); + Assert.assertEquals(list.size(), schema.getInterceptors().size()); + } + + @Test + public void setCallerServiceName() { + String callerServiceName = "serviceName-001"; + schema.setCallerServiceName(callerServiceName); + Assert.assertEquals(callerServiceName, schema.getCallerServiceName()); + } + + @Test + public void testToString() { + schema.setNamespace("ns-001"); + ClientSchema clientSchema = new ClientSchema(); + clientSchema.setNamespace("ns-002"); + Assert.assertNotEquals(schema, clientSchema); + clientSchema.setNamespace("ns-001"); + Assert.assertNotEquals(schema.toString(), clientSchema.toString()); + Assert.assertTrue(schema.toString().contains("ns-001")); + Assert.assertTrue(clientSchema.toString().contains("ns-001")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientServiceSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientServiceSchemaTest.java new file mode 100644 index 0000000000..37b21f5283 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/client/ClientServiceSchemaTest.java @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.client; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ClientServiceSchemaTest { + + private ClientServiceSchema clientServiceSchema; + + @Before + public void setUp() { + clientServiceSchema = new ClientServiceSchema(); + clientServiceSchema.setVersion("1024-version"); + } + + @Test + public void testSetRequestTimeout() { + Integer reqTimeout = 100; + clientServiceSchema.setRequestTimeout(reqTimeout); + Integer requestTimeout = clientServiceSchema.getRequestTimeout(); + long l = Long.parseLong(requestTimeout.toString()); + Assert.assertEquals(100L, l); + } + + @Test + public void testSetFilters() { + List list = Arrays.asList("filter1", "filter2", "filter3"); + clientServiceSchema.setFilters(list); + List filters = clientServiceSchema.getFilters(); + Assert.assertEquals(list.size(), filters.size()); + } + + @Test + public void testSetWorkerPool() { + String name = "workPool1"; + clientServiceSchema.setWorkerPool(name); + String workerPool = clientServiceSchema.getWorkerPool(); + Assert.assertEquals(name, workerPool); + } + + @Test + public void testSetNamingMap() { + Map map = new HashMap<>(); + map.put("k1", new Object()); + map.put("k2", new Object()); + clientServiceSchema.setNamingMap(map); + Map namingMap = clientServiceSchema.getNamingMap(); + Assert.assertEquals(map.size(), namingMap.size()); + Assert.assertTrue(namingMap.keySet().contains("k1")); + Assert.assertTrue(namingMap.keySet().contains("k2")); + } + + @Test + public void testSetNamespace() { + String ns = "public"; + clientServiceSchema.setNamespace(ns); + String namespace = clientServiceSchema.getNamespace(); + Assert.assertEquals(ns, namespace); + } + + @Test + public void testSetGroup() { + String group = "group"; + clientServiceSchema.setGroup(group); + String schemaGroup = clientServiceSchema.getGroup(); + Assert.assertEquals(group, schemaGroup); + } + + @Test + public void testSetBackupRequestTimeMs() { + Integer backReqTime = 3000; + clientServiceSchema.setBackupRequestTimeMs(backReqTime); + Integer backupRequestTimeMs = clientServiceSchema.getBackupRequestTimeMs(); + Assert.assertEquals(3000L, Long.parseLong(backupRequestTimeMs + "")); + } + + @Test + public void testSetCallerServiceName() { + String callServiceName = "callName"; + clientServiceSchema.setCallerServiceName(callServiceName); + String callerServiceName = clientServiceSchema.getCallerServiceName(); + Assert.assertEquals(callServiceName, callerServiceName); + } + + @Test + public void testToString() { + Assert.assertNotNull(clientServiceSchema.toString()); + Assert.assertTrue(clientServiceSchema.toString().contains("1024-version")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/plugin/PluginsSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/plugin/PluginsSchemaTest.java new file mode 100644 index 0000000000..de7d43f53b --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/plugin/PluginsSchemaTest.java @@ -0,0 +1,155 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.plugin; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class PluginsSchemaTest { + + private PluginsSchema pluginsSchema; + + @Before + public void setUp() { + pluginsSchema = new PluginsSchema(); + } + + @Test + public void testSetConfig() { + Map> configMap = new HashMap<>(); + configMap.put("k1", new HashMap<>()); + pluginsSchema.setConfig(configMap); + Map> config = pluginsSchema.getConfig(); + Assert.assertEquals(configMap.size(), config.size()); + } + + @Test + public void testSetTracing() { + Map> traceMap = new HashMap<>(); + traceMap.put("trace1", new HashMap<>()); + pluginsSchema.setTracing(traceMap); + Map> config = pluginsSchema.getTracing(); + Assert.assertEquals(traceMap.size(), config.size()); + } + + @Test + public void testSetTelemetry() { + Map> telemetryMap = new HashMap<>(); + telemetryMap.put("t1", new HashMap<>()); + pluginsSchema.setTelemetry(telemetryMap); + Map> config = pluginsSchema.getTelemetry(); + Assert.assertEquals(telemetryMap.size(), config.size()); + } + + @Test + public void testSetSelector() { + Map> selectMap = new HashMap<>(); + selectMap.put("selectMapKey", new HashMap<>()); + pluginsSchema.setSelector(selectMap); + Map> config = pluginsSchema.getSelector(); + Assert.assertEquals(selectMap.size(), config.size()); + } + + @Test + public void testSetDiscovery() { + Map> discoveryMap = new HashMap<>(); + discoveryMap.put("discoveryKey", new HashMap<>()); + pluginsSchema.setDiscovery(discoveryMap); + Map> config = pluginsSchema.getDiscovery(); + Assert.assertEquals(discoveryMap.size(), config.size()); + } + + @Test + public void testSetLoadbalance() { + Map> loadMap = new HashMap<>(); + loadMap.put("loadKey", new HashMap<>()); + pluginsSchema.setLoadbalance(loadMap); + Map> config = pluginsSchema.getLoadbalance(); + Assert.assertEquals(loadMap.size(), config.size()); + } + + @Test + public void testSetCircuitbreaker() { + Map> circuitbreakerMap = new HashMap<>(); + circuitbreakerMap.put("circuitbreakerKey", new HashMap<>()); + pluginsSchema.setCircuitbreaker(circuitbreakerMap); + Map> config = pluginsSchema.getCircuitbreaker(); + Assert.assertEquals(circuitbreakerMap.size(), config.size()); + } + + @Test + public void testSetRouter() { + Map> routerMap = new HashMap<>(); + routerMap.put("routerKey", new HashMap<>()); + pluginsSchema.setRouter(routerMap); + Map> config = pluginsSchema.getRouter(); + Assert.assertEquals(routerMap.size(), config.size()); + } + + @Test + public void testSetRegistry() { + Map> registryMap = new HashMap<>(); + registryMap.put("registryKey", new HashMap<>()); + pluginsSchema.setRegistry(registryMap); + Map> config = pluginsSchema.getRegistry(); + Assert.assertEquals(registryMap.size(), config.size()); + } + + @Test + public void testSetRemoteLog() { + Map> remoteLogMap = new HashMap<>(); + remoteLogMap.put("remoteLogKey", new HashMap<>()); + pluginsSchema.setRemoteLog(remoteLogMap); + Map> config = pluginsSchema.getRemoteLog(); + Assert.assertEquals(remoteLogMap.size(), config.size()); + } + + @Test + public void testSetMetrics() { + Map> metricsMap = new HashMap<>(); + metricsMap.put("metricsKey", new HashMap<>()); + pluginsSchema.setMetrics(metricsMap); + Map> config = pluginsSchema.getMetrics(); + Assert.assertEquals(metricsMap.size(), config.size()); + } + + @Test + public void testSetLimiter() { + Map> limitMap = new HashMap<>(); + limitMap.put("limitKey", new HashMap<>()); + pluginsSchema.setLimiter(limitMap); + Map> config = pluginsSchema.getLimiter(); + Assert.assertEquals(limitMap.size(), config.size()); + } + + @Test + public void testSetFilter() { + Map> filterMap = new HashMap<>(); + filterMap.put("filterKey", new HashMap<>()); + pluginsSchema.setFilter(filterMap); + Map> config = pluginsSchema.getFilter(); + Assert.assertEquals(filterMap.size(), config.size()); + } + + @Test + public void testToString() { + Map> filterMap = new HashMap<>(); + filterMap.put("filterKey", new HashMap<>()); + pluginsSchema.setFilter(filterMap); + String schemaStr = pluginsSchema.toString(); + Assert.assertNotNull(schemaStr); + Assert.assertTrue(schemaStr.contains("filter={filterKey={}}")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerAdminSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerAdminSchemaTest.java new file mode 100644 index 0000000000..dfd8dd025f --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerAdminSchemaTest.java @@ -0,0 +1,39 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.server; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ServerAdminSchemaTest { + + private ServerAdminSchema schema; + + private static final String IP = "127.0.0.1"; + + private static final Integer PORT = 9527; + + @Before + public void setUp() { + schema = new ServerAdminSchema(); + schema.setAdminIp(IP); + schema.setAdminPort(PORT); + } + + @Test + public void testToString() { + Assert.assertNotNull(schema.toString()); + Assert.assertTrue(schema.toString().contains(IP)); + Assert.assertTrue(schema.toString().contains(PORT.toString())); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerListenerSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerListenerSchemaTest.java new file mode 100644 index 0000000000..a626a57214 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerListenerSchemaTest.java @@ -0,0 +1,42 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.server; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ServerListenerSchemaTest { + + private ServerListenerSchema serverListenerSchema; + + private static final String listenerClass = "myListenerClass"; + + @Before + public void setUp() { + serverListenerSchema = new ServerListenerSchema(); + } + + @Test + public void testGetGetListenerClass() { + serverListenerSchema.setListenerClass(listenerClass); + String result = serverListenerSchema.getListenerClass(); + Assert.assertEquals(listenerClass, result); + } + + @Test + public void testToString() { + serverListenerSchema.setListenerClass(listenerClass); + String result = serverListenerSchema.toString(); + Assert.assertTrue(result.contains(listenerClass)); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerSchemaTest.java new file mode 100644 index 0000000000..2afe371a63 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerSchemaTest.java @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.server; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ServerSchemaTest { + + private ServerSchema schema; + + @Before + public void setUp() { + schema = new ServerSchema(); + } + + @Test + public void testSetServerListener() { + List schemaList = getServerListenerSchemas(); + schema.setServerListener(schemaList); + Assert.assertEquals(schemaList.size(), schema.getServerListener().size()); + } + + private static List getServerListenerSchemas() { + List schemaList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + ServerListenerSchema listenerSchema = new ServerListenerSchema(); + listenerSchema.setListenerClass("listener" + i); + schemaList.add(listenerSchema); + } + return schemaList; + } + + @Test + public void testSetRunListeners() { + List runnerListener = Arrays.asList("listener1", "listener2", "listener3"); + schema.setRunListeners(runnerListener); + Assert.assertEquals(runnerListener.size(), schema.getRunListeners().size()); + + } + + @Test + public void testSetNic() { + String nic = "myNic"; + schema.setNic(nic); + Assert.assertEquals(nic, schema.getNic()); + } + + @Test + public void testSetEnableLinkTimeout() { + schema.setEnableLinkTimeout(Boolean.TRUE); + Assert.assertTrue(schema.getEnableLinkTimeout()); + } + + @Test + public void testSetDisableDefaultFilter() { + schema.setDisableDefaultFilter(Boolean.FALSE); + Assert.assertFalse(schema.getDisableDefaultFilter()); + } + + @Test + public void testSetFilters() { + List testFilter = Arrays.asList("testFilter"); + schema.setFilters(testFilter); + Assert.assertEquals(testFilter.size(), schema.getFilters().size()); + } + + @Test + public void testSetCloseTimeout() { + schema.setCloseTimeout(1000L); + Assert.assertEquals(1000L, Long.parseLong(schema.getCloseTimeout() + "")); + } + + @Test + public void testSetConfigCenter() { + schema.setConfigCenter("rainbow-config"); + Assert.assertEquals("rainbow-config", schema.getConfigCenter()); + } + + @Test + public void testToString() { + schema.setNic("myNic"); + + ServerSchema serverSchema = new ServerSchema(); + serverSchema.setNic("myNic2"); + Assert.assertNotEquals(schema, serverSchema); + Assert.assertTrue(serverSchema.toString().contains("myNic2")); + + serverSchema.setNic("myNic"); + Assert.assertNotEquals(schema, serverSchema); + Assert.assertTrue(schema.toString().contains("myNic")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerServiceSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerServiceSchemaTest.java new file mode 100644 index 0000000000..5c0970eed0 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServerServiceSchemaTest.java @@ -0,0 +1,146 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.configuration.schema.server; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ServerServiceSchemaTest { + + private ServerServiceSchema schema; + + @Before + public void setUp() { + schema = new ServerServiceSchema(); + } + + @Test + public void setVersion() { + String v = "version-01"; + schema.setVersion(v); + String version = schema.getVersion(); + Assert.assertEquals(v, version); + } + + @Test + public void testSetGroup() { + String group = "group"; + schema.setGroup(group); + String schemaGroup = schema.getGroup(); + Assert.assertEquals(group, schemaGroup); + } + + @Test + public void testSetIp() { + String ip = "127.0.0.1"; + schema.setIp(ip); + String schemaIp = schema.getIp(); + Assert.assertEquals(ip, schemaIp); + } + + @Test + public void testSetNic() { + String nic = "nic1"; + schema.setNic(nic); + String schemaNic = schema.getNic(); + Assert.assertEquals(nic, schemaNic); + } + + @Test + public void testSetWorkerPool() { + String workerPoll = "workerPoll"; + schema.setWorkerPool(workerPoll); + String schemaWorkerPool = schema.getWorkerPool(); + Assert.assertEquals(workerPoll, schemaWorkerPool); + } + + @Test + public void testSetExtMap() { + Map extMap = new HashMap<>(); + extMap.put("k1", new Object()); + extMap.put("k2", new Object()); + + schema.setExtMap(extMap); + Map schemaExtMap = schema.getExtMap(); + Assert.assertEquals(extMap.size(), schemaExtMap.size()); + } + + @Test + public void testSetReusePort() { + schema.setReusePort(Boolean.TRUE); + Boolean reusePort = schema.getReusePort(); + Assert.assertTrue(reusePort); + } + + @Test + public void testSetRequestTimeout() { + schema.setRequestTimeout(100); + String reqTime = schema.getRequestTimeout() + ""; + Assert.assertEquals(100L, Long.parseLong(reqTime)); + } + + @Test + public void testSetDisableDefaultFilter() { + schema.setDisableDefaultFilter(Boolean.TRUE); + Boolean defaultFilter = schema.getDisableDefaultFilter(); + Assert.assertTrue(defaultFilter); + } + + @Test + public void testSetFilters() { + List list = Arrays.asList("filter1", "filter2", "filter3"); + schema.setFilters(list); + Assert.assertEquals(list.size(), schema.getFilters().size()); + } + + @Test + public void testSetRegistrys() { + Map> map = new HashMap<>(); + map.put("k1", new HashMap<>()); + schema.setRegistrys(map); + Assert.assertEquals(map.size(), schema.getRegistrys().size()); + } + + @Test + public void testSetBasePath() { + String path = "/usr/local/basePath"; + schema.setBasePath(path); + Assert.assertEquals(path, schema.getBasePath()); + } + + @Test + public void testSetEnableLinkTimeout() { + schema.setEnableLinkTimeout(Boolean.TRUE); + Assert.assertTrue(schema.getEnableLinkTimeout()); + } + + @Test + public void testSetIoMode() { + schema.setIoMode(IoMode.epoll); + Assert.assertEquals(IoMode.epoll, schema.getIoMode()); + } + + @Test + public void testToString() { + String v = "version-01"; + schema.setVersion(v); + String group = "group"; + schema.setGroup(group); + Assert.assertTrue(schema.toString().contains("version='version-01'")); + Assert.assertTrue(schema.toString().contains("ServerServiceSchema")); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServiceProviderSchemaTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServiceProviderSchemaTest.java index 7244a5f345..be6e21dd2c 100644 --- a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServiceProviderSchemaTest.java +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/configuration/schema/server/ServiceProviderSchemaTest.java @@ -90,4 +90,10 @@ public void testSetEnableLinkTimeout() { serviceProviderSchema.setEnableLinkTimeout(Boolean.TRUE); Assert.assertTrue(serviceProviderSchema.getEnableLinkTimeout()); } + + @Test + public void testGetDisableDefaultFilter() { + serviceProviderSchema.setDisableDefaultFilter(Boolean.TRUE); + Assert.assertTrue(serviceProviderSchema.getDisableDefaultFilter()); + } } \ No newline at end of file diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/support/BeanFactoryAwareSupportTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/support/BeanFactoryAwareSupportTest.java new file mode 100644 index 0000000000..6ba4b71d16 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/context/support/BeanFactoryAwareSupportTest.java @@ -0,0 +1,90 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.context.support; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.tencent.trpc.spring.test.TestSpringApplication; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestSpringApplication.class) +public class BeanFactoryAwareSupportTest { + + private BeanFactoryAwareSupport support; + + @Autowired + private BeanFactory beanFactory; + + @Before + public void setUp() { + support = new BeanFactoryAwareSupport(); + support.setBeanFactory(beanFactory); + } + + @Test + public void testSetBeanFactory() { + assertNotNull(beanFactory); + assertEquals(beanFactory, support.beanFactory); + } + + @Test + public void testGetBean() { + TaskExecutionAutoConfiguration bean = support.getBean(TaskExecutionAutoConfiguration.class); + assertNotNull(bean); + support.setBeanFactory(null); + bean = support.getBean(TaskExecutionAutoConfiguration.class); + assertNull(bean); + } + + @Test + public void testGetQualifierBean() { + String qualifier = "applicationTaskExecutor"; + ThreadPoolTaskExecutor bean = support.getQualifierBean(qualifier, ThreadPoolTaskExecutor.class); + assertNotNull(bean); + support.setBeanFactory(null); + try { + support.getQualifierBean(qualifier, ThreadPoolTaskExecutor.class); + } catch (Exception e) { + assertEquals(IllegalStateException.class, e.getClass()); + assertTrue(e.getMessage() + .contains("BeanFactory must be provided to access qualified bean 'applicationTaskExecutor'")); + } + } + + @Test(expected = IllegalStateException.class) + public void testGetQualifierBeanWithBeanFactoryIsNull() { + support.setBeanFactory(null); + String qualifier = "applicationTaskExecutor"; + ThreadPoolTaskExecutor bean = support.getQualifierBean(qualifier, ThreadPoolTaskExecutor.class); + assertNull(bean); + } + + @Test + public void testGetQualifierBeanWithNullQualifier() { + Object qualifierBean = support.getQualifierBean("", Object.class); + Assert.assertNull(qualifierBean); + } + +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/api/HandleExceptionConfigurerTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/api/HandleExceptionConfigurerTest.java new file mode 100644 index 0000000000..96e5c5156a --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/api/HandleExceptionConfigurerTest.java @@ -0,0 +1,80 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.exception.api; + +import java.lang.reflect.Method; +import javax.annotation.Nullable; +import org.junit.Assert; +import org.junit.Test; + +public class HandleExceptionConfigurerTest { + + private HandleExceptionConfigurer handleExceptionConfigurer; + + @Test + public void testGetCustomizedResultTransform() { + handleExceptionConfigurer = new MyHandleExceptionConfigurer(); + ExceptionResultTransformer customizedResultTransform = handleExceptionConfigurer.getCustomizedResultTransform(); + Assert.assertNull(customizedResultTransform); + handleExceptionConfigurer = new MyHandleExceptionConfigurerWithImpl(); + + customizedResultTransform = handleExceptionConfigurer.getCustomizedResultTransform(); + Assert.assertNotNull(customizedResultTransform); + } + + @Test + public void testGetCustomizedHandlerResolver() { + handleExceptionConfigurer = new MyHandleExceptionConfigurer(); + ExceptionHandlerResolver customizedHandlerResolver = handleExceptionConfigurer.getCustomizedHandlerResolver(); + Assert.assertNull(customizedHandlerResolver); + + handleExceptionConfigurer = new MyHandleExceptionConfigurerWithImpl(); + customizedHandlerResolver = handleExceptionConfigurer.getCustomizedHandlerResolver(); + Assert.assertNotNull(customizedHandlerResolver); + } + + static class MyHandleExceptionConfigurer implements HandleExceptionConfigurer { + } + + static class MyHandleExceptionConfigurerWithImpl implements HandleExceptionConfigurer { + + @Override + public ExceptionResultTransformer getCustomizedResultTransform() { + return (result, targetType) -> new Object(); + } + + @Override + public ExceptionHandlerResolver getCustomizedHandlerResolver() { + return new ExceptionHandlerResolver() { + @Nullable + @Override + public ExceptionHandler resolveExceptionHandler(Throwable t, @Nullable Object target, + @Nullable Method targetMethod) { + return new MyExceptionHandler(); + } + }; + } + + static class MyExceptionHandler implements ExceptionHandler { + + @Nullable + @Override + public Object handle(Throwable t, @Nullable Method targetMethod, @Nullable Object[] arguments) { + return new MyClass(); + } + } + + static class MyClass { + + } + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/support/DefaultExceptionHandlerResolverTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/support/DefaultExceptionHandlerResolverTest.java new file mode 100644 index 0000000000..c365f84cb8 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/exception/support/DefaultExceptionHandlerResolverTest.java @@ -0,0 +1,67 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.exception.support; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import com.tencent.trpc.spring.exception.api.ExceptionHandler; +import com.tencent.trpc.spring.exception.api.ExceptionHandlerResolver; +import java.lang.reflect.Method; +import java.util.concurrent.ConcurrentHashMap; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.util.ClassUtils; + +public class DefaultExceptionHandlerResolverTest { + + + @Mock + private DefaultExceptionHandlerResolver resolver; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + resolver = new DefaultExceptionHandlerResolver(); + } + + @Test + public void testResolveExceptionHandlerWithTargetBean() { + Object targetBean = new Object(); + Method targetMethod = getMethod(Object.class, "hashCode"); // 选择一个Object类的方法作为测试方法 + Throwable throwable = new Exception(); + ExceptionHandler result = resolver.resolveExceptionHandler(throwable, targetBean, targetMethod); + assertNull(result); + + AnnotationExceptionHandlerResolver mockResolver = Mockito.mock(AnnotationExceptionHandlerResolver.class); + ExceptionHandler mockExceptionHandler = Mockito.mock(ExceptionHandler.class); + Mockito.when(mockResolver.resolveExceptionHandler(throwable, targetBean, targetMethod)) + .thenReturn(mockExceptionHandler); + ConcurrentHashMap, ExceptionHandlerResolver> specificResolvers = new ConcurrentHashMap<>(); + specificResolvers.put(ClassUtils.getUserClass(targetBean), mockResolver); + ReflectionTestUtils.setField(resolver, "specificResolvers", specificResolvers); + result = resolver.resolveExceptionHandler(throwable, targetBean, targetMethod); + assertSame(mockExceptionHandler, result); + } + + private Method getMethod(Class clazz, String name) { + try { + return clazz.getMethod(name); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/AnnotationUtilsTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/AnnotationUtilsTest.java new file mode 100644 index 0000000000..b5871b6349 --- /dev/null +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/AnnotationUtilsTest.java @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making tRPC available. + * + * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * If you have downloaded a copy of the tRPC source code from Tencent, + * please note that tRPC source code is licensed under the Apache 2.0 License, + * A copy of the Apache 2.0 License can be found in the LICENSE file. + */ + +package com.tencent.trpc.spring.util; + +import static org.junit.Assert.assertArrayEquals; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.env.PropertyResolver; + +public class AnnotationUtilsTest { + + @Mock + private PropertyResolver propertyResolver; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetAttribute() { + String key = "attributeName"; + String value = "testValue"; + AnnotationAttributes attributes = AnnotationAttributes.fromMap(Collections.singletonMap(key, value)); + String object = AnnotationUtils.getAttribute(attributes, key); + Assert.assertEquals(value, object); + + object = AnnotationUtils.getAttribute(attributes, "other"); + Assert.assertNull(object); + } + + @Test + public void testResolvePlaceholders() { + String eleValueKey = "value"; + String eleValueValue = "${placeholderVal}"; + String eleNumberKey = "number"; + int eleNumberValue = 1024; + String result = "resolved_value"; + + Map attributes = new LinkedHashMap<>(); + attributes.put(eleValueKey, eleValueValue); + attributes.put(eleNumberKey, eleNumberValue); + + when(propertyResolver.resolvePlaceholders(eleValueValue)).thenReturn(result); + Map resolvedAttributes = AnnotationUtils.resolvePlaceholders(attributes, propertyResolver); + + Assert.assertEquals(result, resolvedAttributes.get(eleValueKey)); + Assert.assertEquals(Integer.valueOf(eleNumberValue), resolvedAttributes.get(eleNumberKey)); + } + + // 测试resolvePlaceholders处理字符串数组的情况 + @Test + public void testResolvePlaceholdersWithArray() { + Map attributes = new LinkedHashMap<>(); + String[] values = new String[]{"${placeholder1}", "${placeholder2}"}; + attributes.put("values", values); + + // 假设propertyResolver.resolvePlaceholders分别解析两个占位符 + when(propertyResolver.resolvePlaceholders("${placeholder1}")).thenReturn("value1"); + when(propertyResolver.resolvePlaceholders("${placeholder2}")).thenReturn("value2"); + + Map resolvedAttributes = AnnotationUtils.resolvePlaceholders(attributes, propertyResolver); + + assertArrayEquals(new String[]{"value1", "value2"}, (String[]) resolvedAttributes.get("values")); + } + + // 测试resolvePlaceholders忽略特定属性的情况 + @Test + public void testResolvePlaceholdersIgnoreAttributes() { + Map attributes = new LinkedHashMap<>(); + attributes.put("value", "${placeholder}"); + attributes.put("ignore", "${ignore}"); + + // 假设只有value属性需要解析 + when(propertyResolver.resolvePlaceholders("${placeholder}")).thenReturn("val"); + Map resolvedAttributes = AnnotationUtils.resolvePlaceholders(attributes, propertyResolver, + "ignore"); + + Assert.assertNull(resolvedAttributes.get("ignore")); // 忽略未解析的属性 + Assert.assertEquals("val", resolvedAttributes.get("value")); // 忽略未解析的属性 + } + + @Test + public void testAttribute() { + Map objectMap = AnnotationUtils.getAttributes(null, propertyResolver, true, ""); + Assert.assertEquals(0, objectMap.size()); + } +} diff --git a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/TRpcSpringUtilsTest.java b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/TRpcSpringUtilsTest.java index 66416f7e68..4097992cac 100644 --- a/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/TRpcSpringUtilsTest.java +++ b/trpc-spring-support/trpc-spring/src/test/java/com/tencent/trpc/spring/util/TRpcSpringUtilsTest.java @@ -1,7 +1,7 @@ /* * Tencent is pleased to support the open source community by making tRPC available. * - * Copyright (C) 2023 THL A29 Limited, a Tencent company. + * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, @@ -17,6 +17,8 @@ import com.tencent.trpc.core.rpc.anno.TRpcService; import com.tencent.trpc.spring.test.TestSpringApplication; import com.tencent.trpc.spring.util.TRpcSpringUtilsTest.BeanConfiguration; +import java.util.Collections; +import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,6 +29,8 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @@ -38,6 +42,16 @@ public class TRpcSpringUtilsTest { @Autowired private ConfigurableApplicationContext applicationContext; + private static final String NOT_APPLICATION_ID = "notApplication"; + + private static final String APPLICATION_ID = "application"; + + private static final String SPRING_APPLICATION_NAME_KEY = "spring.application.name"; + + private static final String SPRING_APPLICATION_NAME_VALUE = "notApplicationName"; + + private static final String CUSTOM_PROPERTY_SOURCE = "customPropertySource"; + @Test public void testSetRef() throws Exception { ApplicationContext context = new SpringApplicationBuilder() @@ -83,4 +97,43 @@ public TestService testService() { static class ChildContextConfiguration { } + + @Test + public void testIsAwareContext() { + Assert.assertTrue(TRpcSpringUtils.isAwareContext(applicationContext)); + + // test id is not application + applicationContext.setId(NOT_APPLICATION_ID); + Assert.assertFalse(TRpcSpringUtils.isAwareContext(applicationContext)); + + // test id is application + applicationContext.setId(APPLICATION_ID); + Assert.assertTrue(TRpcSpringUtils.isAwareContext(applicationContext)); + + // test id is application and spring.application.name is not null + applicationContext.setId(SPRING_APPLICATION_NAME_VALUE); + setApplicationName(); + String name = applicationContext.getEnvironment().getProperty(SPRING_APPLICATION_NAME_KEY); + Assert.assertEquals(SPRING_APPLICATION_NAME_VALUE, name); + Assert.assertTrue(TRpcSpringUtils.isAwareContext(applicationContext)); + + } + + private void setApplicationName() { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + MapPropertySource propertySource = new MapPropertySource(CUSTOM_PROPERTY_SOURCE, + Collections.singletonMap(SPRING_APPLICATION_NAME_KEY, SPRING_APPLICATION_NAME_VALUE)); + environment.getPropertySources().addFirst(propertySource); + } + + @Test + public void testIsAwareContextWithEmpty() { + // test id is null + applicationContext.setId(StringUtils.EMPTY); + boolean context = TRpcSpringUtils.isAwareContext(applicationContext); + Assert.assertFalse(context); + applicationContext.setId(null); + context = TRpcSpringUtils.isAwareContext(applicationContext); + Assert.assertFalse(context); + } }