|
@@ -0,0 +1,547 @@
|
|
|
|
|
+package com.etotem.cfc.unit;
|
|
|
|
|
+
|
|
|
|
|
+import org.junit.jupiter.api.DisplayName;
|
|
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
|
|
+import org.springframework.http.HttpEntity;
|
|
|
|
|
+import org.springframework.http.HttpHeaders;
|
|
|
|
|
+import org.springframework.http.HttpMethod;
|
|
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
|
|
+
|
|
|
|
|
+import java.lang.annotation.Annotation;
|
|
|
|
|
+import java.lang.reflect.Constructor;
|
|
|
|
|
+import java.lang.reflect.Field;
|
|
|
|
|
+import java.lang.reflect.InvocationTargetException;
|
|
|
|
|
+import java.lang.reflect.Method;
|
|
|
|
|
+import java.lang.reflect.Modifier;
|
|
|
|
|
+import java.util.Collections;
|
|
|
|
|
+
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertNull;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.fail;
|
|
|
|
|
+import static org.mockito.ArgumentMatchers.any;
|
|
|
|
|
+import static org.mockito.ArgumentMatchers.anyString;
|
|
|
|
|
+import static org.mockito.Mockito.doAnswer;
|
|
|
|
|
+import static org.mockito.Mockito.mock;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 契约级单测(TDD-RED):爱云医 AI 检测宿主网关,能力键 {@code ai.aiyunyi.gateway}(任务 S-cfc-449)。
|
|
|
|
|
+ *
|
|
|
|
|
+ * <p><b>溯源</b></p>
|
|
|
|
|
+ * <ul>
|
|
|
|
|
+ * <li>需求:{@code docs/2026-11-24-爱云医AI检测接入方案.md} §3.1(总体设计)/§4.5(后端改动清单);
|
|
|
|
|
+ * {@code docs/爱云医接入/爱云医接口契约-完整版.md} 各接口调用约定。</li>
|
|
|
|
|
+ * <li>设计:同上 §3.1/§4.5 —— {@link #HOST} 仿 {@code AiGateway} 统一收口 HTTP 调用
|
|
|
|
|
+ * (RestTemplate 连接/读取超时 + 连续失败熔断);每次调用拼
|
|
|
|
|
+ * {@code X-App-Key / X-Timestamp / X-Api-Sign},业务接口再加
|
|
|
|
|
+ * {@code Authorization: Bearer {token}} 与 {@code X-User-Id-Encrypt};
|
|
|
|
|
+ * 错误归一:spu 空 = 未开通、无子项 = 次数用完、401/403 = 鉴权失败;
|
|
|
|
|
+ * 配置经 {@link #PROPERTIES} 加载并校验。</li>
|
|
|
|
|
+ * </ul>
|
|
|
|
|
+ *
|
|
|
|
|
+ * <p><b>契约 AC(GREEN 阶段实现方按此落地,方法名/参数签名即测试锚点)</b></p>
|
|
|
|
|
+ * <ol>
|
|
|
|
|
+ * <li>AC1 宿主网关 {@code com.etotem.cfc.service.AicdsGatewayService} 存在(与 S-cfc-447 同一宿主)。</li>
|
|
|
|
|
+ * <li>AC2 配置类 {@code com.etotem.cfc.config.AiYunyiProperties} 存在,标注
|
|
|
|
|
+ * {@code @ConfigurationProperties(prefix = "aiyunyi")}。</li>
|
|
|
|
|
+ * <li>AC3 配置类含必填字段 {@code appKey / privateKey / publicKey / baseUrl}
|
|
|
|
|
+ * (String)与超时字段 {@code timeoutMs / readTimeoutMs}(int,默认值 > 0)。</li>
|
|
|
|
|
+ * <li>AC4 配置加载校验:必填项为空/空白时快速失败——提供 {@code validateConfig()}(抛异常)
|
|
|
|
|
+ * 或 {@code isConfigured()}(返回 false)二者之一。</li>
|
|
|
|
|
+ * <li>AC5 宿主持有可注入的 {@link RestTemplate} 字段(非 final,或提供 setter / 含 RestTemplate 的构造器),
|
|
|
|
|
+ * 以便用 Mockito mock 做纯单测。</li>
|
|
|
|
|
+ * <li>AC6 宿主提供无参 {@code init()}({@code @PostConstruct}),为 RestTemplate 设置连接与读取超时
|
|
|
|
|
+ * (仿 {@code AiGateway}:{@code SimpleClientHttpRequestFactory.setConnectTimeout/setReadTimeout},
|
|
|
|
|
+ * 两者均 > 0)。</li>
|
|
|
|
|
+ * <li>AC7 宿主具备熔断状态:{@code circuitOpen / consecutiveFailures / lastFailureTime} 字段
|
|
|
|
|
+ * 或 {@code isCircuitOpen() / recordFailure()} 方法(仿 {@code AiGateway})。</li>
|
|
|
|
|
+ * <li>AC8 宿主提供统一调用入口
|
|
|
|
|
+ * {@code exchange(String path, Object body, Class<?> responseType, String accessToken, String userId)},
|
|
|
|
|
+ * 内部走 {@code RestTemplate.exchange(String, HttpMethod, HttpEntity, Class, Object...)};
|
|
|
|
|
+ * accessToken/userId 传 null 表示登录类调用。</li>
|
|
|
|
|
+ * <li>AC9 每次调用(含登录)头中必须带 {@code X-App-Key / X-Timestamp / X-Api-Sign}。</li>
|
|
|
|
|
+ * <li>AC10 业务调用(accessToken/userId 非空)额外带
|
|
|
|
|
+ * {@code Authorization: Bearer {accessToken}} 与 {@code X-User-Id-Encrypt};登录调用不带这两个头。</li>
|
|
|
|
|
+ * <li>AC11 错误归一方法 {@code normalizeError(int statusCode, String spu, Object subItems)} 返回文案:
|
|
|
|
|
+ * spu 空 → 含「未开通」;子项为空 → 含「次数用完」;401/403 → 含「鉴权失败」。</li>
|
|
|
|
|
+ * </ol>
|
|
|
|
|
+ *
|
|
|
|
|
+ * <p><b>实现现状(RED 依据)</b>:本分支 {@code src/main} 中 {@code AicdsGatewayService / AiYunyiProperties /
|
|
|
|
|
+ * Aicds / aiyunyi} 0 引用,宿主与配置类均未落地。测试通过反射 + classpath 读取锚定契约
|
|
|
|
|
+ * (避免 import 不存在类导致编译失败),运行时宿主缺失即断言失败(红),失败原文明确「实现未落地」。</p>
|
|
|
|
|
+ *
|
|
|
|
|
+ * <p><b>GREEN 升级指引</b>:实现者按上述 AC1~AC11 落地宿主与配置类后,本测试自动转绿;
|
|
|
|
|
+ * 反射按「方法名 + 参数个数」匹配,等价重载亦可。测试只生成临时 Mockito mock,
|
|
|
|
|
+ * 不依赖 Spring 上下文、DB、真实密钥、网络或外部服务。</p>
|
|
|
|
|
+ */
|
|
|
|
|
+class AiyunyiGatewayContractTest {
|
|
|
|
|
+
|
|
|
|
|
+ private static final String HOST = "com.etotem.cfc.service.AicdsGatewayService";
|
|
|
|
|
+ private static final String PROPERTIES = "com.etotem.cfc.config.AiYunyiProperties";
|
|
|
|
|
+
|
|
|
|
|
+ private static final String APP_KEY = "app-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
|
|
|
|
|
+ private static final String ACCESS_TOKEN = "test-access-token-123456";
|
|
|
|
|
+ private static final String USER_ID = "987654321";
|
|
|
|
|
+
|
|
|
|
|
+ private static final String H_APP_KEY = "X-App-Key";
|
|
|
|
|
+ private static final String H_TIMESTAMP = "X-Timestamp";
|
|
|
|
|
+ private static final String H_API_SIGN = "X-Api-Sign";
|
|
|
|
|
+ private static final String H_AUTHORIZATION = "Authorization";
|
|
|
|
|
+ private static final String H_USER_ID_ENCRYPT = "X-User-Id-Encrypt";
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 正常流:宿主 / 配置契约 ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-1:服务端网关宿主 AicdsGatewayService 应存在(§4.5)")
|
|
|
|
|
+ void hostClass_exists() {
|
|
|
|
|
+ assertNotNull(loadClass(HOST),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] " + HOST + " 不存在:§3.1/§4.5 要求仿 AiGateway 统一收口"
|
|
|
|
|
+ + " 爱云医 HTTP 调用(超时/熔断/头拼装/错误归一)。实现未落地。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-2:配置类 AiYunyiProperties 应存在")
|
|
|
|
|
+ void propertiesClass_exists() {
|
|
|
|
|
+ assertNotNull(loadClass(PROPERTIES),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] " + PROPERTIES + " 不存在:§4.5 要求配置项"
|
|
|
|
|
+ + "(appKey/私钥/公钥/baseUrl/超时)统一加载并校验。实现未落地。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-3:配置类应标注 @ConfigurationProperties(prefix=\"aiyunyi\")")
|
|
|
|
|
+ void properties_hasConfigurationPropertiesPrefix() {
|
|
|
|
|
+ Class<?> clazz = loadClass(PROPERTIES);
|
|
|
|
|
+ if (clazz == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] AiYunyiProperties 不存在,无法校验配置前缀绑定(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ assertTrue(hasAnnotationValue(clazz, "org.springframework.boot.context.properties.ConfigurationProperties",
|
|
|
|
|
+ "aiyunyi", "prefix", "value"),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] AiYunyiProperties 应标注 @ConfigurationProperties(prefix=\"aiyunyi\"),"
|
|
|
|
|
+ + "使 application.yml 的 aiyunyi.* 配置可绑定。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-4:配置类应含 appKey/privateKey/publicKey/baseUrl 及超时字段")
|
|
|
|
|
+ void properties_hasRequiredConfigFields() {
|
|
|
|
|
+ Class<?> clazz = loadClass(PROPERTIES);
|
|
|
|
|
+ if (clazz == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] AiYunyiProperties 不存在,无法校验配置字段(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ for (String name : new String[]{"appKey", "privateKey", "publicKey", "baseUrl"}) {
|
|
|
|
|
+ Field f = findField(clazz, name);
|
|
|
|
|
+ assertNotNull(f, "[ai.aiyunyi.gateway] AiYunyiProperties 缺少必填配置字段 " + name + "(§4.5)。");
|
|
|
|
|
+ assertEquals("java.lang.String", f.getType().getName(),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 配置字段 " + name + " 应为 String。");
|
|
|
|
|
+ }
|
|
|
|
|
+ for (String name : new String[]{"timeoutMs", "readTimeoutMs"}) {
|
|
|
|
|
+ Field f = findField(clazz, name);
|
|
|
|
|
+ assertNotNull(f, "[ai.aiyunyi.gateway] AiYunyiProperties 缺少超时配置字段 " + name
|
|
|
|
|
+ + "(仿 AiGateway 的连接/读取超时,§3.1)。");
|
|
|
|
|
+ assertTrue(f.getType() == int.class || f.getType() == Integer.class,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 超时配置字段 " + name + " 应为 int。");
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("边界流-1:必填配置为空/空白时应快速失败(不得静默使用空 AppKey 发请求)")
|
|
|
|
|
+ void properties_blankAppKeyFailsFast() throws Exception {
|
|
|
|
|
+ Class<?> clazz = loadClass(PROPERTIES);
|
|
|
|
|
+ if (clazz == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] AiYunyiProperties 不存在,无法校验配置加载校验(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ Object props = newInstance(clazz);
|
|
|
|
|
+ setField(props, "appKey", " ");
|
|
|
|
|
+ setField(props, "privateKey", "dummy-private-key");
|
|
|
|
|
+ setField(props, "publicKey", "dummy-public-key");
|
|
|
|
|
+ setField(props, "baseUrl", "http://localhost:9000");
|
|
|
|
|
+
|
|
|
|
|
+ Method validate = findMethod(clazz, "validateConfig", 0);
|
|
|
|
|
+ if (validate != null) {
|
|
|
|
|
+ assertThrows(Exception.class, () -> invokeUnchecked(props, validate),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 空白 appKey 必须使 validateConfig() 快速失败,"
|
|
|
|
|
+ + "禁止用空鉴权配置静默发请求(§4.5)。");
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ Method configured = findMethod(clazz, "isConfigured", 0);
|
|
|
|
|
+ if (configured == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 配置校验契约缺失:应提供 validateConfig() 或 isConfigured()"
|
|
|
|
|
+ + " 之一以校验 ai.aiyunyi 配置完整性(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ Object result = invokeUnchecked(props, configured);
|
|
|
|
|
+ assertFalse(Boolean.TRUE.equals(result),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 空白 appKey 时 isConfigured() 必须返回 false(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 正常流:RestTemplate / 超时 / 熔断 ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-5:宿主应持有可注入的 RestTemplate,以便用 Mockito mock 做纯单测")
|
|
|
|
|
+ void gateway_hasInjectableRestTemplateForMockito() {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ Field template = findFieldOfType(host.getClass(), RestTemplate.class);
|
|
|
|
|
+ assertNotNull(template,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 宿主应持有 RestTemplate 字段(仿 AiGateway),"
|
|
|
|
|
+ + "否则无法以 mock RestTemplate 做网关单测(§4.5)。");
|
|
|
|
|
+
|
|
|
|
|
+ boolean injectable = !Modifier.isFinal(template.getModifiers())
|
|
|
|
|
+ || findMethod(host.getClass(), "setRestTemplate", 1) != null
|
|
|
|
|
+ || hasConstructorWith(host.getClass(), RestTemplate.class);
|
|
|
|
|
+ assertTrue(injectable,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] RestTemplate 必须可注入(非 final 字段 / setter / 构造器),"
|
|
|
|
|
+ + "使测试可替换 mock 并断言请求头。");
|
|
|
|
|
+
|
|
|
|
|
+ RestTemplate mock = mock(RestTemplate.class);
|
|
|
|
|
+ assertNotNull(mock, "RestTemplate 应可被 Mockito mock(无 Spring / 无网络)。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-6:init() 应为 RestTemplate 设置连接与读取超时(仿 AiGateway)")
|
|
|
|
|
+ void gateway_initializesRestTemplateTimeouts() throws Exception {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ Field template = findFieldOfType(host.getClass(), RestTemplate.class);
|
|
|
|
|
+ if (template == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 宿主无 RestTemplate 字段,无法校验超时设置(§3.1)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ template.setAccessible(true);
|
|
|
|
|
+ Object restTemplate = template.get(host);
|
|
|
|
|
+ assertNotNull(restTemplate, "[ai.aiyunyi.gateway] init() 前应已创建 RestTemplate 实例。");
|
|
|
|
|
+
|
|
|
|
|
+ Method init = findMethod(host.getClass(), "init", 0);
|
|
|
|
|
+ assertNotNull(init, "[ai.aiyunyi.gateway] 宿主应提供无参 init()(@PostConstruct)以应用超时配置(§3.1)。");
|
|
|
|
|
+ invokeUnchecked(host, init);
|
|
|
|
|
+
|
|
|
|
|
+ Object factory = invokeUnchecked(restTemplate, findMethod(restTemplate.getClass(), "getRequestFactory", 0));
|
|
|
|
|
+ assertNotNull(factory, "[ai.aiyunyi.gateway] RestTemplate 应配置 ClientHttpRequestFactory 以承载超时。");
|
|
|
|
|
+ int connect = readTimeoutValue(factory, "connectTimeout", "getConnectTimeout");
|
|
|
|
|
+ int read = readTimeoutValue(factory, "readTimeout", "getReadTimeout");
|
|
|
|
|
+ assertTrue(connect > 0,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 连接超时必须 > 0(仿 AiGateway setConnectTimeout),实际 " + connect + "ms。");
|
|
|
|
|
+ assertTrue(read > 0,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 读取超时必须 > 0(仿 AiGateway setReadTimeout),实际 " + read + "ms。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-7:宿主应具备连续失败熔断状态(仿 AiGateway)")
|
|
|
|
|
+ void gateway_hasCircuitBreakerState() {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ Class<?> clazz = host.getClass();
|
|
|
|
|
+ boolean hasState = findField(clazz, "circuitOpen") != null
|
|
|
|
|
+ || findField(clazz, "consecutiveFailures") != null
|
|
|
|
|
+ || findField(clazz, "lastFailureTime") != null;
|
|
|
|
|
+ boolean hasMethods = findMethod(clazz, "isCircuitOpen", 0) != null
|
|
|
|
|
+ || findMethod(clazz, "recordFailure", 0) != null;
|
|
|
|
|
+ assertTrue(hasState || hasMethods,
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 宿主应仿 AiGateway 实现熔断:circuitOpen/consecutiveFailures/"
|
|
|
|
|
+ + "lastFailureTime 字段或 isCircuitOpen()/recordFailure() 方法(§3.1)。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 正常流:请求头拼装(mock RestTemplate 单测) ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-8:每次调用(含登录)都带 X-App-Key/X-Timestamp/X-Api-Sign")
|
|
|
|
|
+ void gateway_outboundCallCarriesAuthHeaders() throws Exception {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ RestTemplate mock = injectMockTemplate(host);
|
|
|
|
|
+ HttpEntity<?> entity = exchangeAndCapture(host, mock, null, null);
|
|
|
|
|
+
|
|
|
|
|
+ assertNotNull(entity, "[ai.aiyunyi.gateway] 调用应经 RestTemplate.exchange 发出 HttpEntity(§4.5)。");
|
|
|
|
|
+ assertEquals(APP_KEY, header(entity, H_APP_KEY),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 每次调用必须带 X-App-Key(§A.1/§3.1)。");
|
|
|
|
|
+ assertNotNull(header(entity, H_TIMESTAMP), "[ai.aiyunyi.gateway] 每次调用必须带 X-Timestamp。");
|
|
|
|
|
+ assertFalse(isBlank(header(entity, H_TIMESTAMP)), "X-Timestamp 不得为空。");
|
|
|
|
|
+ assertNotNull(header(entity, H_API_SIGN), "[ai.aiyunyi.gateway] 每次调用必须带 X-Api-Sign。");
|
|
|
|
|
+ assertFalse(isBlank(header(entity, H_API_SIGN)), "X-Api-Sign 不得为空。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-9:业务调用额外带 Authorization(Bearer) 与 X-User-Id-Encrypt")
|
|
|
|
|
+ void gateway_businessCallAddsBusinessHeaders() throws Exception {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ RestTemplate mock = injectMockTemplate(host);
|
|
|
|
|
+ HttpEntity<?> entity = exchangeAndCapture(host, mock, ACCESS_TOKEN, USER_ID);
|
|
|
|
|
+
|
|
|
|
|
+ assertNotNull(entity, "[ai.aiyunyi.gateway] 业务调用应经 RestTemplate.exchange 发出 HttpEntity。");
|
|
|
|
|
+ assertEquals("Bearer " + ACCESS_TOKEN, header(entity, H_AUTHORIZATION),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 业务接口 Authorization 应为 Bearer {accessToken}(§3.2/§4.5)。");
|
|
|
|
|
+ assertFalse(isBlank(header(entity, H_USER_ID_ENCRYPT)),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 业务接口必须带非空 X-User-Id-Encrypt(RSA 加密 userId)。");
|
|
|
|
|
+ assertNotNull(header(entity, H_API_SIGN), "[ai.aiyunyi.gateway] 业务头也必须带 X-Api-Sign。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-10:登录类调用不带业务头(Authorization / X-User-Id-Encrypt)")
|
|
|
|
|
+ void gateway_loginCallHasNoBusinessHeaders() throws Exception {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ RestTemplate mock = injectMockTemplate(host);
|
|
|
|
|
+ HttpEntity<?> entity = exchangeAndCapture(host, mock, null, null);
|
|
|
|
|
+
|
|
|
|
|
+ assertNotNull(entity, "[ai.aiyunyi.gateway] 登录调用应经 RestTemplate.exchange 发出 HttpEntity。");
|
|
|
|
|
+ assertNull(header(entity, H_AUTHORIZATION),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 登录类调用不应带 Authorization(只有业务接口才带)。");
|
|
|
|
|
+ assertNull(header(entity, H_USER_ID_ENCRYPT),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 登录类调用不应带 X-User-Id-Encrypt(只有业务接口才带)。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 正常流:错误归一 ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-11:spu 为空应归一为「未开通」")
|
|
|
|
|
+ void errorNormalization_spuEmpty_meansNotOpened() {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ String message = callString(host, "normalizeError", 200, "", Collections.emptyList());
|
|
|
|
|
+ assertNotNull(message, "[ai.aiyunyi.gateway] 错误归一结果不得为 null。");
|
|
|
|
|
+ assertTrue(message.contains("未开通"),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] spu 为空必须归一为「未开通」(§4.5 错误归一),实际:" + message);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-12:无子项应归一为「次数用完」")
|
|
|
|
|
+ void errorNormalization_noSubItems_meansQuotaUsedUp() {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ String message = callString(host, "normalizeError", 200, "spu-exists", Collections.emptyList());
|
|
|
|
|
+ assertNotNull(message, "[ai.aiyunyi.gateway] 错误归一结果不得为 null。");
|
|
|
|
|
+ assertTrue(message.contains("次数用完"),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] 子项为空必须归一为「次数用完」(§4.5 错误归一),实际:" + message);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("正常流-13:401/403 应归一为「鉴权失败」")
|
|
|
|
|
+ void errorNormalization_401and403_meanAuthFailure() {
|
|
|
|
|
+ Object host = contractHost();
|
|
|
|
|
+ String unauthorized = callString(host, "normalizeError", 401, "spu-exists",
|
|
|
|
|
+ Collections.singletonList("item-1"));
|
|
|
|
|
+ String forbidden = callString(host, "normalizeError", 403, "spu-exists",
|
|
|
|
|
+ Collections.singletonList("item-1"));
|
|
|
|
|
+ assertNotNull(unauthorized, "[ai.aiyunyi.gateway] 401 归一结果不得为 null。");
|
|
|
|
|
+ assertTrue(unauthorized.contains("鉴权失败"),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] HTTP 401 必须归一为「鉴权失败」(§4.5),实际:" + unauthorized);
|
|
|
|
|
+ assertNotNull(forbidden, "[ai.aiyunyi.gateway] 403 归一结果不得为 null。");
|
|
|
|
|
+ assertTrue(forbidden.contains("鉴权失败"),
|
|
|
|
|
+ "[ai.aiyunyi.gateway] HTTP 403 必须归一为「鉴权失败」(§4.5),实际:" + forbidden);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 权限流(不适用) ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ @DisplayName("权限流:网关为服务端统一收口能力,无用户角色门禁分支,权限流不适用")
|
|
|
|
|
+ void permissionFlow_notApplicable() {
|
|
|
|
|
+ // AC 均为服务端网关的 HTTP 拼装/超时/熔断/错误归一行为;鉴权头由服务端用配置密钥构造,
|
|
|
|
|
+ // 私钥/公钥不下发前端(§3.1),无独立的用户角色/权限校验维度。
|
|
|
|
|
+ assertTrue(true, "权限流不适用:ai.aiyunyi.gateway 为服务端内部网关能力,无用户角色维度。");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 反射 / Mockito 辅助 ====================
|
|
|
|
|
+
|
|
|
|
|
+ private static Class<?> loadClass(String name) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
|
|
|
|
|
+ } catch (ClassNotFoundException e) {
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private Object contractHost() {
|
|
|
|
|
+ Class<?> clazz = loadClass(HOST);
|
|
|
|
|
+ if (clazz == null) {
|
|
|
|
|
+ fail("RED[ai.aiyunyi.gateway] 契约宿主 " + HOST + " 未实现(实现未落地);"
|
|
|
|
|
+ + "§3.1/§4.5 要求仿 AiGateway 统一收口爱云医 HTTP 调用。"
|
|
|
|
|
+ + "请 GREEN 阶段按类注释 AC1~AC11 的方法签名落地。");
|
|
|
|
|
+ }
|
|
|
|
|
+ return newInstance(clazz);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static Object newInstance(Class<?> clazz) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ return clazz.getDeclaredConstructor().newInstance();
|
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
|
+ fail("契约类 " + clazz.getName() + " 实例化失败:" + e.getMessage());
|
|
|
|
|
+ throw new IllegalStateException("unreachable");
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static Method findMethod(Class<?> type, String name, int argCount) {
|
|
|
|
|
+ for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
|
|
|
|
|
+ for (Method m : c.getDeclaredMethods()) {
|
|
|
|
|
+ if (m.getName().equals(name) && m.getParameterCount() == argCount) {
|
|
|
|
|
+ return m;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ for (Method m : type.getMethods()) {
|
|
|
|
|
+ if (m.getName().equals(name) && m.getParameterCount() == argCount) {
|
|
|
|
|
+ return m;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static Field findField(Class<?> type, String name) {
|
|
|
|
|
+ for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
|
|
|
|
|
+ for (Field f : c.getDeclaredFields()) {
|
|
|
|
|
+ if (f.getName().equals(name)) {
|
|
|
|
|
+ return f;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static Field findFieldOfType(Class<?> type, Class<?> fieldType) {
|
|
|
|
|
+ for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
|
|
|
|
|
+ for (Field f : c.getDeclaredFields()) {
|
|
|
|
|
+ if (fieldType.isAssignableFrom(f.getType())) {
|
|
|
|
|
+ return f;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static boolean hasConstructorWith(Class<?> type, Class<?> argType) {
|
|
|
|
|
+ for (Constructor<?> c : type.getDeclaredConstructors()) {
|
|
|
|
|
+ Class<?>[] params = c.getParameterTypes();
|
|
|
|
|
+ if (params.length == 1 && params[0].isAssignableFrom(argType)) {
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static boolean hasAnnotationValue(Class<?> clazz, String annotationName, String expected,
|
|
|
|
|
+ String... valueMethods) {
|
|
|
|
|
+ for (Annotation a : clazz.getDeclaredAnnotations()) {
|
|
|
|
|
+ if (annotationName.equals(a.annotationType().getName())) {
|
|
|
|
|
+ for (String method : valueMethods) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ Object value = a.annotationType().getMethod(method).invoke(a);
|
|
|
|
|
+ if (expected.equals(String.valueOf(value))) {
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (Exception ignored) {
|
|
|
|
|
+ // 尝试下一个取值方法
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static void setField(Object target, String name, Object value) throws Exception {
|
|
|
|
|
+ Field f = findField(target.getClass(), name);
|
|
|
|
|
+ if (f == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 配置类缺少字段 " + name + "(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ f.setAccessible(true);
|
|
|
|
|
+ f.set(target, value);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static Object invokeUnchecked(Object target, Method method, Object... args) {
|
|
|
|
|
+ Method m = method;
|
|
|
|
|
+ if (m == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 契约方法缺失,无法调用。");
|
|
|
|
|
+ }
|
|
|
|
|
+ try {
|
|
|
|
|
+ m.setAccessible(true);
|
|
|
|
|
+ return m.invoke(target, args);
|
|
|
|
|
+ } catch (InvocationTargetException e) {
|
|
|
|
|
+ Throwable cause = e.getCause() == null ? e : e.getCause();
|
|
|
|
|
+ throw new RuntimeException(cause);
|
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
|
+ throw new RuntimeException(e);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private Object call(Object target, String name, Object... args) {
|
|
|
|
|
+ Method m = findMethod(target.getClass(), name, args.length);
|
|
|
|
|
+ if (m == null) {
|
|
|
|
|
+ fail("RED[ai.aiyunyi.gateway] 契约方法 " + HOST + "#" + name + "(...) 未实现(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ return invokeUnchecked(target, m, args);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private String callString(Object target, String name, Object... args) {
|
|
|
|
|
+ Object result = call(target, name, args);
|
|
|
|
|
+ if (result instanceof CharSequence) {
|
|
|
|
|
+ return result.toString();
|
|
|
|
|
+ }
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 契约方法 " + name + " 应返回字符串,实际 " + result);
|
|
|
|
|
+ throw new IllegalStateException("unreachable");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static int readTimeoutValue(Object factory, String fieldName, String getterName) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ Method getter = factory.getClass().getMethod(getterName);
|
|
|
|
|
+ Object value = getter.invoke(factory);
|
|
|
|
|
+ if (value instanceof Number) {
|
|
|
|
|
+ return ((Number) value).intValue();
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (Exception ignored) {
|
|
|
|
|
+ // 回退读字段
|
|
|
|
|
+ }
|
|
|
|
|
+ for (Class<?> c = factory.getClass(); c != null; c = c.getSuperclass()) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ Field f = c.getDeclaredField(fieldName);
|
|
|
|
|
+ f.setAccessible(true);
|
|
|
|
|
+ Object value = f.get(factory);
|
|
|
|
|
+ if (value instanceof Number) {
|
|
|
|
|
+ return ((Number) value).intValue();
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (Exception ignored) {
|
|
|
|
|
+ // 继续向上查找
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return -1;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
|
|
+ private RestTemplate injectMockTemplate(Object host) throws Exception {
|
|
|
|
|
+ Field template = findFieldOfType(host.getClass(), RestTemplate.class);
|
|
|
|
|
+ if (template == null) {
|
|
|
|
|
+ fail("[ai.aiyunyi.gateway] 宿主无 RestTemplate 字段,无法注入 mock(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ RestTemplate mock = mock(RestTemplate.class);
|
|
|
|
|
+ template.setAccessible(true);
|
|
|
|
|
+ template.set(host, mock);
|
|
|
|
|
+ return mock;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @SuppressWarnings({"unchecked", "rawtypes"})
|
|
|
|
|
+ private HttpEntity<?> exchangeAndCapture(Object host, RestTemplate mock,
|
|
|
|
|
+ String accessToken, String userId) {
|
|
|
|
|
+ final HttpEntity<?>[] box = new HttpEntity<?>[1];
|
|
|
|
|
+ doAnswer(invocation -> {
|
|
|
|
|
+ box[0] = invocation.getArgument(2);
|
|
|
|
|
+ return ResponseEntity.ok("{}");
|
|
|
|
|
+ }).when(mock).exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class),
|
|
|
|
|
+ any(Class.class), any(Object[].class));
|
|
|
|
|
+
|
|
|
|
|
+ Method exchange = findMethod(host.getClass(), "exchange", 5);
|
|
|
|
|
+ if (exchange == null) {
|
|
|
|
|
+ fail("RED[ai.aiyunyi.gateway] 契约方法 " + HOST
|
|
|
|
|
+ + "#exchange(String, Object, Class, String, String) 未实现(§4.5)。");
|
|
|
|
|
+ }
|
|
|
|
|
+ invokeUnchecked(host, exchange, "/test", "{}", String.class, accessToken, userId);
|
|
|
|
|
+ return box[0];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static String header(HttpEntity<?> entity, String name) {
|
|
|
|
|
+ if (entity == null) {
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+ HttpHeaders headers = entity.getHeaders();
|
|
|
|
|
+ for (java.util.Map.Entry<String, java.util.List<String>> e : headers.entrySet()) {
|
|
|
|
|
+ if (name.equalsIgnoreCase(e.getKey()) && e.getValue() != null && !e.getValue().isEmpty()) {
|
|
|
|
|
+ return e.getValue().get(0);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static boolean isBlank(String value) {
|
|
|
|
|
+ return value == null || value.trim().isEmpty();
|
|
|
|
|
+ }
|
|
|
|
|
+}
|