Browse Source

Merge remote-tracking branch 'origin/cfclub' into task/S-cfc-294

Agnes Agent 7 hours ago
parent
commit
1325dc0b51

+ 278 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/EnergyDimensionViewScP19ContractTest.java

@@ -0,0 +1,278 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.controller.EnergyController;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
+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.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>本类与已合入的 {@code EnergyDimensionViewContractTest} 互补,不重复其 4 例断言,
+ * 只补两条它未覆盖的 AC 条款:</p>
+ * <ul>
+ *   <li><b>TC-P-19(显示口径)</b>:只读配置端点返回的五维须带「身/心/智/行/富」中文展示名,
+ *       而非只有 body/mind/wisdom/action/wealth 英文码。</li>
+ *   <li><b>TC-P-19-P(权限 / 横向越权)</b>:家长端只读查看须按家庭隔离——端点须以
+ *       {@code @RequestAttribute} 接收 familyId 与 currentMemberId(与
+ *       {@code EnergyController#getEnergyOverview} 的 SC-X-19 隔离口径一致),
+ *       否则无法判定「非归属数据访问 403/401」。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(TDD-RED 阶段核实)</b>:{@code EnergyController} 无 {@code /config} / {@code /dimension}
+ * 只读端点(仅有写入型 {@code /configure})。故两条用例均以反射探测,能编译、能运行、断言失败(红)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:补齐只读端点并让其返回含中文名的五维定义与权重、且按
+ * familyId + currentMemberId 做同家庭校验后,本测试自动转绿。纯反射 + Mockito,
+ * 无 Spring 上下文 / 无 DB / 无外部服务依赖。</p>
+ */
+class EnergyDimensionViewScP19ContractTest {
+
+    private static final String KEY = "energy.dimension.view";
+
+    /** 设计 §1.1 五维码 → 中文口径(SC-P-19 / TC-P-19 展示要求)。 */
+    private static final String[][] DIMENSIONS = {
+            {"body", "身"}, {"mind", "心"}, {"wisdom", "智"}, {"action", "行"}, {"wealth", "富"}
+    };
+
+    // ------------------------------------------------------------------
+    // TC-P-19:五维中文展示名(已有测试只校验英文码与定义字段,未校验「身/心/智/行/富」)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("TC-P-19:只读配置端点返回的五维应带「身/心/智/行/富」中文展示名")
+    void configView_fiveDimensionChineseNames() {
+        Method endpoint = findConfigReadEndpoint();
+        if (endpoint == null) {
+            fail("[RED/" + KEY + "] 缺少家长只读配置查看端点(POST /api/energy/config 或 /dimension),"
+                    + "无法返回身/心/智/行/富中文口径(TC-P-19 / API_REFERENCE §4.5)。实现未落地。");
+        }
+
+        Object response = invoke(endpoint);
+        assertNotNull(response, "[RED/" + KEY + "] 配置查看端点应返回 Result,实际为 null。");
+
+        Object data = getter(response, "getData");
+        assertNotNull(data, "[RED/" + KEY + "] 配置查看端点 Result.data 不应为空。");
+
+        Map<String, Map<String, Object>> dims = extractDimensionMap(data);
+        assertEquals(5, dims.size(),
+                "[RED/" + KEY + "] 应覆盖身/心/智/行/富五维,实际维度数=" + dims.size() + "。");
+
+        for (String[] pair : DIMENSIONS) {
+            String code = pair[0];
+            String expectedName = pair[1];
+            Map<String, Object> dim = dims.get(code);
+            assertNotNull(dim, "[RED/" + KEY + "] 兜底/配置缺少维度 " + code + "(" + expectedName + ")。");
+
+            Object name = firstValue(dim, "name", "displayName", "cnName", "label", "title", "名称");
+            assertNotNull(name,
+                    "[RED/" + KEY + "] 维度 " + code + " 应带中文展示名(" + expectedName + "),"
+                            + "仅返回英文码不满足 SC-P-19「查看身/心/智/行/富定义与权重」。实现未落地。");
+            assertTrue(name.toString().contains(expectedName),
+                    "[RED/" + KEY + "] 维度 " + code + " 展示名应含「" + expectedName + "」,实际=" + name + "。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // TC-P-19-P:家长端只读查看须具备家庭隔离载体的前提(@RequestAttribute familyId/currentMemberId)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("TC-P-19-P:配置查看端点须以 @RequestAttribute 接收 familyId + currentMemberId 以支撑同家庭隔离")
+    void configView_hasFamilyScopedRequestAttributes() {
+        Method endpoint = findConfigReadEndpoint();
+        if (endpoint == null) {
+            fail("[RED/" + KEY + "] 缺少家长只读配置查看端点,无法实施横向越权校验:"
+                    + "契约要求非归属数据访问统一 403/401(TC-P-19-P / SC-X-19)。实现未落地。");
+        }
+
+        Set<String> attributeNames = new HashSet<>();
+        for (Parameter p : endpoint.getParameters()) {
+            RequestAttribute ra = p.getAnnotation(RequestAttribute.class);
+            if (ra == null) {
+                continue;
+            }
+            String value = ra.value();
+            if (value == null || value.trim().isEmpty()) {
+                value = ra.name();
+            }
+            if (value != null) {
+                attributeNames.add(value.trim());
+            }
+        }
+
+        assertTrue(attributeNames.contains("familyId"),
+                "[RED/" + KEY + "] 配置查看端点须声明 @RequestAttribute(\"familyId\") 以限定家庭范围"
+                        + "(TC-P-19-P 横向越权被拒)。实际 attributes=" + attributeNames + "。");
+        assertTrue(attributeNames.contains("currentMemberId") || attributeNames.contains("userId"),
+                "[RED/" + KEY + "] 配置查看端点须声明 @RequestAttribute(\"currentMemberId\"/\"userId\") "
+                        + "以判定访问者归属(TC-P-19-P 403/401)。实际 attributes=" + attributeNames + "。");
+    }
+
+    // ==================================================================
+    // 反射 / 调用辅助(与 EnergyDimensionViewContractTest 同风格,保持本类自包含)
+    // ==================================================================
+
+    private Method findConfigReadEndpoint() {
+        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 && (path.trim().equals("/config") || path.trim().equals("/dimension")
+                    || path.trim().startsWith("/config/") || path.trim().startsWith("/dimension/"))) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 反射构造控制器并注入 Mockito mock;GREEN 阶段端点存在后才会走到这里(RED 阶段不会)。 */
+    private Object invoke(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 Object getter(Object target, String name) {
+        if (target == null) {
+            return null;
+        }
+        try {
+            Method m = target.getClass().getMethod(name);
+            m.setAccessible(true);
+            return m.invoke(target);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    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;
+    }
+
+    /** 兼容 List / Map 两种 Result.data 形态,提取「维度码 → 属性」。 */
+    @SuppressWarnings("unchecked")
+    private Map<String, Map<String, Object>> extractDimensionMap(Object data) {
+        Map<String, Map<String, Object>> out = new LinkedHashMap<>();
+        Set<String> knownCodes = new HashSet<>();
+        for (String[] pair : DIMENSIONS) {
+            knownCodes.add(pair[0]);
+        }
+
+        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 || !knownCodes.contains(codeObj.toString().toLowerCase(Locale.ROOT))) {
+                continue;
+            }
+            out.put(codeObj.toString().toLowerCase(Locale.ROOT), m);
+        }
+        return out;
+    }
+}