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

test(消息通知): 新增 notification.setting.config TDD-RED 契约单测 S-cfc-286

- 覆盖 SC-P-65/SC-P-79:通知开关/提醒时间、关键安全通知不可关闭、非法 HH:mm 拒绝、userId 隔离
- 12 个用例预期全红(服务/DTO/控制器/表未落地),纯反射+Mockito,无 Spring/DB/外部服务
- GREEN 实现载体与默认值口径已在测试 Javadoc 固化,便于后续转绿

Refs: S-cfc-286
zxyj-langgraph 1 день назад
Родитель
Сommit
2910a459ee

+ 414 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/NotificationSettingConfigContractTest.java

@@ -0,0 +1,414 @@
+package com.etotem.cfc.unit;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+
+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.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;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:消息通知开关 / 提醒时间设置(能力键 {@code notification.setting.config})。
+ *
+ * <p><b>需求 / 设计锚点</b></p>
+ * <ul>
+ *   <li>{@code tests/user-scenarios/应用场景总览.md} SC-P-65(消息通知/提醒设置:设通知开关/提醒时间,
+ *       关闭后仍保关键安全通知)与 SC-P-79(推送/通知开关设置:关键安全通知不可关闭);业务域 H / K</li>
+ *   <li>{@code tests/test-cases/parent.md} TC-P-65-E / TC-P-79-E:关全部含安全类 + 提醒时间填 25:00 →
+ *       关键安全通知仍推送不被关、非法时间 400</li>
+ *   <li>{@code docs/superpowers/api/API_REFERENCE.md} §4.15 统计与通知({@code /api/notification} list/read)
+ *       + §4.63.8 设置与通知({@code /api/task/reminder-config/get|save} 提醒开关/时间);模块:消息服务</li>
+ *   <li>{@code docs/tdd/orchestration/sc-key-map.md} SC-P-65 / SC-P-79 → {@code notification.setting.config}
+ *       (S-cfc-286)</li>
+ * </ul>
+ *
+ * <p><b>契约目标(GREEN 阶段按此实现,本测试即验收口径)</b></p>
+ * <ol>
+ *   <li>实体 {@code com.etotem.cfc.entity.NotificationSetting}、DTO
+ *       {@code com.etotem.cfc.dto.NotificationSettingDTO}:字段 {@code userId / enabled /
+ *       reminderEnabled / reminderTime / safetyEnabled}</li>
+ *   <li>服务 {@code com.etotem.cfc.service.NotificationSettingService}:
+ *       {@code getConfig(Long)} 返回 DTO;{@code saveConfig(Long, DTO)} 保存;
+ *       {@code isNotificationEnabled(Long userId, String type)} 告知分发侧某类通知是否可发</li>
+ *   <li>默认值:{@code enabled=1}、{@code reminderEnabled=1}、{@code safetyEnabled=1}(关键安全通知恒开),
+ *       {@code reminderTime} 为合法 {@code HH:mm}</li>
+ *   <li>校验:{@code reminderTime} 必须匹配 {@code ^([01]\d|2[0-3]):[0-5]\d$},否则
+ *       {@code IllegalArgumentException("提醒时间格式不合法")};{@code safetyEnabled=0} 必须拒绝
+ *       ({@code "关键安全通知不可关闭"})</li>
+ *   <li>关键安全通知:即使用户关闭全部通知({@code enabled=0}),
+ *       {@code isNotificationEnabled(userId, "safety")} 仍返回 {@code true}</li>
+ *   <li>控制器 {@code com.etotem.cfc.controller.NotificationSettingController}:
+ *       POST {@code /api/notification/setting/get|save},参数带 {@code @RequestAttribute("userId")}
+ *       (只能读写本人配置)</li>
+ *   <li>DB:{@code schema.sql} 含 {@code notification_settings} 表与上述 4 个配置列</li>
+ * </ol>
+ *
+ * <p><b>RED 预期</b>:本分支 src/main 尚无上述服务/DTO/控制器/表(仅 {@code /api/notification/list|read}
+ * 查看已读闭环),全部用例以反射/结构探测断言失败(红),且失败信息清晰可贴。
+ * 纯 Mockito + 反射,无 Spring 上下文 / 无 DB / 无外部服务。</p>
+ */
+class NotificationSettingConfigContractTest {
+
+    private static final String TAG = "RED[notification.setting.config] ";
+
+    private static final String SERVICE = "com.etotem.cfc.service.NotificationSettingService";
+    private static final String ENTITY = "com.etotem.cfc.entity.NotificationSetting";
+    private static final String DTO = "com.etotem.cfc.dto.NotificationSettingDTO";
+    private static final String CONTROLLER = "com.etotem.cfc.controller.NotificationSettingController";
+    private static final String TABLE = "notification_settings";
+
+    /** 设计口径:HH:mm 时间正则(与 task.reminder.daily 契约一致) */
+    private static final String HHMM_REGEX = "^([01]\\d|2[0-3]):[0-5]\\d$";
+    private static final String MSG_BAD_TIME = "提醒时间格式不合法";
+    private static final String MSG_SAFETY = "关键安全通知不可关闭";
+
+    private static final Long USER_ID = 100L;
+    private static final String SAFETY_TYPE = "safety";
+
+    // ==================== 正常流:契约载体应落地 ====================
+
+    @Test
+    @DisplayName("正常流-1:NotificationSettingService 配置服务类应存在")
+    void service_classExists() {
+        requireClass(SERVICE, "配置服务 NotificationSettingService 不存在:契约要求提供"
+                + " getConfig/saveConfig/isNotificationEnabled(SC-P-65/79 通知开关+提醒时间+安全保底)。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:配置服务应提供 getConfig/saveConfig/isNotificationEnabled 三个入口")
+    void service_hasContractMethods() {
+        Class<?> service = requireClass(SERVICE, "无法验证服务方法:配置服务类未落地。");
+        assertTrue(findMethod(service, "getConfig", 1) != null,
+                TAG + "应提供 getConfig(Long userId) 读取用户通知配置(含默认值回显)。");
+        assertTrue(findMethod(service, "saveConfig", 2) != null,
+                TAG + "应提供 saveConfig(Long userId, DTO dto) 保存通知开关/提醒时间。");
+        Method canSend = findMethod(service, "isNotificationEnabled", 2);
+        assertTrue(canSend != null && canSend.getReturnType() == boolean.class,
+                TAG + "应提供 boolean isNotificationEnabled(Long userId, String type) 供消息分发侧判定;"
+                        + "关键安全通知(type=safety)须恒可发。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:实体与 DTO 应声明五项配置字段")
+    void entityAndDto_haveConfigFields() {
+        String[] fields = {"userId", "enabled", "reminderEnabled", "reminderTime", "safetyEnabled"};
+        for (String fqcn : new String[]{ENTITY, DTO}) {
+            Class<?> clazz = requireClass(fqcn, "配置载体未落地,无法验证字段契约。");
+            for (String field : fields) {
+                boolean found = false;
+                for (Field f : clazz.getDeclaredFields()) {
+                    if (f.getName().equals(field)) {
+                        found = true;
+                        break;
+                    }
+                }
+                assertTrue(found, TAG + simpleName(fqcn) + " 缺字段 " + field
+                        + ":契约要求 userId/enabled/reminderEnabled/reminderTime/safetyEnabled(SC-P-65/79)。");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("正常流-4:未配置用户 getConfig 应回显默认开关/时间且安全通知恒开")
+    void getConfig_unconfigured_returnsDefaults() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = invoke(service, "getConfig", 1, USER_ID);
+        assertNotNull(dto, TAG + "getConfig 未配置时应返回带默认值的 DTO,而非 null。");
+
+        assertEquals(1, intProp(dto, "getEnabled"), TAG + "enabled 默认应为 1(默认开启通知,由用户主动关闭)。");
+        assertEquals(1, intProp(dto, "getReminderEnabled"), TAG + "reminderEnabled 默认应为 1。");
+        assertEquals(1, intProp(dto, "getSafetyEnabled"),
+                TAG + "safetyEnabled 默认必须为 1:关键安全通知不可关闭(SC-P-65/79)。");
+        Object time = prop(dto, "getReminderTime");
+        assertTrue(time instanceof String && ((String) time).matches(HHMM_REGEX),
+                TAG + "reminderTime 默认值必须为合法 HH:mm(形如 08:00),实际=" + time);
+    }
+
+    @Test
+    @DisplayName("正常流-5:合法通知配置(07:30 + 开关)应可保存")
+    void saveConfig_acceptsValidConfig() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setReminderTime", "07:30");
+        setProp(dto, "setEnabled", 1);
+        setProp(dto, "setReminderEnabled", 1);
+        setProp(dto, "setSafetyEnabled", 1);
+
+        invoke(service, "saveConfig", 2, USER_ID, dto);
+    }
+
+    // ==================== 异常流:时间校验 + 关键安全不可关闭 ====================
+
+    @Test
+    @DisplayName("异常流-1:saveConfig 应拒绝非法提醒时间 25:00(HH:mm 校验)")
+    void saveConfig_rejectsTime_25_00() throws Exception {
+        assertRejectsBadTime("25:00");
+    }
+
+    @Test
+    @DisplayName("异常流-2:saveConfig 应拒绝缺前导零的提醒时间 7:30(HH:mm 校验)")
+    void saveConfig_rejectsTime_7_30() throws Exception {
+        assertRejectsBadTime("7:30");
+    }
+
+    @Test
+    @DisplayName("异常流-3:saveConfig 应拒绝含非数字的提醒时间 07:3x(HH:mm 校验)")
+    void saveConfig_rejectsTime_07_3x() throws Exception {
+        assertRejectsBadTime("07:3x");
+    }
+
+    @Test
+    @DisplayName("异常流-4:saveConfig 不应允许关闭关键安全通知(safetyEnabled=0)")
+    void saveConfig_cannotDisableSafetyNotifications() throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setReminderTime", "08:00");
+        setProp(dto, "setEnabled", 0);          // 用户关闭全部普通通知
+        setProp(dto, "setReminderEnabled", 0);
+        setProp(dto, "setSafetyEnabled", 0);    // 试图连关键安全通知一起关 → 必须被拒
+
+        try {
+            invoke(service, "saveConfig", 2, USER_ID, dto);
+            fail(TAG + "safetyEnabled=0 被接受:违反「关键安全通知不可关闭」(SC-P-65/79,TC-P-65-E/79-E)。");
+        } catch (java.lang.reflect.InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            assertTrue(cause instanceof IllegalArgumentException,
+                    TAG + "关闭关键安全通知应抛 IllegalArgumentException,实际=" + cause);
+            assertTrue(cause.getMessage() != null && cause.getMessage().contains(MSG_SAFETY),
+                    TAG + "拒绝文案应含「" + MSG_SAFETY + "」,实际=" + cause.getMessage());
+        }
+    }
+
+    @Test
+    @DisplayName("异常流-5:关闭全部通知后 safety 类通知仍可发(消息服务保底)")
+    void safetyNotification_stillDeliveredWhenAllDisabled() throws Exception {
+        Object service = newServiceWithMockMapper();
+        stubMapperConfig(service, configEntity(0, "08:00", 0)); // 全关(含安全类)落库数据
+
+        Object result = invoke(service, "isNotificationEnabled", 2, USER_ID, SAFETY_TYPE);
+        assertEquals(Boolean.TRUE, result,
+                TAG + "enabled=0 且 safetyEnabled=0 的脏配置下,type=safety 仍须返回 true"
+                        + "(关闭后仍保关键安全通知,SC-P-65/79)。");
+
+        Object normal = invoke(service, "isNotificationEnabled", 2, USER_ID, "coupon_gift");
+        assertEquals(Boolean.FALSE, normal,
+                TAG + "普通通知(如 coupon_gift)在 enabled=0 时应返回 false,否则开关无效。");
+    }
+
+    // ==================== 权限流:本人配置只能本人读写 ====================
+
+    @Test
+    @DisplayName("权限流-1:设置端点应为 POST /api/notification/setting/get|save 且按 userId 隔离")
+    void controller_scopesConfigByUserId() {
+        Class<?> controller = requireClass(CONTROLLER,
+                "配置控制器未落地:无法验证「家长只能读写本人通知设置」的权限契约。");
+
+        for (String suffix : new String[]{"/get", "/save"}) {
+            String path = "/api/notification/setting" + suffix;
+            boolean mapped = false;
+            boolean userIdScoped = false;
+            for (Method m : controller.getDeclaredMethods()) {
+                PostMapping post = m.getAnnotation(PostMapping.class);
+                if (post == null || !Arrays.asList(post.value()).contains(path)) {
+                    continue;
+                }
+                mapped = true;
+                for (Annotation[] paramAnns : m.getParameterAnnotations()) {
+                    for (Annotation ann : paramAnns) {
+                        if (ann instanceof RequestAttribute
+                                && "userId".equals(((RequestAttribute) ann).value())) {
+                            userIdScoped = true;
+                        }
+                    }
+                }
+            }
+            assertTrue(mapped, TAG + "缺少 POST " + path + " 端点(SC-P-65/79 通知设置读写)。");
+            assertTrue(userIdScoped, TAG + "POST " + path
+                    + " 参数须带 @RequestAttribute(\"userId\"),按当前登录用户隔离配置,禁止跨用户读写。");
+        }
+    }
+
+    // ==================== DB 迁移契约 ====================
+
+    @Test
+    @DisplayName("DB 迁移-1:schema.sql 应含 notification_settings 表及四项配置列(安全列默认 1)")
+    void schemaSql_hasNotificationSettingsTable() {
+        String schema = readSchemaSql();
+        int idx = schema.indexOf("CREATE TABLE IF NOT EXISTS " + TABLE);
+        if (idx < 0) {
+            idx = schema.indexOf("CREATE TABLE `" + TABLE + "`");
+        }
+        assertTrue(idx >= 0, TAG + "schema.sql 缺 " + TABLE + " 建表(通知设置持久化未落地)。");
+        String tableDef = schema.substring(idx, Math.min(idx + 1500, schema.length()));
+
+        for (String col : new String[]{"user_id", "enabled", "reminder_enabled",
+                "reminder_time", "safety_enabled"}) {
+            assertTrue(tableDef.contains(col), TAG + TABLE + " 缺列 " + col + "(SC-P-65/79 配置契约)。");
+        }
+        assertTrue(tableDef.contains("safety_enabled") && tableDef.contains("DEFAULT 1"),
+                TAG + "safety_enabled 默认必须为 1(关键安全通知不可关闭,默认保底)。");
+    }
+
+    // ==================== 辅助 ====================
+
+    private void assertRejectsBadTime(String badTime) throws Exception {
+        Object service = newServiceWithMockMapper();
+        Object dto = newDto();
+        setProp(dto, "setReminderTime", badTime);
+        setProp(dto, "setEnabled", 1);
+        setProp(dto, "setReminderEnabled", 1);
+        setProp(dto, "setSafetyEnabled", 1);
+
+        try {
+            invoke(service, "saveConfig", 2, USER_ID, dto);
+            fail(TAG + "非法提醒时间 " + badTime + " 未被拒绝:要求 HH:mm 正则 " + HHMM_REGEX
+                    + ",否则 400/IllegalArgumentException(TC-P-65-E/79-E)。");
+        } catch (java.lang.reflect.InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            assertTrue(cause instanceof IllegalArgumentException,
+                    TAG + "非法提醒时间 " + badTime + " 应抛 IllegalArgumentException,实际=" + cause);
+            assertEquals(MSG_BAD_TIME, cause.getMessage(), TAG + "非法 HH:mm 报错文案");
+        }
+    }
+
+    /** 无配置用户:service 的 Mapper 字段全部注入 mock(selectOne 默认返回 null)。 */
+    private Object newServiceWithMockMapper() throws Exception {
+        Class<?> clazz = requireClass(SERVICE, "无法构造配置服务:服务类未落地。");
+        Object service = clazz.getDeclaredConstructor().newInstance();
+        for (Field f : clazz.getDeclaredFields()) {
+            if (f.getType().isInterface() && f.getType().getName().endsWith("Mapper")) {
+                f.setAccessible(true);
+                f.set(service, mock(f.getType()));
+            }
+        }
+        return service;
+    }
+
+    /** 把 mock Mapper 的 selectOne 桩为返回指定配置,用于「全关」边界场景。 */
+    private void stubMapperConfig(Object service, Object config) throws Exception {
+        Field mapperField = null;
+        for (Field f : service.getClass().getDeclaredFields()) {
+            if (f.getType().isInterface() && f.getType().getName().endsWith("Mapper")) {
+                mapperField = f;
+                break;
+            }
+        }
+        assertNotNull(mapperField, TAG + "配置服务未注入 Mapper,无法读取用户配置。");
+        mapperField.setAccessible(true);
+        Object mapper = mapperField.get(service);
+        Method selectOne = null;
+        for (Method m : mapper.getClass().getMethods()) {
+            if (m.getName().equals("selectOne") && m.getParameterCount() == 1) {
+                selectOne = m;
+                break;
+            }
+        }
+        assertNotNull(selectOne, TAG + "Mapper 缺 selectOne(Wrapper) 查询入口。");
+        try {
+            when(selectOne.invoke(mapper, new Object[]{null})).thenReturn(config);
+        } catch (Exception e) {
+            fail(TAG + "无法桩接 Mapper.selectOne:" + e);
+        }
+    }
+
+    private Object configEntity(int enabled, String time, int safetyEnabled) throws Exception {
+        Class<?> clazz = requireClass(ENTITY, "无法构造配置实体:实体未落地。");
+        Object entity = clazz.getDeclaredConstructor().newInstance();
+        setProp(entity, "setUserId", USER_ID);
+        setProp(entity, "setEnabled", enabled);
+        setProp(entity, "setReminderEnabled", enabled);
+        setProp(entity, "setReminderTime", time);
+        setProp(entity, "setSafetyEnabled", safetyEnabled);
+        return entity;
+    }
+
+    private Object newDto() throws Exception {
+        Class<?> clazz = requireClass(DTO, "无法构造配置 DTO:DTO 未落地。");
+        return clazz.getDeclaredConstructor().newInstance();
+    }
+
+    private Class<?> requireClass(String fqcn, String reason) {
+        try {
+            return Class.forName(fqcn, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            fail(TAG + reason + " 期望类:" + fqcn);
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    private Method findMethod(Class<?> clazz, String name, int paramCount) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals(name) && m.getParameterCount() == paramCount) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    private Object invoke(Object target, String name, int paramCount, Object... args) throws Exception {
+        Method m = findMethod(target.getClass(), name, paramCount);
+        assertNotNull(m, TAG + target.getClass().getName() + " 缺方法 " + name + "(参数 " + paramCount + ")。");
+        m.setAccessible(true);
+        return m.invoke(target, args);
+    }
+
+    private Object prop(Object target, String getter) throws Exception {
+        try {
+            Method m = target.getClass().getMethod(getter);
+            return m.invoke(target);
+        } catch (NoSuchMethodException e) {
+            fail(TAG + target.getClass().getName() + " 缺访问器 " + getter + "(配置字段契约未落地)。");
+            throw new IllegalStateException("unreachable");
+        }
+    }
+
+    private int intProp(Object target, String getter) throws Exception {
+        Object value = prop(target, getter);
+        assertTrue(value instanceof Number, TAG + getter + " 应返回数值,实际=" + value);
+        return ((Number) value).intValue();
+    }
+
+    private void setProp(Object target, String setter, Object value) throws Exception {
+        Method found = null;
+        for (Method m : target.getClass().getMethods()) {
+            if (m.getName().equals(setter) && m.getParameterCount() == 1) {
+                found = m;
+                break;
+            }
+        }
+        assertNotNull(found, TAG + target.getClass().getName() + " 缺写入器 " + setter + "。");
+        found.invoke(target, value);
+    }
+
+    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 "";
+        }
+    }
+}