Эх сурвалжийг харах

test(S-cfc-266): energy.dimension.view 补充边界/权限/异常 RED 契约单测(4 例预期红)

E2E Test Bot 1 цаг өмнө
parent
commit
82d8770b93

+ 481 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/EnergyDimensionViewEdgeContractTest.java

@@ -0,0 +1,481 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.controller.EnergyController;
+import com.etotem.cfc.entity.EnergyDimensionConfig;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockingDetails;
+
+/**
+ * TDD-RED 契约单测补充:能量维度配置查看(能力键 {@code energy.dimension.view},任务 S-cfc-266 / SC-P-19)。
+ *
+ * <p>本类与已合入的 {@code EnergyDimensionViewContractTest}(4 例)及
+ * {@code EnergyDimensionViewScP19ContractTest}(2 例)互补,不重复其断言,
+ * 只补四条尚未覆盖的 AC 条款:</p>
+ * <ul>
+ *   <li><b>SC-P-19 边界(部分同步)</b>:配置仅同步部分维度时,仍须返回身/心/智/行/富五维完整兜底,
+ *       缺失维度补默认值,权重合计 100%,非 500;</li>
+ *   <li><b>TC-P-19-P 权限(只读行为)</b>:家长端只读查看不得触发任何 Mapper 写操作;</li>
+ *   <li><b>TC-P-19-P 权限(越权实际拦截)</b>:body 指定非本家庭成员 memberId 时须 403/401,
+ *       不得泄露他人维度配置;</li>
+ *   <li><b>TC-P-19-E 异常(权重合计非法)</b>:权重合计 ≠100% 须 400 并提示「权重合计需为 100%」,
+ *       不得静默展示非法权重。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(RED 基线,已核实 origin/cfclub)</b>:{@code EnergyController} 仅有 /sandbox、/overview、
+ * /logs、/grant、/deduct-for-wish、/configure(写)、/score-history、/family-score-history、/wealth-detail,
+ * 无 {@code /config} / {@code /dimension} 只读端点。故 4 例均在定位端点时立即失败(红),失败信息清晰可贴。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:补齐只读端点并按上述条款实现后,反射调用分支才会被执行,测试自动转绿。
+ * 纯反射 + Mockito,无 Spring 上下文 / 无 DB / 无外部服务依赖。</p>
+ */
+class EnergyDimensionViewEdgeContractTest {
+
+    private static final String KEY = "energy.dimension.view";
+
+    private static final String[] CODES = {"body", "mind", "wisdom", "action", "wealth"};
+    private static final String[] NAMES = {"身", "心", "智", "行", "富"};
+
+    /** TC-P-19-E 非法合计锚点:body 60 + mind 60 = 120%。 */
+    private static final int[] ILLEGAL_WEIGHTS = {60, 60};
+
+    // ------------------------------------------------------------------
+    // 边界流:部分配置同步 → 五维完整兜底
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界补充:仅部分维度配置同步时仍返回五维完整兜底(缺失补默认、合计100%、非500)")
+    void partialConfig_stillReturnsFullFiveDimensions() throws Exception {
+        Method endpoint = requireEndpoint("部分配置兜底");
+
+        Fixture fixture = newFixture(partialConfigAnswer());
+        Object response = invoke(endpoint, fixture, body("body", 60, "mind", 40));
+
+        assertEquals(200, codeOf(response),
+                "[RED/" + KEY + "] 部分配置同步(非全量)不应 500,应返回 200 + 兜底(SC-P-19 边界 / TC-P-19-E)。");
+        Object data = dataOf(response);
+        assertNotNull(data, "[RED/" + KEY + "] 部分配置同步时 Result.data 不应为空。");
+
+        Map<String, Map<String, Object>> dims = extractDimensionMap(data);
+        assertEquals(5, dims.size(),
+                "[RED/" + KEY + "] 配置仅同步部分维度时仍须覆盖身/心/智/行/富五维,实际维度数=" + dims.size() + "。");
+
+        double sum = 0.0;
+        for (int i = 0; i < CODES.length; i++) {
+            Map<String, Object> dim = dims.get(CODES[i]);
+            assertNotNull(dim,
+                    "[RED/" + KEY + "] 部分同步时缺失维度 " + CODES[i] + "(" + NAMES[i] + ") 未兜底(SC-P-19)。");
+            Object weight = first(dim, "weight", "ratio", "defaultWeight", "weightPercent", "percent");
+            assertNotNull(weight,
+                    "[RED/" + KEY + "] 维度 " + CODES[i] + " 兜底须带权重(默认值未实现)。");
+            assertTrue(weight instanceof Number,
+                    "[RED/" + KEY + "] 维度 " + CODES[i] + " 权重应为数值,实际=" + weight);
+            Object definition = first(dim, "definition", "description", "remark", "intro", "explanation", "口径");
+            assertNotNull(definition,
+                    "[RED/" + KEY + "] 维度 " + CODES[i] + " 兜底须带定义/口径说明(SC-P-19)。");
+            sum += toPercent((Number) weight);
+        }
+        assertEquals(100.0, sum, 1e-6,
+                "[RED/" + KEY + "] 部分同步兜底后五维权重合计须为 100%,实际=" + sum + "%。");
+        assertTrue(fallbackNotice(response, data),
+                "[RED/" + KEY + "] 部分配置未同步时须给出兜底说明(SC-P-19 边界),不得静默返回。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流:只读行为,不得写库
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限补充:家长端只读配置查看不得触发任何 Mapper 写操作(写配置走 admin.dimension.config)")
+    void readOnlyView_noWriteOperations() throws Exception {
+        Method endpoint = requireEndpoint("只读校验");
+
+        Fixture fixture = newFixture(partialConfigAnswer());
+        invoke(endpoint, fixture, body("body", 60, "mind", 40));
+
+        List<String> writes = new ArrayList<>();
+        for (Object mock : fixture.mocks) {
+            for (org.mockito.invocation.InvocationOnMock inv : mockingDetails(mock).getInvocations()) {
+                String name = inv.getMethod().getName().toLowerCase(Locale.ROOT);
+                if (name.startsWith("insert") || name.startsWith("update") || name.startsWith("delete")
+                        || name.startsWith("save") || name.startsWith("remove")) {
+                    writes.add(name);
+                }
+            }
+        }
+        assertTrue(writes.isEmpty(),
+                "[RED/" + KEY + "] 家长端配置查看为只读操作,不得触发 Mapper 写入 " + writes
+                        + "(写配置走 admin.dimension.config / S-cfc-199)。实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流:横向越权实际拦截(非仅注解声明)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限补充:指定非本家庭成员 memberId 须403/401,不得泄露他人维度配置")
+    void crossFamilyMemberId_forbidden() throws Exception {
+        Method endpoint = requireEndpoint("横向越权校验");
+
+        Fixture fixture = newFixture(foreignMemberAnswer());
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("memberId", 999L); // familyId=2,当前请求家庭 familyId=1
+        Object response = invoke(endpoint, fixture, params);
+
+        int code = codeOf(response);
+        assertTrue(code == 403 || code == 401,
+                "[RED/" + KEY + "] 查看非本家庭成员(memberId=999, familyId=2)的配置须 403/401,实际 code="
+                        + code + "(TC-P-19-P / SC-X-19:非归属数据访问统一 403/401)。");
+        Object data = dataOf(response);
+        assertTrue(data == null || !extractDimensionMap(data).containsKey("body"),
+                "[RED/" + KEY + "] 越权时不得返回他人维度配置数据(TC-P-19-P 不泄露)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 异常流:权重合计非法 → 400 提示
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("异常补充:权重合计≠100%(60+60=120)须400并提示『权重合计需为100%』")
+    void illegalWeightSum_returns400WithPrompt() throws Exception {
+        Method endpoint = requireEndpoint("权重合计校验");
+
+        Fixture fixture = newFixture(illegalConfigAnswer());
+        Object response = invoke(endpoint, fixture, new HashMap<String, Object>());
+
+        int code = codeOf(response);
+        assertEquals(400, code,
+                "[RED/" + KEY + "] 配置权重合计=120%(≠100%)须 400 拒绝,不得静默返回非法权重(TC-P-19-E)。");
+        String message = messageOf(response);
+        assertTrue(message.contains("权重合计需为 100%") || message.contains("权重合计需为100%"),
+                "[RED/" + KEY + "] 非法合计的提示须含『权重合计需为 100%』,实际 message=" + message
+                        + "(TC-P-19-E)。");
+    }
+
+    // ==================================================================
+    // 公共辅助:端点定位 / 反射调用 / 响应解析
+    // ==================================================================
+
+    /** 定位家长只读配置查看端点;缺失即 fail(RED 信号),GREEN 阶段才会继续执行。 */
+    private static Method requireEndpoint(String clause) {
+        for (Method m : EnergyController.class.getDeclaredMethods()) {
+            PostMapping mapping = m.getAnnotation(PostMapping.class);
+            if (mapping == null) {
+                continue;
+            }
+            for (String path : mapping.value()) {
+                if (path != null && (path.trim().equals("/config") || path.trim().equals("/dimension")
+                        || path.trim().startsWith("/config/") || path.trim().startsWith("/dimension/"))) {
+                    return m;
+                }
+            }
+        }
+        return fail("[RED/" + KEY + "] EnergyController 缺少 POST /api/energy/config(或 /dimension)只读端点,"
+                + "无法验证契约条款「" + clause + "」:SC-P-19 / API_REFERENCE §4.5 要求家长端只读查看"
+                + "身/心/智/行/富定义与权重。当前仅有 /configure(写),实现未落地。");
+    }
+
+    private static Map<String, Object> body(String code1, int w1, String code2, int w2) {
+        Map<String, Object> body = new HashMap<String, Object>();
+        body.put("dimensions", Arrays.asList(dimConfig(code1, w1), dimConfig(code2, w2)));
+        return body;
+    }
+
+    private static EnergyDimensionConfig dimConfig(String dim, int weight) {
+        EnergyDimensionConfig c = new EnergyDimensionConfig();
+        c.setDimension(dim);
+        c.setWeight(weight);
+        c.setIsActive(1);
+        return c;
+    }
+
+    /** 仅两维已同步(body/mind),其余须走兜底。 */
+    private static org.mockito.stubbing.Answer<Object> partialConfigAnswer() {
+        return invocation -> {
+            Class<?> rt = invocation.getMethod().getReturnType();
+            if (List.class.isAssignableFrom(rt)) {
+                return Arrays.asList(dimConfig("body", 60), dimConfig("mind", 40));
+            }
+            if (EnergyDimensionConfig.class == rt) {
+                return dimConfig("body", 60);
+            }
+            return org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation);
+        };
+    }
+
+    /** 权重合计 120% 的非法配置。 */
+    private static org.mockito.stubbing.Answer<Object> illegalConfigAnswer() {
+        return invocation -> {
+            Class<?> rt = invocation.getMethod().getReturnType();
+            if (List.class.isAssignableFrom(rt)) {
+                return Arrays.asList(dimConfig("body", 60), dimConfig("mind", 60));
+            }
+            if (EnergyDimensionConfig.class == rt) {
+                return dimConfig("body", 60);
+            }
+            return org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation);
+        };
+    }
+
+    /** familyId=2 的他人成员 + 非归属判定 false。 */
+    private static org.mockito.stubbing.Answer<Object> foreignMemberAnswer() {
+        return invocation -> {
+            Class<?> rt = invocation.getMethod().getReturnType();
+            if (boolean.class == rt || Boolean.class == rt) {
+                return Boolean.FALSE;
+            }
+            if (List.class.isAssignableFrom(rt)) {
+                return Arrays.asList(dimConfig("body", 60), dimConfig("mind", 40));
+            }
+            String name = invocation.getMethod().getName();
+            if ("selectById".equals(name) && rt.getName().contains("FamilyMember")) {
+                try {
+                    Object member = rt.getDeclaredConstructor().newInstance();
+                    setProp(member, "id", 999L);
+                    setProp(member, "familyId", 2L);
+                    return member;
+                } catch (Exception ignored) {
+                    return null;
+                }
+            }
+            return org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation);
+        };
+    }
+
+    private static void setProp(Object target, String name, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    /** 反射构造控制器并给所有非静态字段注入 mock,返回调用句柄以便后续验写。 */
+    private static Fixture newFixture(org.mockito.stubbing.Answer<Object> answer) throws Exception {
+        Object controller = EnergyController.class.getDeclaredConstructor().newInstance();
+        Fixture fixture = new Fixture(answer);
+        for (Field f : EnergyController.class.getDeclaredFields()) {
+            if (Modifier.isStatic(f.getModifiers()) || f.getType().isPrimitive()
+                    || f.getType() == String.class) {
+                continue;
+            }
+            Object mocked = mock(f.getType(), answer);
+            f.setAccessible(true);
+            f.set(controller, mocked);
+            fixture.mocks.add(mocked);
+        }
+        return fixture;
+    }
+
+    private static Object invoke(Method endpoint, Fixture fixture, Map<String, Object> params) {
+        try {
+            Object controller = fixture.controller;
+            Object[] args = new Object[endpoint.getParameterCount()];
+            Class<?>[] types = endpoint.getParameterTypes();
+            for (int i = 0; i < types.length; i++) {
+                Class<?> t = types[i];
+                if (Map.class.isAssignableFrom(t)) {
+                    args[i] = params;
+                } else if (t == String.class) {
+                    args[i] = "parent";
+                } else if (t == Long.class || t == long.class) {
+                    args[i] = 1L;
+                } else if (t == Integer.class || t == int.class) {
+                    args[i] = 1;
+                } else {
+                    args[i] = null;
+                }
+            }
+            endpoint.setAccessible(true);
+            return endpoint.invoke(controller, args);
+        } catch (InvocationTargetException e) {
+            return fail("[RED/" + KEY + "] 反射调用配置查看端点抛异常:" + e.getCause());
+        } catch (Exception e) {
+            return fail("[RED/" + KEY + "] 反射调用配置查看端点失败:" + e);
+        }
+    }
+
+    private static int codeOf(Object response) {
+        Object v = prop(response, "code", "getCode");
+        return v instanceof Number ? ((Number) v).intValue() : -1;
+    }
+
+    private static String messageOf(Object response) {
+        Object v = prop(response, "message", "getMessage");
+        return v == null ? "" : String.valueOf(v);
+    }
+
+    private static Object dataOf(Object response) {
+        return prop(response, "data", "getData");
+    }
+
+    private static Object first(Map<String, Object> map, String... keys) {
+        for (String key : keys) {
+            Object v = map.get(key);
+            if (v != null) {
+                return v;
+            }
+        }
+        return null;
+    }
+
+    private static Object prop(Object target, String... names) {
+        if (target == null) {
+            return null;
+        }
+        if (target instanceof Map) {
+            Map<?, ?> map = (Map<?, ?>) target;
+            for (String name : names) {
+                if (map.containsKey(name)) {
+                    return map.get(name);
+                }
+            }
+            return null;
+        }
+        for (String name : names) {
+            if (name.startsWith("get")) {
+                try {
+                    Method m = target.getClass().getMethod(name);
+                    m.setAccessible(true);
+                    return m.invoke(target);
+                } catch (Exception ignored) {
+                    continue;
+                }
+            }
+            try {
+                Field f = target.getClass().getDeclaredField(name);
+                f.setAccessible(true);
+                return f.get(target);
+            } catch (Exception ignored) {
+                // 继续下一个候选名
+            }
+        }
+        return null;
+    }
+
+    private static double toPercent(Number n) {
+        double v = n.doubleValue();
+        return v > 0.0 && v <= 1.0 ? v * 100.0 : v;
+    }
+
+    /** 兼容 Result.data 的 Map / List / DTO 形态,提取「维度码 → 属性」。 */
+    @SuppressWarnings("unchecked")
+    private static Map<String, Map<String, Object>> extractDimensionMap(Object data) {
+        Map<String, Map<String, Object>> out = new LinkedHashMap<String, Map<String, Object>>();
+        Set<String> known = new HashSet<String>(Arrays.asList(CODES));
+
+        if (data instanceof Map) {
+            Map<String, Object> map = (Map<String, Object>) data;
+            if (map.containsKey("body") && map.containsKey("wealth")) {
+                for (Map.Entry<String, Object> e : map.entrySet()) {
+                    if (e.getValue() instanceof Map && known.contains(e.getKey())) {
+                        out.put(e.getKey(), (Map<String, Object>) e.getValue());
+                    }
+                }
+                if (!out.isEmpty()) {
+                    return out;
+                }
+            }
+        }
+
+        List<Object> items = new ArrayList<Object>();
+        if (data instanceof List) {
+            items.addAll((List<Object>) data);
+        } else if (data instanceof Map) {
+            Map<String, Object> map = (Map<String, Object>) data;
+            for (String key : new String[]{"dimensions", "configs", "list", "data", "items"}) {
+                Object v = map.get(key);
+                if (v instanceof List) {
+                    items.addAll((List<Object>) v);
+                    break;
+                }
+            }
+            if (items.isEmpty()) {
+                for (Object v : map.values()) {
+                    if (v instanceof List) {
+                        items.addAll((List<Object>) v);
+                        break;
+                    }
+                }
+            }
+        }
+        for (Object item : items) {
+            Object codeObj = prop(item, "code", "dimension", "dimensionCode");
+            if (codeObj == null || !known.contains(codeObj.toString().toLowerCase(Locale.ROOT))) {
+                continue;
+            }
+            Map<String, Object> props = new LinkedHashMap<String, Object>();
+            if (item instanceof Map) {
+                props.putAll((Map<String, Object>) item);
+            } else {
+                for (String key : new String[]{"code", "name", "weight", "ratio", "defaultWeight",
+                        "weightPercent", "percent", "definition", "description", "remark", "intro", "explanation", "口径"}) {
+                    Object v = prop(item, key);
+                    if (v != null) {
+                        props.put(key, v);
+                    }
+                }
+            }
+            out.put(codeObj.toString().toLowerCase(Locale.ROOT), props);
+        }
+        return out;
+    }
+
+    private static boolean fallbackNotice(Object response, Object data) {
+        String message = messageOf(response);
+        if (message.contains("兜底") || message.contains("默认")) {
+            return true;
+        }
+        if (data instanceof Map) {
+            Map<?, ?> map = (Map<?, ?>) data;
+            for (String key : new String[]{"fallback", "isFallback", "fallbackNotice", "notice", "tip", "message"}) {
+                Object v = map.get(key);
+                if (v instanceof Boolean && (Boolean) v) {
+                    return true;
+                }
+                if (v instanceof String && !((String) v).trim().isEmpty()) {
+                    return true;
+                }
+            }
+            Object synced = map.get("synced");
+            if (synced instanceof Boolean && !((Boolean) synced)) {
+                return true;
+            }
+            Object configSynced = map.get("configSynced");
+            if (configSynced instanceof Boolean && !((Boolean) configSynced)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static final class Fixture {
+        final org.mockito.stubbing.Answer<Object> answer;
+        final List<Object> mocks = new ArrayList<Object>();
+        Object controller;
+
+        Fixture(org.mockito.stubbing.Answer<Object> answer) {
+            this.answer = answer;
+        }
+    }
+}