diff --git a/CHANGELOG.md b/CHANGELOG.md index 4527cbadc..2664a8fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,3 +27,4 @@ - [feat:support tsf unit.](https://github.com/Tencent/spring-cloud-tencent/pull/1722) - [feat: support service registry and discovery with Polaris and Nacos](https://github.com/Tencent/spring-cloud-tencent/pull/1724) - [test:add junit tests to sct-common.](https://github.com/Tencent/spring-cloud-tencent/pull/1727) +- [test:add junit tests to sct-gw-plugin.](https://github.com/Tencent/spring-cloud-tencent/pull/1731) diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/main/java/com/tencent/tsf/gateway/core/model/GroupSecret.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/main/java/com/tencent/tsf/gateway/core/model/GroupSecret.java index 48bc99801..dcaa63ff5 100644 --- a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/main/java/com/tencent/tsf/gateway/core/model/GroupSecret.java +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/main/java/com/tencent/tsf/gateway/core/model/GroupSecret.java @@ -101,4 +101,16 @@ public class GroupSecret implements Serializable { public void setExpiredTime(String expiredTime) { this.expiredTime = expiredTime; } + + @Override + public String toString() { + return "GroupSecret{" + + "secretId='" + secretId + '\'' + + ", secretKey='" + secretKey + '\'' + + ", secretName='" + secretName + '\'' + + ", groupId='" + groupId + '\'' + + ", status='" + status + '\'' + + ", expiredTime='" + expiredTime + '\'' + + '}'; + } } diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/context/PathRewriteTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/context/PathRewriteTest.java new file mode 100644 index 000000000..deec11022 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/context/PathRewriteTest.java @@ -0,0 +1,53 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.plugin.gateway.context; + +import java.util.Collections; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PathRewrite}. + * + * @author Haotian Zhang + */ +public class PathRewriteTest { + + @Test + public void basicProperties() { + PathRewrite one = new PathRewrite(); + one.setPathRewriteId("id"); + one.setGatewayGroupId("gatewayGroupId"); + one.setRegex("regex"); + one.setReplacement("replacement"); + one.setBlocked("Y"); + one.setOrder(1); + one.setPathRewriteIds(Collections.emptyList()); + + assertThat(one.getPathRewriteId()).isEqualTo("id"); + assertThat(one.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(one.getRegex()).isEqualTo("regex"); + assertThat(one.getReplacement()).isEqualTo("replacement"); + assertThat(one.getBlocked()).isEqualTo("Y"); + assertThat(one.getOrder()).isEqualTo(1); + assertThat(one.getPathRewriteIds()).hasSize(0); + assertThat(one.toString()).isNotEmpty(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/TsfGatewayRequestTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/TsfGatewayRequestTest.java new file mode 100644 index 000000000..0660fa07a --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/TsfGatewayRequestTest.java @@ -0,0 +1,57 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core; + +import java.net.URI; +import java.util.HashMap; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link TsfGatewayRequest}. + * + * @author Haotian Zhang + */ +public class TsfGatewayRequestTest { + + @Test + public void testTsfGatewayRequest() { + TsfGatewayRequest tsfGatewayRequest = new TsfGatewayRequest(); + tsfGatewayRequest.setUri(URI.create("http://localhost:8080/test")); + tsfGatewayRequest.setMethod("GET"); + tsfGatewayRequest.setHeaders(new HashMap<>()); + tsfGatewayRequest.setRequestHeaders(new HashMap<>()); + tsfGatewayRequest.putRequestHeader("request", "test"); + tsfGatewayRequest.setParameterMap(new HashMap<>()); + tsfGatewayRequest.setCookieMap(new HashMap<>()); + tsfGatewayRequest.putCookie("cookie", "test"); + + assertThat(tsfGatewayRequest.getUri().toString()).isEqualTo("http://localhost:8080/test"); + assertThat(tsfGatewayRequest.getMethod()).isEqualTo("GET"); + assertThat(tsfGatewayRequest.getHeaders()).isNotNull(); + assertThat(tsfGatewayRequest.getHeader("test")).isNull(); + assertThat(tsfGatewayRequest.getRequestHeaders()).isNotNull(); + assertThat(tsfGatewayRequest.getRequestHeader("request")).isEqualTo("test"); + assertThat(tsfGatewayRequest.getParameterMap()).isNotNull(); + assertThat(tsfGatewayRequest.getCookieMap()).isNotNull(); + assertThat(tsfGatewayRequest.getCookie("cookie")).isEqualTo("test"); + assertThat(tsfGatewayRequest.toString()).isNotBlank(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/AuthModeTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/AuthModeTest.java new file mode 100644 index 000000000..afce73972 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/AuthModeTest.java @@ -0,0 +1,37 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link AuthMode}. + * + * @author Haotian Zhang + */ +public class AuthModeTest { + + @Test + public void testGetMode() { + assertThat(AuthMode.getMode("none")).isEqualTo(AuthMode.NONE); + assertThat(AuthMode.getMode("secret")).isEqualTo(AuthMode.SECRET); + assertThat(AuthMode.getMode("test")).isNull(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/CommonStatusTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/CommonStatusTest.java new file mode 100644 index 000000000..a37ae0f0e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/CommonStatusTest.java @@ -0,0 +1,44 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link CommonStatus}. + * + * @author Haotian Zhang + */ +public class CommonStatusTest { + + @Test + public void testGetStatus() { + assertThat(CommonStatus.getStatus("enabled")).isEqualTo(CommonStatus.ENABLED); + assertThat(CommonStatus.getStatus("disabled")).isEqualTo(CommonStatus.DISABLED); + assertThat(CommonStatus.getStatus("test")).isNull(); + + assertThat(CommonStatus.getStatus("enabled", "")).isEqualTo(CommonStatus.ENABLED); + assertThat(CommonStatus.getStatus("disabled", "")).isEqualTo(CommonStatus.DISABLED); + assertThat(CommonStatus.getStatus("test", "")).isNull(); + + assertThat(CommonStatus.ENABLED.getStatus()).isEqualTo("enabled"); + assertThat(CommonStatus.DISABLED.getStatus()).isEqualTo("disabled"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/GatewayConstantTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/GatewayConstantTest.java new file mode 100644 index 000000000..3b954f3e1 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/GatewayConstantTest.java @@ -0,0 +1,37 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThatNoException; + +/** + * Test for {@link GatewayConstant}. + * + * @author Haotian Zhang + */ +public class GatewayConstantTest { + + @Test + public void testGatewayConstant() { + assertThatNoException().isThrownBy(() -> { + System.out.println(GatewayConstant.GATEWAY_REPO_PREFIX); + }); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/HttpMethodTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/HttpMethodTest.java new file mode 100644 index 000000000..d86f7a536 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/HttpMethodTest.java @@ -0,0 +1,38 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link HttpMethod}. + * + * @author Haotian Zhang + */ +public class HttpMethodTest { + + @Test + public void testHttpMethod() { + assertThat(HttpMethod.getHttpMethod("POST")).isEqualTo(HttpMethod.POST); + assertThat(HttpMethod.getHttpMethod("GET")).isEqualTo(HttpMethod.GET); + assertThat(HttpMethod.getHttpMethod("PUT")).isEqualTo(HttpMethod.PUT); + assertThat(HttpMethod.getHttpMethod("DELETE")).isEqualTo(HttpMethod.DELETE); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginConstantsTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginConstantsTest.java new file mode 100644 index 000000000..e08b3dffd --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginConstantsTest.java @@ -0,0 +1,51 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link PluginConstants}. + * + * @author Haotian Zhang + */ +public class PluginConstantsTest { + + @Test + public void testTraceIdEnabledType() { + assertThat(PluginConstants.TraceIdEnabledType.getTraceIdEnabledType("Y")).isEqualTo(PluginConstants.TraceIdEnabledType.Y); + assertThat(PluginConstants.TraceIdEnabledType.getTraceIdEnabledType("N")).isEqualTo(PluginConstants.TraceIdEnabledType.N); + assertThat(PluginConstants.TraceIdEnabledType.getTraceIdEnabledType("test")).isNull(); + + assertThatNoException().isThrownBy(() -> { + PluginConstants.TraceIdEnabledType.checkValidity("Y"); + }); + assertThatNoException().isThrownBy(() -> { + PluginConstants.TraceIdEnabledType.checkValidity("N"); + }); + assertThatThrownBy(() -> { + PluginConstants.TraceIdEnabledType.checkValidity("test"); + }).isExactlyInstanceOf(TsfGatewayException.class).hasMessageContaining("Tag插件TraceIdEnabled类型"); + + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginScopeTypeTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginScopeTypeTest.java new file mode 100644 index 000000000..1de60dbe1 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginScopeTypeTest.java @@ -0,0 +1,40 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginScopeType}. + * + * @author Haotian Zhang + */ +public class PluginScopeTypeTest { + + @Test + public void testPluginScopeType() { + assertThat(PluginScopeType.getScopeType("group")).isEqualTo(PluginScopeType.GROUP); + assertThat(PluginScopeType.getScopeType("api")).isEqualTo(PluginScopeType.API); + assertThat(PluginScopeType.getScopeType("test")).isNull(); + + assertThat(PluginScopeType.GROUP.getScopeType()).isEqualTo("group"); + assertThat(PluginScopeType.API.getScopeType()).isEqualTo("api"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginTypeTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginTypeTest.java new file mode 100644 index 000000000..dded05bb5 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/PluginTypeTest.java @@ -0,0 +1,60 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import java.util.Map; + +import com.tencent.tsf.gateway.core.model.JwtPlugin; +import com.tencent.tsf.gateway.core.model.OAuthPlugin; +import com.tencent.tsf.gateway.core.model.RequestTransformerPlugin; +import com.tencent.tsf.gateway.core.model.TagPlugin; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginType}. + * + * @author Haotian Zhang + */ +public class PluginTypeTest { + + @Test + public void testPluginType() { + assertThat(PluginType.getPluginType("ReqTransformer")).isEqualTo(PluginType.REQ_TRANSFORMER); + assertThat(PluginType.getPluginType("OAuth")).isEqualTo(PluginType.OAUTH); + assertThat(PluginType.getPluginType("Jwt")).isEqualTo(PluginType.JWT); + assertThat(PluginType.getPluginType("Tag")).isEqualTo(PluginType.TAG); + assertThat(PluginType.getPluginType("Unknown")).isNull(); + assertThat(PluginType.getPluginType("")).isNull(); + + Map map = PluginType.toMap(); + assertThat(map.get("OAUTH")).isEqualTo("OAuth"); + assertThat(map.get("JWT")).isEqualTo("Jwt"); + assertThat(map.get("TAG")).isEqualTo("Tag"); + + assertThat(PluginType.OAUTH.getPluginClazz()).isEqualTo(OAuthPlugin.class); + assertThat(PluginType.JWT.getPluginClazz()).isEqualTo(JwtPlugin.class); + assertThat(PluginType.TAG.getPluginClazz()).isEqualTo(TagPlugin.class); + + PluginType.JWT.setType("newType"); + assertThat(PluginType.JWT.getType()).isEqualTo("newType"); + PluginType.JWT.setPluginClazz(RequestTransformerPlugin.class); + assertThat(PluginType.JWT.getPluginClazz()).isEqualTo(RequestTransformerPlugin.class); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/TsfAlgTypeTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/TsfAlgTypeTest.java new file mode 100644 index 000000000..a1a24f3cc --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/constant/TsfAlgTypeTest.java @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.constant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link TsfAlgType}. + * + * @author Haotian Zhang + */ +public class TsfAlgTypeTest { + + @Test + public void testTsfAlgType() { + assertThat(TsfAlgType.getSecurityCode("0")).isEqualTo(TsfAlgType.HMAC_MD5); + assertThat(TsfAlgType.getSecurityCode("1")).isEqualTo(TsfAlgType.HMAC_SHA_1); + assertThat(TsfAlgType.getSecurityCode("2")).isEqualTo(TsfAlgType.HMAC_SHA_256); + assertThat(TsfAlgType.getSecurityCode("3")).isEqualTo(TsfAlgType.HMAC_SHA_512); + assertThat(TsfAlgType.getSecurityCode("4")).isEqualTo(TsfAlgType.HMAC_SM3); + assertThat(TsfAlgType.getSecurityCode("test")).isNull(); + + assertThat(TsfAlgType.HMAC_MD5.getAlg()).isEqualTo("0"); + assertThat(TsfAlgType.HMAC_SHA_1.getAlg()).isEqualTo("1"); + assertThat(TsfAlgType.HMAC_SHA_256.getAlg()).isEqualTo("2"); + assertThat(TsfAlgType.HMAC_SHA_512.getAlg()).isEqualTo("3"); + assertThat(TsfAlgType.HMAC_SM3.getAlg()).isEqualTo("4"); + + TsfAlgType.HMAC_MD5.setAlg("00"); + assertThat(TsfAlgType.HMAC_MD5.getAlg()).isEqualTo("00"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/ClaimMappingTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/ClaimMappingTest.java new file mode 100644 index 000000000..21612f2ef --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/ClaimMappingTest.java @@ -0,0 +1,42 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link ClaimMapping}. + * + * @author Haotian Zhang + */ +public class ClaimMappingTest { + + @Test + public void testClaimMapping() { + ClaimMapping claimMapping = new ClaimMapping(); + claimMapping.setParameterName("parameterName"); + claimMapping.setMappingParameterName("mappingParameterName"); + claimMapping.setLocation("location"); + + assertThat(claimMapping.getParameterName()).isEqualTo("parameterName"); + assertThat(claimMapping.getMappingParameterName()).isEqualTo("mappingParameterName"); + assertThat(claimMapping.getLocation()).isEqualTo("location"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GatewayAllResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GatewayAllResultTest.java new file mode 100644 index 000000000..f072378a5 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GatewayAllResultTest.java @@ -0,0 +1,44 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link GatewayAllResult}. + * + * @author Haotian Zhang + */ +public class GatewayAllResultTest { + + @Test + public void testGatewayAllResult() { + GatewayAllResult gatewayAllResult = new GatewayAllResult(null, null, null, null); + gatewayAllResult.setGroupResult(new GroupResult()); + gatewayAllResult.setGroupApiResult(new GroupApiResult()); + gatewayAllResult.setPathRewriteResult(new PathRewriteResult()); + gatewayAllResult.setPathWildcardResult(new PathWildcardResult()); + + assertThat(gatewayAllResult.getGroupResult()).isNotNull(); + assertThat(gatewayAllResult.getGroupApiResult()).isNotNull(); + assertThat(gatewayAllResult.getPathRewriteResult()).isNotNull(); + assertThat(gatewayAllResult.getPathWildcardResult()).isNotNull(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiResultTest.java new file mode 100644 index 000000000..0162a143e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiResultTest.java @@ -0,0 +1,52 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link GroupApiResult}. + * + * @author Haotian Zhang + */ +public class GroupApiResultTest { + + @Test + public void testGroupApiResult() { + GroupApiResult groupApiResult = new GroupApiResult(); + groupApiResult.setGatewayId("gatewayId"); + groupApiResult.setGatewayName("gatewayName"); + groupApiResult.setGatewayGroupId("gatewayGroupId"); + groupApiResult.setReversion(1); + groupApiResult.setUpdatedTime("updatedTime"); + groupApiResult.setResult(new ArrayList<>()); + groupApiResult.getResult().add(new GroupApi()); + + assertThat(groupApiResult.getGatewayId()).isEqualTo("gatewayId"); + assertThat(groupApiResult.getGatewayName()).isEqualTo("gatewayName"); + assertThat(groupApiResult.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(groupApiResult.getReversion()).isEqualTo(1); + assertThat(groupApiResult.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(groupApiResult.getResult()).isNotEmpty(); + assertThat(groupApiResult.getResult()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiTest.java new file mode 100644 index 000000000..7dbabef67 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupApiTest.java @@ -0,0 +1,71 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link GroupApi}. + * + * @author Haotian Zhang + */ +public class GroupApiTest { + + @Test + public void testGroupApi() { + GroupApi groupApi = new GroupApi(); + groupApi.setApiId("apiId"); + groupApi.setGroupId("groupId"); + groupApi.setPath("path"); + groupApi.setMethod("method"); + groupApi.setServiceName("serviceName"); + groupApi.setNamespaceId("namespaceId"); + groupApi.setNamespaceName("namespaceName"); + groupApi.setReleaseStatus("releaseStatus"); + groupApi.setUsableStatus("usableStatus"); + groupApi.setPathMapping("pathMapping"); + groupApi.setTimeout(100); + groupApi.setHost("host"); + groupApi.setDescription("description"); + groupApi.setApiType("apiType"); + groupApi.setRpcType("rpcType"); + groupApi.setRpcExt("rpcExt"); + Object rpcExtObj = new Object(); + groupApi.setRpcExtObj(rpcExtObj); + + assertThat(groupApi.getApiId()).isEqualTo("apiId"); + assertThat(groupApi.getGroupId()).isEqualTo("groupId"); + assertThat(groupApi.getPath()).isEqualTo("path"); + assertThat(groupApi.getMethod()).isEqualTo("method"); + assertThat(groupApi.getServiceName()).isEqualTo("serviceName"); + assertThat(groupApi.getNamespaceId()).isEqualTo("namespaceId"); + assertThat(groupApi.getNamespaceName()).isEqualTo("namespaceName"); + assertThat(groupApi.getReleaseStatus()).isEqualTo("releaseStatus"); + assertThat(groupApi.getUsableStatus()).isEqualTo("usableStatus"); + assertThat(groupApi.getPathMapping()).isEqualTo("pathMapping"); + assertThat(groupApi.getTimeout()).isEqualTo(100); + assertThat(groupApi.getHost()).isEqualTo("host"); + assertThat(groupApi.getDescription()).isEqualTo("description"); + assertThat(groupApi.getApiType()).isEqualTo("apiType"); + assertThat(groupApi.getRpcType()).isEqualTo("rpcType"); + assertThat(groupApi.getRpcExt()).isEqualTo("rpcExt"); + assertThat(groupApi.getRpcExtObj()).isEqualTo(rpcExtObj); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupResultTest.java new file mode 100644 index 000000000..dcb5d940e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupResultTest.java @@ -0,0 +1,52 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link GroupResult}. + * + * @author Haotian Zhang + */ +public class GroupResultTest { + + @Test + public void testGroupResult() { + GroupResult groupResult = new GroupResult(); + groupResult.setGatewayId("gatewayId"); + groupResult.setGatewayName("gatewayName"); + groupResult.setGatewayGroupId("gatewayGroupId"); + groupResult.setReversion(1); + groupResult.setUpdatedTime("updatedTime"); + groupResult.setResult(new ArrayList<>()); + groupResult.getResult().add(new Group()); + + assertThat(groupResult.getGatewayId()).isEqualTo("gatewayId"); + assertThat(groupResult.getGatewayName()).isEqualTo("gatewayName"); + assertThat(groupResult.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(groupResult.getReversion()).isEqualTo(1); + assertThat(groupResult.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(groupResult.getResult()).isNotEmpty(); + assertThat(groupResult.getResult()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupSecretTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupSecretTest.java new file mode 100644 index 000000000..2ae9fe4a1 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupSecretTest.java @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link GroupSecret}. + * + * @author Haotian Zhang + */ +public class GroupSecretTest { + + @Test + public void testGroupSecret() { + GroupSecret groupSecret = new GroupSecret(); + groupSecret.setSecretId("secretId"); + groupSecret.setSecretKey("secretKey"); + groupSecret.setSecretName("secretName"); + groupSecret.setGroupId("groupId"); + groupSecret.setStatus("status"); + groupSecret.setExpiredTime("expiredTime"); + + assertThat(groupSecret.getSecretId()).isEqualTo("secretId"); + assertThat(groupSecret.getSecretKey()).isEqualTo("secretKey"); + assertThat(groupSecret.getSecretName()).isEqualTo("secretName"); + assertThat(groupSecret.getGroupId()).isEqualTo("groupId"); + assertThat(groupSecret.getStatus()).isEqualTo("status"); + assertThat(groupSecret.getExpiredTime()).isEqualTo("expiredTime"); + assertThat(groupSecret.toString()).isEqualTo("GroupSecret{secretId='secretId', secretKey='secretKey', secretName='secretName', groupId='groupId', status='status', expiredTime='expiredTime'}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupTest.java new file mode 100644 index 000000000..df7f5c691 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/GroupTest.java @@ -0,0 +1,76 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link Group}. + * + * @author Haotian Zhang + */ +public class GroupTest { + + @Test + public void testGroup() { + Group group = new Group(); + group.setGroupId("groupId"); + group.setGroupName("groupName"); + group.setGroupContext("groupContext"); + group.setReleaseStatus("releaseStatus"); + group.setAuthMode("authMode"); + group.setGroupType("groupType"); + group.setSecretList(generateGroupSecretList()); + group.setNamespaceNameKey("namespaceNameKey"); + group.setServiceNameKey("serviceNameKey"); + group.setNamespaceNameKeyPosition("Header"); + group.setServiceNameKeyPosition("Query"); + + assertThat(group.getGroupId()).isEqualTo("groupId"); + assertThat(group.getGroupName()).isEqualTo("groupName"); + assertThat(group.getGroupContext()).isEqualTo("groupContext"); + assertThat(group.getReleaseStatus()).isEqualTo("releaseStatus"); + assertThat(group.getAuthMode()).isEqualTo("authMode"); + assertThat(group.getGroupType()).isEqualTo("groupType"); + assertThat(group.getSecretList()).isNotNull(); + assertThat(group.getSecretList()).hasSize(1); + assertThat(group.getNamespaceNameKey()).isEqualTo("namespaceNameKey"); + assertThat(group.getServiceNameKey()).isEqualTo("serviceNameKey"); + assertThat(group.getNamespaceNameKeyPosition()).isEqualTo("Header"); + assertThat(group.getServiceNameKeyPosition()).isEqualTo("Query"); + assertThat(group.toString()).isEqualTo("Group{groupId='groupId', groupName='groupName', groupContext='groupContext', releaseStatus='releaseStatus', authMode='authMode', groupType='groupType', secretList=[GroupSecret{secretId='secretId', secretKey='secretKey', secretName='secretName', groupId='groupId', status='status', expiredTime='expiredTime'}], namespaceNameKey='namespaceNameKey', serviceNameKey='serviceNameKey', namespaceNameKeyPosition='Header', serviceNameKeyPosition='Query'}"); + } + + private List generateGroupSecretList() { + GroupSecret groupSecret = new GroupSecret(); + groupSecret.setSecretId("secretId"); + groupSecret.setSecretKey("secretKey"); + groupSecret.setSecretName("secretName"); + groupSecret.setGroupId("groupId"); + groupSecret.setStatus("status"); + groupSecret.setExpiredTime("expiredTime"); + List groupSecretList = new ArrayList<>(); + groupSecretList.add(groupSecret); + return groupSecretList; + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/JwtPluginTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/JwtPluginTest.java new file mode 100644 index 000000000..62ffa726b --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/JwtPluginTest.java @@ -0,0 +1,85 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link JwtPlugin}. + * + * @author Haotian Zhang + */ +public class JwtPluginTest { + + @Test + public void testJwtPlugin() { + JwtPlugin jwtPlugin = new JwtPlugin(); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件名称参数错误"); + jwtPlugin.setName("jwt"); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件类型参数错误"); + jwtPlugin.setType("Jwt"); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("publicKeyJson"); + jwtPlugin.setPublicKeyJson("publicKeyJson"); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenBaggagePosition"); + jwtPlugin.setTokenBaggagePosition("tokenBaggagePosition"); + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenBaggagePosition"); + jwtPlugin.setTokenBaggagePosition("query"); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenKeyName"); + jwtPlugin.setTokenKeyName("tokenKeyName"); + + assertThatThrownBy(jwtPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("kid"); + jwtPlugin.setKid("kid"); + + assertThatNoException().isThrownBy(jwtPlugin::check); + jwtPlugin.setRedirectUrl("redirectUrl"); + jwtPlugin.setClaimMappingJson("claimMappingJson"); + jwtPlugin.setTokenBaggagePosition("header"); + assertThatNoException().isThrownBy(jwtPlugin::check); + + assertThat(jwtPlugin.getKid()).isEqualTo("kid"); + assertThat(jwtPlugin.getPublicKeyJson()).isEqualTo("publicKeyJson"); + assertThat(jwtPlugin.getTokenBaggagePosition()).isEqualTo("header"); + assertThat(jwtPlugin.getTokenKeyName()).isEqualTo("tokenKeyName"); + assertThat(jwtPlugin.getRedirectUrl()).isEqualTo("redirectUrl"); + assertThat(jwtPlugin.getClaimMappingJson()).isEqualTo("claimMappingJson"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthPluginTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthPluginTest.java new file mode 100644 index 000000000..a8dce872e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthPluginTest.java @@ -0,0 +1,116 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link OAuthPlugin}. + * + * @author Haotian Zhang + */ +public class OAuthPluginTest { + + @Test + public void testOAuthPlugin() { + OAuthPlugin oAuthPlugin = new OAuthPlugin(); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件名称参数错误"); + oAuthPlugin.setName("oauth"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件类型参数错误"); + oAuthPlugin.setType("OAuth"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenAuthUrl"); + oAuthPlugin.setTokenAuthUrl("tokenAuthUrl"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenAuthMethod"); + oAuthPlugin.setTokenAuthMethod("tokenAuthMethod"); + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenAuthMethod"); + oAuthPlugin.setTokenAuthMethod("get"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenBaggagePosition"); + oAuthPlugin.setTokenBaggagePosition("tokenBaggagePosition"); + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenBaggagePosition"); + oAuthPlugin.setTokenBaggagePosition("query"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("tokenKeyName"); + oAuthPlugin.setTokenKeyName("tokenKeyName"); + + oAuthPlugin.setPayloadMappingPosition("payloadMappingPosition"); + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("payloadMappingPosition"); + oAuthPlugin.setPayloadMappingPosition("query"); + + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("expireTime"); + oAuthPlugin.setExpireTime(100); + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("expireTime"); + oAuthPlugin.setExpireTime(-100); + assertThatThrownBy(oAuthPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("expireTime"); + oAuthPlugin.setExpireTime(15); + + + oAuthPlugin.setTokenAuthServiceName("tokenAuthServiceName"); + oAuthPlugin.setRedirectUrl("redirectUrl"); + oAuthPlugin.setTokenKeyName("tokenKeyName"); + oAuthPlugin.setPayloadMappingName("payloadMappingName"); + + assertThatNoException().isThrownBy(oAuthPlugin::check); + oAuthPlugin.setTokenAuthMethod("post"); + oAuthPlugin.setPayloadMappingPosition("header"); + assertThatNoException().isThrownBy(oAuthPlugin::check); + + assertThat(oAuthPlugin.getTokenAuthServiceName()).isEqualTo("tokenAuthServiceName"); + assertThat(oAuthPlugin.getTokenAuthUrl()).isEqualTo("tokenAuthUrl"); + assertThat(oAuthPlugin.getTokenAuthMethod()).isEqualTo("post"); + assertThat(oAuthPlugin.getExpireTime()).isEqualTo(15); + assertThat(oAuthPlugin.getRedirectUrl()).isEqualTo("redirectUrl"); + assertThat(oAuthPlugin.getTokenBaggagePosition()).isEqualTo("query"); + assertThat(oAuthPlugin.getTokenKeyName()).isEqualTo("tokenKeyName"); + assertThat(oAuthPlugin.getPayloadMappingName()).isEqualTo("payloadMappingName"); + assertThat(oAuthPlugin.getPayloadMappingPosition()).isEqualTo("header"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthResultTest.java new file mode 100644 index 000000000..160e173b1 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/OAuthResultTest.java @@ -0,0 +1,40 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link OAuthResult}. + * + * @author Haotian Zhang + */ +public class OAuthResultTest { + + @Test + public void test() { + OAuthResult oAuthResult = new OAuthResult(); + oAuthResult.setResult(true); + oAuthResult.setPayload("payload"); + + assertThat(oAuthResult.getResult()).isTrue(); + assertThat(oAuthResult.getPayload()).isEqualTo("payload"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathRewriteResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathRewriteResultTest.java new file mode 100644 index 000000000..aea165651 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathRewriteResultTest.java @@ -0,0 +1,53 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import com.tencent.cloud.plugin.gateway.context.PathRewrite; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PathRewriteResult}. + * + * @author Haotian Zhang + */ +public class PathRewriteResultTest { + + @Test + public void testPathRewriteResult() { + PathRewriteResult pathRewriteResult = new PathRewriteResult(); + pathRewriteResult.setGatewayId("gatewayId"); + pathRewriteResult.setGatewayName("gatewayName"); + pathRewriteResult.setGatewayGroupId("gatewayGroupId"); + pathRewriteResult.setReversion(1); + pathRewriteResult.setUpdatedTime("updatedTime"); + pathRewriteResult.setResult(new ArrayList<>()); + pathRewriteResult.getResult().add(new PathRewrite()); + + assertThat(pathRewriteResult.getGatewayId()).isEqualTo("gatewayId"); + assertThat(pathRewriteResult.getGatewayName()).isEqualTo("gatewayName"); + assertThat(pathRewriteResult.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(pathRewriteResult.getReversion()).isEqualTo(1); + assertThat(pathRewriteResult.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(pathRewriteResult.getResult()).isNotEmpty(); + assertThat(pathRewriteResult.getResult()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardResultTest.java new file mode 100644 index 000000000..bfdfdab21 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardResultTest.java @@ -0,0 +1,52 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PathWildcardResult}. + * + * @author Haotian Zhang + */ +public class PathWildcardResultTest { + + @Test + public void testPathWildcardResult() { + PathWildcardResult pathWildcardResult = new PathWildcardResult(); + pathWildcardResult.setGatewayId("gatewayId"); + pathWildcardResult.setGatewayName("gatewayName"); + pathWildcardResult.setGatewayGroupId("gatewayGroupId"); + pathWildcardResult.setReversion(1); + pathWildcardResult.setUpdatedTime("updatedTime"); + pathWildcardResult.setResult(new ArrayList<>()); + pathWildcardResult.getResult().add(new PathWildcardRule()); + + assertThat(pathWildcardResult.getGatewayId()).isEqualTo("gatewayId"); + assertThat(pathWildcardResult.getGatewayName()).isEqualTo("gatewayName"); + assertThat(pathWildcardResult.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(pathWildcardResult.getReversion()).isEqualTo(1); + assertThat(pathWildcardResult.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(pathWildcardResult.getResult()).isNotEmpty(); + assertThat(pathWildcardResult.getResult()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardRuleTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardRuleTest.java new file mode 100644 index 000000000..ba7ead606 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PathWildcardRuleTest.java @@ -0,0 +1,59 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.Collections; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PathWildcardRule}. + * + * @author Haotian Zhang + */ +public class PathWildcardRuleTest { + + @Test + public void testPathWildcardRule() { + PathWildcardRule pathWildcardRule = new PathWildcardRule(); + pathWildcardRule.setWildCardId("wildCardId"); + pathWildcardRule.setGroupId("groupId"); + pathWildcardRule.setWildCardPath("wildCardPath"); + pathWildcardRule.setMethod("method"); + pathWildcardRule.setServiceId("serviceId"); + pathWildcardRule.setServiceName("serviceName"); + pathWildcardRule.setNamespaceId("namespaceId"); + pathWildcardRule.setNamespaceName("namespaceName"); + pathWildcardRule.setTimeout(100); + pathWildcardRule.setWildCardIds(Collections.singletonList("wildCardId")); + + assertThat(pathWildcardRule.getWildCardId()).isEqualTo("wildCardId"); + assertThat(pathWildcardRule.getGroupId()).isEqualTo("groupId"); + assertThat(pathWildcardRule.getWildCardPath()).isEqualTo("wildCardPath"); + assertThat(pathWildcardRule.getMethod()).isEqualTo("method"); + assertThat(pathWildcardRule.getServiceId()).isEqualTo("serviceId"); + assertThat(pathWildcardRule.getServiceName()).isEqualTo("serviceName"); + assertThat(pathWildcardRule.getNamespaceId()).isEqualTo("namespaceId"); + assertThat(pathWildcardRule.getNamespaceName()).isEqualTo("namespaceName"); + assertThat(pathWildcardRule.getTimeout()).isEqualTo(100); + assertThat(pathWildcardRule.getWildCardIds()).containsExactly("wildCardId"); + assertThat(pathWildcardRule.toString()).isEqualTo("PathWildcardRule{wildCardId='wildCardId', groupId='groupId', wildCardPath='wildCardPath', method='method', serviceId='serviceId', serviceName='serviceName', namespaceId='namespaceId', namespaceName='namespaceName', wildCardIds=[wildCardId], timeout=100}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginArgInfoTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginArgInfoTest.java new file mode 100644 index 000000000..3c46922b7 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginArgInfoTest.java @@ -0,0 +1,44 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginArgInfo}. + * + * @author Haotian Zhang + */ +public class PluginArgInfoTest { + + @Test + public void testPluginArgInfo() { + PluginArgInfo pluginArgInfo = new PluginArgInfo(); + pluginArgInfo.setId("123"); + pluginArgInfo.setPluginId("456"); + pluginArgInfo.setKey("key"); + pluginArgInfo.setValue("value"); + + assertThat(pluginArgInfo.getId()).isEqualTo("123"); + assertThat(pluginArgInfo.getPluginId()).isEqualTo("456"); + assertThat(pluginArgInfo.getKey()).isEqualTo("key"); + assertThat(pluginArgInfo.getValue()).isEqualTo("value"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginDetailTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginDetailTest.java new file mode 100644 index 000000000..7101b213b --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginDetailTest.java @@ -0,0 +1,55 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginDetail}. + * + * @author Haotian Zhang + */ +public class PluginDetailTest { + + @Test + public void testPluginDetail() { + PluginDetail pluginDetail = new PluginDetail(); + pluginDetail.setId("id"); + pluginDetail.setPluginArgInfos(new ArrayList<>()); + PluginArgInfo pluginArgInfo = new PluginArgInfo(); + pluginArgInfo.setId("123"); + pluginArgInfo.setPluginId("456"); + pluginArgInfo.setKey("key"); + pluginArgInfo.setValue("value"); + pluginDetail.getPluginArgInfos().add(pluginArgInfo); + + PluginDetail otherPluginDetail = new PluginDetail(); + otherPluginDetail.setId("id"); + otherPluginDetail.setPluginArgInfos(new ArrayList<>()); + otherPluginDetail.getPluginArgInfos().add(pluginArgInfo); + + assertThat(pluginDetail).isEqualTo(pluginDetail); + assertThat(pluginDetail).isNotEqualTo(pluginArgInfo); + assertThat(pluginDetail).isEqualTo(otherPluginDetail); + assertThat(pluginDetail.hashCode()).isEqualTo(otherPluginDetail.hashCode()); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInfoTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInfoTest.java new file mode 100644 index 000000000..f671f1f2a --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInfoTest.java @@ -0,0 +1,64 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Tests for {@link PluginInfo}. + * + * @author Haotian Zhang + */ +public class PluginInfoTest { + + @Test + public void testPluginInfo() { + PluginInfo pluginInfo = new PluginInfo(); + + assertThatThrownBy(pluginInfo::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件名称参数错误"); + pluginInfo.setName("name"); + + assertThatThrownBy(pluginInfo::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件类型参数错误"); + pluginInfo.setType("type"); + + pluginInfo.setId("id"); + pluginInfo.setOrder(1); + pluginInfo.setDescription("description"); + pluginInfo.setCreatedTime("createdTime"); + pluginInfo.setUpdatedTime("updatedTime"); + assertThatNoException().isThrownBy(pluginInfo::check); + + assertThat(pluginInfo.getId()).isEqualTo("id"); + assertThat(pluginInfo.getName()).isEqualTo("name"); + assertThat(pluginInfo.getType()).isEqualTo("type"); + assertThat(pluginInfo.getOrder()).isEqualTo(1); + assertThat(pluginInfo.getDescription()).isEqualTo("description"); + assertThat(pluginInfo.getCreatedTime()).isEqualTo("createdTime"); + assertThat(pluginInfo.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(pluginInfo.toString()).isEqualTo("PluginInfo{id='id', name='name', type='type', order=1, description='description', createdTime='createdTime', updatedTime='updatedTime'}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoResultTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoResultTest.java new file mode 100644 index 000000000..b06488c58 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoResultTest.java @@ -0,0 +1,52 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginInstanceInfoResult}. + * + * @author Haotian Zhang + */ +public class PluginInstanceInfoResultTest { + + @Test + public void testPluginInstanceInfoResult() { + PluginInstanceInfoResult pluginInstanceInfoResult = new PluginInstanceInfoResult(); + pluginInstanceInfoResult.setGatewayId("gatewayId"); + pluginInstanceInfoResult.setGatewayName("gatewayName"); + pluginInstanceInfoResult.setGatewayGroupId("gatewayGroupId"); + pluginInstanceInfoResult.setReversion(1); + pluginInstanceInfoResult.setUpdatedTime("updatedTime"); + pluginInstanceInfoResult.setResult(new ArrayList<>()); + pluginInstanceInfoResult.getResult().add(new PluginInstanceInfo()); + + assertThat(pluginInstanceInfoResult.getGatewayId()).isEqualTo("gatewayId"); + assertThat(pluginInstanceInfoResult.getGatewayName()).isEqualTo("gatewayName"); + assertThat(pluginInstanceInfoResult.getGatewayGroupId()).isEqualTo("gatewayGroupId"); + assertThat(pluginInstanceInfoResult.getReversion()).isEqualTo(1); + assertThat(pluginInstanceInfoResult.getUpdatedTime()).isEqualTo("updatedTime"); + assertThat(pluginInstanceInfoResult.getResult()).isNotEmpty(); + assertThat(pluginInstanceInfoResult.getResult()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoTest.java new file mode 100644 index 000000000..3e57321b6 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginInstanceInfoTest.java @@ -0,0 +1,46 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginInstanceInfo}. + * + * @author Haotian Zhang + */ +public class PluginInstanceInfoTest { + + @Test + public void testPluginInstanceInfo() { + PluginInstanceInfo pluginInstanceInfo = new PluginInstanceInfo(); + pluginInstanceInfo.setScopeValue("scopeValue"); + pluginInstanceInfo.setScopeType("scopeType"); + pluginInstanceInfo.setPluginDetails(new ArrayList<>()); + pluginInstanceInfo.getPluginDetails().add(new PluginDetail()); + + assertThat(pluginInstanceInfo.getScopeValue()).isEqualTo("scopeValue"); + assertThat(pluginInstanceInfo.getScopeType()).isEqualTo("scopeType"); + assertThat(pluginInstanceInfo.getPluginDetails()).isNotEmpty(); + assertThat(pluginInstanceInfo.getPluginDetails()).hasSize(1); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginPayloadTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginPayloadTest.java new file mode 100644 index 000000000..1cf2ae90d --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/PluginPayloadTest.java @@ -0,0 +1,48 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.HashMap; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PluginPayload}. + * + * @author Haotian Zhang + */ +public class PluginPayloadTest { + + @Test + public void testPluginPayload() { + PluginPayload pluginPayload = new PluginPayload(); + pluginPayload.setRequestHeaders(new HashMap<>()); + pluginPayload.getRequestHeaders().put("request", "test"); + pluginPayload.setResponseHeaders(new HashMap<>()); + pluginPayload.getResponseHeaders().put("response", "test"); + pluginPayload.setRequestCookies(new HashMap<>()); + pluginPayload.getRequestCookies().put("cookie", "test"); + pluginPayload.setParameterMap(new HashMap<>()); + pluginPayload.getParameterMap().put("param", new String[] {"test"}); + pluginPayload.setRedirectUrl("redirectUrl"); + + assertThat(pluginPayload.getRedirectUrl()).isEqualTo("redirectUrl"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginInfoTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginInfoTest.java new file mode 100644 index 000000000..2fd3a308b --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginInfoTest.java @@ -0,0 +1,55 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; +import java.util.List; + +import com.tencent.cloud.plugin.gateway.context.Position; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link RequestTransformerPluginInfo}. + * + * @author Haotian Zhang + */ +public class RequestTransformerPluginInfoTest { + + @Test + public void testRequestTransformerPluginInfo() { + RequestTransformerPluginInfo requestTransformerPluginInfo = new RequestTransformerPluginInfo(); + List filters = new ArrayList<>(); + TransformerTag transformerTag = new TransformerTag(); + transformerTag.setTagPosition(Position.COOKIE); + filters.add(transformerTag); + requestTransformerPluginInfo.setFilters(filters); + List actions = new ArrayList<>(); + TransformerAction transformerAction = new TransformerAction(); + transformerAction.setAction("add"); + transformerAction.setTagPosition(Position.HEADER); + transformerAction.setTagName("tagName"); + transformerAction.setTagValue("tagValue"); + transformerAction.setWeight(100); + actions.add(transformerAction); + requestTransformerPluginInfo.setActions(actions); + + assertThat(requestTransformerPluginInfo.toString()).isEqualTo("RequestTransformerPluginInfo{filters=[TransformerTag{tagPosition=COOKIE} TagCondition{tagId=null, tagType='null', tagField='null', tagOperator='null', tagValue='null'}], actions=[TransformerAction{action='add', tagPosition=HEADER, tagName='tagName', tagValue='tagValue', weight=100}]}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginTest.java new file mode 100644 index 000000000..aed60a97d --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/RequestTransformerPluginTest.java @@ -0,0 +1,107 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.tencent.cloud.common.util.JacksonUtils; +import com.tencent.cloud.plugin.gateway.context.Position; +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link RequestTransformerPlugin}. + * + * @author Haotian Zhang + */ +public class RequestTransformerPluginTest { + + @Test + public void testRequestTransformerPlugin() { + RequestTransformerPlugin requestTransformerPlugin = new RequestTransformerPlugin(); + + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件名称参数错误"); + requestTransformerPlugin.setName("reqTransformer"); + + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件类型参数错误"); + requestTransformerPlugin.setType("ReqTransformer"); + + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("验证插件参数"); + requestTransformerPlugin.setPluginInfo(generateRequestTransformerPluginInfo(-1).substring(2)); + + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("验证插件格式"); + requestTransformerPlugin.setPluginInfo(generateRequestTransformerPluginInfo(-1)); + + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("权重值不合法"); + requestTransformerPlugin.setPluginInfo(generateRequestTransformerPluginInfo(null)); + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("权重值不合法"); + requestTransformerPlugin.setPluginInfo(generateRequestTransformerPluginInfo(101)); + assertThatThrownBy(requestTransformerPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("验证插件权重失败,当前权重总和为"); + requestTransformerPlugin.setPluginInfo(generateRequestTransformerPluginInfo(50)); + + assertThatNoException().isThrownBy(requestTransformerPlugin::check); + assertThat(requestTransformerPlugin.toString()).isEqualTo("PluginInfo{id='null', name='reqTransformer', type='ReqTransformer', order=null, description='null', createdTime='null', updatedTime='null'}"); + requestTransformerPlugin.setRequestTransformerPluginInfo(JacksonUtils.deserialize(generateRequestTransformerPluginInfo(50), new TypeReference() { })); + assertThatNoException().isThrownBy(requestTransformerPlugin::check); + + assertThat(requestTransformerPlugin.getPluginInfo()).isEqualTo(generateRequestTransformerPluginInfo(50)); + assertThat(requestTransformerPlugin.getRequestTransformerPluginInfo()).isNotNull(); + assertThat(requestTransformerPlugin.toString()).isEqualTo("PluginInfo{id='null', name='reqTransformer', type='ReqTransformer', order=null, description='null', createdTime='null', updatedTime='null'}"); + } + + private String generateRequestTransformerPluginInfo(Integer weight) { + RequestTransformerPluginInfo requestTransformerPluginInfo = new RequestTransformerPluginInfo(); + List filters = new ArrayList<>(); + TransformerTag transformerTag = new TransformerTag(); + transformerTag.setTagPosition(Position.COOKIE); + filters.add(transformerTag); + requestTransformerPluginInfo.setFilters(filters); + List actions = new ArrayList<>(); + TransformerAction transformerAction = new TransformerAction(); + transformerAction.setAction("add"); + transformerAction.setTagPosition(Position.HEADER); + transformerAction.setTagName("tagName"); + transformerAction.setTagValue("tagValue"); + if (weight != null) { + transformerAction.setWeight(weight); + } + actions.add(transformerAction); + requestTransformerPluginInfo.setActions(actions); + return JacksonUtils.serialize2Json(requestTransformerPluginInfo); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginInfoTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginInfoTest.java new file mode 100644 index 000000000..f281f1e3d --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginInfoTest.java @@ -0,0 +1,45 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.cloud.plugin.gateway.context.Position; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link TagPluginInfo}. + * + * @author Haotian Zhang + */ +public class TagPluginInfoTest { + + @Test + public void testTagPluginInfo() { + TagPluginInfo tagPluginInfo = new TagPluginInfo(); + tagPluginInfo.setTagPosition(Position.QUERY); + tagPluginInfo.setPreTagName("preTagName"); + tagPluginInfo.setPostTagName("postTagName"); + tagPluginInfo.setTraceIdEnabled("Y"); + + assertThat(tagPluginInfo.getTagPosition()).isEqualTo(Position.QUERY); + assertThat(tagPluginInfo.getPreTagName()).isEqualTo("preTagName"); + assertThat(tagPluginInfo.getPostTagName()).isEqualTo("postTagName"); + assertThat(tagPluginInfo.getTraceIdEnabled()).isEqualTo("Y"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginTest.java new file mode 100644 index 000000000..cb2fbb438 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TagPluginTest.java @@ -0,0 +1,62 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link TagPlugin}. + * + * @author Haotian Zhang + */ +public class TagPluginTest { + + @Test + public void testTagPlugin() { + TagPlugin tagPlugin = new TagPlugin(); + + assertThatThrownBy(tagPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件名称参数错误"); + tagPlugin.setName("tag"); + + assertThatThrownBy(tagPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("插件类型参数错误"); + tagPlugin.setType("Tag"); + + assertThatThrownBy(tagPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("验证Tag插件参数"); + tagPlugin.setTagPluginInfoList("[{\"tagPosition\":\"QUERY\",\"preTagName\":\"preTagName\",\"postTagName\":\"postTagName\",\"traceIdEnabled\":\"Y\""); + + assertThatThrownBy(tagPlugin::check) + .isExactlyInstanceOf(TsfGatewayException.class) + .hasMessageContaining("验证Tag插件参数"); + tagPlugin.setTagPluginInfoList("[{\"tagPosition\":\"QUERY\",\"preTagName\":\"preTagName\",\"postTagName\":\"postTagName\",\"traceIdEnabled\":\"Y\"}]"); + + assertThatNoException().isThrownBy(tagPlugin::check); + + assertThat(tagPlugin.getTagPluginInfoList()).isNotBlank(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerActionTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerActionTest.java new file mode 100644 index 000000000..cdd072884 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerActionTest.java @@ -0,0 +1,48 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.cloud.plugin.gateway.context.Position; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link TransformerAction}. + * + * @author Haotian Zhang + */ +public class TransformerActionTest { + + @Test + public void testTransformerAction() { + TransformerAction transformerAction = new TransformerAction(); + transformerAction.setAction("add"); + transformerAction.setTagPosition(Position.HEADER); + transformerAction.setTagName("tagName"); + transformerAction.setTagValue("tagValue"); + transformerAction.setWeight(1); + + assertThat(transformerAction.getAction()).isEqualTo("add"); + assertThat(transformerAction.getTagPosition()).isEqualTo(Position.HEADER); + assertThat(transformerAction.getTagName()).isEqualTo("tagName"); + assertThat(transformerAction.getTagValue()).isEqualTo("tagValue"); + assertThat(transformerAction.getWeight()).isEqualTo(1); + assertThat(transformerAction.toString()).isEqualTo("TransformerAction{action='add', tagPosition=HEADER, tagName='tagName', tagValue='tagValue', weight=1}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerTagTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerTagTest.java new file mode 100644 index 000000000..fac7c5eae --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/model/TransformerTagTest.java @@ -0,0 +1,40 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.model; + +import com.tencent.cloud.plugin.gateway.context.Position; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link TransformerTag}. + * + * @author Haotian Zhang + */ +public class TransformerTagTest { + + @Test + public void testTransformerTag() { + TransformerTag transformerTag = new TransformerTag(); + transformerTag.setTagPosition(Position.TSF_TAG); + + assertThat(transformerTag.getTagPosition()).isEqualTo(Position.TSF_TAG); + assertThat(transformerTag.toString()).isEqualTo("TransformerTag{tagPosition=TSF_TAG} TagCondition{tagId=null, tagType='null', tagField='null', tagOperator='null', tagValue='null'}"); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/CookieUtilTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/CookieUtilTest.java new file mode 100644 index 000000000..9f9cb2cc5 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/CookieUtilTest.java @@ -0,0 +1,46 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.util; + +import java.util.HashMap; + +import org.junit.jupiter.api.Test; + +/** + * Test for {@link CookieUtil}. + * + * @author Haotian Zhang + */ +public class CookieUtilTest { + + @Test + public void testBuildCookie() { + StringBuilder stringBuilder1 = new StringBuilder(); + CookieUtil.buildCookie(stringBuilder1, new HashMap<>() {{ + put("test1", "123"); + put("test2", "123"); + }}); + + StringBuilder stringBuilder2 = new StringBuilder(); + stringBuilder2.append("aaa=bbb"); + CookieUtil.buildCookie(stringBuilder2, new HashMap<>() {{ + put("test1", "123"); + put("test2", "123"); + }}); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/IdGeneratorTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/IdGeneratorTest.java new file mode 100644 index 000000000..ab8e664f2 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/IdGeneratorTest.java @@ -0,0 +1,36 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.util; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link IdGenerator}. + * + * @author Haotian Zhang + */ +public class IdGeneratorTest { + + @Test + public void testGenerateId() { + String uuid = IdGenerator.generateId("test"); + assertThat(uuid).isNotBlank(); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/JwtTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/JwtTest.java new file mode 100644 index 000000000..52f57b741 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/JwtTest.java @@ -0,0 +1,92 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.util; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import org.junit.jupiter.api.Test; +import shade.polaris.org.jose4j.json.JsonUtil; +import shade.polaris.org.jose4j.jwk.RsaJsonWebKey; +import shade.polaris.org.jose4j.jws.JsonWebSignature; +import shade.polaris.org.jose4j.jwt.JwtClaims; +import shade.polaris.org.jose4j.jwt.MalformedClaimException; +import shade.polaris.org.jose4j.lang.JoseException; + +/** + * Test for Jwt. + * + * @author vmershen + **/ +public class JwtTest { + + @Test + public void testJwt() throws JoseException, MalformedClaimException { + RsaJsonWebKey jwk = new RsaJsonWebKey(JsonUtil.parseJson("{\"kty\":\"RSA\",\"alg\":\"RS256\",\"n\":\"mrX5ROEw4kCYDXR94FQsm33gr5o5dQXvuOoe-eG_yvdNW83MMt9GgG_eBBq_1b7HgyP9lo15BfKX3GH1igCjEKoXJxcHC5xox4xC0tvbBNCDwG_987ZsqlgCb4f7X66DCcHh17AyAHYa8JhO2kXvtD1OIQxSajSgmk1C1sxI5kqJXfvJwRLcCEK87P6Bs9YNLnnJeouSkYce04AhspmyQKKax4GllbMjcrUUMRoqpCBMklh5Pgl9sOGRLo-6uzzowtI_SyF03YsE2ejh9m-YWqTYsx7PIg6SdWrNRIprKtjnhc9nk-QBzWbOTFH3bpMoXl0T9KPndaLpi1pXtaej9Q\",\"e\":\"AQAB\",\"d\":\"lL9vqdUl7fMS_qTJPf1QYjPV6qBKrAQIJ28aV0DA6YF6pFCrCyJ3I5frC2E4nmbuZl0dPTpKaPiFIAQjUwsnvSb8Wb4fLP-2El3-BcQSwX9FnalPrpnvwpwZw2gnvSgJn0EFRh6HBMCJSFf4QI7LWC01SDsTpj9xRsoQAHurf5YZ8YRpi_-XEWBaL-4R_RxpoeAnSgSbJkcGoJNcxqwWbCun37KYBS_71sd155VWycMd-uHtTRnW6SenVG49pexXq-tIQxOwmatpTj0XF7hhshKgdTF1xXPbMSX6XOvxiy929jPMercBL_-OUu0PPUZTTVp0gNziGdevzufHkEfHxQ\",\"p\":\"5dOs8Q0SHIuCq-gAOx2c2JaqXzPRsmmZ7nXx1P1jbddDIenVPA6q5zUVqXIRRQgMA7AdD9x7anJ2_kaKSFoE2D8peuObvmjrbmJeYE4F4138pNESOHlBmhUH93Oo4i5TvmNZ5hxu3CmonGKMafeDoMpopN15yeDGkTVFKoOfuys\",\"q\":\"rFRhmJIIj3o__CbjVOlUgiVzrk-ZgK9jGXHhyt6LELQae1nUiZNZuwZeHwgzTonsTMJ2JHnmCuDpwuhjf_kha5KHeuczE7gmnlaGd3s6kaKDyB9bXbMTs122SnNiB-lJcwm4wRNWI-irSh8PyHSQVnjvKkQCCEPi4i0Ky1KgDV8\",\"dp\":\"qBUJNDn09v9pD8Ra9uEPZq-55mqFgFAPDgEgXj76yshWBqV3F7c6cmG2d_g-fRgHgWL5vjHn6M_SCuEYHRYI2QZIleGEc9tT46T5lME7OS_xp7Bn_PlhawjajLT_3Hs5L9KFWu-MfGPTNpw0SQOGNsARjBGWEnjbgDNPZGpjFYU\",\"dq\":\"F_0rFNUHUgm_jHdRYAmXFQLnppU4FhzUG7-podb23t1jblZj6r7TV-CcC4_VrJIwjcLoNU2uw0bp45L7_t2MVHAyYd57Urxoy9PZphpGXe2UkLAkxNdf37Ek5hpHxDgqXFQ3HtF1RUxnQ8stJEdtrEvrZyPOcJ4aoEeK4CDhXNs\",\"qi\":\"QdwkKs9n6jswVsbYKprvpNr2Mbg-RBPp5xx1p-ypVJnFOd_lnCA6P3gRJ-pe6tSCIB6AYViEhZpzKMSu47f27_38VHkH9qOOL38ZVeVFo8Yt8lkBwMEKQdDOghfF74L5Fczo9bH7QX679dC847cDEa1oaV2Cdv6XcSKGywwvq3Y\"}")); + // Create the Claims, which will be the content of the JWT + JwtClaims claims = new JwtClaims(); + claims.setIssuer("Issuer"); // who creates the token and signs it + claims.setAudience("Audience"); // to whom the token is intended to be sent + claims.setExpirationTimeMinutesInTheFuture(1); // time when the token will expire (10 minutes from now) + claims.setGeneratedJwtId(); // a unique identifier for the token + claims.setIssuedAtToNow(); // when the token was issued/created (now) + claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago) + claims.setSubject("subject"); // the subject/principal is whom the token is about + claims.setClaim("email", "mail@example.com"); // additional claims/attributes about the subject can be added + List groups = Arrays.asList("group-one", "other-group", "group-three"); + claims.setStringListClaim("groups", groups); // multi-valued claims work too and will end up as a JSON array + + JsonWebSignature jws = new JsonWebSignature(); + + // The payload of the JWS is JSON content of the JWT Claims + jws.setPayload(claims.toJson()); + + // The JWT is signed using the private key + jws.setKey(jwk.getPrivateKey()); + + // Set the Key ID (kid) header because it's just the polite thing to do. + // We only have one key in this example but a using a Key ID helps + // facilitate a smooth key rollover process + jws.setKeyIdHeaderValue("kid"); + + // Set the signature algorithm on the JWT/JWS that will integrity protect the claims + jws.setAlgorithmHeaderValue(jwk.getAlgorithm()); + + // Sign the JWS and produce the compact serialization or the complete JWT/JWS + // representation, which is a string consisting of three dot ('.') separated + // base64url-encoded parts in the form Header.Payload.Signature + // If you wanted to encrypt it, you can simply set this jwt as the payload + // of a JsonWebEncryption object and set the cty (Content Type) header to "jwt". + String jwt = jws.getCompactSerialization(); + + long expirationTime = claims.getExpirationTime().getValueInMillis(); + Instant instant = Instant.ofEpochMilli(expirationTime); + ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai")); + DateTimeFormatter formatter = DateTimeFormatter + .ofPattern("yyyy-MM-dd HH:mm:ss z", Locale.SIMPLIFIED_CHINESE); + String formattedTime = formatter.format(zonedDateTime); + String msg = String.format("JWT expired at (%d -> %s)", expirationTime, formattedTime); + System.out.println(msg); + System.out.println(jwt); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/PluginUtilTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/PluginUtilTest.java new file mode 100644 index 000000000..4fec2a1e7 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/PluginUtilTest.java @@ -0,0 +1,916 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.util; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import com.tencent.cloud.plugin.gateway.context.Position; +import com.tencent.tsf.gateway.core.TsfGatewayRequest; +import com.tencent.tsf.gateway.core.exception.TsfGatewayException; +import com.tencent.tsf.gateway.core.model.PluginDetail; +import com.tencent.tsf.gateway.core.model.PluginPayload; +import com.tencent.tsf.gateway.core.model.RequestTransformerPluginInfo; +import com.tencent.tsf.gateway.core.model.TagPluginInfo; +import com.tencent.tsf.gateway.core.model.TransformerAction; +import com.tencent.tsf.gateway.core.model.TransformerTag; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import org.springframework.tsf.core.TsfContext; +import org.springframework.tsf.core.entity.Tag; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; + +/** + * Test for {@link PluginUtil}. + * + * @author Haotian Zhang + */ +public class PluginUtilTest { + + private TsfGatewayRequest tsfGatewayRequest; + private PluginPayload pluginPayload; + + @BeforeEach + void setUp() throws URISyntaxException { + // init TsfGatewayRequest + tsfGatewayRequest = new TsfGatewayRequest(); + tsfGatewayRequest.setUri(new URI("http://localhost:8080/test_group/test_namespace/test_service/api/v1/users/123")); + + // set request headers + Map requestHeaders = new HashMap<>(); + requestHeaders.put("x-user-id", "user123"); + requestHeaders.put("authorization", "Bearer token123"); + tsfGatewayRequest.setRequestHeaders(requestHeaders); + + // set request parameters + Map parameterMap = new HashMap<>(); + parameterMap.put("userId", new String[] {"123", "456"}); + parameterMap.put("type", new String[] {"admin"}); + tsfGatewayRequest.setParameterMap(parameterMap); + + // set request cookies + Map cookieMap = new HashMap<>(); + cookieMap.put("sessionId", "session123"); + cookieMap.put("lang", "zh-CN"); + tsfGatewayRequest.setCookieMap(cookieMap); + + // init PluginPayload + pluginPayload = new PluginPayload(); + } + + @Test + public void testSortPluginDetail() { + List pluginDetails = new ArrayList<>(); + PluginDetail pluginDetail = new PluginDetail(); + pluginDetail.setName("test"); + pluginDetails.add(pluginDetail); + Stream pluginDetailStream = Stream.of(pluginDetails).flatMap(Collection::stream); + List result = PluginUtil.sortPluginDetail(pluginDetailStream); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + assertThat(result.get(0).getName()).isEqualTo("test"); + } + + @Test + public void testDeserializeTagPluginInfoList() { + String tagPluginInfoListJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"preTagName\",\"postTagName\":\"postTagName\",\"traceIdEnabled\":\"Y\"}]"; + List tagPluginInfoList = PluginUtil.deserializeTagPluginInfoList(tagPluginInfoListJson); + assertThat(tagPluginInfoList).isNotEmpty(); + assertThat(tagPluginInfoList).hasSize(1); + TagPluginInfo tagPluginInfo = tagPluginInfoList.get(0); + assertThat(tagPluginInfo.getTagPosition().name()).isEqualTo("QUERY"); + assertThat(tagPluginInfo.getPreTagName()).isEqualTo("preTagName"); + assertThat(tagPluginInfo.getPostTagName()).isEqualTo("postTagName"); + assertThat(tagPluginInfo.getTraceIdEnabled()).isEqualTo("Y"); + + assertThatThrownBy(() -> { + PluginUtil.deserializeTagPluginInfoList("[{\"tagPosition\":\"QUERY\",\"preTagName\":\"preTagName\",\"postTagName\":\"postTagName\",\"traceIdEnabled\":\"Y\""); + }).isInstanceOf(TsfGatewayException.class); + + assertThatThrownBy(() -> { + PluginUtil.deserializeTagPluginInfoList(""); + }).isInstanceOf(TsfGatewayException.class); + } + + @Test + public void testTransferToTag_EmptyTagPluginList() { + String emptyJson = "[]"; + PluginPayload result = PluginUtil.transferToTag(emptyJson, tsfGatewayRequest, pluginPayload); + assertThat(result).isEqualTo(pluginPayload); + } + + @Test + public void testTransferToTag_QueryPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"userId\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_QueryPosition_WithoutPostTagName() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"userId\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_QueryPosition_NotFound() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"nonExistentParam\",\"postTagName\":\"test_tag\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_CookiePosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"COOKIE\",\"preTagName\":\"sessionId\",\"postTagName\":\"session_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_CookiePosition_WithoutPostTagName() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"COOKIE\",\"preTagName\":\"sessionId\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_CookiePosition_NotFound() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"COOKIE\",\"preTagName\":\"nonExistentCookie\",\"postTagName\":\"test_tag\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_HeaderPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"HEADER\",\"preTagName\":\"x-user-id\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_HeaderPosition_WithoutPostTagName() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"HEADER\",\"preTagName\":\"x-user-id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_HeaderPosition_NotFound() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"HEADER\",\"preTagName\":\"non-existent-header\",\"postTagName\":\"test_tag\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_PathPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"PATH\",\"preTagName\":\"/api/v1/users/{userId}\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_PathPosition_NotMatched() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"PATH\",\"preTagName\":\"/api/v2/products/{productId}\",\"postTagName\":\"product_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_PathPosition_WithoutPostTagName() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"PATH\",\"preTagName\":\"/api/v1/users/{userId}\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_PathPosition_EmptyPath() throws Exception { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + // set empty path + tsfGatewayRequest.setUri(new URI("http://localhost:8080")); + String tagPluginJson = "[{\"tagPosition\":\"PATH\",\"preTagName\":\"/api/v1/users/{userId}\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_PathPosition_PathWithoutLeadingSlash() throws Exception { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + tsfGatewayRequest.setUri(new URI("http://localhost:8080/api/v1/users/123")); + String tagPluginJson = "[{\"tagPosition\":\"PATH\",\"preTagName\":\"/api/v1/users/{userId}\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_WithTraceIdEnabled() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"userId\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"Y\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + // verify that the response headers contain the expected keys + assertThat(result.getResponseHeaders()).isNotNull(); + assertThat(result.getResponseHeaders()).containsKey("user_id"); + assertThat(result.getResponseHeaders()).containsKey("X-Tsf-TraceId"); + + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_MultipleTagPlugins() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + String tagPluginJson = "[" + + "{\"tagPosition\":\"QUERY\",\"preTagName\":\"userId\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"N\"}," + + "{\"tagPosition\":\"HEADER\",\"preTagName\":\"x-user-id\",\"postTagName\":\"header_user_id\",\"traceIdEnabled\":\"N\"}," + + "{\"tagPosition\":\"COOKIE\",\"preTagName\":\"sessionId\",\"postTagName\":\"session_id\",\"traceIdEnabled\":\"N\"}" + + "]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_WithExistingResponseHeaders() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + // set existing response headers + Map existingHeaders = new HashMap<>(); + existingHeaders.put("existing-header", "existing-value"); + pluginPayload.setResponseHeaders(existingHeaders); + + String tagPluginJson = "[{\"tagPosition\":\"QUERY\",\"preTagName\":\"userId\",\"postTagName\":\"user_id\",\"traceIdEnabled\":\"Y\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + // verify that the response headers contain the expected keys + assertThat(result.getResponseHeaders()).containsKey("existing-header"); + assertThat(result.getResponseHeaders()).containsKey("user_id"); + assertThat(result.getResponseHeaders()).containsKey("X-Tsf-TraceId"); + + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testTransferToTag_DefaultPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + // create a TagPluginInfo with a non-existent Position + TagPluginInfo tagPluginInfo = new TagPluginInfo(); + tagPluginInfo.setTagPosition(Position.TSF_TAG); // 使用一个不在switch中处理的Position + tagPluginInfo.setPreTagName("testTag"); + tagPluginInfo.setPostTagName("test_tag"); + tagPluginInfo.setTraceIdEnabled("N"); + + String tagPluginJson = "[{\"tagPosition\":\"TSF_TAG\",\"preTagName\":\"testTag\",\"postTagName\":\"test_tag\",\"traceIdEnabled\":\"N\"}]"; + + PluginPayload result = PluginUtil.transferToTag(tagPluginJson, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testPredicateJsonFormat() { + String tagPluginInfoListJson = ""; + assertThat(PluginUtil.predicateJsonFormat(tagPluginInfoListJson)).isFalse(); + } + + @Test + public void testDoRequestTransformer_NullRequestTransformerPluginInfo() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + PluginPayload result = PluginUtil.doRequestTransformer(null, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verifyNoInteractions(); + } + } + + @Test + public void testDoRequestTransformer_EmptyActions() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + pluginInfo.setActions(new ArrayList<>()); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verifyNoInteractions(); + } + } + + @Test + public void testDoRequestTransformer_NullActions() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + pluginInfo.setActions(null); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verifyNoInteractions(); + } + } + + @Test + public void testDoRequestTransformer_NoFilters_TsfTagAction() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("test-tag"); + action.setTagValue("test-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_NoFilters_HeaderAction() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.HEADER); + action.setTagName("X-Custom-Header"); + action.setTagValue("custom-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + assertThat(result.getRequestHeaders()).isNotNull(); + assertThat(result.getRequestHeaders()).containsEntry("X-Custom-Header", "custom-value"); + + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_NoFilters_HeaderAction_WithExistingHeaders() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + // set existing request headers + Map existingHeaders = new HashMap<>(); + existingHeaders.put("existing-header", "existing-value"); + pluginPayload.setRequestHeaders(existingHeaders); + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + // create action + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.HEADER); + action.setTagName("X-Custom-Header"); + action.setTagValue("custom-value"); + action.setWeight(100); + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + assertThat(result.getRequestHeaders()).containsEntry("existing-header", "existing-value"); + assertThat(result.getRequestHeaders()).containsEntry("X-Custom-Header", "custom-value"); + + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_QueryFilter_Match() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.QUERY); + filter.setTagField("userId"); + filter.setTagValue("123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("matched-tag"); + action.setTagValue("matched-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_QueryFilter_NotMatch() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.QUERY); + filter.setTagField("userId"); + filter.setTagValue("999"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("matched-tag"); + action.setTagValue("matched-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_QueryFilter_NullQueryValue() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.QUERY); + filter.setTagField("nonExistentParam"); + filter.setTagValue("test"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("matched-tag"); + action.setTagValue("matched-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_CookieFilter_Match() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.COOKIE); + filter.setTagField("sessionId"); + filter.setTagValue("session123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("session-tag"); + action.setTagValue("session-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_HeaderFilter_Match() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.HEADER); + filter.setTagField("x-user-id"); + filter.setTagValue("user123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("user-tag"); + action.setTagValue("user-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_PathFilter_Match() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.PATH); + filter.setTagField("/api/v1/users/{userId}"); + filter.setTagValue("123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("path-tag"); + action.setTagValue("path-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_PathFilter_NotMatch() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + // create filter with not match path + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.PATH); + filter.setTagField("/api/v2/products/{productId}"); + filter.setTagValue("123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("path-tag"); + action.setTagValue("path-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_PathFilter_EmptyPath() throws Exception { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + // set empty path + tsfGatewayRequest.setUri(new URI("http://localhost:8080")); + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.PATH); + filter.setTagField("/api/v1/users/{userId}"); + filter.setTagValue("123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("path-tag"); + action.setTagValue("path-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_PathFilter_PathWithoutLeadingSlash() throws Exception { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + tsfGatewayRequest.setUri(new URI("http://localhost:8080/api/v1/users/123")); + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.PATH); + filter.setTagField("/api/v1/users/{userId}"); + filter.setTagValue("123"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("path-tag"); + action.setTagValue("path-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_MultipleFilters_AllMatch() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag queryFilter = new TransformerTag(); + queryFilter.setTagPosition(Position.QUERY); + queryFilter.setTagField("userId"); + queryFilter.setTagValue("123"); + + TransformerTag headerFilter = new TransformerTag(); + headerFilter.setTagPosition(Position.HEADER); + headerFilter.setTagField("x-user-id"); + headerFilter.setTagValue("user123"); + + List filters = new ArrayList<>(); + filters.add(queryFilter); + filters.add(headerFilter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("multi-tag"); + action.setTagValue("multi-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_MultipleFilters_OneNotMatch() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + TransformerTag queryFilter = new TransformerTag(); + queryFilter.setTagPosition(Position.QUERY); + queryFilter.setTagField("userId"); + queryFilter.setTagValue("123"); + + TransformerTag headerFilter = new TransformerTag(); + headerFilter.setTagPosition(Position.HEADER); + headerFilter.setTagField("x-user-id"); + headerFilter.setTagValue("user999"); + + List filters = new ArrayList<>(); + filters.add(queryFilter); + filters.add(headerFilter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("multi-tag"); + action.setTagValue("multi-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_DefaultActionPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + // create action with default position (not TSF_TAG or HEADER) + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.QUERY); // 使用一个不在switch中处理的Position + action.setTagName("test-tag"); + action.setTagValue("test-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } + + @Test + public void testDoRequestTransformer_DefaultFilterPosition() { + try (MockedStatic mockedTsfContext = Mockito.mockStatic(TsfContext.class)) { + RequestTransformerPluginInfo pluginInfo = new RequestTransformerPluginInfo(); + + // create filter with default position (not in switch cases) + TransformerTag filter = new TransformerTag(); + filter.setTagPosition(Position.TSF_TAG); // 使用一个不在switch中处理的Position + filter.setTagField("test-field"); + filter.setTagValue("test-value"); + + List filters = new ArrayList<>(); + filters.add(filter); + pluginInfo.setFilters(filters); + + TransformerAction action = new TransformerAction(); + action.setTagPosition(Position.TSF_TAG); + action.setTagName("test-tag"); + action.setTagValue("test-value"); + action.setWeight(100); + + List actions = new ArrayList<>(); + actions.add(action); + pluginInfo.setActions(actions); + + PluginPayload result = PluginUtil.doRequestTransformer(pluginInfo, tsfGatewayRequest, pluginPayload); + + assertThat(result).isSameAs(pluginPayload); + mockedTsfContext.verify(() -> TsfContext.putTags(anyMap(), eq(Tag.ControlFlag.TRANSITIVE))); + } + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/TsfSignUtilTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/TsfSignUtilTest.java new file mode 100644 index 000000000..c53cc6d25 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-gateway-plugin/src/test/java/com/tencent/tsf/gateway/core/util/TsfSignUtilTest.java @@ -0,0 +1,181 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.tsf.gateway.core.util; + +import com.tencent.tsf.gateway.core.constant.TsfAlgType; +import org.junit.jupiter.api.Test; +import shade.polaris.org.apache.commons.codec.binary.Base64; +import shade.polaris.org.apache.commons.codec.digest.HmacUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link TsfSignUtil}. + * + * @author Haotian Zhang + */ +public class TsfSignUtilTest { + + private static final String TEST_NONCE = "test-nonce"; + private static final String TEST_SECRET_ID = "test-secret-id"; + private static final String TEST_SECRET_KEY = "test-secret-key"; + + @Test + public void testGenerateWithHmacMd5() { + // Given + String expectedDigestValue = TEST_NONCE + TEST_SECRET_ID + TEST_SECRET_KEY; + byte[] expectedBytes = HmacUtils.hmacMd5(TEST_SECRET_KEY, expectedDigestValue); + String expectedSignature = Base64.encodeBase64String(expectedBytes); + + // When + String actualSignature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_MD5); + + // Then + assertThat(actualSignature).isEqualTo(expectedSignature); + assertThat(actualSignature).isNotEmpty(); + } + + @Test + public void testGenerateWithHmacSha1() { + // Given + String expectedDigestValue = TEST_NONCE + TEST_SECRET_ID + TEST_SECRET_KEY; + byte[] expectedBytes = HmacUtils.hmacSha1(TEST_SECRET_KEY, expectedDigestValue); + String expectedSignature = Base64.encodeBase64String(expectedBytes); + + // When + String actualSignature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_1); + + // Then + assertThat(actualSignature).isEqualTo(expectedSignature); + assertThat(actualSignature).isNotEmpty(); + } + + @Test + public void testGenerateWithHmacSha256() { + // Given + String expectedDigestValue = TEST_NONCE + TEST_SECRET_ID + TEST_SECRET_KEY; + byte[] expectedBytes = HmacUtils.hmacSha256(TEST_SECRET_KEY, expectedDigestValue); + String expectedSignature = Base64.encodeBase64String(expectedBytes); + + // When + String actualSignature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_256); + + // Then + assertThat(actualSignature).isEqualTo(expectedSignature); + assertThat(actualSignature).isNotEmpty(); + } + + @Test + public void testGenerateWithHmacSha512() { + // Given + String expectedDigestValue = TEST_NONCE + TEST_SECRET_ID + TEST_SECRET_KEY; + byte[] expectedBytes = HmacUtils.hmacSha512(TEST_SECRET_KEY, expectedDigestValue); + String expectedSignature = Base64.encodeBase64String(expectedBytes); + + // When + String actualSignature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_512); + + // Then + assertThat(actualSignature).isEqualTo(expectedSignature); + assertThat(actualSignature).isNotEmpty(); + } + + @Test + public void testGenerateWithUnsupportedAlgorithm() { + // When & Then + assertThatThrownBy(() -> TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SM3)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("不支持的鉴权算法: HMAC_SM3"); + } + + @Test + public void testGenerateWithEmptyParameters() { + // Given + String emptyNonce = ""; + String emptySecretId = ""; + String emptySecretKey = ""; + + // When & Then + assertThatThrownBy(() -> TsfSignUtil.generate(emptyNonce, emptySecretId, emptySecretKey, TsfAlgType.HMAC_MD5)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testGenerateConsistency() { + // Given - Same input should produce same output + String nonce = "consistent-nonce"; + String secretId = "consistent-secret-id"; + String secretKey = "consistent-secret-key"; + + // When + String signature1 = TsfSignUtil.generate(nonce, secretId, secretKey, TsfAlgType.HMAC_SHA_256); + String signature2 = TsfSignUtil.generate(nonce, secretId, secretKey, TsfAlgType.HMAC_SHA_256); + + // Then + assertThat(signature1).isEqualTo(signature2); + } + + @Test + public void testGenerateDifferentAlgorithmsProduceDifferentResults() { + // When + String md5Signature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_MD5); + String sha1Signature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_1); + String sha256Signature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_256); + String sha512Signature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_512); + + // Then - Different algorithms should produce different signatures + assertThat(md5Signature).isNotEqualTo(sha1Signature); + assertThat(md5Signature).isNotEqualTo(sha256Signature); + assertThat(md5Signature).isNotEqualTo(sha512Signature); + assertThat(sha1Signature).isNotEqualTo(sha256Signature); + assertThat(sha1Signature).isNotEqualTo(sha512Signature); + assertThat(sha256Signature).isNotEqualTo(sha512Signature); + } + + @Test + public void testGenerateWithSpecialCharacters() { + // Given + String specialNonce = "test-nonce-with-special-chars!@#$%^&*()"; + String specialSecretId = "special-chars-secret-id-with-symbols"; + String specialSecretKey = "secret-key-with-special-characters"; + + // When + String signature = TsfSignUtil.generate(specialNonce, specialSecretId, specialSecretKey, TsfAlgType.HMAC_SHA_256); + + // Then + assertThat(signature).isNotNull(); + assertThat(signature).isNotEmpty(); + + // Verify signature result with special characters + String expectedDigestValue = specialNonce + specialSecretId + specialSecretKey; + byte[] expectedBytes = HmacUtils.hmacSha256(specialSecretKey, expectedDigestValue); + String expectedSignature = Base64.encodeBase64String(expectedBytes); + assertThat(signature).isEqualTo(expectedSignature); + } + + @Test + public void testGenerateSignatureFormat() { + // When + String signature = TsfSignUtil.generate(TEST_NONCE, TEST_SECRET_ID, TEST_SECRET_KEY, TsfAlgType.HMAC_SHA_256); + + // Then - Verify Base64 encoding format + assertThat(signature).matches("^[A-Za-z0-9+/]*={0,2}$"); // Base64 format regex + assertThat(Base64.isBase64(signature)).isTrue(); + } +}