Prechádzať zdrojové kódy

Merge task/S-cfc-422: RED contract test for health.ops.parseMonitor

E2E Test Bot 2 dní pred
rodič
commit
e2ddd9003f

+ 401 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/ParseMonitorContractTest.java

@@ -0,0 +1,401 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.nio.charset.StandardCharsets;
+import java.util.Scanner;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * 契约级单测:健康报告解析运营与监控看板(能力键 {@code health.ops.parseMonitor})。
+ *
+ * <p><b>契约来源</b>(浠艾福程序-谷禾新版解析与五维归因升级方案 v1.0,ef8eb62be 已合入):
+ * <blockquote>
+ *   §三 P2 运营与监控(可独立推进):
+ *   <ul>
+ *     <li>{@code _解析自检} 落库后建看板:<b>{@code P0 命中率}</b>、<b>{@code P1 Top 5}</b>
+ *         ({@code 健康问题索引} 摘录切头 / PAGEBREAK 残留 / ND 语义未区分 / 状态词缺失 / 索引切头),
+ *         用于后续版本迭代;</li>
+ *     <li>解析耗时监控:170 页大报告单次约 4–5 分钟({@code bun-report-parser} 实测),异步队列要有超时与重试
+ *         ({@code health_report_drafts.next_retry_at} <b>已有</b>,勿重复建);</li>
+ *     <li>上游同步机制:{@code bun-report-parser} 每次 minor/major 升级(v1.3.2 / v1.4 / v1.5 …)需评估同步到
+ *         langgraph 子包,建立 changelog 订阅。</li>
+ *   </ul>
+ * </blockquote>
+ * §八 8.5 上游同步:{@code bun-report-parser} 后续升级需评估同步到 langgraph 子包;建议建立 changelog 订阅或 submodule。</p>
+ *
+ * <p><b>场景溯源</b>:{@code tests/user-scenarios/应用场景总览.md} SC-A-01(管理端登录+全局统计)、
+ * SC-A-02(报告解析中台——维护解析能力:类型/聚类/自学习标注)。监控看板为管理端能力(SC-A-02)。</p>
+ *
+ * <p><b>实现现状(src/main 探测)</b>:本分支(origin/cfclub)无 {@code ParseMonitor} / {@code 命中率} /
+ * {@code p1Top5} / {@code bun-report-parser} 字符串,无解析监控服务类与看板指标入口——本能力
+ * <b>实现未落地</b>。因此本测试以「反射结构契约」探测契约所需监控载体缺失:能编译、能运行、
+ * 断言失败(红),失败断言原文清晰可贴。</p>
+ *
+ * <p><b>既有基建(勿重复建)</b>:{@code health_report_drafts.collect_validation}(采集校验 JSON)与
+ * {@code next_retry_at}(指数退避重试)已在 schema.sql(迁移 354 / 既有迁移)落地,本测试只断言其
+ * 「已存在、被监控复用」作为基线(绿),<b>不</b>要求新建;RED 断言聚焦看板/指标/上游同步的缺失。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者落地解析监控看板后本测试自动转绿——建立解析监控服务
+ * (候选类见 {@link #MONITOR_SERVICES},不限定包路径),暴露看板入口方法(名含
+ * {@code overview}/{@code dashboard}/{@code metrics}/{@code summary})与指标:
+ * <ol>
+ *   <li>{@code P0 命中率}(方法名含 {@code p0} 且 {@code hit/rate/命中},或常量名含 {@code P0_HIT_RATE});</li>
+ *   <li>{@code P1 Top 5}(方法名含 {@code p1} 且 {@code top5/topFive},或常量名含 {@code P1_TOP5});</li>
+ *   <li>P1 Top 5 五类问题锚点(摘录切头 / PAGEBREAK 残留 / ND 语义未区分 / 状态词缺失 / 索引切头);</li>
+ *   <li>解析耗时监控(方法名含 {@code duration/elapsed/耗时});</li>
+ *   <li>上游同步 {@code bun-report-parser} changelog 订阅/submodule 锚点(常量值含 {@code bun-report-parser})。</li>
+ * </ol>
+ * 届时可将结构探测升级为行为级 mock 验证(看板聚合 {@code collect_validation} 的 P0 命中率与 P1 Top 5)。</p>
+ *
+ * <p><b>权限流说明</b>:SC-A-02 为管理端能力,监控看板端点应做 admin 角色校验(控制器内
+ * {@code @RequestAttribute("role")} + {@code "admin"} 检查);当前无看板端点,权限流断言失败(红)。</p>
+ */
+class ParseMonitorContractTest {
+
+    // ------------------------------------------------------------------
+    // 契约锚点(§三 P2 运营与监控 / §八 8.5 上游同步)
+    // ------------------------------------------------------------------
+
+    /** 解析监控服务候选类(实现未落地,GREEN 时在此落地其一;不限定包路径) */
+    private static final String[] MONITOR_SERVICES = {
+            "com.etotem.cfc.service.ParseMonitorService",
+            "com.etotem.cfc.service.ReportParseMonitorService",
+            "com.etotem.cfc.service.HealthParseMonitorService",
+            "com.etotem.cfc.service.ReportParserMonitorService",
+            "com.etotem.cfc.service.ReportParserDashboardService",
+            "com.etotem.cfc.service.ParseDashboardService",
+            "com.etotem.cfc.service.ReportParseMetricService"
+    };
+
+    /** 解析监控看板控制器候选类(管理端能力 SC-A-02) */
+    private static final String[] MONITOR_CONTROLLERS = {
+            "com.etotem.cfc.controller.admin.ParseMonitorController",
+            "com.etotem.cfc.controller.admin.ReportParseMonitorController",
+            "com.etotem.cfc.controller.admin.ReportParserMonitorController",
+            "com.etotem.cfc.controller.admin.ReportParserDashboardController",
+            "com.etotem.cfc.controller.admin.HealthReportMonitorController"
+    };
+
+    /** 既有挂载类(feature 分支可在其上追加监控锚点,探测时一并扫描) */
+    private static final String[] EXISTING_MOUNTS = {
+            "com.etotem.cfc.service.ReportParserDispatchService",
+            "com.etotem.cfc.service.ReportCollectService",
+            "com.etotem.cfc.controller.admin.ReportParserAdminController",
+            "com.etotem.cfc.controller.HealthReportController"
+    };
+
+    /** P1 Top 5 五类问题锚点(§三 P2:健康问题索引摘录切头 / PAGEBREAK 残留 / ND 语义未区分 / 状态词缺失 / 索引切头) */
+    private static final String[] P1_TOP5_CATEGORIES = {
+            "摘录切头",       // 健康问题索引 摘录切头
+            "PAGEBREAK",      // PAGEBREAK 残留(大小写不敏感)
+            "语义未区分",      // ND 语义未区分
+            "状态词缺失",      // 状态词缺失
+            "索引切头"        // 索引切头
+    };
+
+    /** 上游同步机制(§八 8.5):bun-report-parser changelog 订阅 / submodule 锚点 */
+    private static final String UPSTREAM_PARSER = "bun-report-parser";
+
+    // ------------------------------------------------------------------
+    // 正常流:解析监控看板载体(服务 + 看板入口 + P0 命中率 + P1 Top 5)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:解析监控服务类应存在(§三 P2 看板载体)")
+    void monitorService_classExists() {
+        assertTrue(findLoadable(MONITOR_SERVICES) != null,
+                "[health.ops.parseMonitor] 解析监控服务类不存在(候选:"
+                        + String.join(" / ", MONITOR_SERVICES)
+                        + "):契约 §三 P2 要求 _解析自检 落库后建看板,需监控服务载体。"
+                        + " 当前 src/main 无解析监控类,实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:监控服务应暴露看板入口(overview/dashboard/metrics/summary)")
+    void monitorService_exposesDashboardEntry() {
+        // 仅探测解析监控服务候选类(MONITOR_SERVICES),不扫既有挂载类:既有 HealthReportController
+        // 已含 getBodyFatMetrics/getDeficiencySummary/getFamilyFoodOverview 等 overview/summary/metrics
+        // 方法,扫描会误绿,须限定在监控服务载体上判定看板入口。
+        assertTrue(anyClassHasMethodNamedLike(MONITOR_SERVICES, "overview", "dashboard", "metrics", "summary"),
+                "[health.ops.parseMonitor] 监控服务应暴露看板入口方法"
+                        + "(方法名含 overview/dashboard/metrics/summary):契约 §三 P2 要求"
+                        + " 建立 P0 命中率、P1 Top 5 看板。当前无看板入口,实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:看板应暴露 P0 命中率指标(§三 P2)")
+    void dashboard_exposesP0HitRateMetric() {
+        boolean hasMetric = anyClassHasMethodNamedLike(monitorCandidates(), "p0hitrate", "p0Rate", "p0命中")
+                || anyClassHasStringConstantNamedLike(monitorCandidates(), "P0_HIT_RATE", "P0_HIT", "P0_命中");
+        assertTrue(hasMetric,
+                "[health.ops.parseMonitor] 看板应暴露 P0 命中率指标"
+                        + "(方法名含 p0 且 hit/rate/命中,或常量名含 P0_HIT_RATE/P0_HIT/P0_命中):"
+                        + "契约 §三 P2 建看板需展示 P0 命中率(_解析自检.P0告警数=0 的占比)。"
+                        + " 当前无 P0 命中率锚点,实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:看板应暴露 P1 Top 5 指标(§三 P2)")
+    void dashboard_exposesP1Top5Metric() {
+        boolean hasMetric = anyClassHasMethodNamedLike(monitorCandidates(), "p1top5", "p1TopFive", "p1Top")
+                || anyClassHasStringConstantNamedLike(monitorCandidates(), "P1_TOP5", "P1_TOP_FIVE");
+        assertTrue(hasMetric,
+                "[health.ops.parseMonitor] 看板应暴露 P1 Top 5 指标"
+                        + "(方法名含 p1 且 top5/topFive,或常量名含 P1_TOP5/P1_TOP_FIVE):"
+                        + "契约 §三 P2 建看板需展示 P1 Top 5(健康问题索引摘录切头 / PAGEBREAK 残留 /"
+                        + " ND 语义未区分 / 状态词缺失 / 索引切头)。当前无 P1 Top 5 锚点,实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:P1 Top 5 五类问题锚点(§三 P2)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:P1 Top 5 应可寻址「健康问题索引 摘录切头」")
+    void p1Top5_addressable_dietSnippetCut() {
+        assertCategoryAddressable(P1_TOP5_CATEGORIES[0]);
+    }
+
+    @Test
+    @DisplayName("边界流-2:P1 Top 5 应可寻址「PAGEBREAK 残留」")
+    void p1Top5_addressable_pagebreakResidue() {
+        assertCategoryAddressable(P1_TOP5_CATEGORIES[1]);
+    }
+
+    @Test
+    @DisplayName("边界流-3:P1 Top 5 应可寻址「ND 语义未区分」")
+    void p1Top5_addressable_ndSemantics() {
+        assertCategoryAddressable(P1_TOP5_CATEGORIES[2]);
+    }
+
+    @Test
+    @DisplayName("边界流-4:P1 Top 5 应可寻址「状态词缺失」")
+    void p1Top5_addressable_statusWordMissing() {
+        assertCategoryAddressable(P1_TOP5_CATEGORIES[3]);
+    }
+
+    @Test
+    @DisplayName("边界流-5:P1 Top 5 应可寻址「索引切头」")
+    void p1Top5_addressable_indexSnippetCut() {
+        assertCategoryAddressable(P1_TOP5_CATEGORIES[4]);
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:解析耗时监控(§三 P2,复用既有 next_retry_at 指数退避)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-6:看板应暴露解析耗时监控(duration/elapsed/耗时)")
+    void dashboard_exposesParseDurationMetric() {
+        assertTrue(anyClassHasMethodNamedLike(monitorCandidates(), "duration", "elapsed", "耗时"),
+                "[health.ops.parseMonitor] 看板应暴露解析耗时监控"
+                        + "(方法名含 duration/elapsed/耗时):契约 §三 P2 要求解析耗时监控"
+                        + "(170 页大报告 4–5 分钟,异步队列超时与重试复用 health_report_drafts.next_retry_at)。"
+                        + " 当前无耗时指标锚点,实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:上游同步机制(§八 8.5,bun-report-parser changelog/submodule)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-7:应暴露 bun-report-parser 上游同步锚点(changelog 订阅/submodule)")
+    void upstreamSync_bunReportParserAnchor() {
+        boolean hasAnchor = anyClassHasStringConstantContaining(monitorCandidates(), UPSTREAM_PARSER)
+                || anyClassHasStringConstantNamedLike(monitorCandidates(), "BUN_REPORT_PARSER");
+        assertTrue(hasAnchor,
+                "[health.ops.parseMonitor] 应暴露 bun-report-parser 上游同步锚点"
+                        + "(静态 String 常量值含 bun-report-parser 或常量名含 BUN_REPORT_PARSER):"
+                        + "契约 §八 8.5 要求 bun-report-parser 每次 minor/major 升级(v1.3.2 / v1.4 / v1.5 …)"
+                        + " 评估同步到 langgraph 子包,建立 changelog 订阅或 submodule。"
+                        + " 当前无上游同步锚点,实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:既有基建基线(勿重复建)—— collect_validation / next_retry_at 已在 schema.sql
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-8:既有基建 collect_validation / next_retry_at 应已存在(监控复用,勿重复建)")
+    void existingInfra_reusedNotRecreated() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains("collect_validation"),
+                "[health.ops.parseMonitor] 既有基建 health_report_drafts.collect_validation 应在 schema.sql"
+                        + "(_解析自检 透传落库载体,P0-3)。若缺失属其他能力回归,非本键新建范围。");
+        assertTrue(schema.contains("next_retry_at"),
+                "[health.ops.parseMonitor] 既有基建 health_report_drafts.next_retry_at 应在 schema.sql"
+                        + "(异步队列指数退避重试,§三 P2 明确已有,勿重复建)。若缺失属其他能力回归,"
+                        + " 非本键新建范围。");
+        // 监控应复用既有重试基建,不要求本键新建额外重试列(此处仅作基线绿断言)
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流:SC-A-02 管理端能力——看板端点应做 admin 角色校验
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:解析监控看板为管理端能力,端点应做 admin 角色校验(SC-A-02)")
+    void permissionFlow_adminGatedDashboard() {
+        boolean gated = anyControllerMethodAdminGated();
+        assertTrue(gated,
+                "[health.ops.parseMonitor] 解析监控看板为 SC-A-02 管理端能力,端点应做 admin 角色校验"
+                        + "(@RequestAttribute(\"role\") 参数 + \"admin\" 检查)。当前无 admin 门控的看板端点,"
+                        + " 实现未落地。");
+    }
+
+    // ------------------------------------------------------------------
+    // 断言辅助
+    // ------------------------------------------------------------------
+
+    private void assertCategoryAddressable(String category) {
+        boolean ignoreCase = category.equalsIgnoreCase(category.toUpperCase())
+                && category.chars().noneMatch(Character::isLowerCase);
+        boolean addressed = anyClassHasStringConstantContaining(monitorCandidates(), category, ignoreCase);
+        assertTrue(addressed,
+                "[health.ops.parseMonitor] P1 Top 5 应可寻址「" + category + "」"
+                        + "(静态 String 常量值含之,§三 P2 五类问题类别)。"
+                        + " 当前 src/main 无此类别锚点,P1 Top 5 看板无法归类,实现未落地。");
+    }
+
+    private String[] monitorCandidates() {
+        String[] all = new String[MONITOR_SERVICES.length + MONITOR_CONTROLLERS.length + EXISTING_MOUNTS.length];
+        int i = 0;
+        for (String s : MONITOR_SERVICES) all[i++] = s;
+        for (String s : MONITOR_CONTROLLERS) all[i++] = s;
+        for (String s : EXISTING_MOUNTS) all[i++] = s;
+        return all;
+    }
+
+    /** 在候选类中找到第一个可加载的(返回其 FQCN;均不可加载返回 null) */
+    private String findLoadable(String[] candidates) {
+        for (String c : candidates) {
+            if (loadClass(c) != null) return c;
+        }
+        return null;
+    }
+
+    /** 任一候选类存在方法名(忽略大小写)含全部给定片段之一 */
+    private boolean anyClassHasMethodNamedLike(String[] candidates, String... fragments) {
+        for (String c : candidates) {
+            Class<?> clazz = loadClass(c);
+            if (clazz == null) continue;
+            for (Method m : clazz.getDeclaredMethods()) {
+                String name = m.getName().toLowerCase();
+                for (String frag : fragments) {
+                    if (name.contains(frag.toLowerCase())) return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /** 任一候选类存在静态 String 常量名(忽略大小写)含给定片段之一 */
+    private boolean anyClassHasStringConstantNamedLike(String[] candidates, String... fragments) {
+        for (String c : candidates) {
+            Class<?> clazz = loadClass(c);
+            if (clazz == null) continue;
+            for (Field f : clazz.getDeclaredFields()) {
+                if (f.getType() != String.class) continue;
+                if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) continue;
+                String fieldName = f.getName().toUpperCase();
+                for (String frag : fragments) {
+                    if (fieldName.contains(frag.toUpperCase())) return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /** 任一候选类存在静态 String 常量值包含 target(默认大小写敏感) */
+    private boolean anyClassHasStringConstantContaining(String[] candidates, String target) {
+        return anyClassHasStringConstantContaining(candidates, target, false);
+    }
+
+    private boolean anyClassHasStringConstantContaining(String[] candidates, String target, boolean ignoreCase) {
+        for (String c : candidates) {
+            Class<?> clazz = loadClass(c);
+            if (clazz == null) continue;
+            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 value = (String) v;
+                        if (ignoreCase) {
+                            if (value.toUpperCase().contains(target.toUpperCase())) return true;
+                        } else if (value.contains(target)) {
+                            return true;
+                        }
+                    }
+                } catch (Exception ignored) {
+                    // 常量读取失败 → 跳过
+                }
+            }
+        }
+        return false;
+    }
+
+    /** 任一控制器候选类存在方法:含 @RequestAttribute("role") 参数且方法名像看板端点 */
+    private boolean anyControllerMethodAdminGated() {
+        String[] controllers = MONITOR_CONTROLLERS;
+        for (String c : controllers) {
+            Class<?> clazz = loadClass(c);
+            if (clazz == null) continue;
+            for (Method m : clazz.getDeclaredMethods()) {
+                if (!looksLikeDashboardEndpoint(m.getName())) continue;
+                for (Annotation[] paramAnns : m.getParameterAnnotations()) {
+                    for (Annotation a : paramAnns) {
+                        String type = a.annotationType().getName();
+                        if (type.equals("org.springframework.web.bind.annotation.RequestAttribute")) {
+                            return true;
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
+    private boolean looksLikeDashboardEndpoint(String methodName) {
+        String name = methodName.toLowerCase();
+        return name.contains("overview") || name.contains("dashboard")
+                || name.contains("monitor") || name.contains("metrics");
+    }
+
+    // ------------------------------------------------------------------
+    // 反射 / 资源辅助
+    // ------------------------------------------------------------------
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException 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 "";
+        }
+    }
+}