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

Merge task/S-cfc-415: S-cfc-415 契约级RED单测 谷禾新版解析P0-3 (health.report.guheV2Parse)

E2E Test Bot 8 часов назад
Родитель
Сommit
f9757a4774

+ 346 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/GuheV2ParseContractTest.java

@@ -0,0 +1,346 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 契约级单测:guhe_v2 新版报告「Python 主路径解析接入」(能力键 {@code health.report.guheV2Parse},P0-3)。
+ *
+ * <p><b>契约来源</b>(《浠艾福线上程序·谷禾新版解析与五维归因升级方案》v1.0 §三 P0-3,ef8eb62be 已合入
+ * origin/cfclub 设计契约 v1.0;需求溯源 SC-P-20 健康报告 PDF 上传解析 / SC-P-22 报告解析预览):
+ * <blockquote>
+ *   P0-3 Python 侧接入 bun-report-parser v1.3.1:langgraph 的 {@code report_parse_agent} 在
+ *   {@code reportFormatHint="guhe_v2"} 时调用 {@code extract_guhe_v2};
+ *   返回 JSON <b>直接作为 {@code payload_json} 落库</b>(保持与 bun-report-parser 输出一致);
+ *   {@code _解析自检} 字段透传({@code 通过} / {@code P0告警数} / {@code P1提示数} / {@code 告警})
+ *   落进 {@code health_report_drafts.collect_validation}(JSON 字符串),并暴露到
+ *   {@code POST /api/health/report/collect/status} 接口响应里;
+ *   <b>关键决策:保留完整 payload(35 键),不裁剪</b>。
+ * </blockquote></p>
+ *
+ * <p><b>平台现状(src/main 探测,C 档 Adapter / 转发形态)</b>:谷禾新版解析以 Python(langgraph)为主路径,
+ * Java 只做「识别 + 转发 + 回填」,本次契约关注 Java 侧转发/回填的可观测落点:
+ * <ul>
+ *   <li>{@code LangGraphReportParseService}(异步采集转发层):仅 {@code file_path} + {@code indicators}
+ *       请求体,<b>无 {@code reportFormatHint} 字段</b>,无法路由到 guhe_v2 专用提取器(P0-2 转发缺口);</li>
+ *   <li>{@code ReportCollectService#runCollectValidation}(采集回填层):collect_validation 仅写
+ *       {@code typeId/expected/matched/pass/missing},<b>无 {@code _解析自检} 四子键透传</b>(P0-3 ③缺口);</li>
+ *   <li>{@code HealthReportController#collectStatus}(用户端轮询响应):仅 draftId/parseStatus/parseMethod/
+ *       parseError/reportId/reportType,<b>未暴露 collect_validation</b>(P0-3 ③暴露缺口;
+ *       {@code collectValidation} 目前仅在管理端 ReportParseAdminController 出);</li>
+ *   <li>{@code ParsedReportPayload} / {@code ParsedReportResult}:无「35 键完整 payload 保留」边界声明
+ *       (P0-3 关键决策缺口;ParsedReportResult 已有 21/32 键口径,但那是格式识别口径,非 35 键 payload 口径)。</li>
+ * </ul>
+ * 全库(src/main)无 {@code reportFormatHint} / {@code _解析自检} / {@code P0告警数} / {@code P1提示数}——
+ * 本能力<b>实现未落地</b>。因此本测试以「反射结构契约」探测契约所需标记缺失:能编译、能运行、
+ * 断言失败(红),失败断言原文清晰可贴。</p>
+ *
+ * <p><b>GREEN 升级指引</b>(P0-3 实现落地后本测试自动转绿;{@code app/parsers/guhe_v2} 子包形态
+ * 以实现时探测为准,本测试不假定 Python 包路径)——
+ * <ol>
+ *   <li>{@code LangGraphReportParseService} 暴露 {@code reportFormatHint} 转发字段(静态 String 常量
+ *       值含 {@code "reportFormatHint"} / {@code "guhe_v2"},或方法名含 FormatHint),使 guhe_v2 报告
+ *       解析请求携带格式提示,Python 侧按 {@code reportFormatHint="guhe_v2"} 路由到 {@code extract_guhe_v2};</li>
+ *   <li>采集回填层({@code ReportCollectService} / {@code HealthReportDraftService})声明 {@code _解析自检}
+ *       四子键锚点(静态 String 常量值含 {@code "通过"} / {@code "P0告警数"} / {@code "P1提示数"} / {@code "告警"},
+ *       或以集合常量声明四键),解析结果中的自检信息透传并入 collect_validation JSON;</li>
+ *   <li>{@code HealthReportController} 在 <b>collect/status</b> 响应中暴露 collect_validation
+ *       (静态 String 常量值含 {@code "collect_validation"} / {@code "collectValidation"} 或
+ *       extract 方法名含 Validation),前端可核对 {@code _解析自检} 结果;</li>
+ *   <li>声明 <b>35 键完整 payload 保留</b>边界(静态 int 常量名含 GUHE_V2/PAYLOAD 且值 35,
+ *       或静态 String 键集常量 size=35),保证解析 JSON 不裁剪直接落 {@code payload_json}。</li>
+ * </ol>
+ * 届时可将结构探测升级为行为级验证(mock 转发服务断言 request body 含 reportFormatHint;assert collect/status
+ * 响应含 collect_validation)。</p>
+ *
+ * <p><b>权限流说明</b>:本能力为「上传 → 识别 guhe_v2 → 转发 langgraph → 回填自检」的内部解析管道,
+ * 无用户权限维度,「权限(适用时)」三流中的权限流不适用,以说明性用例标注。</p>
+ */
+class GuheV2ParseContractTest {
+
+    /** 能力键:health.report.guheV2Parse(谷禾方案 v1.0 §三 P0-3) */
+    private static final String CAP_KEY = "health.report.guheV2Parse";
+
+    /** P0-3 关键决策:保留完整 payload(35 键),不裁剪 */
+    private static final int GUHE_V2_FULL_PAYLOAD_KEYS_35 = 35;
+
+    // ------------------------------------------------------------------
+    // 挂载层类(src/main 现状探测;实现者在其上落地 P0-3 转发/回填/透传)
+    // ------------------------------------------------------------------
+
+    private static final String LANGGRAPH_PARSE_SERVICE = "com.etotem.cfc.service.LangGraphReportParseService";
+    private static final String REPORT_COLLECT_SERVICE = "com.etotem.cfc.service.ReportCollectService";
+    private static final String DRAFT_SERVICE = "com.etotem.cfc.service.HealthReportDraftService";
+    private static final String HEALTH_REPORT_CONTROLLER = "com.etotem.cfc.controller.HealthReportController";
+    private static final String PARSED_REPORT_PAYLOAD = "com.etotem.cfc.dto.ParsedReportPayload";
+    private static final String PARSED_REPORT_RESULT = "com.etotem.cfc.dto.ParsedReportResult";
+
+    // ------------------------------------------------------------------
+    // 正常流:reportFormatHint 转发字段(P0-2 转发 / P0-3 路由前提)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:LangGraphReportParseService 应暴露 reportFormatHint 转发字段(guhe_v2 路由前提)")
+    void langGraphParseService_exposesFormatHintField() {
+        Class<?> clazz = loadClass(LANGGRAPH_PARSE_SERVICE);
+        if (clazz == null) {
+            fail("[" + CAP_KEY + "] LangGraphReportParseService 类不存在(P0-3 异步采集转发层),"
+                    + "无法验证 reportFormatHint 转发字段。");
+        }
+        boolean hasHint = hasStringConstantContaining(clazz, "reportFormatHint")
+                || hasStringConstantContaining(clazz, "guhe_v2")
+                || hasMethodNamedLike(clazz, "formathint");
+        assertTrue(hasHint,
+                "[" + CAP_KEY + "] LangGraphReportParseService 应暴露 reportFormatHint 转发字段"
+                        + "(静态 String 常量值含 \"reportFormatHint\" / \"guhe_v2\",或方法名含 FormatHint),"
+                        + "使 guhe_v2 报告解析请求携带格式提示,Python 侧按 reportFormatHint=\"guhe_v2\" "
+                        + "路由到 extract_guhe_v2(P0-2 转发 / P0-3 路由前提,方案 §三 P0-2 ② P0-3 ②)。"
+                        + "当前请求体仅 file_path + indicators,无格式提示,32 键 guhe_v2 报告无法被"
+                        + " Python 主路径识别解析。");
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:_解析自检 四子键透传(P0-3 ③ 落 collect_validation)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-2:采集回填层应声明 _解析自检 四子键锚点(通过/P0告警数/P1提示数/告警)")
+    void collectLayer_exposesParseSelfCheckKeys() {
+        String[] keys = {"通过", "P0告警数", "P1提示数", "告警"};
+        for (String key : keys) {
+            boolean addressed = false;
+            for (String clazzName : new String[]{REPORT_COLLECT_SERVICE, DRAFT_SERVICE}) {
+                Class<?> clazz = loadClass(clazzName);
+                if (clazz != null && hasStringConstantContaining(clazz, key)) {
+                    addressed = true;
+                    break;
+                }
+            }
+            assertTrue(addressed,
+                    "[" + CAP_KEY + "] 采集回填层(ReportCollectService / HealthReportDraftService)"
+                            + " 应声明 _解析自检 子键「" + key + "」锚点(静态 String 常量值含之,P0-3 ③),"
+                            + "把 guhe_v2 解析结果中的自检信息透传并入 health_report_drafts.collect_validation(JSON)。"
+                            + "当前 collect_validation 仅写 typeId/expected/matched/pass/missing,自检四子键未透传。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:collect/status 响应暴露 collect_validation(P0-3 ③ 暴露出口)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-3:HealthReportController 的 collect/status 应暴露 collect_validation(_解析自检 出口)")
+    void healthReportController_collectStatusExposesValidation() {
+        Class<?> clazz = loadClass(HEALTH_REPORT_CONTROLLER);
+        if (clazz == null) {
+            fail("[" + CAP_KEY + "] HealthReportController 类不存在(P0-3 ③ collect/status 暴露落点)。");
+        }
+        boolean exposed = hasStringConstantContaining(clazz, "collect_validation")
+                || hasStringConstantContaining(clazz, "collectValidation")
+                || hasMethodNamedLike(clazz, "attachvalidation")
+                || hasMethodNamedLike(clazz, "exposevalidation");
+        assertTrue(exposed,
+                "[" + CAP_KEY + "] HealthReportController 的 POST /api/health/report/collect/status 响应"
+                        + " 应暴露 collect_validation(静态 String 常量值含 \"collect_validation\" / "
+                        + "\"collectValidation\",或 attach/expose Validation 方法),"
+                        + "使前端轮询时能核对 _解析自检 结果(P0-3 ③「暴露到 collect/status 接口响应里」)。"
+                        + "当前用户端 collectStatus 响应仅 draftId/parseStatus/parseMethod/parseError/"
+                        + "reportId/reportType,collectValidation 仅在管理端 ReportParseAdminController 出,"
+                        + "用户端无法看到 _解析自检 透传结果。");
+    }
+
+    // ------------------------------------------------------------------
+    // 结构契约:挂载层类应存在(GREEN 锚点;说明性稳定绿)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("结构契约:P0-3 Java 转发/回填挂载类应存在(GREEN 时在其上落地)")
+    void mountClassesExist() {
+        String[] classes = {
+                LANGGRAPH_PARSE_SERVICE, REPORT_COLLECT_SERVICE,
+                DRAFT_SERVICE, HEALTH_REPORT_CONTROLLER,
+                PARSED_REPORT_PAYLOAD, PARSED_REPORT_RESULT
+        };
+        for (String cn : classes) {
+            assertTrue(loadClass(cn) != null,
+                    "[" + CAP_KEY + "] P0-3 挂载类不存在:" + cn
+                            + "(Java 转发/回填落点;若平台已重构,请按当前实现更新本探测)。");
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:35 键完整 payload 保留(P0-3 关键决策,不裁剪)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:P0-3 应声明 35 键完整 payload 保留边界(不裁剪直接落 payload_json)")
+    void fullPayloadPreservedDeclares35Keys() {
+        boolean has35 = false;
+        for (String clazzName : new String[]{PARSED_REPORT_PAYLOAD, PARSED_REPORT_RESULT, LANGGRAPH_PARSE_SERVICE}) {
+            Class<?> clazz = loadClass(clazzName);
+            if (clazz == null) continue;
+            if (hasIntConstantNamedLike(clazz, "RAW", GUHE_V2_FULL_PAYLOAD_KEYS_35)
+                    || hasIntConstantNamedLike(clazz, "PAYLOAD", GUHE_V2_FULL_PAYLOAD_KEYS_35)
+                    || hasIntConstantNamedLike(clazz, "GUHE_V2", GUHE_V2_FULL_PAYLOAD_KEYS_35)) {
+                has35 = true;
+                break;
+            }
+            if (hasKeyCollectionOfSize(clazz, GUHE_V2_FULL_PAYLOAD_KEYS_35)) {
+                has35 = true;
+                break;
+            }
+        }
+        assertTrue(has35,
+                "[" + CAP_KEY + "] P0-3 应声明 35 键完整 payload 保留边界"
+                        + "(静态 int 常量名含 RAW/PAYLOAD/GUHE_V2 且值 35,或静态 String 键集常量 size=35),"
+                        + "保证 guhe_v2 解析返回的完整 payload 直接作为 payload_json 落库、不裁剪"
+                        + "(P0-3 关键决策:保留完整 payload(35 键)——后续归因引擎 / 健康计划 / 前端展示"
+                        + " 都从 payload 取,避免每加一个功能就重解析 PDF)。当前无 35 键边界声明,"
+                        + "payload 完整性无法校验。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:guhe_v2 判定链中的 Python 主路径路由语义(P0-3 ②)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-2:转发层应寻址 guhe_v2 专用提取器(extract_guhe_v2 路由语义)")
+    void forwardLayer_addressesGuheV2Extractor() {
+        Class<?> clazz = loadClass(LANGGRAPH_PARSE_SERVICE);
+        if (clazz == null) {
+            fail("[" + CAP_KEY + "] LangGraphReportParseService 类不存在(P0-3 转发层)。");
+        }
+        boolean addressed = hasStringConstantContaining(clazz, "reportFormatHint")
+                || hasStringConstantContaining(clazz, "guhe_v2")
+                || hasStringConstantContaining(clazz, "extract_guhe_v2");
+        assertTrue(addressed,
+                "[" + CAP_KEY + "] 转发层(LangGraphReportParseService)应寻址 guhe_v2 解析路由锚点"
+                        + "(静态 String 常量值含 \"reportFormatHint\" / \"guhe_v2\" / \"extract_guhe_v2\"),"
+                        + "使 Python 侧 report_parse_agent 在 reportFormatHint=\"guhe_v2\" 时调用 "
+                        + "bun-report-parser 的 extract_guhe_v2(P0-3 ②)。当前转发层无 guhe_v2 路由锚点,"
+                        + "32 键新版报告无法进入 Python 主路径专用提取器。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流(不适用):内部解析管道,无用户权限维度
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:本能力为内部解析管道(上传→识别→转发→回填自检),无用户权限维度,权限流不适用")
+    void permissionFlow_notApplicable() {
+        // 说明性用例:契约 AC 为「guhe_v2 识别 → reportFormatHint 转发 → _解析自检 回填」内部管道,
+        // 不产生断言失败;仅为三流覆盖标注「不适用」。
+        assertTrue(true, "权限流不适用:" + CAP_KEY + " 为内部解析/转发/回填管道,无用户权限维度。");
+    }
+
+    // ------------------------------------------------------------------
+    // 反射辅助
+    // ------------------------------------------------------------------
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    /** 是否存在静态 String 常量值包含 target(转发字段/自检子键/暴露键探针) */
+    private boolean hasStringConstantContaining(Class<?> clazz, String target) {
+        if (clazz == null) return false;
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType() != String.class) continue;
+            if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) continue;
+            try {
+                f.setAccessible(true);
+                Object v = f.get(null);
+                if (v instanceof String && ((String) v).contains(target)) return true;
+            } catch (Exception ignored) {
+                // 常量读取失败 → 跳过
+            }
+        }
+        return false;
+    }
+
+    /** 是否存在静态 int 常量名含 fragment 且值等于 target(35 键 payload 探针) */
+    private boolean hasIntConstantNamedLike(Class<?> clazz, String fragment, int target) {
+        if (clazz == null) return false;
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType() != int.class && f.getType() != Integer.class) continue;
+            if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) continue;
+            if (!f.getName().toUpperCase().contains(fragment.toUpperCase())) continue;
+            try {
+                f.setAccessible(true);
+                Object v = f.get(null);
+                if (v instanceof Integer && ((Integer) v) == target) return true;
+            } catch (Exception ignored) {
+                // 常量读取失败 → 跳过
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 是否存在静态「键集合」常量(List/Set/String[] 等,元素为 String)长度为 size 且
+     * 字段名(忽略大小写)含 KEY/KEYS/PAYLOAD —— 完整 payload 键集探针。
+     */
+    private boolean hasKeyCollectionOfSize(Class<?> clazz, int size) {
+        if (clazz == null) return false;
+        for (Field f : clazz.getDeclaredFields()) {
+            if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) continue;
+            Class<?> type = f.getType();
+            boolean isCollection = Collection.class.isAssignableFrom(type)
+                    || Set.class.isAssignableFrom(type)
+                    || List.class.isAssignableFrom(type)
+                    || type.isArray();
+            if (!isCollection) continue;
+            String name = f.getName().toLowerCase();
+            if (!name.contains("key") && !name.contains("payload")) continue;
+            try {
+                f.setAccessible(true);
+                Object v = f.get(null);
+                if (v == null) continue;
+                int len = v instanceof Collection
+                        ? ((Collection<?>) v).size()
+                        : (v.getClass().isArray() ? java.lang.reflect.Array.getLength(v) : -1);
+                if (len != size) continue;
+                if (v instanceof Collection) {
+                    boolean allString = true;
+                    for (Object o : (Collection<?>) v) {
+                        if (o != null && !(o instanceof String)) {
+                            allString = false;
+                            break;
+                        }
+                    }
+                    if (allString) return true;
+                } else if (v.getClass().getComponentType() == String.class) {
+                    return true;
+                }
+            } catch (Exception ignored) {
+                // 常量读取失败 → 跳过
+            }
+        }
+        return false;
+    }
+
+    /** 是否存在方法名(忽略大小写)包含 fragment(转发/暴露入口探针) */
+    private boolean hasMethodNamedLike(Class<?> clazz, String fragment) {
+        if (clazz == null) return false;
+        String needle = fragment.toLowerCase();
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().toLowerCase().contains(needle)) return true;
+        }
+        return false;
+    }
+}