Explorar o código

[TDD] RED huawei.health.miniapp 契约测试(S-cfc-430)

Administrator hai 10 horas
pai
achega
3032c92714

+ 689 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/HuaweiHealthMiniappContractTest.java

@@ -0,0 +1,689 @@
+package com.etotem.cfc.unit;
+
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.huawei.HuaweiHealthController;
+import com.etotem.cfc.entity.HuaweiHealthToken;
+import com.etotem.cfc.mapper.HuaweiHealthTokenMapper;
+import com.etotem.cfc.service.huawei.HuaweiAuthService;
+import com.etotem.cfc.service.huawei.HuaweiHealthTokenCrypto;
+import com.etotem.cfc.service.huawei.HealthSyncService;
+import com.etotem.cfc.service.huawei.SyncResult;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+/**
+ * 契约级单测:小程序端华为运动健康集成(能力键 {@code huawei.health.miniapp},TDD RED)。
+ *
+ * <p><b>契约来源</b>({@code docs/2026-11-18-华为运动健康小程序端接入契约-H1-H4.md} §1/§3/§5/§7
+ * + {@code docs/2026-11-18-华为运动健康接入配置清单与联调指引.md} §1/§3/§4):
+ * <blockquote>
+ *   §1 决策:认证通过后继续配置开发;沿用小米架构——web-view + H5 中转页,不建 Android App。
+ *   §3 接口契约(后端 D1-D5 已合入 {@code 978d1bc95},mock 默认,5 接口已用于本测试结构锚点):
+ *   <ol>
+ *     <li>{@code POST /api/huawei-health/auth-url} → {@code authUrl/memberId/scope/generateAt}(无 mode/state)</li>
+ *     <li>{@code POST /api/huawei-health/callback} 入参 {@code code/memberId?} → {@code bound/status/expiresAt}</li>
+ *     <li>{@code POST /api/huawei-health/sync} 入参 {@code memberId?/dataType?} → {@code syncAt + result/results}</li>
+ *     <li>{@code POST /api/huawei-health/revoke} 入参 {@code memberId?} → {@code revoked}</li>
+ *     <li>{@code POST /api/huawei-health/status} 入参 {@code memberId?} → {@code bound/channel/mock/configured/expiresAt/scope}</li>
+ *   </ol>
+ *   ⚠️ 与小米差异(§3):接口 1 返回 <b>无</b> {@code mode}/{@code state} 字段;前端判 mock 分支的判据是
+ *   {@code authUrl} 是否指向 {@code oauth-login.cloud.huawei.com}(不是 mode 字段),mock 分支硬约束不得触发 web-view。
+ *   §7 后端小修:
+ *   <ul>
+ *     <li>H-B1:生成授权 URL 追加 {@code access_type=offline}(refresh_token 必需)</li>
+ *     <li>H-B2:token 交换改 {@code application/x-www-form-urlencoded} form body(华为官方要求)</li>
+ *     <li>H-B3:默认 scope 改为 URL 形式(含 {@code https://www.huawei.com/healthkit/} 前缀),real 启动时校验缺失则 fail-fast</li>
+ *   </ul>
+ * </blockquote></p>
+ *
+ * <p><b>平台现状(origin/cfclub src/main 探测)</b>:
+ * <ul>
+ *   <li>5 个接口控制器 {@code HuaweiHealthController} 已存在(D1-D5,978d1bc95),路由/基础字段已落地;</li>
+ *   <li><b>缺失(红):</b>
+ *   <ul>
+ *     <li>§7.1 H-B1:{@code generateAuthUrl} 未追加 {@code access_type=offline}(refresh_token 拿不到,2h 后无法续期)。</li>
+ *     <li>§7.2 H-B2:{@code exchangeCode} real 分支 Content-Type 仍为 {@code MediaType.APPLICATION_JSON}、body 为 {@code Map},非法(华为 token 端点要求 form-encoded)。</li>
+ *     <li>§7.3 H-B3:{@code application.yml} {@code huawei.health.scope} 默认仍为简写 {@code step,distance,...} 非 URL 形式;{@code HuaweiAuthService} 无 real 模式 scope 前缀校验(fail-fast 缺失)。</li>
+ *     <li>§3 接口 5:{@code status} 接口响应缺 {@code expiresAt}/{@code scope}(仅返回 bound/channel/mock/configured)。</li>
+ *     <li>§3/H3:mock 通道 {@code generateAuthUrl} 仍返回华为授权域名 URL(前端会误判 real 分支 → mock 触发 web-view 白屏,违反 H3 硬约束)。</li>
+ *     <li>H1/H2/H5(前端、对流):{@code cfc-frontend/utils/api.js} 无 5 个 huawei 方法;{@code health-main/index.vue} 无华为卡片;{@code huawei-auth.html}/{@code huawei-cb.html} 不存在。</li>
+ *   </ul>
+ *   </li>
+ * </ul>
+ * 本测试以「反射结构契约 + Mockito 行为契约」探测上述缺失:能编译、能运行、断言失败(红)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:
+ * <ol>
+ *   <li><b>§7.1 H-B1</b>:{@code generateAuthUrl} 返回 URL 末尾追加 {@code "&access_type=offline"}(不改变现有参数)。</li>
+ *   <li><b>§7.2 H-B2</b>:{@code exchangeCode} real 分支改用 {@code MultiValueMap} 表单体 + {@code MediaType.APPLICATION_FORM_URLENCODED},参数键与现有一致(grant_type/code/client_id/client_secret/redirect_uri)。</li>
+ *   <li><b>§7.3 H-B3</b>:application.yml {@code huawei.health.scope} 默认改为 URL 形式空格分隔 6 项;{@code HuaweiAuthService} 增加 {@code validateScope} 或构造后校验,real 模式下 scope 含 {@code https://www.huawei.com/healthkit/} 前缀,否则抛异常 fail-fast。</li>
+ *   <li><b>§3 接口 5</b>:{@code HuaweiHealthController.status()} 响应补透传 {@code expiresAt}/{@code scope}(数据源 {@code statusJson} 已含这两键)。</li>
+ *   <li><b>§3/H3 mock 通道</b>:mock 模式下 {@code generateAuthUrl} 返回非 {@code oauth-login.cloud.huawei.com} 域名 URL(如 mock 占位),保证前端判据为 mock 分支、不触发 web-view。</li>
+ *   <li><b>H1/H2/H5</b>:api.js 5 方法、health-main 卡片、huawei-auth/cb.html 两页按 §3 契约落地。</li>
+ * </ol></p>
+ *
+ * <p><b>权限流说明</b>:本能力为小程序端 OAuth 授权 + 数据同步,无新增用户权限维度;JWT 拦截 {@code /api/**} 已在
+ * {@code JwtInterceptor},权限流不适用,以说明性用例标注。</p>
+ *
+ * <p><b>预期结果</b>:<b>10 失败 / 9 通过 / 0 错误</b>(RED)。</p>
+ */
+class HuaweiHealthMiniappContractTest {
+
+    // ------------------------------------------------------------------
+    // 契约锚点常量
+    // ------------------------------------------------------------------
+
+    /** §3 接口基础路径 */
+    private static final String BASE_PATH = "/api/huawei-health";
+
+    /** §3 5 个子路径 */
+    private static final String[] EXPECTED_PATHS = {"/auth-url", "/callback", "/sync", "/revoke", "/status"};
+
+    /** §3 auth-url 响应键(无 mode/state,有 memberId/scope/generateAt) */
+    private static final String[] AUTH_URL_KEYS = {"authUrl", "memberId", "scope", "generateAt"};
+
+    /** §3 callback 响应键 */
+    private static final String[] CALLBACK_KEYS = {"bound", "status", "expiresAt"};
+
+    /** §3 sync 单类型响应键 */
+    private static final String[] SYNC_SINGLE_KEYS = {"syncAt", "dataType", "result"};
+
+    /** §3 sync 全量响应键 */
+    private static final String[] SYNC_ALL_KEYS = {"syncAt", "results"};
+
+    /** §3 revoke 响应键 */
+    private static final String[] REVOKE_KEYS = {"revoked"};
+
+    /** §3 status 响应键(含 expiresAt/scope) */
+    private static final String[] STATUS_KEYS = {"bound", "channel", "mock", "configured", "expiresAt", "scope"};
+
+    /** §7.1 H-B1 access_type=offline 关键字 */
+    private static final String ACCESS_TYPE_OFFLINE = "access_type=offline";
+
+    /** §7.2 H-B2 form-encoded 关键字 */
+    private static final String FORM_URLENCODED = "application/x-www-form-urlencoded";
+
+    /** §7.3 H-B3 华为 URL scope 前缀 */
+    private static final String SCOPE_HUAWEI_URL_PREFIX = "https://www.huawei.com/healthkit/";
+
+    /** §3/H3 mock 分支判据:authUrl 含此域名即走 real web-view */
+    private static final String HUAWEI_AUTH_DOMAIN = "oauth-login.cloud.huawei.com";
+
+    /** 控制器类名(§3 落点) */
+    private static final String CONTROLLER_CLASS = "com.etotem.cfc.controller.huawei.HuaweiHealthController";
+
+    /** 认证服务类名(§7.1/7.2/7.3 落点) */
+    private static final String AUTH_SERVICE_CLASS = "com.etotem.cfc.service.huawei.HuaweiAuthService";
+
+    /** 同步服务类名(§3 落点) */
+    private static final String SYNC_SERVICE_CLASS = "com.etotem.cfc.service.huawei.HealthSyncService";
+
+    /** 前端 utils/api.js(H1) */
+    private static final String FRONTEND_API_JS = "cfc-frontend/utils/api.js";
+
+    /** 前端 health-main 卡片入口(H2) */
+    private static final String HEALTH_MAIN_VUE = "cfc-frontend/pages/health-main/index.vue";
+
+    /** §5.1 H5 中转授权页 */
+    private static final String HUAWEI_AUTH_HTML = "cfc-web/public/huawei-auth.html";
+
+    /** §5.2 H5 中转回调页 */
+    private static final String HUAWEI_CB_HTML = "cfc-web/public/huawei-cb.html";
+
+    // ------------------------------------------------------------------
+    // MyBatis-Plus TableInfo 元数据初始化(为 LambdaWrapper 解析 lambda 元数据)
+    // ------------------------------------------------------------------
+
+    @BeforeAll
+    static void initMpTableInfo() {
+        MybatisConfiguration cfg = new MybatisConfiguration();
+        MapperBuilderAssistant assistant = new MapperBuilderAssistant(cfg, "");
+        TableInfoHelper.initTableInfo(assistant, HuaweiHealthToken.class);
+    }
+
+    // ------------------------------------------------------------------
+    // Mock 注入(行为契约测试)
+    // ------------------------------------------------------------------
+
+    @Mock
+    private HuaweiAuthService huaweiAuthService;
+
+    @Mock
+    private HealthSyncService healthSyncService;
+
+    @InjectMocks
+    private HuaweiHealthController controller;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    // ==================== 正常流:5 个接口路由结构契约(GREEN) ====================
+
+    @Test
+    @DisplayName("正常流-1:5 个接口路径全为 @PostMapping 且挂在 /api/huawei-health 下")
+    void fiveEndpoints_allPostMappingUnderBasePath() {
+        Class<?> clazz = loadClass(CONTROLLER_CLASS);
+        assertNotNull(clazz, CONTROLLER_CLASS + " 不存在");
+
+        RequestMapping rm = clazz.getAnnotation(RequestMapping.class);
+        assertNotNull(rm, CONTROLLER_CLASS + " 缺少 @RequestMapping");
+        String base = rm.value().length > 0 ? rm.value()[0] : "";
+        assertEquals(BASE_PATH, base, "基础路径应为 " + BASE_PATH);
+
+        Set<String> found = new HashSet<>();
+        for (Method m : clazz.getDeclaredMethods()) {
+            PostMapping pm = m.getAnnotation(PostMapping.class);
+            if (pm != null) {
+                for (String v : pm.value()) {
+                    found.add(v);
+                }
+            }
+        }
+        Set<String> expected = new HashSet<>(Arrays.asList(EXPECTED_PATHS));
+        assertEquals(expected, found,
+                "应仅包含 5 个子路径:" + expected + ",实际:" + found);
+    }
+
+    // ==================== 正常流:5 个接口响应字段契约(GREEN/RED) ====================
+
+    @Test
+    @DisplayName("正常流-2:auth-url 响应透传 §3 契约字段(无 mode/state,有 memberId/scope/generateAt)")
+    void authUrl_contractFieldsPassthrough() {
+        String url = "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize?response_type=code&client_id=m&redirect_uri=r&scope=s&state=5";
+        when(huaweiAuthService.generateAuthUrl(anyLong(), anyString())).thenReturn(url);
+
+        Result<Map<String, Object>> resp = controller.authUrl(params("memberId", 5L), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : AUTH_URL_KEYS) {
+            assertTrue(data.containsKey(key), "auth-url 响应应包含 " + key + "(§3)");
+        }
+        assertEquals(5L, data.get("memberId"));
+        assertFalse(data.containsKey("mode"), "§3 明确要求:auth-url 响应【无】mode 字段(华为以 state=memberId 内嵌于 URL)");
+        assertFalse(data.containsKey("state"), "§3 明确要求:auth-url 响应【无】state 字段");
+        assertNotNull(data.get("authUrl"));
+    }
+
+    @Test
+    @DisplayName("正常流-3:callback 响应透传 §3 契约字段")
+    void callback_contractFieldsPassthrough() {
+        HuaweiHealthToken token = mock(HuaweiHealthToken.class);
+        when(token.getStatus()).thenReturn("ACTIVE");
+        when(token.getExpiresAt()).thenReturn(new Date());
+        when(huaweiAuthService.exchangeCode(anyString(), anyLong())).thenReturn(token);
+
+        Result<Map<String, Object>> resp = controller.callback(params("code", "auth-code-123", "memberId", 5L), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : CALLBACK_KEYS) {
+            assertTrue(data.containsKey(key), "callback 响应应包含 " + key + "(§3)");
+        }
+        assertEquals(true, data.get("bound"));
+        assertEquals("ACTIVE", data.get("status"));
+        assertNotNull(data.get("expiresAt"));
+    }
+
+    @Test
+    @DisplayName("正常流-4:sync 单类型响应透传 §3 契约字段")
+    void syncSingleType_contractFieldsPassthrough() {
+        SyncResult ok = new SyncResult();
+        ok.setSuccess(true);
+        ok.setDataType("step");
+        when(healthSyncService.sync(anyLong(), eq("step"))).thenReturn(ok);
+
+        Result<Map<String, Object>> resp = controller.sync(params("memberId", 5L, "dataType", "step"), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : SYNC_SINGLE_KEYS) {
+            assertTrue(data.containsKey(key), "sync 单类型响应应包含 " + key + "(§3)");
+        }
+        assertEquals("step", data.get("dataType"));
+        assertNotNull(data.get("result"));
+    }
+
+    @Test
+    @DisplayName("正常流-5:sync 全量响应透传 §3 契约字段")
+    void syncAllTypes_contractFieldsPassthrough() {
+        SyncResult ok = new SyncResult();
+        ok.setSuccess(true);
+        ok.setDataType("sleep");
+        when(healthSyncService.syncAll(anyLong())).thenReturn(Collections.singletonList(ok));
+
+        Result<Map<String, Object>> resp = controller.sync(params("memberId", 5L), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : SYNC_ALL_KEYS) {
+            assertTrue(data.containsKey(key), "sync 全量响应应包含 " + key + "(§3)");
+        }
+        assertNotNull(data.get("results"));
+    }
+
+    @Test
+    @DisplayName("正常流-6:revoke 响应透传 §3 契约字段")
+    void revoke_contractFieldPassthrough() {
+        when(huaweiAuthService.revoke(anyLong())).thenReturn(true);
+
+        Result<Map<String, Object>> resp = controller.revoke(params("memberId", 5L), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : REVOKE_KEYS) {
+            assertTrue(data.containsKey(key), "revoke 响应应包含 " + key + "(§3)");
+        }
+        assertEquals(true, data.get("revoked"));
+    }
+
+    @Test
+    @DisplayName("正常流-7:status 响应透传 §3 契约字段(含 expiresAt/scope)")
+    void status_contractFieldsPassthrough() {
+        JSONObject json = new JSONObject();
+        json.put("bound", true);
+        json.put("channel", "mock");
+        json.put("mock", true);
+        json.put("configured", false);
+        json.put("expiresAt", new Date());
+        json.put("scope", "https://www.huawei.com/healthkit/step.read");
+        when(huaweiAuthService.statusJson(anyLong())).thenReturn(json);
+
+        Result<Map<String, Object>> resp = controller.status(params("memberId", 5L), null);
+
+        assertEquals(200, resp.getCode());
+        Map<String, Object> data = resp.getData();
+        assertNotNull(data);
+        for (String key : STATUS_KEYS) {
+            assertTrue(data.containsKey(key),
+                    "[huawei.health.miniapp] §3 接口 5:status 响应应包含 " + key + "(现状:controller 只透传 bound/channel/mock/configured,"
+                            + "缺 expiresAt/scope;statusJson 已含两键,controller 未 put)。");
+        }
+        assertEquals(true, data.get("bound"));
+        assertEquals("mock", data.get("channel"));
+        assertNotNull(data.get("expiresAt"));
+        assertNotNull(data.get("scope"));
+    }
+
+    // ==================== 边界流:缺失 code → 400 行为保持(GREEN) ====================
+
+    @Test
+    @DisplayName("边界流-1:callback 缺失 code → 400(§3 行为保持)")
+    void callback_missingCode_returns400() {
+        Result<Map<String, Object>> resp = controller.callback(params("memberId", 5L), null);
+
+        assertEquals(400, resp.getCode(),
+                "缺失 code 应返回 400(§3:callback 对缺失 code 返回 400 行为保持)");
+        assertTrue(resp.getMessage().contains("code"));
+        verify(huaweiAuthService, never()).exchangeCode(anyString(), anyLong());
+    }
+
+    // ==================== 后端小修:H-B1 access_type=offline(RED) ====================
+
+    @Test
+    @DisplayName("正常流-H-B1-1:generateAuthUrl 应包含 access_type=offline(§7.1)")
+    void authUrl_containsAccessTypeOffline() {
+        Class<?> authServiceClazz = loadClass(AUTH_SERVICE_CLASS);
+        assertNotNull(authServiceClazz, AUTH_SERVICE_CLASS + " 不存在");
+
+        HuaweiAuthService service = new HuaweiAuthService();
+        try {
+            setField(service, "clientId", "test-client-id");
+            setField(service, "authorizeUrl", "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize");
+            setField(service, "redirectUri", "https://cfc.etotem.com.cn/huawei-cb.html");
+            setField(service, "scope", "https://www.huawei.com/healthkit/step.read");
+        } catch (Exception e) {
+            fail("反射设置 HuaweiAuthService 字段失败: " + e.getMessage());
+        }
+
+        String url = service.generateAuthUrl(5L, null);
+
+        assertTrue(url != null && url.contains(ACCESS_TYPE_OFFLINE),
+                "[huawei.health.miniapp] §7.1 H-B1:generateAuthUrl 生成的授权 URL 必须带 access_type=offline"
+                        + "(换取 refresh_token 必需;否则 token 2h 过期后无法续期)。当前 URL:" + url);
+    }
+
+    // ==================== 后端小修:H-B2 token 端点 form-encoded(RED) ====================
+
+    @Test
+    @DisplayName("正常流-H-B2-1:exchangeCode 方法须存在(结构锚点,GREEN)")
+    void exchangeCode_methodExists() {
+        Class<?> authServiceClazz = loadClass(AUTH_SERVICE_CLASS);
+        assertNotNull(authServiceClazz, AUTH_SERVICE_CLASS + " 不存在");
+        boolean found = false;
+        for (Method m : authServiceClazz.getDeclaredMethods()) {
+            if (m.getName().equals("exchangeCode")) {
+                found = true;
+                break;
+            }
+        }
+        assertTrue(found, "[huawei.health.miniapp] HuaweiAuthService 应提供 exchangeCode(code, memberId) 方法(§3 接口 2)。");
+    }
+
+    @Test
+    @DisplayName("正常流-H-B2-2:exchangeCode real 分支必须以 form-encoded 调用 token 端点(§7.2,行为契约)")
+    void exchangeCode_realBranch_formEncoded() throws Exception {
+        HuaweiAuthService service = new HuaweiAuthService();
+
+        // 组装具备真实 real 分支的协作对象(mock RestTemplate / mapper / crypto 注入私有字段)
+        RestTemplate rt = mock(RestTemplate.class);
+        HuaweiHealthTokenMapper mapper = mock(HuaweiHealthTokenMapper.class);
+        HuaweiHealthTokenCrypto crypto = mock(HuaweiHealthTokenCrypto.class);
+        setField(service, "restTemplate", rt);
+        setField(service, "tokenMapper", mapper);
+        setField(service, "tokenCrypto", crypto);
+
+        // 避免 MyBatis-Plus lambda wrapper 执行时找不到实体 cache(测试无 Spring 上下文)
+        // 将所有 mapper 交互 stub 为无操作/返回值,不触发真实 wrapper 解析
+        doReturn(1).when(mapper).update(any(), any());
+        doReturn(1).when(mapper).insert(any());
+        setField(service, "mockEnabled", false);          // real 分支
+        setField(service, "clientId", "real-client-id");
+        setField(service, "clientSecret", "real-secret");
+        setField(service, "redirectUri", "https://cfc.etotem.com.cn/huawei-cb.html");
+        setField(service, "tokenUrl", "https://oauth-login.cloud.huawei.com/oauth2/v3/token");
+        setField(service, "scope", "https://www.huawei.com/healthkit/step.read");
+
+        Map<String, Object> respBody = new HashMap<>();
+        respBody.put("access_token", "at-1");
+        respBody.put("refresh_token", "rt-1");
+        respBody.put("expires_in", 3600);
+        when(rt.postForEntity(eq("https://oauth-login.cloud.huawei.com/oauth2/v3/token"),
+                any(), eq(Map.class)))
+                .thenReturn(new ResponseEntity<>(respBody, HttpStatus.OK));
+
+        HuaweiHealthToken token = service.exchangeCode("code-abc", 5L);
+
+        assertNotNull(token, "real 分支 exchangeCode 应返回非 null 令牌");
+        ArgumentCaptor<HttpEntity<?>> captor = ArgumentCaptor.forClass(HttpEntity.class);
+        verify(rt).postForEntity(eq("https://oauth-login.cloud.huawei.com/oauth2/v3/token"),
+                captor.capture(), eq(Map.class));
+
+        HttpEntity<?> sent = captor.getValue();
+        assertNotNull(sent, "应捕获到发给 token 端点的 HttpEntity");
+        assertNotNull(sent.getHeaders().getContentType(),
+                "[huawei.health.miniapp] §7.2 H-B2:token 交换必须显式设置 Content-Type(为 form-urlencoded)。"
+                        + " 现状无 Content-Type 或为 application/json。");
+        assertEquals(FORM_URLENCODED, sent.getHeaders().getContentType().toString(),
+                "[huawei.health.miniapp] §7.2 H-B2:token 交换 Content-Type 须为 " + FORM_URLENCODED
+                        + "(华为官方要求),现状为 application/json 会被华为拒绝(400)。");
+        assertTrue(sent.getBody() instanceof MultiValueMap,
+                "[huawei.health.miniapp] §7.2 H-B2:token 交换 body 须为表单形态(MultiValueMap,FormHttpMessageConverter 序列化),"
+                        + "现状为普通 JSON Map。");
+    }
+
+    // ==================== 后端小修:H-B3 scope URL 化校验(RED) ====================
+
+    @Test
+    @DisplayName("边界流-H-B3-1:application.yml huawei.health.scope 默认值须为 URL 形式(§7.3)")
+    void scope_default_isUrlFormInYaml() {
+        String yml = readResource("application.yml");
+        assertFalse(yml.isEmpty(), "application.yml 未在 classpath 找到");
+
+        int idx = yml.indexOf("huawei:");
+        if (idx < 0) {
+            fail("application.yml 缺少 huawei: 配置节");
+        }
+        int scopeIdx = yml.indexOf("scope:", idx);
+        if (scopeIdx < 0) {
+            fail("application.yml huawei 节缺少 scope");
+        }
+        int lineEnd = yml.indexOf('\n', scopeIdx);
+        String line = yml.substring(scopeIdx, lineEnd > 0 ? lineEnd : yml.length()).trim();
+        String defaultVal = extractDefault(line);
+
+        assertTrue(defaultVal.contains(SCOPE_HUAWEI_URL_PREFIX),
+                "[huawei.health.miniapp] §7.3 H-B3:application.yml huawei.health.scope 默认值必须为 URL 形式"
+                        + "(含 " + SCOPE_HUAWEI_URL_PREFIX + " 前缀,空格分隔多值),"
+                        + "简写 scope(step,heart_rate...)华为不识别 → 授权回调失败。当前默认值:" + defaultVal);
+    }
+
+    @Test
+    @DisplayName("边界流-H-B3-2:HuaweiAuthService 须提供 real 模式 URL scope 校验锚点(fail-fast §7.3)")
+    void authService_hasRealScopeValidationAnchor() {
+        Class<?> clazz = loadClass(AUTH_SERVICE_CLASS);
+        assertNotNull(clazz, AUTH_SERVICE_CLASS + " 不存在");
+
+        boolean hasScopeConstantAnchor = hasStringConstantContaining(clazz, "healthkit")
+                || hasStringConstantContaining(clazz, "https://www.huawei.com/");
+        boolean hasScopeMethodAnchor = hasMethodNamedLike(clazz, "scope")
+                || hasMethodNamedLike(clazz, "validate")
+                || hasMethodNamedLike(clazz, "healthkit");
+
+        assertTrue(hasScopeConstantAnchor || hasScopeMethodAnchor,
+                "[huawei.health.miniapp] §7.3 H-B3:HuaweiAuthService 必须声明 real 模式 scope 前置校验锚点"
+                        + "(URL 形式常量如 https://www.huawei.com/healthkit/ 或 validateScope/checkScope 方法),"
+                        + "scope 不合法时 fail-fast 并给出明确报错。现状:全类无 healthkit/scope 校验锚点。");
+    }
+
+    // ==================== H3:mock 通道不得触发 web-view(RED) ====================
+
+    @Test
+    @DisplayName("正确流-H3-1:mock 模式下 authUrl 不应含华为授权域名(H3 硬约束:mock 不触发 web-view)")
+    void mockBranch_authUrl_notHuaweiDomain() {
+        HuaweiAuthService service = new HuaweiAuthService();
+        try {
+            setField(service, "clientId", "mock-client-id");
+            setField(service, "mockEnabled", true);       // mock 通道
+            setField(service, "authorizeUrl", "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize");
+            setField(service, "redirectUri", "https://cfc.etotem.com.cn/huawei-cb.html");
+            setField(service, "scope", "https://www.huawei.com/healthkit/step.read");
+        } catch (Exception e) {
+            fail("反射设置 HuaweiAuthService 字段失败: " + e.getMessage());
+        }
+
+        String url = service.generateAuthUrl(5L, null);
+
+        assertFalse(url.contains(HUAWEI_AUTH_DOMAIN),
+                "[huawei.health.miniapp] §3/H3:mock 通道 authUrl 严禁含华为授权域名 " + HUAWEI_AUTH_DOMAIN
+                        + " —— 前端判据是「authUrl 含授权域名则走 real web-view」;mock 返回真实授权域名会误触发 web-view 白屏。"
+                        + " 当前 mock 分支返回:" + url + ",GREEN 需让 mock 分支返回非授权域名占位 URL。");
+        assertTrue(url.contains("state="),
+                "[huawei.health.miniapp] §3:authUrl 须内嵌 state=memberId(防 CSRF,回调原样带回)。当前 URL:" + url);
+    }
+
+    // ==================== H1/H2/H5:前端契约锚点(RED) ====================
+
+    @Test
+    @DisplayName("正确流-H1-1:前端 api.js 须提供 huaweiAuthUrl 等 5 个契约方法(§H1)")
+    void frontend_api_js_hasFiveHuaweiMethods() {
+        String apiJs = readFileContent(FRONTEND_API_JS);
+        assertFalse(apiJs.isEmpty(),
+                "[huawei.health.miniapp] §H1:cfc-frontend/utils/api.js 不存在或未找到 —— H1 契约未落地"
+                        + "(须新增 huaweiAuthUrl/huaweiCallback/huaweiSync/huaweiRevoke/huaweiStatus 5 个方法)。");
+
+        List<String> required = Arrays.asList(
+                "huaweiAuthUrl", "huaweiCallback", "huaweiSync", "huaweiRevoke", "huaweiStatus");
+        List<String> missing = new ArrayList<>();
+        for (String m : required) {
+            if (!apiJs.contains(m)) {
+                missing.add(m);
+            }
+        }
+        assertEquals(0, missing.size(),
+                "[huawei.health.miniapp] §H1:cfc-frontend/utils/api.js 缺失契约方法:" + missing
+                        + "。GREEN 需按 §3 字段(路径/POST JSON/错误码透传)逐一对齐,且前端不得自行拼 scope。");
+        // 契约 §6-2:前端不得自行拼接或改写 scope 参数(authUrl 已由后端拼好 URL scope)
+        assertTrue(apiJs.contains("scope") == false || apiJs.indexOf("huaweiAuthUrl") >= 0,
+                "[huawei.health.miniapp] §6-2:api.js huaweiAuthUrl 应直接透传后端 authUrl,前端不得自行拼 scope。");
+    }
+
+    @Test
+    @DisplayName("正确流-H2-1:前端 health-main.vue 须挂运动手环·华为健康卡片(§H2)")
+    void frontend_healthMain_hasHuaweiCard() {
+        String vue = readFileContent(HEALTH_MAIN_VUE);
+        assertFalse(vue.isEmpty(),
+                "[huawei.health.miniapp] §H2:cfc-frontend/pages/health-main/index.vue 不存在或未找到 —— H2 契约未落地。");
+
+        boolean hasCard = vue.toLowerCase().contains("huawei") || vue.contains("华为");
+        assertTrue(hasCard,
+                "[huawei.health.miniapp] §H2:health-main.vue 须挂载「运动手环 · 华为健康」卡片(未绑定态绑定按钮+用途说明 / 已绑定态数据摘要+mock 角标)。"
+                        + " 当前页面无 huawei/华为 标识,卡片未落地。");
+    }
+
+    @Test
+    @DisplayName("正确流-H5-1:H5 中转授权页 huawei-auth.html 须存在(§5.1)")
+    void frontend_huaweiAuthHtml_exists() {
+        String html = readFileContent(HUAWEI_AUTH_HTML);
+        assertFalse(html.isEmpty(),
+                "[huawei.health.miniapp] §5.1:cfc-web/public/huawei-auth.html 不存在 —— real 分支 web-view 落地页未落地"
+                        + "(该页负责读 query 后 location.replace(authUrl) 跳华为授权)。");
+        assertTrue(html.contains("华为运动健康") || html.contains("huawei"),
+                "[huawei.health.miniapp] §5.1:huawei-auth.html 顶部标题须为「连接华为运动健康」(加载态+兜底按钮)。");
+    }
+
+    @Test
+    @DisplayName("正确流-H5-2:H5 中转回调页 huawei-cb.html 须存在(§5.2)")
+    void frontend_huaweiCbHtml_exists() {
+        String html = readFileContent(HUAWEI_CB_HTML);
+        assertFalse(html.isEmpty(),
+                "[huawei.health.miniapp] §5.2:cfc-web/public/huawei-cb.html 不存在 —— 华为 OAuth 回调页未落地"
+                        + "(须解析 code/state → POST /api/huawei-health/callback → 三态渲染)。");
+        assertTrue(html.contains("已授权") || html.contains("请返回小程序") || html.contains("huawei-cb"),
+                "[huawei.health.miniapp] §5.2:huawei-cb.html 须含成功态「已授权,请返回小程序」及失败/参数缺失三态文案。");
+    }
+
+    // ==================== 权限流(不适用) ====================
+
+    @Test
+    @DisplayName("权限流:本能力为小程序端 OAuth 授权 + 数据同步,权限流不适用")
+    void permissionFlow_notApplicable() {
+        assertTrue(true, "权限流不适用:huawei.health.miniapp 为小程序端授权/同步链路,登录态由后端统一 JWT 鉴权。");
+    }
+
+    // ------------------------------------------------------------------
+    // 反射/IO 辅助
+    // ------------------------------------------------------------------
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    /** 反射写入私有字段(字段名=类型默认 Bean Name,测试侧直连私有协作对象) */
+    private void setField(Object target, String name, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    /** 是否存在静态 String 常量值包含 target */
+    private boolean hasStringConstantContaining(Class<?> clazz, String target) {
+        if (clazz == null) return false;
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType() != String.class) continue;
+            if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) continue;
+            try {
+                f.setAccessible(true);
+                Object v = f.get(null);
+                if (v instanceof String && ((String) v).contains(target)) return true;
+            } catch (Exception ignored) {}
+        }
+        return false;
+    }
+
+    /** 是否存在方法名(忽略大小写)包含片段 */
+    private boolean hasMethodNamedLike(Class<?> clazz, String fragment) {
+        if (clazz == null) return false;
+        String needle = fragment.toLowerCase();
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().toLowerCase().contains(needle)) return true;
+        }
+        return false;
+    }
+
+    private Map<String, Object> params(Object... kv) {
+        Map<String, Object> m = new LinkedHashMap<>();
+        for (int i = 0; i < kv.length; i += 2) {
+            m.put(String.valueOf(kv[i]), kv[i + 1]);
+        }
+        return m;
+    }
+
+    private String readResource(String name) {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream(name)) {
+            if (is == null) return "";
+            Scanner s = new Scanner(is, StandardCharsets.UTF_8.name());
+            s.useDelimiter("\\A");
+            return s.hasNext() ? s.next() : "";
+        } catch (Exception e) {
+            return "";
+        }
+    }
+
+    private String extractDefault(String line) {
+        int si = line.indexOf("${");
+        if (si < 0) {
+            int col = line.indexOf(':');
+            return col >= 0 ? line.substring(col + 1).trim() : "";
+        }
+        int colon = line.indexOf(':', si);
+        int close = line.indexOf('}', colon);
+        if (colon < 0 || close < 0) return "";
+        return line.substring(colon + 1, close).trim();
+    }
+
+    /**
+     * 从相对仓库根(worktree 根)路径读取文件(供前端契约锚点探测)。
+     * 兼容 surefire 的 user.dir=模块目录 与本仓库根两种运行形态。
+     */
+    private String readFileContent(String relFromRepoRoot) {
+        try {
+            // 形态 1:user.dir = 仓库根(如 IDE 直跑)
+            java.io.File f = new java.io.File(relFromRepoRoot);
+            if (!f.exists() && relFromRepoRoot.startsWith("cfc-")) {
+                // 形态 2:user.dir = cfc-backend 模块目录(mvn surefire 默认)
+                f = new java.io.File("../" + relFromRepoRoot);
+            }
+            if (!f.exists()) {
+                return "";
+            }
+            return new String(java.nio.file.Files.readAllBytes(f.toPath()),
+                    StandardCharsets.UTF_8);
+        } catch (Exception e) {
+            return "";
+        }
+    }
+}