Browse Source

test(S-cfc-266): 新增 energy.dimension.view 契约RED单测(4例预期红)

Agnes Agent 1 day ago
parent
commit
9d8940e5df

+ 421 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/EnergyDimensionViewContractTest.java

@@ -0,0 +1,421 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.EnergyController;
+import com.etotem.cfc.entity.EnergyDimension;
+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.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;
+
+/**
+ * 契约级单测:能量维度配置查看(能力键 {@code energy.dimension.view},任务 S-cfc-266 / 场景 SC-P-19)。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-19「能量维度配置查看」——
+ *       目标:理解维度口径;流程:查看身/心/智/行/富定义与权重;边界:配置未同步时展示兜底。</li>
+ *   <li>用例:{@code tests/test-cases/parent.md} TC-P-19「显示身/心/智/行/富口径与权重;
+ *       配置未同步展示兜底说明」;TC-P-19-E「配置缺失展示兜底说明非 500;
+ *       权重和非法提示『权重合计需为 100%』」。</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.5 ——
+ *       {@code POST /api/energy/config}(能量配置)、{@code POST /api/energy/dimension}(五维详情);
+ *       模块 EnergyController / 维度配置(Web 管理端)。家长端<b>只读</b>查看定义与权重,
+ *       写配置走 {@code admin.dimension.config}(S-cfc-199)。</li>
+ *   <li>设计基线:{@code docs/superpowers/specs/2026-06-05-five-dimension-energy-design.md}
+ *       §1.1(energy_dimension 维度定义表:body/mind/wisdom/action/wealth = 身/心/智/行/富)、
+ *       §1.2(配置比例之和 = 1.0 / 100%)、§2.1(EnergyController 概览/流水/配置)。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(TDD-RED 阶段核实)</b>:{@code EnergyController} 仅有 /sandbox、/overview、/logs、
+ * /grant、/deduct-for-wish、/configure(写)、/score-history、/family-score-history、/wealth-detail,
+ * <b>无 /config、/dimension 只读端点</b>;{@code EnergyDimension} 仅有 code/name/icon/element/sortOrder/status,
+ * {@code EnergyDimensionConfig} 仅有 dimension/dataSource/category/weight/isActive —— 两者均
+ * <b>无「定义/口径」字段</b>;配置未同步时无兜底定义与权重的返回来源。故本测试以反射 + Mockito
+ * 探测契约(能编译、能运行、断言失败),失败信息可直接作为 GREEN 阶段实现清单。</p>
+ *
+ * <p><b>RED 预期(4 例全红)</b>:只读配置端点缺失、五维定义载体缺失、兜底行为缺失、只读权限流无载体。
+ * GREEN 阶段补齐端点 + 定义载体 + 兜底默认值(权重合计 100%)后,本测试自动转绿。</p>
+ *
+ * <p>纯反射 + Mockito,无 Spring 上下文 / 无 DB / 无外部服务依赖。</p>
+ */
+class EnergyDimensionViewContractTest {
+
+    private static final String KEY = "energy.dimension.view";
+
+    /** 五维码与中文口径(设计 §1.1 种子:身/心/智/行/富)。 */
+    private static final String[] CODES = {"body", "mind", "wisdom", "action", "wealth"};
+    private static final String[] NAMES = {"身", "心", "智", "行", "富"};
+
+    /** 比例口径:ratio(0~1) 或百分比(0~100) 均折算为百分比;合计应为 100%(TC-P-19-E)。 */
+    private static final double EXPECTED_WEIGHT_SUM_PERCENT = 100.0;
+
+    /** 定义/口径字段候选名(GREEN 实现可在任一维度载体上提供)。 */
+    private static final String[] DEFINITION_FIELDS = {
+            "definition", "description", "remark", "intro", "explanation", "口径", "definitionText"
+    };
+
+    // ------------------------------------------------------------------
+    // 正常流:家长只读配置查看端点应存在
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:EnergyController 应提供家长只读的维度配置查看端点(POST /api/energy/config 或 /dimension)")
+    void energyConfig_readOnlyEndpointExists() {
+        Method m = findConfigReadMethod();
+        assertNotNull(m,
+                "[RED/" + KEY + "] EnergyController 缺少家长只读配置查看端点:契约要求查看身/心/智/行/富"
+                        + "定义与权重(API_REFERENCE §4.5 POST /api/energy/config、/api/energy/dimension;"
+                        + "SC-P-19 / TC-P-19)。当前仅有 /configure(写),读端点实现未落地。");
+
+        PostMapping mapping = m.getAnnotation(PostMapping.class);
+        assertNotNull(mapping,
+                "[RED/" + KEY + "] 配置查看端点应使用 @PostMapping(项目统一 POST 约定)。");
+        assertTrue(isConfigReadPath(mapping.value()),
+                "[RED/" + KEY + "] 配置查看端点路径应为 /config 或 /dimension,实际为 "
+                        + Arrays.toString(mapping.value()) + "。");
+
+        String methodName = m.getName().toLowerCase(Locale.ROOT);
+        assertFalse(methodName.contains("save") || methodName.contains("update")
+                        || methodName.contains("create") || methodName.contains("set"),
+                "[RED/" + KEY + "] 家长端配置端点应为只读查询,方法名不应含 save/update/create/set 语义"
+                        + "(写配置走 admin.dimension.config,S-cfc-199)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:五维「定义/口径」应有持久化载体
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-2:五维定义(口径)应有载体——EnergyDimension / EnergyDimensionConfig 应含 definition/description 字段")
+    void dimensionDefinition_carrierFieldExists() {
+        boolean energyDimensionHasDefinition = hasDefinitionField(EnergyDimension.class);
+        boolean configHasDefinition = hasDefinitionField(EnergyDimensionConfig.class);
+
+        assertFalse(!energyDimensionHasDefinition && !configHasDefinition,
+                "[RED/" + KEY + "] 五维定义(口径)无载体:EnergyDimension 与 EnergyDimensionConfig 均无"
+                        + " definition/description 字段,无法返回身/心/智/行/富定义"
+                        + "(SC-P-19「定义与权重」;设计 §1.1 目前仅 code/name/icon/element)。实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:配置未同步时展示兜底(默认值未实现)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:配置未同步时应返回 200 + 五维兜底定义与权重(合计100%)+ 兜底说明")
+    void configNotSynced_fallbackFiveDimensions() {
+        Method m = findConfigReadMethod();
+        if (m == null) {
+            fail("[RED/" + KEY + "] 无配置查看端点,『配置未同步时展示兜底』缺少实现载体:应返回五维"
+                    + "兜底定义 + 权重(合计 100%)+ 兜底说明,且不得 500(SC-P-19 边界 / TC-P-19-E)。实现未落地。");
+        }
+
+        Object response = invokeConfigReadMethod(m);
+        assertNotNull(response,
+                "[RED/" + KEY + "] 配置查看端点应返回 Result,实际返回 null。");
+
+        int code = intGetter(response, "getCode", -1);
+        assertEquals(200, code,
+                "[RED/" + KEY + "] 配置未同步(无种子/空配置)时端点不应报错,应返回 200 + 兜底数据(TC-P-19-E)。");
+
+        Object data = objectGetter(response, "getData");
+        assertNotNull(data,
+                "[RED/" + KEY + "] 配置未同步时 Result.data 不应为空,应含五维兜底定义与权重。");
+
+        Map<String, Map<String, Object>> dims = extractDimensionMap(data);
+        assertEquals(5, dims.size(),
+                "[RED/" + KEY + "] 兜底应覆盖身/心/智/行/富五维(SC-P-19),实际维度数=" + dims.size() + "。");
+
+        double weightSum = 0.0;
+        for (int i = 0; i < CODES.length; i++) {
+            String dimCode = CODES[i];
+            Map<String, Object> dim = dims.get(dimCode);
+            assertNotNull(dim,
+                    "[RED/" + KEY + "] 兜底缺少维度 " + dimCode + "(" + NAMES[i] + ")(五维全覆盖)。");
+
+            Object weight = firstValue(dim, "weight", "ratio", "defaultWeight", "weightPercent", "percent");
+            assertNotNull(weight,
+                    "[RED/" + KEY + "] 维度 " + dimCode + " 兜底应带权重字段(SC-P-19「定义与权重」)。");
+            assertTrue(weight instanceof Number,
+                    "[RED/" + KEY + "] 维度 " + dimCode + " 权重应为数值,实际=" + weight);
+            double percent = toPercent((Number) weight);
+            assertTrue(percent >= 0.0,
+                    "[RED/" + KEY + "] 维度 " + dimCode + " 兜底权重不应为负,实际=" + percent + "%");
+            weightSum += percent;
+
+            Object definition = firstValue(dim, "definition", "description", "remark", "intro",
+                    "explanation", "口径", "definitionText");
+            assertNotNull(definition,
+                    "[RED/" + KEY + "] 维度 " + dimCode + " 兜底应带定义/口径说明(SC-P-19「配置未同步展示兜底说明」)。");
+            assertFalse(definition.toString().trim().isEmpty(),
+                    "[RED/" + KEY + "] 维度 " + dimCode + " 兜底定义不应为空串。");
+        }
+        assertEquals(EXPECTED_WEIGHT_SUM_PERCENT, weightSum, 1e-6,
+                "[RED/" + KEY + "] 五维兜底权重合计应 = 100%,实际=" + weightSum
+                        + "%。默认值未实现(TC-P-19-E)。");
+
+        assertTrue(fallbackNoticePresent(response, data),
+                "[RED/" + KEY + "] 配置未同步时应在响应中给出兜底说明(如 fallback/notice/兜底/默认),"
+                        + "而非静默返回(SC-P-19 边界)。实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流:家长端只读,写配置走 admin.dimension.config(S-cfc-199)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:家长端只读查看配置;/api/energy 不得暴露配置写入端点(写配置走 admin.dimension.config)")
+    void permissionFlow_readOnlyNoWriteEndpoint() {
+        Method m = findConfigReadMethod();
+        if (m == null) {
+            fail("[RED/" + KEY + "] 无配置查看端点,无法验证只读权限流:契约要求家长端只读,"
+                    + "写配置走 admin.dimension.config(S-cfc-199)。实现未落地。");
+        }
+
+        String methodName = m.getName().toLowerCase(Locale.ROOT);
+        assertFalse(methodName.contains("save") || methodName.contains("update") || methodName.contains("set"),
+                "[RED/" + KEY + "] 家长端配置端点应为只读查询,方法名不应含 save/update/set 语义。");
+
+        for (Method candidate : EnergyController.class.getDeclaredMethods()) {
+            PostMapping mapping = candidate.getAnnotation(PostMapping.class);
+            if (mapping == null) {
+                continue;
+            }
+            for (String path : mapping.value()) {
+                assertFalse(path.matches(".*/(config|dimension)/(save|update|set|edit|create|delete|add).*"),
+                        "[RED/" + KEY + "] /api/energy 不应暴露配置写入端点 " + path
+                                + ":家长端只读,写配置走 admin.dimension.config(S-cfc-199)。");
+            }
+        }
+    }
+
+    // ==================================================================
+    // 反射 / 调用辅助
+    // ==================================================================
+
+    /** 在 EnergyController 上定位家长只读配置查看端点(@PostMapping + /config 或 /dimension)。 */
+    private Method findConfigReadMethod() {
+        for (Method m : EnergyController.class.getDeclaredMethods()) {
+            PostMapping mapping = m.getAnnotation(PostMapping.class);
+            if (mapping != null && isConfigReadPath(mapping.value())) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    private boolean isConfigReadPath(String[] paths) {
+        if (paths == null) {
+            return false;
+        }
+        for (String path : paths) {
+            if (path == null) {
+                continue;
+            }
+            String p = path.trim();
+            if (p.equals("/config") || p.equals("/dimension")
+                    || p.startsWith("/config/") || p.startsWith("/dimension/")) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private boolean hasDefinitionField(Class<?> clazz) {
+        if (clazz == null) {
+            return false;
+        }
+        for (Field f : clazz.getDeclaredFields()) {
+            String name = f.getName().toLowerCase(Locale.ROOT);
+            for (String candidate : DEFINITION_FIELDS) {
+                if (name.equals(candidate.toLowerCase(Locale.ROOT))) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * GREEN 阶段用:反射构造控制器(字段注入 Mockito mock)并调用配置端点。
+     * 本分支 RED 阶段因端点不存在不会走到这里。
+     */
+    private Object invokeConfigReadMethod(Method method) {
+        try {
+            Object controller = EnergyController.class.getDeclaredConstructor().newInstance();
+            for (Field f : EnergyController.class.getDeclaredFields()) {
+                if (Modifier.isStatic(f.getModifiers()) || f.getType().isPrimitive()
+                        || f.getType() == String.class) {
+                    continue;
+                }
+                f.setAccessible(true);
+                f.set(controller, mock(f.getType()));
+            }
+            method.setAccessible(true);
+            return method.invoke(controller, buildArgs(method));
+        } catch (Exception e) {
+            return fail("[RED/" + KEY + "] 反射调用配置查看端点失败:" + e.toString());
+        }
+    }
+
+    private Object[] buildArgs(Method method) {
+        Class<?>[] types = method.getParameterTypes();
+        Object[] args = new Object[types.length];
+        for (int i = 0; i < types.length; i++) {
+            Class<?> t = types[i];
+            if (t == String.class) {
+                args[i] = "parent";
+            } else if (Map.class.isAssignableFrom(t)) {
+                args[i] = new HashMap<String, Object>(); // 空配置 → 触发兜底
+            } 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;
+            }
+        }
+        return args;
+    }
+
+    private int intGetter(Object target, String getter, int fallback) {
+        Object v = objectGetter(target, getter);
+        return v instanceof Number ? ((Number) v).intValue() : fallback;
+    }
+
+    private Object objectGetter(Object target, String getter) {
+        if (target == null) {
+            return null;
+        }
+        try {
+            Method m = target.getClass().getMethod(getter);
+            m.setAccessible(true);
+            return m.invoke(target);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** ratio(0~1) 折算为百分比;已为百分比的值原样返回。 */
+    private double toPercent(Number n) {
+        double v = n.doubleValue();
+        return v > 0.0 && v <= 1.0 ? v * 100.0 : v;
+    }
+
+    /** 从 Result.data 中提取「维度码 → 属性」映射(兼容 List / Map 两种返回形态)。 */
+    @SuppressWarnings("unchecked")
+    private Map<String, Map<String, Object>> extractDimensionMap(Object data) {
+        Map<String, Map<String, Object>> out = new LinkedHashMap<>();
+        Set<String> knownCodes = new HashSet<>(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> entry : map.entrySet()) {
+                    if (entry.getValue() instanceof Map && knownCodes.contains(entry.getKey())) {
+                        out.put(entry.getKey(), (Map<String, Object>) entry.getValue());
+                    }
+                }
+                if (!out.isEmpty()) {
+                    return out;
+                }
+            }
+        }
+
+        List<Object> items = new ArrayList<>();
+        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) {
+            if (!(item instanceof Map)) {
+                continue;
+            }
+            Map<String, Object> m = (Map<String, Object>) item;
+            Object codeObj = firstValue(m, "code", "dimension", "dimensionCode");
+            if (codeObj == null) {
+                continue;
+            }
+            String dimCode = codeObj.toString();
+            if (knownCodes.contains(dimCode)) {
+                out.put(dimCode, m);
+            }
+        }
+        return out;
+    }
+
+    private Object firstValue(Map<String, Object> map, String... keys) {
+        for (String key : keys) {
+            if (map.containsKey(key) && map.get(key) != null) {
+                return map.get(key);
+            }
+        }
+        return null;
+    }
+
+    /** 兜底说明探测:兼容 message 文案、fallback/notice 文本、synced=false 等形态。 */
+    private boolean fallbackNoticePresent(Object response, Object data) {
+        String message = String.valueOf(objectGetter(response, "getMessage"));
+        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;
+    }
+}