Browse Source

test(RED): S-cfc-439 food.rule.weightEngine 契约级单测(CR-02 加权规则引擎,14红/1对照绿)

Agnes Agent 2 days ago
parent
commit
4c8684076c

+ 410 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/FoodRuleWeightEngineContractTest.java

@@ -0,0 +1,410 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Scanner;
+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;
+
+/**
+ * 契约级单测:能力键 {@code food.rule.weightEngine}(S-cfc-439,TDD-RED 阶段)。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code docs/需求分析/2026-11-22-食材推荐加权规则引擎需求变更.md}
+ *       CR-02 + §4.2(加权规则引擎)+ §7.1 G-2(加权引擎验收门禁)</li>
+ *   <li>设计锚点(§4.2 公式):
+ *       <pre>
+ *       final_score = clamp( base_report_score × w1
+ *                          + health_adjust_score × w2
+ *                          + preference_boost × w3
+ *                          + pairing_effect × w4
+ *                          + processing_effect × w5
+ *                          + disease_group_adjust × w6
+ *                          , -100, 100 )
+ *       </pre>
+ *   </li>
+ *   <li>权重规则表(§4.2 / §5):{@code food_recommend_weight_rule},字段
+ *       {@code factor_type / weight / threshold / disease_code / version / enabled / updated_by / updated_at},
+ *       factor_type 枚举 = {@code base_report / health_adjust / preference / pairing / processing / disease_group},
+ *       默认权重和 = 1。</li>
+ *   <li>11-09 标记升级(§4.2):{@code blocked=-50 / warning=-15 / boost=+10 / normal=0}
+ *       作为 {@code health_adjust_score} 输入(四态展示语义保留)。</li>
+ *   <li>写回(§4.2 / G-2):{@code final_score} 写 {@code food_recommend_idx.index_score};
+ *       {@code food_recommend_idx_log.change_reason} 记录「加权规则引擎 vX」。</li>
+ * </ul>
+ *
+ * <p><b>实现现状(origin/cfclub 源码核实)</b>:{@code FoodRecommendService.recalculateForUser}
+ * 仍为「报告分 → {@code indexScore = food.getScore()}」直接写入(F-01),无多因子加权;
+ * {@code src/main} 中无加权引擎宿主类、无 {@code food_recommend_weight_rule} 表/实体。
+ * 故本测试以「反射宿主探测 + 结构/源码锚点」定义契约:能编译通过、能运行、断言失败(红),
+ * 失败原文清晰可贴;GREEN 实现落地后自动转绿。</p>
+ *
+ * <p><b>契约宿主(实现方按此落地)</b>:{@code com.etotem.cfc.service.FoodRecommendWeightEngine}
+ * —— 通过反射按方法名 + 参数个数探测,避免直接 import 不存在类导致编译失败:</p>
+ * <ul>
+ *   <li>{@code Map<String,Double> defaultWeights()} —— 6 因子默认权重表,和 = 1</li>
+ *   <li>{@code double healthAdjustScore(String adjustment)} —— 四态 → 数值映射</li>
+ *   <li>{@code double clamp(double rawScore)} —— 截断到 [-100,100]</li>
+ *   <li>{@code double finalScoreWithWeights(Map<String,Double> weights, double baseReportScore,
+ *       double healthAdjustScore, double preferenceBoost, double pairingEffect,
+ *       double processingEffect, double diseaseGroupAdjust)} —— 显式权重精确公式 + clamp</li>
+ *   <li>{@code double finalScore(double baseReportScore, double healthAdjustScore,
+ *       double preferenceBoost, double pairingEffect, double processingEffect,
+ *       double diseaseGroupAdjust)} —— 默认权重路径,等价于用 defaultWeights() 调上法</li>
+ * </ul>
+ *
+ * <p><b>测试范围</b>:纯 JUnit5 + 反射(无 Spring / 无 DB / 无外部服务),与同批已合入主链的 RED
+ * 契约测试(TeamProfitHookContractTest / TeamStarMultiplierContractTest /
+ * FamilyJoinValidationRulesContractTest / DietFoodHealthAdjustContractTest)同风格。</p>
+ *
+ * <p><b>权限流</b>:加权引擎为后端内部计算服务(规则表由独立能力键 {@code ops.foodRuleManagement}
+ * 承载后台 CRUD/灰度),无用户侧鉴权分支,权限流不适用(说明性用例标注)。</p>
+ *
+ * <p><b>RED 预期</b>:全部行为用例在 {@code contractHost()} 处失败(宿主类未实现),
+ * 结构用例在实体/schema.sql/写回源码锚点处失败,失败原文前缀 {@code RED[food.rule.weightEngine]}。</p>
+ */
+class FoodRuleWeightEngineContractTest {
+
+    /** 契约宿主类(§4.2 加权规则引擎核心,当前未实现)。 */
+    private static final String HOST_CLASS = "com.etotem.cfc.service.FoodRecommendWeightEngine";
+
+    /** 加权规则实体(§4.2 food_recommend_weight_rule 表,当前未实现)。 */
+    private static final String RULE_ENTITY = "com.etotem.cfc.entity.FoodRecommendWeightRule";
+
+    // §4.2 factor_type 六个枚举值
+    private static final String FACTOR_BASE = "base_report";
+    private static final String FACTOR_HEALTH = "health_adjust";
+    private static final String FACTOR_PREFERENCE = "preference";
+    private static final String FACTOR_PAIRING = "pairing";
+    private static final String FACTOR_PROCESSING = "processing";
+    private static final String FACTOR_DISEASE = "disease_group";
+
+    private static final double EPS = 1e-9;
+
+    // ==================== 正常流:宿主与默认权重 ====================
+
+    @Test
+    @DisplayName("正常流-1:契约宿主 FoodRecommendWeightEngine 应存在(§4.2 加权规则引擎核心)")
+    void weightEngine_hostClassExists() {
+        assertNotNull(contractHost(),
+                "[food.rule.weightEngine] 契约宿主 FoodRecommendWeightEngine 应存在:§4.2 要求多因子加权"
+                        + "final_score 计算,现状 recalculateForUser 直接写 food.getScore()(F-01)。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:defaultWeights() 应覆盖 6 个因子且权重和=1(§4.2)")
+    void defaultWeights_coverSixFactorsAndSumToOne() {
+        Object host = contractHost();
+        Map<String, Double> weights = defaultWeights(host);
+
+        assertNotNull(weights, "[food.rule.weightEngine] defaultWeights() 应返回因子权重表(§4.2)。");
+        Set<String> expected = new HashSet<String>(Arrays.asList(
+                FACTOR_BASE, FACTOR_HEALTH, FACTOR_PREFERENCE,
+                FACTOR_PAIRING, FACTOR_PROCESSING, FACTOR_DISEASE));
+        assertEquals(expected, weights.keySet(),
+                "[food.rule.weightEngine] 默认权重表应恰好覆盖 6 个 factor_type(§4.2):"
+                        + "base_report/health_adjust/preference/pairing/processing/disease_group。");
+
+        double sum = 0.0;
+        for (Double w : weights.values()) {
+            if (w != null) {
+                sum += w.doubleValue();
+            }
+        }
+        assertEquals(1.0, sum, EPS,
+                "[food.rule.weightEngine] 默认权重和应 = 1(§4.2「默认和 = 1」),实际=" + sum);
+    }
+
+    // ==================== 正常流:11-09 标记升级为数值(§4.2) ====================
+
+    @Test
+    @DisplayName("正常流-3:healthAdjustScore 四态映射 blocked=-50 / warning=-15 / boost=+10 / normal=0")
+    void healthAdjustScore_mapsFourStatesToNumbers() {
+        Object host = contractHost();
+        assertEquals(-50.0, callDouble(host, "healthAdjustScore", "blocked"), EPS,
+                "[food.rule.weightEngine] blocked 应映射为 -50(§4.2 升级逻辑)。");
+        assertEquals(-15.0, callDouble(host, "healthAdjustScore", "warning"), EPS,
+                "[food.rule.weightEngine] warning 应映射为 -15(§4.2 升级逻辑)。");
+        assertEquals(10.0, callDouble(host, "healthAdjustScore", "boost"), EPS,
+                "[food.rule.weightEngine] boost 应映射为 +10(§4.2 升级逻辑)。");
+        assertEquals(0.0, callDouble(host, "healthAdjustScore", "normal"), EPS,
+                "[food.rule.weightEngine] normal 应映射为 0(§4.2 升级逻辑)。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:healthAdjustScore 未知/空标记应为 0(normal 兜底)")
+    void healthAdjustScore_unknownOrNullFallsBackToZero() {
+        Object host = contractHost();
+        assertEquals(0.0, callDouble(host, "healthAdjustScore", (Object) null), EPS,
+                "[food.rule.weightEngine] null 标记应兜底为 0(无调整)。");
+        assertEquals(0.0, callDouble(host, "healthAdjustScore", "unexpected"), EPS,
+                "[food.rule.weightEngine] 未知标记应兜底为 0(normal),不得抛异常或产生负调整。");
+    }
+
+    // ==================== 正常流:多因子公式(§4.2 / G-2) ====================
+
+    @Test
+    @DisplayName("正常流-5:finalScoreWithWeights 按 6 因子公式精确计算(§4.2)")
+    void finalScoreWithWeights_weightedFormulaIsExact() {
+        Object host = contractHost();
+        Map<String, Double> w = explicitWeights();
+        // 80×0.5 + (-15)×0.2 + 10×0.1 + (-20)×0.1 + (-5)×0.05 + 0×0.05 = 35.75
+        double score = callDouble(host, "finalScoreWithWeights", w,
+                80.0, -15.0, 10.0, -20.0, -5.0, 0.0);
+        assertEquals(35.75, score, EPS,
+                "[food.rule.weightEngine] 应按 §4.2 公式 base×w1 + health×w2 + preference×w3"
+                        + " + pairing×w4 + processing×w5 + disease_group×w6 精确计算,期望 35.75。");
+    }
+
+    @Test
+    @DisplayName("正常流-6:finalScore 默认权重路径应与显式默认权重一致(§4.2/G-2)")
+    void finalScore_matchesExplicitDefaultWeightPath() {
+        Object host = contractHost();
+        Map<String, Double> defaults = defaultWeights(host);
+        double expected = callDouble(host, "finalScoreWithWeights", defaults,
+                70.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        double actual = callDouble(host, "finalScore",
+                70.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        assertEquals(expected, actual, EPS,
+                "[food.rule.weightEngine] finalScore(默认权重) 应等价于 finalScoreWithWeights(defaultWeights(), ...)。");
+    }
+
+    // ==================== 边界流:clamp 到 [-100,100](§4.2/G-2) ====================
+
+    @Test
+    @DisplayName("边界流-1:clamp 上限 100")
+    void clamp_upperBoundIsOneHundred() {
+        Object host = contractHost();
+        assertEquals(100.0, callDouble(host, "clamp", 150.0), EPS,
+                "[food.rule.weightEngine] clamp(150) 应 = 100(§4.2 上界)。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:clamp 下限 -100")
+    void clamp_lowerBoundIsMinusOneHundred() {
+        Object host = contractHost();
+        assertEquals(-100.0, callDouble(host, "clamp", -150.0), EPS,
+                "[food.rule.weightEngine] clamp(-150) 应 = -100(§4.2 下界)。");
+    }
+
+    @Test
+    @DisplayName("边界流-3:clamp 区间内值不变")
+    void clamp_inRangeUnchanged() {
+        Object host = contractHost();
+        assertEquals(35.75, callDouble(host, "clamp", 35.75), EPS,
+                "[food.rule.weightEngine] clamp(35.75) 应保持原值。");
+        assertEquals(0.0, callDouble(host, "clamp", 0.0), EPS,
+                "[food.rule.weightEngine] clamp(0) 应保持原值。");
+    }
+
+    @Test
+    @DisplayName("边界流-4:finalScore 汇总超上界被截断为 100")
+    void finalScore_overflowClampedToUpperBound() {
+        Object host = contractHost();
+        double score = callDouble(host, "finalScore",
+                1000.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        assertEquals(100.0, score, EPS,
+                "[food.rule.weightEngine] 加权汇总 > 100 时必须 clamp 到 100(§4.2/G-2)。");
+    }
+
+    @Test
+    @DisplayName("边界流-5:finalScore 汇总超下界被截断为 -100")
+    void finalScore_underflowClampedToLowerBound() {
+        Object host = contractHost();
+        double score = callDouble(host, "finalScore",
+                -1000.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        assertEquals(-100.0, score, EPS,
+                "[food.rule.weightEngine] 加权汇总 < -100 时必须 clamp 到 -100(§4.2/G-2)。");
+    }
+
+    // ==================== 结构契约:权重规则表与实体(§4.2/§5) ====================
+
+    @Test
+    @DisplayName("结构-1:加权规则实体应存在并含 factor_type/weight/threshold/disease_code/version/enabled 等字段")
+    void weightRuleEntity_hasContractFields() {
+        Class<?> entity = loadClass(RULE_ENTITY);
+        if (entity == null) {
+            fail("RED[food.rule.weightEngine] FoodRecommendWeightRule 实体不存在:§4.2/§5 要求"
+                    + " food_recommend_weight_rule 表承载 6 因子权重、阈值、病症分组、版本与灰度开关。");
+            throw new IllegalStateException("unreachable");
+        }
+        String[] fields = {
+                "factorType", "weight", "threshold", "diseaseCode",
+                "version", "enabled", "updatedBy", "updatedAt"
+        };
+        for (String name : fields) {
+            assertNotNull(findField(entity, name),
+                    "[food.rule.weightEngine] FoodRecommendWeightRule 缺少字段 " + name
+                            + "(§4.2 加权规则表字段清单)。");
+        }
+    }
+
+    @Test
+    @DisplayName("结构-2:schema.sql 应含 food_recommend_weight_rule 建表及关键列")
+    void schemaSql_containsWeightRuleTable() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("food_recommend_weight_rule"),
+                "[food.rule.weightEngine] schema.sql 缺少 food_recommend_weight_rule 建表(§4.2/§5)。");
+        assertTrue(schema.contains("factor_type"),
+                "[food.rule.weightEngine] 权重规则表应含 factor_type 列(§4.2)。");
+        assertTrue(schema.contains("disease_code"),
+                "[food.rule.weightEngine] 权重规则表应含 disease_code 列(§4.2,null=通用)。");
+    }
+
+    // ==================== 写回契约:接入 recalculateForUser 并记录版本(§4.2/G-2) ====================
+
+    @Test
+    @DisplayName("写回-1:recalculateForUser 应接入加权引擎并按版本写 change_reason")
+    void recalculateForUser_integratesEngineAndRecordsVersion() {
+        String src = readMainSource("service/FoodRecommendService.java");
+        assertTrue(src.contains(HOST_CLASS.substring(HOST_CLASS.lastIndexOf('.') + 1)),
+                "[food.rule.weightEngine] FoodRecommendService.recalculateForUser 应接入"
+                        + " FoodRecommendWeightEngine(§4.2「写回:final_score 写 index_score」);"
+                        + "现状直接写 food.getScore()(F-01)。");
+        assertTrue(src.contains("加权规则引擎"),
+                "[food.rule.weightEngine] change_reason 应记录「加权规则引擎 vX」(§4.2/G-2),"
+                        + "现状仅记录「健康报告更新」等固定文案。");
+    }
+
+    // ==================== 权限流(不适用):内部计算服务 ====================
+
+    @Test
+    @DisplayName("权限流:加权引擎为内部计算服务,无用户侧鉴权分支,权限流不适用")
+    void permissionFlow_notApplicable() {
+        assertTrue(true,
+                "权限流不适用:food.rule.weightEngine 为后端内部加权计算 + 规则表;"
+                        + "后台规则 CRUD/灰度开关由独立能力键 ops.foodRuleManagement(CR-06)承载。");
+    }
+
+    // ==================== 反射辅助(锚定宿主契约,避免编译期依赖不存在类) ====================
+
+    private Object contractHost() {
+        try {
+            Class<?> clazz = Class.forName(HOST_CLASS, false, Thread.currentThread().getContextClassLoader());
+            return clazz.getDeclaredConstructor().newInstance();
+        } catch (ClassNotFoundException e) {
+            fail("RED[food.rule.weightEngine] 契约宿主 FoodRecommendWeightEngine 未实现(实现未落地):"
+                    + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        } catch (Exception e) {
+            fail("RED[food.rule.weightEngine] 契约宿主 FoodRecommendWeightEngine 实例化失败:"
+                    + e.getMessage());
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    /** 按方法名 + 参数个数匹配并调用(宽松适配基本/包装类型),契约方法缺失即断言失败。 */
+    private Object call(Object host, String method, Object... args) {
+        for (Method m : host.getClass().getMethods()) {
+            if (m.getName().equals(method) && m.getParameterCount() == args.length) {
+                try {
+                    return m.invoke(host, args);
+                } catch (Exception e) {
+                    fail("RED[food.rule.weightEngine] 契约方法 " + HOST_CLASS + "#" + method
+                            + " 调用失败:" + e.getMessage());
+                    throw new IllegalStateException("unreachable");
+                }
+            }
+        }
+        fail("RED[food.rule.weightEngine] 契约方法 " + HOST_CLASS + "#" + method + " 未实现");
+        throw new IllegalStateException("unreachable");
+    }
+
+    private double callDouble(Object host, String method, Object... args) {
+        Object r = call(host, method, args);
+        if (r instanceof Number) {
+            return ((Number) r).doubleValue();
+        }
+        fail("契约方法 " + method + " 应返回数值,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String, Double> defaultWeights(Object host) {
+        Object r = call(host, "defaultWeights");
+        if (r instanceof Map) {
+            return (Map<String, Double>) r;
+        }
+        fail("契约方法 defaultWeights() 应返回 Map<String,Double>,实际 " + r);
+        throw new IllegalStateException("unreachable");
+    }
+
+    /** 显式权重(§4.2 六因子,和=1),用于精确验证加权公式而与默认权重解耦。 */
+    private Map<String, Double> explicitWeights() {
+        Map<String, Double> w = new HashMap<String, Double>();
+        w.put(FACTOR_BASE, 0.5);
+        w.put(FACTOR_HEALTH, 0.2);
+        w.put(FACTOR_PREFERENCE, 0.1);
+        w.put(FACTOR_PAIRING, 0.1);
+        w.put(FACTOR_PROCESSING, 0.05);
+        w.put(FACTOR_DISEASE, 0.05);
+        return w;
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private Field findField(Class<?> clazz, String name) {
+        try {
+            return clazz.getDeclaredField(name);
+        } catch (NoSuchFieldException e) {
+            return null;
+        }
+    }
+
+    private String readSchemaSql() {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream("schema.sql")) {
+            if (is == null) {
+                return "";
+            }
+            try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
+                scanner.useDelimiter("\\A");
+                return scanner.hasNext() ? scanner.next() : "";
+            }
+        } catch (Exception e) {
+            return "";
+        }
+    }
+
+    /** 读取 src/main 源码文件(surefire 工作目录 = cfc-backend 模块目录),找不到返回空串。 */
+    private String readMainSource(String relative) {
+        String[] candidates = {
+                "src/main/java/com/etotem/cfc/" + relative,
+                "cfc-backend/src/main/java/com/etotem/cfc/" + relative,
+                "../cfc-backend/src/main/java/com/etotem/cfc/" + relative
+        };
+        for (String candidate : candidates) {
+            File file = new File(candidate);
+            if (file.isFile()) {
+                try {
+                    return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+                } catch (IOException e) {
+                    return "";
+                }
+            }
+        }
+        return "";
+    }
+}