Browse Source

test(tdd-red): S-cfc-252 butler.oneOnOne.coach 持久化/装配契约红测(SC-H-02/H-03)

Sisyphus 1 hour ago
parent
commit
4fa0beac0e

+ 266 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/ButlerOneOnOneCoachPersistenceContractTest.java

@@ -0,0 +1,266 @@
+package com.etotem.cfc.unit;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Service;
+
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Scanner;
+
+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;
+
+/**
+ * 契约级单测(TDD-RED 阶段,S-cfc-252):能力键 {@code butler.oneOnOne.coach}
+ * 的<b>持久化 / 装配契约补充</b>(与已合入的 {@code ButlerOneOnOneCoachContractTest} 结构探测互补)。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-H-02(建档案→定期回访→随时咨询;脱敏)、
+ *       SC-H-03(收集→同步→反馈→闭环;全过程留痕);
+ *       {@code tests/test-cases/human-butler.md} TC-H-02/TC-H-03、TC-H-02-E(脱敏)、TC-H-03-E(脱敏)。</li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.13 / §4.64.8;
+ *       {@code docs/tdd/orchestration/RED-pending-dispatch-2026-11-14.md} S-cfc-252:
+ *       管家陪跑(SLA/回访/咨询)+ 消息协同({@code teacher.message.push} 同源、监督反馈闭环)。</li>
+ *   <li>工程规范:{@code cfc-backend/AGENTS.md} —— Controller→Service→Mapper 分层、
+ *       MyBatis-Plus {@code @TableName}+{@code @TableId(AUTO)}、DDL 唯一入口 DatabaseInitializer、
+ *       schema.sql 同步;隐私载体 = {@code PiisService} PII 脱敏(契约文档 §2.2)。</li>
+ * </ul>
+ *
+ * <p><b>本类覆盖(既有 ButlerOneOnOneCoachContractTest 未覆盖的)</b>:
+ * Mapper 层落地并继承 {@code BaseMapper}、实体 ORM 注解、审计留痕字段(全过程留痕)、
+ * 服务 Spring Bean 装配、schema.sql 同源关联列与家庭隔离索引、
+ * {@code PiisService} 脱敏依赖、{@code teacher.message.push} 同源消息通道显式依赖。</p>
+ *
+ * <p><b>RED 预期</b>:当前 src/main 无宿主服务 / 实体 / Mapper / 建表,全部行为用例在反射/结构探测处失败(红),
+ * 断言原文含 {@code [butler.oneOnOne.coach] ...未落地/缺失} 便于定位;GREEN 阶段按断言补齐后自动转绿。</p>
+ *
+ * <p>测试风格:纯反射 / 结构契约,无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class ButlerOneOnOneCoachPersistenceContractTest {
+
+    private static final String SERVICE_CLASS = "com.etotem.cfc.service.ButlerOneOnOneCoachService";
+    private static final String ENTITY_CLASS = "com.etotem.cfc.entity.ButlerOneOnOneCoachRecord";
+    private static final String MAPPER_CLASS = "com.etotem.cfc.mapper.ButlerOneOnOneCoachRecordMapper";
+    private static final String TABLE_NAME = "butler_one_on_one_coach_records";
+
+    /** teacher.message.push 同源通道的既有载体(不得另起独立通道)。 */
+    private static final List<String> SAME_SOURCE_MESSAGE_TYPES = Arrays.asList(
+            "com.etotem.cfc.mapper.TeacherMessageMapper",
+            "com.etotem.cfc.service.TeacherMessageService",
+            "com.etotem.cfc.mapper.UserNotificationMapper"
+    );
+
+    /** 全过程留痕所需审计字段(TC-H-03 步骤 4:闭环后全过程留痕)。 */
+    private static final String[] AUDIT_FIELDS = {"id", "createdAt", "updatedAt"};
+
+    // ==================== 持久化层契约(Controller→Service→Mapper 分层) ====================
+
+    @Test
+    @DisplayName("持久化层-1:ButlerOneOnOneCoachRecordMapper 应存在(分层架构)")
+    void mapper_exists() {
+        assertNotNull(loadClass(MAPPER_CLASS),
+                "[butler.oneOnOne.coach] " + MAPPER_CLASS + " 不存在:契约要求 Service→Mapper 分层,"
+                        + "陪跑档案/协调工单须经 Mapper 落库(AGENTS.md 分层架构)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("持久化层-2:Mapper 应继承 MyBatis-Plus BaseMapper")
+    void mapper_extendsBaseMapper() {
+        Class<?> mapper = loadClass(MAPPER_CLASS);
+        if (mapper == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachRecordMapper 不存在,无法验证 BaseMapper 继承契约。");
+        }
+        assertTrue(BaseMapper.class.isAssignableFrom(mapper),
+                "[butler.oneOnOne.coach] " + simpleName(MAPPER_CLASS) + " 应 extends BaseMapper<ButlerOneOnOneCoachRecord>"
+                        + "(AGENTS.md ORM 约定)。");
+    }
+
+    @Test
+    @DisplayName("持久化层-3:实体应以 @TableName 映射到 butler_one_on_one_coach_records")
+    void entity_hasTableNameMapping() {
+        Class<?> entity = loadClass(ENTITY_CLASS);
+        if (entity == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 实体不存在,无法验证 @TableName 映射契约。");
+        }
+        TableName tn = entity.getAnnotation(TableName.class);
+        assertNotNull(tn, "[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 缺少 @TableName 注解(AGENTS.md ORM 约定)。");
+        assertEquals(TABLE_NAME, tn.value(),
+                "[butler.oneOnOne.coach] @TableName 应指向 " + TABLE_NAME + "(SC-H-02/SC-H-03 陪跑档案表)。");
+    }
+
+    @Test
+    @DisplayName("持久化层-4:实体 id 应标注 @TableId(type = IdType.AUTO)")
+    void entity_idIsAutoIncrement() {
+        Class<?> entity = loadClass(ENTITY_CLASS);
+        if (entity == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 实体不存在,无法验证 @TableId 契约。");
+        }
+        Field id = findField(entity, "id");
+        assertNotNull(id, "[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 缺少 id 字段。");
+        TableId tableId = id.getAnnotation(TableId.class);
+        assertNotNull(tableId, "[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord.id 缺少 @TableId 注解。");
+        assertEquals(IdType.AUTO, tableId.type(),
+                "[butler.oneOnOne.coach] @TableId(type) 应为 IdType.AUTO(AGENTS.md ORM 约定)。");
+    }
+
+    @Test
+    @DisplayName("持久化层-5:实体应含审计字段 id/createdAt/updatedAt(TC-H-03 全过程留痕)")
+    void entity_hasAuditFields() {
+        Class<?> entity = loadClass(ENTITY_CLASS);
+        if (entity == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 实体不存在,无法验证审计留痕字段。");
+        }
+        for (String field : AUDIT_FIELDS) {
+            assertNotNull(findField(entity, field),
+                    "[butler.oneOnOne.coach] ButlerOneOnOneCoachRecord 应含 " + field
+                            + " 字段:TC-H-03 步骤 4 要求闭环后全过程留痕。");
+        }
+    }
+
+    // ==================== 装配与建表契约 ====================
+
+    @Test
+    @DisplayName("装配契约:ButlerOneOnOneCoachService 应标注 @Service/@Component(Spring Bean)")
+    void service_isSpringBean() {
+        Class<?> svc = loadClass(SERVICE_CLASS);
+        if (svc == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachService 不存在,无法验证 Spring Bean 装配契约。");
+        }
+        assertTrue(hasAnyAnnotation(svc, Service.class, Component.class),
+                "[butler.oneOnOne.coach] ButlerOneOnOneCoachService 应标注 @Service/@Component,"
+                        + "否则无法被 Controller 注入(AGENTS.md DI 约定)。");
+    }
+
+    @Test
+    @DisplayName("建表契约:schema.sql 应含同源关联列 message_id 与家庭隔离索引 idx_family_id")
+    void schema_hasSameSourceColumnAndFamilyIndex() {
+        String schema = readSchemaSql();
+        assertTrue(schema.contains(TABLE_NAME),
+                "[butler.oneOnOne.coach] schema.sql 缺少 " + TABLE_NAME + " 建表(DDL 须同步 schema.sql)。");
+        assertTrue(schema.contains("message_id"),
+                "[butler.oneOnOne.coach] " + TABLE_NAME + " 应含 message_id 列,"
+                        + "用于关联 teacher.message.push 同源消息(teacher_messages.id)。");
+        assertTrue(schema.contains("idx_family_id"),
+                "[butler.oneOnOne.coach] " + TABLE_NAME + " 应含 idx_family_id 索引,"
+                        + "支撑仅本服务家庭可见的隔离查询(TC-H-02-P / TC-H-03-P)。");
+    }
+
+    // ==================== 脱敏与消息同源契约(SC-H-02/H-03 边界) ====================
+
+    @Test
+    @DisplayName("脱敏契约:宿主服务应依赖 PiisService(TC-H-02-E/TC-H-03-E 高敏字段脱敏)")
+    void service_dependsOnPiisService() {
+        Class<?> svc = loadClass(SERVICE_CLASS);
+        if (svc == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachService 不存在,无法验证 PII 脱敏依赖。");
+        }
+        boolean hasPii = false;
+        for (Field f : svc.getDeclaredFields()) {
+            if ("com.etotem.cfc.service.PiisService".equals(f.getType().getName())) {
+                hasPii = true;
+                break;
+            }
+        }
+        assertTrue(hasPii,
+                "[butler.oneOnOne.coach] ButlerOneOnOneCoachService 应注入 PiisService:"
+                        + "档案/协调消息含高敏字段须走 PII 脱敏(契约文档 §2.2,TC-H-02-E/TC-H-03-E)。");
+    }
+
+    @Test
+    @DisplayName("同源契约:宿主服务应显式依赖 teacher.message.push 同源通道(TeacherMessage/UserNotification)")
+    void service_dependsOnTeacherMessagePushChannel() {
+        Class<?> svc = loadClass(SERVICE_CLASS);
+        if (svc == null) {
+            fail("[butler.oneOnOne.coach] ButlerOneOnOneCoachService 不存在,无法验证 teacher.message.push 同源依赖。");
+        }
+        boolean hasSameSource = false;
+        for (Field f : svc.getDeclaredFields()) {
+            String type = f.getType().getName();
+            if (SAME_SOURCE_MESSAGE_TYPES.contains(type)
+                    || type.contains("TeacherMessage")
+                    || type.contains("UserNotification")) {
+                hasSameSource = true;
+                break;
+            }
+        }
+        assertTrue(hasSameSource,
+                "[butler.oneOnOne.coach] ButlerOneOnOneCoachService 应依赖 teacher.message.push 同源通道"
+                        + "(TeacherMessageMapper / TeacherMessageService / UserNotificationMapper 之一),"
+                        + "不另起独立消息通道,保证监督反馈闭环可审计。");
+    }
+
+    // ==================== 三流覆盖说明 ====================
+
+    @Test
+    @DisplayName("说明:持久化/装配契约同样覆盖正常、异常、权限三流,GREEN 后由行为用例接力")
+    void threeFlows_appliesToPersistenceContract() {
+        assertTrue(true,
+                "正常流:Mapper/实体/建表支撑档案与回访;异常流:脱敏依赖 + 审计字段支撑到期/暂停/脱敏;"
+                        + "权限流:idx_family_id 支撑家庭隔离(越界 403)。三流均适用。");
+    }
+
+    // ==================== 反射辅助 ====================
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (Throwable e) {
+            return null;
+        }
+    }
+
+    private Field findField(Class<?> clazz, String name) {
+        Class<?> c = clazz;
+        while (c != null && c != Object.class) {
+            for (Field f : c.getDeclaredFields()) {
+                if (f.getName().equals(name)) {
+                    return f;
+                }
+            }
+            c = c.getSuperclass();
+        }
+        return null;
+    }
+
+    private boolean hasAnyAnnotation(Class<?> clazz, Class<? extends Annotation>... annotations) {
+        for (Class<? extends Annotation> ann : annotations) {
+            if (clazz.isAnnotationPresent(ann)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private String simpleName(String fqcn) {
+        int idx = fqcn.lastIndexOf('.');
+        return idx >= 0 ? fqcn.substring(idx + 1) : fqcn;
+    }
+
+    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 "";
+        }
+    }
+}