Просмотр исходного кода

test(S-cfc-416): 新增 health.report.guheV2Schema 契约红测 (RED)

按方案 v1.0 §三 P0-4 + §五 DDL 写契约级单测:schema.sql 三表新列/新表/视图、DatabaseInitializer 迁移一致性、ParsedReportResult + 两个 DTO 字段。实测 9 跑 8 失败 0 错误(纯反射/资源读取,无 Spring/DB)。仅新增测试,不改 src/main。
Administrator 7 часов назад
Родитель
Сommit
d20f79f27c

+ 397 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/HealthReportGuheV2SchemaContractTest.java

@@ -0,0 +1,397 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+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.report.guheV2Schema})。
+ *
+ * <p><b>契约来源</b>(《浠艾福程序-谷禾新版解析与五维归因升级方案 v1.0》,提交 {@code ef8eb62be}
+ * 已合入 origin/cfclub 设计契约 v1.0;溯源 {@code SC-P-22 · 报告解析预览(菌群明细/疾病风险)}、
+ * {@code SC-P-23 · 报告确认入库},见 {@code tests/user-scenarios/应用场景总览.md}):
+ * <blockquote>
+ *   §三 P0-4「DTO 与表结构扩展」:把 guhe_v2 的关键字段从 payload 提出来,落到可查询的表里,供前端与归因引擎使用。
+ *   <ul>
+ *     <li>{@code health_reports}:{@code fb_ratio}(TEXT)、{@code shannon_index_norm}(分级文字)、
+ *         {@code subhealth_label}(亚健康标签)、{@code parse_self_check}(JSON,_解析自检);</li>
+ *     <li>{@code health_disease_risk}:{@code similarity_level}(TEXT,低/中/高相似);</li>
+ *     <li>{@code health_gut_flora}:{@code reference_range}(参考范围原文)、{@code direction}(▲/▼)、
+ *         {@code species_code}(拉丁名)、{@code functional_tag}(功能标签);</li>
+ *     <li>新表 {@code health_species_library}(76 条/份,知识层 + 个人层):
+ *         report_id / species_no / cn_name / latin_name / function_tag / detection_rate /
+ *         function_desc / improve_method / abundance / ref_range / status / direction;</li>
+ *     <li>新视图 {@code health_abnormal_species}:从 species_library 派生,{@code direction IS NOT NULL}(▲▼ 条目);</li>
+ *     <li>DTO {@code ParsedReportResult} 新增 {@code List<ParsedSpeciesLibrary> speciesLibrary} 与
+ *         {@code List<ParsedAbnormalSpecies> abnormalSpecies}(由 Python 解析结果反序列化)。</li>
+ *   </ul>
+ *   §五「表结构变更(DDL 草案)」:上述列 ALTER TABLE + 新表 CREATE TABLE + 视图 CREATE OR REPLACE VIEW。
+ * </blockquote></p>
+ *
+ * <p><b>实现现状(origin/cfclub 实测探测)</b>:本分支 src/main 中上述列名、两张新表/视图、
+ * 两个新 DTO 类均为 0 引用(schema.sql 无对应定义,DatabaseInitializer 无对应迁移,
+ * ParsedReportResult 仍只有旧版字段)。因此本测试以「DDL 资源结构 + 反射契约」探测实现缺失:
+ * 能编译通过、能运行、断言失败(红),且失败断言原文清晰可贴
+ * ({@code schema.sql} 资源读取 + {@code DatabaseInitializer} 源码读取 + 反射,
+ * <b>无 Spring / 无 DB / 无外部服务 / 无 Mockito</b>)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者按 P0-4 + §五 DDL 落地后,本测试自动转绿——
+ * <ol>
+ *   <li>schema.sql 三张表补齐新列、追加 health_species_library 建表与 health_abnormal_species 视图;</li>
+ *   <li>DatabaseInitializer.runMigrations() 增加对应幂等迁移(schema.sql ↔ 迁移一致原则);</li>
+ *   <li>ParsedReportResult 增加 speciesLibrary / abnormalSpecies 两个 List 字段,
+ *       并新增 ParsedSpeciesLibrary / ParsedAbnormalSpecies DTO(包路径不限,本测试按简单类名探测)。</li>
+ * </ol>
+ * 结构落点以 GREEN 时 src/main 实测为准(实现仅在 feature 分支,不得假定包路径)。</p>
+ *
+ * <p><b>权限流说明</b>:本能力为 DTO/表结构扩展(解析服务 → 结构化落库),无用户权限维度,
+ * 权限流不适用,以说明性用例标注。</p>
+ */
+class HealthReportGuheV2SchemaContractTest {
+
+    private static final String CAP = "health.report.guheV2Schema";
+
+    /** classpath 下的完整建表快照(稳定锚点) */
+    private static final String SCHEMA_RESOURCE = "schema.sql";
+
+    /** DDL 迁移唯一入口(AGENTS.md 固定路径) */
+    private static final String DB_INIT_SOURCE =
+            "src/main/java/com/etotem/cfc/config/DatabaseInitializer.java";
+
+    /** 已存在的解析结果 DTO(稳定锚点,GREEN 时向其追加两个 List 字段) */
+    private static final String PARSED_REPORT_RESULT = "com.etotem.cfc.dto.ParsedReportResult";
+
+    /** P0-4:health_reports 四个新列 */
+    private static final String[] HEALTH_REPORTS_COLUMNS = {
+            "fb_ratio", "shannon_index_norm", "subhealth_label", "parse_self_check"
+    };
+
+    /** P0-4:health_gut_flora 四个新列 */
+    private static final String[] HEALTH_GUT_FLORA_COLUMNS = {
+            "reference_range", "direction", "species_code", "functional_tag"
+    };
+
+    /** P0-4 / §五④:health_species_library 全量列 */
+    private static final String[] HEALTH_SPECIES_LIBRARY_COLUMNS = {
+            "report_id", "species_no", "cn_name", "latin_name", "function_tag",
+            "detection_rate", "function_desc", "improve_method", "abundance",
+            "ref_range", "status", "direction"
+    };
+
+    /** P0-4 / §五⑤:health_abnormal_species 视图列 */
+    private static final String[] HEALTH_ABNORMAL_SPECIES_COLUMNS = {
+            "report_id", "species_no", "cn_name", "latin_name", "abundance",
+            "ref_range", "direction", "category"
+    };
+
+    /** 迁移一致性检查锚点:{表名, 列/对象名}(§五 DDL 六项) */
+    private static final String[][] MIGRATION_ANCHORS = {
+            {"health_reports", "fb_ratio"},
+            {"health_reports", "shannon_index_norm"},
+            {"health_reports", "subhealth_label"},
+            {"health_reports", "parse_self_check"},
+            {"health_disease_risk", "similarity_level"},
+            {"health_gut_flora", "reference_range"},
+            {"health_gut_flora", "direction"},
+            {"health_gut_flora", "species_code"},
+            {"health_gut_flora", "functional_tag"},
+            {"health_species_library", "species_no"},
+            {"health_abnormal_species", "direction"}
+    };
+
+    /** DTO 契约:ParsedReportResult 应新增的两个 List 字段 */
+    private static final String[] DTO_LIST_FIELDS = {"speciesLibrary", "abnormalSpecies"};
+
+    // ------------------------------------------------------------------
+    // 正常流:schema.sql 三张表新列 + 新表 + 派生视图
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:schema.sql 的 health_reports 应含谷禾新版四列(fb_ratio/shannon_index_norm/subhealth_label/parse_self_check)")
+    void schemaSql_healthReports_hasGuheV2Columns() {
+        String block = createTableBlock(readSchemaSql(), "health_reports");
+        assertTrue(!block.isEmpty(),
+                "[" + CAP + "] schema.sql 缺少 health_reports 建表块(§五 DDL 草案①)。");
+        String missing = firstMissing(block, HEALTH_REPORTS_COLUMNS);
+        assertTrue(missing == null,
+                "[" + CAP + "] health_reports 缺少列 " + missing
+                        + ":契约要求 fb_ratio(TEXT)/shannon_index_norm(分级文字)/subhealth_label(亚健康标签)"
+                        + "/parse_self_check(JSON,_解析自检) 从 payload 提出落表(§三 P0-4 + §五 DDL①)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:schema.sql 的 health_gut_flora 应含参考范围/方向/拉丁名/功能标签四列")
+    void schemaSql_healthGutFlora_hasGuheV2Columns() {
+        String block = createTableBlock(readSchemaSql(), "health_gut_flora");
+        assertTrue(!block.isEmpty(),
+                "[" + CAP + "] schema.sql 缺少 health_gut_flora 建表块(§五 DDL 草案③)。");
+        String missing = firstMissing(block, HEALTH_GUT_FLORA_COLUMNS);
+        assertTrue(missing == null,
+                "[" + CAP + "] health_gut_flora 缺少列 " + missing
+                        + ":契约要求 reference_range(参考范围原文)/direction(▲/▼)/species_code(拉丁名)"
+                        + "/functional_tag(功能标签)(§三 P0-4 + §五 DDL③)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:health_disease_risk 应含 similarity_level(低/中/高相似)")
+    void schemaSql_healthDiseaseRisk_hasSimilarityLevel() {
+        // 该表当前由 DatabaseInitializer 建表(schema.sql 尚未收录其 CREATE TABLE),
+        // 故在「DDL 全表面」上探测列契约,避免把已有历史不同步误判为本次缺失。
+        String ddlSurface = readSchemaSql() + "\n" + readDbInitSource();
+        assertTrue(ddlSurface.contains("similarity_level"),
+                "[" + CAP + "] health_disease_risk 缺少 similarity_level 列:契约要求"
+                        + "疾病相似评估表[].status → similarity_level(TEXT,低/中/高相似)"
+                        + "(§三 P0-4 + §五 DDL②)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:schema.sql 应含新表 health_species_library(76 条/份物种功能库全量列)")
+    void schemaSql_hasHealthSpeciesLibraryTable() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("health_species_library"),
+                "[" + CAP + "] schema.sql 缺少 health_species_library 建表:契约要求存储"
+                        + "肠道菌群重要菌种 76 条全量(知识层 + 个人层,§三 P0-4 + §五 DDL④)。");
+        String block = createTableBlock(schema, "health_species_library");
+        assertTrue(!block.isEmpty(),
+                "[" + CAP + "] schema.sql 中 health_species_library 无有效 CREATE TABLE 块(§五 DDL④)。");
+        String missing = firstMissing(block, HEALTH_SPECIES_LIBRARY_COLUMNS);
+        assertTrue(missing == null,
+                "[" + CAP + "] health_species_library 缺少列 " + missing
+                        + ":契约要求 report_id/species_no/cn_name/latin_name/function_tag/"
+                        + "detection_rate/function_desc/improve_method/abundance/ref_range/status/direction"
+                        + "(§五 DDL④,76 条/份,含知识层 + 个人层)。");
+    }
+
+    @Test
+    @DisplayName("正常流-5:schema.sql 应含派生视图 health_abnormal_species(direction IS NOT NULL)")
+    void schemaSql_hasHealthAbnormalSpeciesView() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("health_abnormal_species"),
+                "[" + CAP + "] schema.sql 缺少 health_abnormal_species 视图:契约要求"
+                        + "从 health_species_library 派生 ▲▼ 异常菌清单(§三 P0-4 + §五 DDL⑤,SC-P-22 疾病风险/菌种明细预览)。");
+        assertTrue(schema.contains("direction IS NOT NULL"),
+                "[" + CAP + "] health_abnormal_species 视图缺少 direction IS NOT NULL 过滤:"
+                        + "契约要求仅收录 ▲▼ 条目(§五 DDL⑤);无过滤会把全部 76 条菌都当异常菌展示。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:DDL 迁移一致性(schema.sql ↔ DatabaseInitializer,AGENTS 迁移一致原则)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:DatabaseInitializer 应为 §五 DDL 六项提供幂等迁移")
+    void databaseInitializer_hasGuheV2SchemaMigrations() {
+        String source = readDbInitSource();
+        assertTrue(!source.isEmpty(),
+                "[" + CAP + "] 无法读取 DatabaseInitializer 源码:" + DB_INIT_SOURCE);
+        for (String[] anchor : MIGRATION_ANCHORS) {
+            assertTrue(migrationMentions(source, anchor[0], anchor[1]),
+                    "[" + CAP + "] DatabaseInitializer 缺少 " + anchor[0] + "." + anchor[1]
+                            + " 的迁移:AGENTS 迁移一致原则要求 schema.sql 的每条 DDL"
+                            + "在 DatabaseInitializer.runMigrations() 有对应幂等迁移(§五 DDL)。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:DTO 反序列化契约(ParsedReportResult + 两个新 DTO 类,包路径不限)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-6:ParsedReportResult 应新增 speciesLibrary / abnormalSpecies 两个 List 字段")
+    void parsedReportResult_hasSpeciesDTOFields() {
+        Class<?> clazz = loadClass(PARSED_REPORT_RESULT);
+        assertNotNull(clazz,
+                "[" + CAP + "] " + PARSED_REPORT_RESULT + " 类不存在,无法承载物种明细 DTO(§三 P0-4)。");
+        for (String field : DTO_LIST_FIELDS) {
+            assertTrue(hasDeclaredField(clazz, field),
+                    "[" + CAP + "] " + clazz.getSimpleName() + " 缺少 " + field
+                            + " 字段:契约要求 List<ParsedSpeciesLibrary> speciesLibrary 与"
+                            + " List<ParsedAbnormalSpecies> abnormalSpecies(由 Python 解析结果反序列化,§三 P0-4)。"
+                            + " 当前仍只有旧版列表字段(diseaseRisks/gutFlora/probioticSpecies)。");
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-7:ParsedSpeciesLibrary / ParsedAbnormalSpecies DTO 类应存在并含核心字段")
+    void parsedSpeciesDtos_existWithCoreFields() {
+        Class<?> library = findClassBySimpleName("ParsedSpeciesLibrary");
+        assertNotNull(library,
+                "[" + CAP + "] ParsedSpeciesLibrary DTO 类不存在:契约要求承载"
+                        + "76 条物种功能库明细(reportId/speciesNo/cnName/latinName/direction 等,§三 P0-4)。");
+        Class<?> abnormal = findClassBySimpleName("ParsedAbnormalSpecies");
+        assertNotNull(abnormal,
+                "[" + CAP + "] ParsedAbnormalSpecies DTO 类不存在:契约要求承载"
+                        + "▲▼ 异常菌清单(reportId/speciesNo/cnName/latinName/direction/category,§三 P0-4)。");
+        for (String field : new String[]{"speciesNo", "cnName", "latinName", "direction"}) {
+            assertTrue(hasDeclaredField(library, field),
+                    "[" + CAP + "] ParsedSpeciesLibrary 缺少核心字段 " + field + "(§三 P0-4 物种明细契约)。");
+            assertTrue(hasDeclaredField(abnormal, field),
+                    "[" + CAP + "] ParsedAbnormalSpecies 缺少核心字段 " + field + "(§三 P0-4 异常菌清单契约)。");
+        }
+        assertTrue(hasDeclaredField(abnormal, "category"),
+                "[" + CAP + "] ParsedAbnormalSpecies 缺少 category 字段(异常菌分类,§三 P0-4)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流(不适用):DTO/表结构扩展,无用户权限维度
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:本能力为 DTO/表结构扩展,无用户权限维度,权限流不适用")
+    void permissionFlow_notApplicable() {
+        // 说明性用例:契约 AC 为「解析结果 → 结构化落表 → 前端/归因引擎查询」,无权限校验维度。
+        assertTrue(true, "权限流不适用:" + CAP + " 为 DTO/表结构扩展,无用户权限维度。");
+    }
+
+    // ------------------------------------------------------------------
+    // 辅助:资源读取 / 结构提取 / 反射(均手工推导期望,不复用被测代码)
+    // ------------------------------------------------------------------
+
+    private String readSchemaSql() {
+        return readResource(SCHEMA_RESOURCE);
+    }
+
+    private String readDbInitSource() {
+        // mvn test 工作目录为模块根(cfc-backend),相对路径可直接读取;失败则回退 classpath。
+        try {
+            return new String(Files.readAllBytes(Paths.get(DB_INIT_SOURCE)), StandardCharsets.UTF_8);
+        } catch (Exception e) {
+            return readResource("DatabaseInitializer.java");
+        }
+    }
+
+    private String readResource(String name) {
+        try (InputStream is = getClass().getClassLoader().getResourceAsStream(name)) {
+            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 "";
+        }
+    }
+
+    /** 提取 CREATE TABLE 语句块(兼容 IF NOT EXISTS 与反引号,截止到下一个 CREATE TABLE 前)。 */
+    private String createTableBlock(String schema, String table) {
+        Pattern p = Pattern.compile(
+                "CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?`?" + Pattern.quote(table)
+                        + "`?\\s*\\(", Pattern.CASE_INSENSITIVE);
+        Matcher m = p.matcher(schema);
+        if (!m.find()) {
+            return "";
+        }
+        int nextCreate = schema.indexOf("CREATE TABLE", m.end());
+        if (nextCreate < 0) {
+            nextCreate = schema.length();
+        }
+        String segment = schema.substring(m.start(), nextCreate);
+        int end = segment.indexOf(");");
+        if (end < 0) {
+            end = segment.indexOf(") ENGINE");
+        }
+        if (end < 0) {
+            end = segment.length() - 1;
+        }
+        return segment.substring(0, end + 1);
+    }
+
+    private String firstMissing(String block, String[] columns) {
+        for (String column : columns) {
+            if (!block.contains(column)) {
+                return column;
+            }
+        }
+        return null;
+    }
+
+    /** 迁移存在性:表名与列/对象名须在源码中相邻出现(容忍 ensureColumn / ALTER TABLE 两种写法)。 */
+    private boolean migrationMentions(String source, String table, String token) {
+        int from = 0;
+        while (from < source.length()) {
+            int idx = source.indexOf(table, from);
+            if (idx < 0) {
+                return false;
+            }
+            int end = Math.min(source.length(), idx + 240);
+            if (source.substring(idx, end).contains(token)) {
+                return true;
+            }
+            from = idx + table.length();
+        }
+        return false;
+    }
+
+    private boolean hasDeclaredField(Class<?> clazz, String name) {
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getName().equals(name)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    /** 按简单类名在 src/main/java 下定位源码并推导 FQCN(不假定包路径,兼容 mvn 模块根 cwd)。 */
+    private Class<?> findClassBySimpleName(String simpleName) {
+        List<Path> found = new ArrayList<Path>();
+        String[] roots = {
+                "src/main/java", "../src/main/java",
+                Paths.get(System.getProperty("user.dir", "."), "src", "main", "java").toString()
+        };
+        for (String rootStr : roots) {
+            Path root = Paths.get(rootStr);
+            if (!Files.isDirectory(root)) {
+                continue;
+            }
+            try (Stream<Path> paths = Files.walk(root)) {
+                paths.filter(p -> p.getFileName().toString().equals(simpleName + ".java"))
+                        .forEach(found::add);
+            } catch (Exception ignored) {
+                // 继续尝试下一个候选根
+            }
+            if (!found.isEmpty()) {
+                break;
+            }
+        }
+        if (found.isEmpty()) {
+            return null;
+        }
+        Path file = found.get(0);
+        Path javaRoot = file;
+        while (javaRoot != null && !"java".equals(javaRoot.getFileName().toString())) {
+            javaRoot = javaRoot.getParent();
+        }
+        if (javaRoot == null) {
+            return null;
+        }
+        String rel = javaRoot.relativize(file).toString().replace('\\', '/');
+        String fqcn = rel.substring(0, rel.length() - ".java".length()).replace('/', '.');
+        return loadClass(fqcn);
+    }
+}