Browse Source

test(backend): train.eval.rating 冲突边界 RED 契约单测(replay/C4092/C422/C404/C403)

liaoxg 3 hours ago
parent
commit
8fe9daa990

+ 241 - 0
train-backend/src/test/java/com/train/service/impl/TrainEvalRatingBoundaryContractTest.java

@@ -0,0 +1,241 @@
+package com.train.service.impl;
+
+import com.train.common.Result;
+import com.train.entity.TrainEvalRecord;
+import com.train.entity.TrainPractitionerProfile;
+import com.train.mapper.TrainEvalRecordMapper;
+import com.train.mapper.TrainPractitionerProfileMapper;
+import com.train.mapper.TrainServiceOrderMapper;
+import com.train.service.CertService;
+import com.train.service.EvalService;
+import com.train.service.PractitionerService;
+import com.train.service.RoleGuard;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code train.eval.rating} 契约级单测——冲突边界补证(TDD-RED,S-train-32;TC-1032/TC-3005)。
+ *
+ * <p>需求锚点:docs/tdd/SRS.md §5.5 / 场景定义 §3.2 E4-S1(Should)
+ * 「聚合 rating/serve_count 口径一致、可被晋升规则读取,聚合幂等」。</p>
+ *
+ * <p>与同目录 {@link TrainEvalRatingContractTest}(8a11169,覆盖 rating/serve_count 口径一致、
+ * 归一与无数据归零)互补:本类专门覆盖任务单要求的五类冲突边界——幂等重放 replay=true、
+ * 同键异载荷 C4092、乐观锁冲突 C422、不存在 C404、越权 C403(适用时)。</p>
+ *
+ * <p>被测面为 E4 综合评级聚合写链路 {@link EvalServiceImpl#mine(Long)} →
+ * {@code recalcRating} → {@code practitioner_profile.rating} 覆盖写。本轮只写测试、不改 src/main。
+ * 纯 Mockito(不启 Spring、不连 DB)。</p>
+ *
+ * <p>RED 依据:EvalService 仅暴露 {@code mine(userId)},无 replay / 幂等键 / payloadHash / operator
+ * 入参;recalcRating 忽略 profile 更新影响行数(并发丢失更新静默成功);被评人不存在时 ensureProfile
+ * 为 null 仍返回 200;聚合视图无显式冲突码。故五类边界用例均预期失败(红)。</p>
+ *
+ * <p>契约错误码({@code Result.code}):C4092=4092 同键异载荷;C422=422 乐观锁/并发冲突;
+ * C404=404 目标不存在;C403=403 越权。</p>
+ *
+ * <p>目录说明:本仓后端模块为 train-backend(无字面量 train-impl / train-contract 模块,
+ * 亦无独立 action 常量类;键名 train.eval.rating 仅见 docs/tdd 登记),测试按既有契约单测惯例
+ * 落在 train-backend/src/test/java/com/train/service/impl/,与 S-train-31 同类测试同目录。</p>
+ */
+class TrainEvalRatingBoundaryContractTest {
+
+    private static final int CODE_OK = 200;
+    private static final int CODE_SAME_KEY_DIFF_PAYLOAD = 4092; // C4092
+    private static final int CODE_OPTIMISTIC_LOCK = 422;        // C422
+    private static final int CODE_NOT_FOUND = 404;              // C404
+    private static final int CODE_FORBIDDEN = 403;              // C403
+
+    private static final Long USER = 88001L;
+    private static final Long MISSING_USER = 999999L;
+    private static final int SCORE_FULL = 5;   // 客户层满分(1-5 星)
+    private static final int SCORE_LOWER = 3;  // 同键下的异载荷评分
+
+    private EvalServiceImpl service;
+    private TrainEvalRecordMapper evalRecordMapper;
+    private TrainPractitionerProfileMapper profileMapper;
+    private PractitionerService practitionerService;
+    private RoleGuard roleGuard;
+    private TrainPractitionerProfile profile;
+    /** 当前聚合使用的客户层评分,用于模拟「同键异载荷」。 */
+    private int currentScore = SCORE_FULL;
+    private final AtomicInteger seq = new AtomicInteger();
+
+    @BeforeEach
+    void setUp() {
+        service = new EvalServiceImpl();
+        evalRecordMapper = mock(TrainEvalRecordMapper.class);
+        profileMapper = mock(TrainPractitionerProfileMapper.class);
+        practitionerService = mock(PractitionerService.class);
+        roleGuard = mock(RoleGuard.class);
+
+        ReflectionTestUtils.setField(service, "trainEvalRecordMapper", evalRecordMapper);
+        ReflectionTestUtils.setField(service, "trainServiceOrderMapper", mock(TrainServiceOrderMapper.class));
+        ReflectionTestUtils.setField(service, "trainPractitionerProfileMapper", profileMapper);
+        ReflectionTestUtils.setField(service, "practitionerService", practitionerService);
+        ReflectionTestUtils.setField(service, "certService", mock(CertService.class));
+        ReflectionTestUtils.setField(service, "roleGuard", roleGuard);
+
+        profile = new TrainPractitionerProfile();
+        profile.setUserId(USER);
+        profile.setRating(0.0);
+        profile.setServeCount(0);
+
+        // aggregate 查询顺序固定 client→org→training;每次 mine() 触发两次 aggregate
+        // (mine 自身一次 + recalcRating 一次)。按调用序 mod 3 派驻 client 数据,
+        // 保证单次 mine() 的三层聚合稳定;currentScore 变更即模拟同键异载荷。
+        when(evalRecordMapper.selectList(any())).thenAnswer(
+                inv -> seq.incrementAndGet() % 3 == 1 ? clientRecords(currentScore) : Collections.emptyList());
+        when(practitionerService.ensureProfile(any())).thenReturn(profile);
+    }
+
+    private static List<TrainEvalRecord> clientRecords(int score) {
+        List<TrainEvalRecord> list = new ArrayList<TrainEvalRecord>();
+        for (int i = 0; i < 2; i++) { // 客户层评价次数 = 2,与 serve_count 口径一致
+            TrainEvalRecord r = new TrainEvalRecord();
+            r.setUserId(USER);
+            r.setEvalType("client");
+            r.setScore(score);
+            r.setStatus("valid");
+            r.setDeleted(0);
+            list.add(r);
+        }
+        return list;
+    }
+
+    // ==================== 边界 0:幂等重放 replay=true ====================
+
+    /** 评级聚合写链路须暴露显式 replay=true 幂等重放入口,避免晋升规则重读时重复写入。 */
+    @Test
+    void replayTrueRequiresIdempotentRatingEntry() {
+        Method entry = findRatingEntryWith(Boolean.class, Boolean.TYPE);
+        assertNotNull(entry,
+                "train.eval.rating(TC-1032) 幂等重放 replay=true 要求评级聚合入口携带 replay 标识:"
+                        + "需 EvalService 暴露返回 Result 且带 Boolean replay 入参的评级入口;"
+                        + "当前仅有 mine(Long userId),无 replay/key,晋升规则重读将重复触发 recalcRating 覆盖写");
+    }
+
+    // ==================== 边界 1:同键异载荷 C4092 ====================
+
+    /** 同一评级键(同一学员 userId)携带不同评分载荷时须返回 C4092,禁止静默覆盖 profile.rating。 */
+    @Test
+    void sameKeyDifferentPayloadReturnsC4092() {
+        Result<Map<String, Object>> first = service.mine(USER);
+        assertEquals(CODE_OK, first.getCode());
+
+        currentScore = SCORE_LOWER; // 同键异载荷:评分由 5 变为 3
+        Result<Map<String, Object>> second = service.mine(USER);
+
+        assertEquals(CODE_SAME_KEY_DIFF_PAYLOAD, second.getCode(),
+                "同一评级键(userId=" + USER + ")携带不同评分载荷必须返回 C4092(" + CODE_SAME_KEY_DIFF_PAYLOAD
+                        + ") 冲突,禁止静默覆盖 profile.rating;当前第二次仍返回 " + second.getCode());
+    }
+
+    // ==================== 边界 2:乐观锁冲突 C422 ====================
+
+    /** profile.rating 覆盖写影响 0 行(并发丢失更新)必须 C422,不得静默按成功返回。 */
+    @Test
+    void staleProfileUpdateReturnsC422() {
+        when(profileMapper.updateById(any(TrainPractitionerProfile.class))).thenReturn(0);
+
+        Result<Map<String, Object>> r = service.mine(USER);
+
+        assertEquals(CODE_OPTIMISTIC_LOCK, r.getCode(),
+                "评级覆盖写影响 0 行(乐观锁冲突/并发丢失更新)必须返回 C422(" + CODE_OPTIMISTIC_LOCK
+                        + "),不得忽略 updateById 返回行数按 " + r.getCode() + " 成功返回");
+    }
+
+    // ==================== 边界 3:不存在 C404 ====================
+
+    /** 被评学员不存在(ensureProfile 无法取得档案)须 C404,而非空转返回 200。 */
+    @Test
+    void nonExistentPractitionerReturnsC404() {
+        when(practitionerService.ensureProfile(any())).thenReturn(null);
+
+        Result<Map<String, Object>> r = service.mine(MISSING_USER);
+
+        assertEquals(CODE_NOT_FOUND, r.getCode(),
+                "评级聚合的被评学员不存在必须返回 C404(" + CODE_NOT_FOUND
+                        + ");当前 mine() 在 ensureProfile 为 null 时仍返回 " + r.getCode());
+    }
+
+    // ==================== 边界 4:越权 C403(适用时) ====================
+
+    /**
+     * 评级聚合会覆盖写 profile.rating 并被晋升规则读取——若允许第三方触发,必须经授权入口返回 C403;
+     * 当前 mine(userId) 无 operator 入参且从不经过 RoleGuard,无法表达越权拒绝。
+     */
+    @Test
+    void ratingRecomputeRequiresAuthorizedOperatorEntry() {
+        Method entry = findRatingEntryWithOperatorAndAdmin();
+        assertNotNull(entry,
+                "train.eval.rating(越权 C403) 要求评级聚合在代他人触发时经授权入口校验 operatorId/isAdmin:"
+                        + "需 EvalService 暴露返回 Result、且除 userId 外还带 operatorId 与 isAdmin 入参的评级入口;"
+                        + "当前 mine(Long userId) 无 operator 参数、不调用 RoleGuard,无法返回 C403(" + CODE_FORBIDDEN + ")");
+    }
+
+    // ==================== 反射辅助 ====================
+
+    /** 返回 Result、名称与评级/聚合相关、且同时带 operatorId(Long) 与 isAdmin(Boolean) 的授权入口。 */
+    private static Method findRatingEntryWithOperatorAndAdmin() {
+        for (Method m : EvalService.class.getMethods()) {
+            if (!Result.class.isAssignableFrom(m.getReturnType())) {
+                continue;
+            }
+            String name = m.getName().toLowerCase();
+            if (!name.contains("rating") && !name.contains("rate") && !name.contains("mine")) {
+                continue;
+            }
+            boolean hasLong = false;
+            boolean hasBoolean = false;
+            for (Class<?> p : m.getParameterTypes()) {
+                if (Long.class.equals(p) || Long.TYPE.equals(p)) {
+                    hasLong = true;
+                }
+                if (Boolean.class.equals(p) || Boolean.TYPE.equals(p)) {
+                    hasBoolean = true;
+                }
+            }
+            if (hasLong && hasBoolean) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    /** 返回 Result、名称与评级/聚合相关、且入参类型命中给定类型的 EvalService 方法。 */
+    private static Method findRatingEntryWith(Class<?>... paramTypes) {
+        for (Method m : EvalService.class.getMethods()) {
+            if (!Result.class.isAssignableFrom(m.getReturnType())) {
+                continue;
+            }
+            String name = m.getName().toLowerCase();
+            if (!name.contains("rating") && !name.contains("rate") && !name.contains("mine")) {
+                continue;
+            }
+            Class<?>[] params = m.getParameterTypes();
+            for (Class<?> want : paramTypes) {
+                for (Class<?> p : params) {
+                    if (want.equals(p)) {
+                        return m;
+                    }
+                }
+            }
+        }
+        return null;
+    }
+}