瀏覽代碼

Merge task/S-cfc-417: S-cfc-417 契约级RED单测 health.attribution.normFill(11 失败/4 通过)

zxyj-langgraph 9 小時之前
父節點
當前提交
dac5ef97a8
共有 1 個文件被更改,包括 428 次插入 和 0 次删除
  1. 428 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/AttributionNormFillContractTest.java

+ 428 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/AttributionNormFillContractTest.java

@@ -0,0 +1,428 @@
+package com.etotem.cfc.unit;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
+import java.util.Scanner;
+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;
+
+/**
+ * 契约级单测:归因归一化真实数据填充(能力键 {@code health.attribution.normFill})。
+ *
+ * <p><b>契约来源</b>(《谷禾新版解析与五维归因升级方案 v1.0》,提交 {@code ef8eb62be} 已合入 origin/cfclub;
+ * 溯源 {@code SC-P-22 · 报告解析预览},{@code tests/user-scenarios/应用场景总览.md}):
+ * <blockquote>
+ *   §三 P0-5 归因归一化真实数据填充管线:让 {@code FiveDimAttributionEngine} 真正跑起来——
+ *   目前 {@code attribution_norm_values} 是空表({@code placeholder=true})。
+ *   <ol>
+ *     <li>新建脚本 {@code scripts/import_norm_from_reports.py}:输入 17 份样本(毛静明 / 吴介洋 / 廖某人 /
+ *         侯 / 547982403 等),输出 {@code attribution_norm_gut_flora.json} 的 {@code data[]};
+ *         规则:每个菌种 / 疾病相关菌的 {@code 正常范围{最小值,最大值}} → 映射 {@code p5=最小值, p95=最大值};
+ *         {@code 处于人群%水平} → 推算 {@code p25/p50/p75}(线性插值);{@code 年龄段带} 取 {@code all},
+ *         {@code gender} 取 {@code all};{@code source="谷禾样本回归"},{@code normVersion="v1"};</li>
+ *     <li>更新 {@code attribution_norm_gut_flora.json}:{@code placeholder=false}、
+ *         {@code schemaVersion="1.1"},data 长度记录(预估 100+ 条,视去重);</li>
+ *     <li>{@code DatabaseInitializer.importAttributionNormGutFlora()} 首次启动自动导入(已有逻辑,只需 JSON 非空);</li>
+ *     <li><b>红线</b>:样本数据 ≠ 人群常模,{@code source} 字段写清楚「样本回归估算,非谷禾官方 710 常模」
+ *         (§5.7 证据码:DEV 层,非 PUB 层)。</li>
+ *   </ol>
+ *   §四 决策3:首期归一化数据来自 17 份样本回归(推荐 A),不是官方 710 常模,人群代表性有限;
+ *   §八 8.3:展示时必须写 {@code source} 字段,<b>禁写「符合人群 xx%」等断言</b>。
+ * </blockquote></p>
+ *
+ * <p><b>平台现状(origin/cfclub 探测,见实施计划 plan-guhe-v1.0-upgrade-2026-11-16.md §一 P0-5)</b>:
+ * {@code norm/attribution_norm_gut_flora.json} 仍为占位模板:
+ * <ul>
+ *   <li>{@code placeholder=true}、{@code schemaVersion="1.0"}、{@code data=[]}
+ *       (note 注释「真实710条待业务侧填充」);</li>
+ *   <li>{@code scripts/import_norm_from_reports.py} 不存在;</li>
+ *   <li>归因引擎空壳常模 → 跑不出真实百分位结论(映射无法产出 P5/P25/P50/P75/P95)。</li>
+ * </ul>
+ * 因此本测试以「资源结构契约」探测契约缺失:能编译通过、能运行、断言失败(红),
+ * 且失败断言原文清晰可贴(纯 JSON 资源读取 + 反射,无 Spring / 无 DB / 无外部服务)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者按 P0-5 落地后,本测试自动转绿——
+ * <ol>
+ *   <li>{@code scripts/import_norm_from_reports.py} 落地:17 份样本 → min→p5、max→p95、线性插值 p25/p50/p75;
+ *       年龄段带/gender=all、normVersion=v1;</li>
+ *   <li>{@code attribution_norm_gut_flora.json}:{@code placeholder=false}、{@code schemaVersion="1.1"}、
+ *       {@code normType="gut_flora"},{@code data[]} 填充真实五百分位行(无重复唯一键,防幂等 upsert 覆盖),
+ *       每条 {@code source} 按 §八8.3 标注「样本回归估算,非官方 710 常模」;</li>
+ *   <li>启动导入管线({@code DatabaseInitializer.importAttributionNormGutFlora()})保持在位,
+ *       首次启动自动灌入 {@code attribution_norm_values}。</li>
+ * </ol>
+ * 届时结构探测可升级为行为级验证(§6.4 / P0-5 验证:{@code POST /api/attribution/analyze}
+ * 返回真实百分位结论,mock mapper 断言 p25/p75 分档)。结构落点以当前 src/main 实测为准
+ * (实现仅在 feature 分支,不得假定包路径)。</p>
+ *
+ * <p><b>权限流说明</b>:本能力为后台归一化数据填充管线(脚本生成 → JSON → 启动导入),
+ * 无用户权限维度,权限流不适用,以说明性用例标注。</p>
+ */
+class AttributionNormFillContractTest {
+
+    // ------------------------------------------------------------------
+    // 契约锚点(方案 v1.0 §三 P0-5 + §四决策3 + §八8.3)
+    // ------------------------------------------------------------------
+
+    /** 常模种子文件 classpath 路径(与 DatabaseInitializer.NORM_GUT_FLORA_CLASSPATH 同源) */
+    private static final String NORM_RESOURCE = "norm/attribution_norm_gut_flora.json";
+
+    /** P0-5 目标 schemaVersion(1.0 → 1.1) */
+    private static final String SCHEMA_VERSION_TARGET = "1.1";
+
+    /** P0-5 菌群常模类型 */
+    private static final String NORM_TYPE_GUT_FLORA = "gut_flora";
+
+    /** P0-5:年龄段带取 all */
+    private static final String AGE_BAND_ALL = "all";
+
+    /** P0-5:gender 取 all */
+    private static final String GENDER_ALL = "all";
+
+    /** P0-5:常模版本 v1 */
+    private static final String NORM_VERSION_V1 = "v1";
+
+    /** §四决策3 / §八8.3:source 数据来源标注必须含「样本回归」(样本回归估算,非官方 710 常模) */
+    private static final String SOURCE_PHRASE_SAMPLE = "样本回归";
+
+    /** §八8.3:source 必须明示「非官方」(非谷禾官方 710 常模) */
+    private static final String SOURCE_PHRASE_NOT_OFFICIAL = "非官方";
+
+    /** §八8.3:禁写「符合人群 xx%」等夸大人群代表性断言 */
+    private static final String FORBIDDEN_CROWD_CLAIM = "符合人群";
+
+    /** P0-5 五百分位字段(min→p5、max→p95、线性插值→p25/p50/p75) */
+    private static final String[] PERCENTILE_FIELDS = {"p5", "p25", "p50", "p75", "p95"};
+
+    /** 方案 §三 P0-5 做法①:导入脚本名(17 份样本 → 五百分位 data[]) */
+    private static final String IMPORT_SCRIPT_NAME = "import_norm_from_reports.py";
+
+    /** 启动导入管线(方案 P0-5 做法③:已有逻辑,只需 JSON 非空) */
+    private static final String DATABASE_INITIALIZER = "com.etotem.cfc.config.DatabaseInitializer";
+
+    // ------------------------------------------------------------------
+    // 正常流:常模种子文件应升级为真实数据(placeholder=false, schemaVersion=1.1, data 非空)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:常模种子文件应存在于 classpath(norm/attribution_norm_gut_flora.json)")
+    void normResource_exists() {
+        assertNotNull(readRawNorm(),
+                "[health.attribution.normFill] classpath 缺少 " + NORM_RESOURCE
+                        + ":契约要求 attribution_norm_gut_flora.json 承载菌群五百分位常模数据"
+                        + "(方案 §三 P0-5),DatabaseInitializer.importAttributionNormGutFlora() 启动时按此导入。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:placeholder 应置为 false(占位模板 → 真实数据)")
+    void normResource_placeholderFlagFalse() {
+        JsonNode root = normJson();
+        assertFalse(root.path("placeholder").asBoolean(false),
+                "[health.attribution.normFill] attribution_norm_gut_flora.json 仍为占位模板"
+                        + "(placeholder=true,note=\"真实710条待业务侧填充\"):FiveDimAttributionEngine"
+                        + " 空壳常模跑不出真实百分位结论(方案 §三 P0-5 目标)。GREEN 时 placeholder 应置为 false,"
+                        + "data[] 填充 17 份样本回归五百分位。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:schemaVersion 应升级为 1.1")
+    void normResource_schemaVersionIs11() {
+        JsonNode root = normJson();
+        assertEquals(SCHEMA_VERSION_TARGET, textOf(root, "schemaVersion"),
+                "[health.attribution.normFill] attribution_norm_gut_flora.json schemaVersion 应为 \"1.1\""
+                        + "(方案 §三 P0-5 做法②,当前仍为 \"1.0\" 占位模板),标识真实数据版本。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:数据行应非空(预估 100+ 条,视去重)")
+    void normResource_dataNonEmpty() {
+        JsonNode root = normJson();
+        JsonNode data = root.path("data");
+        boolean nonEmpty = data.isArray() && data.size() >= 1;
+        assertTrue(nonEmpty,
+                "[health.attribution.normFill] attribution_norm_gut_flora.json data[] 应为空(当前 data=[])。"
+                        + "契约要求填充真实五百分位常模,长度预估 100+ 条(视去重,方案 §三 P0-5 做法②)。"
+                        + "归因引擎目前因空壳常模无法映射 P5/P25/P50/P75/P95。");
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:每条数据行的字段契约(code + 五百分位 + all 年龄段/性别 + v1 版本)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-5:每条数据应含 code 与完整五百分位 p5/p25/p50/p75/p95")
+    void normResource_eachRow_hasCodeAndFullPercentiles() {
+        JsonNode rows = requireDataRows();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String code = textOf(row, "code");
+            assertTrue(code != null && !code.trim().isEmpty(),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据缺少 code(菌种学名/指标编码,"
+                            + "importAttributionNormGutFlora 以 code 为导入主键,空 code 行会被跳过)。");
+            for (String f : PERCENTILE_FIELDS) {
+                assertTrue(row.has(f) && row.get(f).isNumber(),
+                        "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code + ") 缺百分位字段 "
+                                + f + ":契约要求 正常范围{min,max}→p5/p95、线性插值→p25/p50/p75"
+                                + "(方案 §三 P0-5 做法①)。");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-6:每条数据五百分位应单调递增(p5≤p25≤p50≤p75≤p95)")
+    void normResource_percentilesMonotonic() {
+        JsonNode rows = requireDataRows();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String code = textOf(row, "code");
+            for (int i = 0; i < PERCENTILE_FIELDS.length - 1; i++) {
+                double lo = row.path(PERCENTILE_FIELDS[i]).asDouble();
+                double hi = row.path(PERCENTILE_FIELDS[i + 1]).asDouble();
+                assertTrue(lo <= hi,
+                        "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code + ") 百分位不单调:"
+                                + PERCENTILE_FIELDS[i] + "=" + lo + " > " + PERCENTILE_FIELDS[i + 1] + "=" + hi
+                                + "(p5≤p25≤p50≤p75≤p95,min→p5、max→p95 语义)。");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-7:每条数据年龄段带与性别应取 all(方案 P0-5 规则)")
+    void normResource_eachRow_ageBandAndGenderAll() {
+        JsonNode rows = requireDataRows();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String code = textOf(row, "code");
+            assertEquals(AGE_BAND_ALL, textOf(row, "memberAgeBand"),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code
+                            + ") 年龄段带应为 \"all\"(方案 §三 P0-5 做法①:样本回归阶段年龄段带取 all)。");
+            assertEquals(GENDER_ALL, textOf(row, "gender"),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code
+                            + ") gender 应为 \"all\"(方案 §三 P0-5 做法①:样本回归阶段 gender 取 all)。");
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-8:每条数据常模版本应为 v1(normVersion=v1)")
+    void normResource_eachRow_normVersionV1() {
+        JsonNode rows = requireDataRows();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String code = textOf(row, "code");
+            assertEquals(NORM_VERSION_V1, textOf(row, "normVersion"),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code
+                            + ") normVersion 应为 \"v1\"(方案 §三 P0-5 做法①:normVersion=\"v1\","
+                            + "与 attribution_norm_values 唯一键 uk_type_code_band_gender_ver 对齐)。");
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-9:数据行唯一键(code+年龄段+性别+版本)不得重复(防幂等 upsert 覆盖)")
+    void normResource_uniqueKeyNoDuplicate() {
+        JsonNode rows = requireDataRows();
+        Set<String> seen = new HashSet<>();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String key = (textOf(row, "code") == null ? "<null>" : textOf(row, "code"))
+                    + "|" + textOf(row, "memberAgeBand")
+                    + "|" + textOf(row, "gender")
+                    + "|" + textOf(row, "normVersion");
+            assertTrue(seen.add(key),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据唯一键重复:" + key
+                            + "。attribution_norm_values 唯一键 uk_type_code_band_gender_ver 幂等 upsert"
+                            + " 会静默覆盖,重复行致数据丢失(importAttributionNormGutFlora ON DUPLICATE KEY UPDATE)。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:source 标注(§四决策3:样本回归估算,非官方 710 常模)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-10:每条数据 source 应标注「样本回归」(§四决策3 / P0-5)")
+    void normResource_eachRow_sourceAnnotatedSampleRegression() {
+        JsonNode rows = requireDataRows();
+        int idx = 0;
+        for (JsonNode row : rows) {
+            idx++;
+            String code = textOf(row, "code");
+            String source = textOf(row, "source");
+            assertTrue(source != null && source.contains(SOURCE_PHRASE_SAMPLE),
+                    "[health.attribution.normFill] 第 " + idx + " 条数据(code=" + code + ") source 应为空或未标注"
+                            + "「样本回归」。契约要求 source=\"谷禾样本回归\"(方案 §三 P0-5 做法① / §四决策3 推荐 A:"
+                            + "17 份样本回归估算,人群代表性有限,展示时必须写 source 字段)。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:导入管线(脚本生成 + 启动自动导入)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:导入脚本 scripts/import_norm_from_reports.py 应存在(方案 P0-5 做法①)")
+    void importScript_exists() {
+        assertTrue(fileExists(IMPORT_SCRIPT_NAME),
+                "[health.attribution.normFill] 导入脚本 scripts/" + IMPORT_SCRIPT_NAME + " 不存在。"
+                        + "契约要求新建该脚本:17 份样本(毛静明/吴介洋/廖某人/侯/547982403 等)→ "
+                        + "正常范围{min,max}→p5/p95、人群%水平→线性插值 p25/p50/p75 → 输出 data[]"
+                        + "(方案 §三 P0-5 做法①)。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:启动导入管线应保持可寻址(DatabaseInitializer.importAttributionNormGutFlora)")
+    void databaseInitializer_hasImportPipelineAddressable() {
+        Class<?> clazz = loadClass(DATABASE_INITIALIZER);
+        assertNotNull(clazz,
+                "[health.attribution.normFill] DatabaseInitializer 类不存在:" + DATABASE_INITIALIZER);
+        boolean hasImport = false;
+        for (java.lang.reflect.Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals("importAttributionNormGutFlora")) {
+                hasImport = true;
+                break;
+            }
+        }
+        assertTrue(hasImport,
+                "[health.attribution.normFill] DatabaseInitializer 应保留 importAttributionNormGutFlora()"
+                        + " 启动导入入口(方案 §三 P0-5 做法③:JSON 非空后首次启动自动灌入"
+                        + " attribution_norm_values,幂等 upsert)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 红线流:§八 8.3 归一化数据代表性(最重红线:样本 ≠ 官方 710 常模)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("红线流-1:文件应明示「样本回归…非官方 710 常模」(§八8.3,禁当官方常模)")
+    void redLine_sourceDisclaimsOfficial710() {
+        String raw = readRawNorm();
+        boolean disclaimed = raw.contains(SOURCE_PHRASE_SAMPLE) && raw.contains(SOURCE_PHRASE_NOT_OFFICIAL);
+        assertTrue(disclaimed,
+                "[health.attribution.normFill·§8.3红线] attribution_norm_gut_flora.json 未明示数据代表性限制:"
+                        + "应写清「样本回归估算,非官方 710 常模」(方案 §三 P0-5 做法④ / §四决策3 推荐 A:"
+                        + "首期归一化数据来自 17 份样本回归,非官方 710 常模,人群代表性有限)。"
+                        + "当前占位模板 note=\"真实710条待业务侧填充\" 无样本回归标注,存在被误读为官方常模的风险。");
+    }
+
+    @Test
+    @DisplayName("红线流-2:禁写「符合人群 xx%」等夸大人群代表性断言(§八8.3)")
+    void redLine_noCrowdPercentageClaim() {
+        String raw = readRawNorm();
+        assertFalse(raw.contains(FORBIDDEN_CROWD_CLAIM),
+                "[health.attribution.normFill·§8.3红线] 文件出现「" + FORBIDDEN_CROWD_CLAIM
+                        + "」断言:样本回归数据不代表人群总分布,禁止「符合人群 xx%」式表述"
+                        + "(方案 §八8.3;证据码 DEV 层,非 PUB 层,§5.7)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流(不适用):后台数据填充管线,无用户权限维度
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:本能力为后台归一化数据填充管线,无用户权限维度,权限流不适用")
+    void permissionFlow_notApplicable() {
+        // 说明性用例:契约 AC 为「脚本生成 → JSON 填充 → 启动自动导入」内部数据管线,无权限校验维度。
+        // 不产生断言失败;仅为三流覆盖标注「不适用」。
+        assertTrue(true, "权限流不适用:health.attribution.normFill 为内部归一化数据填充管线,无用户权限维度。");
+    }
+
+    // ------------------------------------------------------------------
+    // 辅助:JSON 读取 / 反射 / 文件探测
+    // ------------------------------------------------------------------
+
+    private JsonNode normJson() {
+        String raw = readRawNorm();
+        if (raw == null || raw.trim().isEmpty()) {
+            fail("[health.attribution.normFill] classpath 缺少 " + NORM_RESOURCE
+                    + "(契约基座,见正常流-1)。");
+        }
+        try {
+            return new ObjectMapper().readTree(raw);
+        } catch (Exception e) {
+            fail("[health.attribution.normFill] " + NORM_RESOURCE + " 不是合法 JSON:" + e.getMessage());
+            return null; // 不可达
+        }
+    }
+
+    private JsonNode requireDataRows() {
+        JsonNode data = normJson().path("data");
+        if (!data.isArray() || data.size() == 0) {
+            fail("[health.attribution.normFill] data[] 为空:无数据行可校验。"
+                    + "契约要求填充真实五百分位常模(预估 100+ 条,视去重,方案 §三 P0-5)。");
+        }
+        return data;
+    }
+
+    private String textOf(JsonNode node, String field) {
+        JsonNode v = node.get(field);
+        if (v == null || v.isNull()) {
+            return null;
+        }
+        return v.asText();
+    }
+
+    private String readRawNorm() {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream(NORM_RESOURCE)) {
+            if (is == null) {
+                return null;
+            }
+            try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
+                scanner.useDelimiter("\\A");
+                return scanner.hasNext() ? scanner.next() : "";
+            }
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** 探测导入脚本是否存在(容忍 Maven 模块 cwd 与仓库根 cwd 两种运行形态) */
+    private boolean fileExists(String scriptName) {
+        String[] candidates = {
+                "scripts/" + scriptName,
+                "../scripts/" + scriptName,
+                "src/main/resources/scripts/" + scriptName
+        };
+        for (String c : candidates) {
+            File f = new File(c);
+            if (f.isFile()) {
+                return true;
+            }
+        }
+        String userDir = System.getProperty("user.dir");
+        if (userDir != null) {
+            File f = new File(userDir, "../scripts/" + scriptName);
+            if (f.isFile()) {
+                return true;
+            }
+            File f2 = new File(userDir, "scripts/" + scriptName);
+            if (f2.isFile()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+}