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

merge: 合入 S-train-33 的 train.badge.lecturer RED 契约边界补强单测

liaoxg 12 минут назад
Родитель
Сommit
24f69cf5dc

+ 323 - 0
train-backend/src/test/java/com/train/service/impl/TrainBadgeLecturerContractTest.java

@@ -0,0 +1,323 @@
+package com.train.service.impl;
+
+import com.train.common.Result;
+import com.train.entity.TrainBadge;
+import com.train.entity.TrainPractitionerProfile;
+import com.train.entity.TrainPromotionRule;
+import com.train.entity.TrainUserBadge;
+import com.train.mapper.TrainBadgeMapper;
+import com.train.mapper.TrainCreditLedgerMapper;
+import com.train.mapper.TrainEvalRecordMapper;
+import com.train.mapper.TrainPractitionerProfileMapper;
+import com.train.mapper.TrainPromotionRecordMapper;
+import com.train.mapper.TrainPromotionRuleMapper;
+import com.train.mapper.TrainServiceOrderMapper;
+import com.train.mapper.TrainUserBadgeMapper;
+import com.train.service.BadgeService;
+import com.train.service.PractitionerService;
+import com.train.service.PromotionService;
+import com.train.service.RoleGuard;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+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.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code train.badge.lecturer} 契约级单测(TDD-RED,S-train-33;TC-1033、TC-3005)。
+ *
+ * <p>需求锚点:docs/tdd/SRS.md「场景定义 §2 域六 P1-S1(Must)」——资质达标审核通过后发放
+ * {@code train_user_badge} 对应档位 {@code lec_t1~t4},档位唯一且留痕,未达标不发。
+ * 契约键在 .tdd/state.json 注册为 {@code train.badge.lecturer}(red_task=S-train-33,stage=RED)。</p>
+ *
+ * <p>本轮只写测试、不改任何 src/main 实现。纯 Mockito(不启 Spring、不连 DB),被测面为
+ * {@link PromotionServiceImpl#evaluateAndRecord(Long, Long)} 经 {@link BadgeService#grantBadge(Long, String, Long, String)}
+ * 发放讲师徽章的链路。覆盖幂等重放 replay=true、同键异载荷 C4092、乐观锁冲突 C422、不存在 C404、
+ * 越权 C403 五类边界。当前实现全部错误语义走 {@code Result.error}(code=500)、无 replay/key/payload
+ * 入参、{@code TrainUserBadge} 无 version 字段、忽略并发写影响行数,故本类预期为 RED(至少 1 条断言失败)。
+ * 契约错误码({@code Result.code}):</p>
+ * <ul>
+ *   <li>C4092 = 4092 同档位键(lec_tX)但载荷不一致(晋升规则/指标阈值/操作人变化)</li>
+ *   <li>C422  = 422  乐观锁/并发更新冲突(实体须有 version,并发写影响 0 行须报错)</li>
+ *   <li>C404  = 404  晋升规则/档位不存在</li>
+ *   <li>C403  = 403  非管理员触发批量晋升降发章</li>
+ * </ul>
+ *
+ * <p>说明:本仓后端模块为 train-backend(无字面量 train-impl 模块),测试按既有契约单测惯例落在
+ * train-backend/src/test/java/com/train/service/impl/,与 S-train-4/5/7~14 的契约测试同目录;
+ * 当前契约层尚未落地(SRS 全键「⏳未契约化·契约先行待落地」),错误码直接以 Result.code 表达。</p>
+ */
+class TrainBadgeLecturerContractTest {
+
+    private static final int CODE_OK = 200;
+    private static final int CODE_SAME_KEY_DIFF_PAYLOAD = 4092;
+    private static final int CODE_VERSION_CONFLICT = 422;
+    private static final int CODE_NOT_FOUND = 404;
+    private static final int CODE_FORBIDDEN = 403;
+
+    private static final Long USER_ID = 3001L;
+    private static final Long RULE_ID = 5001L;
+    private static final Long OTHER_RULE_ID = 5002L;
+
+    private PromotionServiceImpl service;
+    private BadgeService badgeService;
+    private TrainPromotionRuleMapper ruleMapper;
+    private TrainPractitionerProfileMapper profileMapper;
+    private TrainPromotionRecordMapper recordMapper;
+    private TrainServiceOrderMapper orderMapper;
+    private TrainCreditLedgerMapper ledgerMapper;
+    private TrainEvalRecordMapper evalMapper;
+    private PractitionerService practitionerService;
+    private RoleGuard roleGuard;
+    private TrainPractitionerProfile profile;
+
+    @BeforeEach
+    void setUp() {
+        service = new PromotionServiceImpl();
+        badgeService = mock(BadgeService.class);
+        ruleMapper = mock(TrainPromotionRuleMapper.class);
+        profileMapper = mock(TrainPractitionerProfileMapper.class);
+        recordMapper = mock(TrainPromotionRecordMapper.class);
+        orderMapper = mock(TrainServiceOrderMapper.class);
+        ledgerMapper = mock(TrainCreditLedgerMapper.class);
+        evalMapper = mock(TrainEvalRecordMapper.class);
+        practitionerService = mock(PractitionerService.class);
+        roleGuard = mock(RoleGuard.class);
+
+        ReflectionTestUtils.setField(service, "trainPromotionRuleMapper", ruleMapper);
+        ReflectionTestUtils.setField(service, "trainPromotionRecordMapper", recordMapper);
+        ReflectionTestUtils.setField(service, "trainPractitionerProfileMapper", profileMapper);
+        ReflectionTestUtils.setField(service, "trainServiceOrderMapper", orderMapper);
+        ReflectionTestUtils.setField(service, "trainCreditLedgerMapper", ledgerMapper);
+        ReflectionTestUtils.setField(service, "trainEvalRecordMapper", evalMapper);
+        ReflectionTestUtils.setField(service, "practitionerService", practitionerService);
+        ReflectionTestUtils.setField(service, "badgeService", badgeService);
+        ReflectionTestUtils.setField(service, "roleGuard", roleGuard);
+
+        profile = new TrainPractitionerProfile();
+        profile.setId(7001L);
+        profile.setUserId(USER_ID);
+        profile.setDisplayName("张*三");
+        profile.setAuthLevel("none");
+        profile.setStatus("active");
+        profile.setDeleted(0);
+        when(profileMapper.selectOne(any())).thenReturn(profile);
+    }
+
+    private static TrainPromotionRule rule(Long id, String authLevel, String conditions) {
+        TrainPromotionRule r = new TrainPromotionRule();
+        r.setId(id);
+        r.setName(authLevel + " 讲师晋升规则");
+        r.setAuthLevel(authLevel);
+        r.setConditions(conditions);
+        r.setEnabled(1);
+        r.setVersion(1);
+        r.setDeleted(0);
+        return r;
+    }
+
+    private static String serveCountAtLeast(long value) {
+        return "[{\"metric\":\"serve_count\",\"op\":\">=\",\"value\":" + value + "}]";
+    }
+
+    // ==================== 对照基线(当前实现已覆盖,作为 RED 的对照) ====================
+
+    /** TC-1033 主路径:达标晋升 T2 → 发放 lec_t2 档位徽章(系统颁发 grantedBy=0)。 */
+    @Test
+    void eligiblePromotionGrantsLecturerBadgeT2() {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(rule(RULE_ID, "T2", serveCountAtLeast(1)));
+        when(orderMapper.selectCount(any())).thenReturn(5L);
+
+        Result<Map<String, Object>> r = service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        assertEquals(CODE_OK, r.getCode());
+        assertEquals(Boolean.TRUE, r.getData().get("promoted"));
+        verify(badgeService, times(1)).grantBadge(eq(USER_ID), eq("lec_t2"), eq(0L), anyString());
+    }
+
+    /** 未达标不发:条件缺口存在时不得发放任何讲师徽章。 */
+    @Test
+    void notEligibleDoesNotGrantAnyBadge() {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(rule(RULE_ID, "T2", serveCountAtLeast(10)));
+        when(orderMapper.selectCount(any())).thenReturn(2L);
+
+        Result<Map<String, Object>> r = service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        assertEquals(CODE_OK, r.getCode());
+        assertEquals(Boolean.FALSE, r.getData().get("promoted"));
+        verify(badgeService, never()).grantBadge(any(), any(), any(), any());
+    }
+
+    /** 档位唯一:T1~T4 各自只发放对应的唯一档位键,不串档。 */
+    @ParameterizedTest
+    @CsvSource({"T1,lec_t1", "T2,lec_t2", "T3,lec_t3", "T4,lec_t4"})
+    void eachEligibleTierGrantsItsOwnUniqueBadge(String authLevel, String expectedBadgeKey) {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(rule(RULE_ID, authLevel, serveCountAtLeast(1)));
+        when(orderMapper.selectCount(any())).thenReturn(5L);
+
+        Result<Map<String, Object>> r = service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        assertEquals(CODE_OK, r.getCode());
+        verify(badgeService, times(1)).grantBadge(eq(USER_ID), eq(expectedBadgeKey), eq(0L), anyString());
+    }
+
+    /** 留痕:发章备注须记录晋升档位(proof),便于审计 trail。 */
+    @Test
+    void grantBadgeRecordsProofForAudit() {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(rule(RULE_ID, "T2", serveCountAtLeast(1)));
+        when(orderMapper.selectCount(any())).thenReturn(5L);
+
+        service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        ArgumentCaptor<String> remark = ArgumentCaptor.forClass(String.class);
+        verify(badgeService).grantBadge(eq(USER_ID), eq("lec_t2"), eq(0L), remark.capture());
+        assertTrue(remark.getValue().contains("T2"), "留痕:发章备注 proof 须记录晋升档位 T2");
+    }
+
+    /** replay=true 同键重放:徽章已存在时复用首次结果,不重复 insert(档位唯一)。 */
+    @Test
+    void replayTrueSameKeyKeepsFirstGrantAndSkipsSecondInsert() {
+        BadgeService badge = new BadgeService();
+        TrainBadgeMapper badgeMapper = mock(TrainBadgeMapper.class);
+        TrainUserBadgeMapper userBadgeMapper = mock(TrainUserBadgeMapper.class);
+        ReflectionTestUtils.setField(badge, "trainBadgeMapper", badgeMapper);
+        ReflectionTestUtils.setField(badge, "trainUserBadgeMapper", userBadgeMapper);
+
+        when(badgeMapper.selectCount(any())).thenReturn(1L); // 目录已存在,ensureCatalog 早返回
+        TrainBadge catalog = new TrainBadge();
+        catalog.setBadgeKey("lec_t2");
+        catalog.setConditionDesc("T2认证");
+        when(badgeMapper.selectOne(any())).thenReturn(catalog);
+
+        final int[] exist = {0};
+        when(userBadgeMapper.selectCount(any())).thenAnswer(inv -> (long) exist[0]);
+        doAnswer(inv -> {
+            TrainUserBadge ub = inv.getArgument(0);
+            assertEquals("lec_t2", ub.getBadgeKey());
+            exist[0]++;
+            return 1;
+        }).when(userBadgeMapper).insert(any(TrainUserBadge.class));
+
+        assertTrue(badge.grantBadge(USER_ID, "lec_t2", 0L, "首次发放"));
+        assertTrue(badge.grantBadge(USER_ID, "lec_t2", 0L, "replay=true 重放"));
+        verify(userBadgeMapper, times(1)).insert(any(TrainUserBadge.class));
+    }
+
+    // ==================== 边界 0:幂等重放契约入口 ====================
+
+    /**
+     * 契约入口:发章须暴露可显式表达 replay/key/payload 的 Result 入口(至少 4 入参),
+     * 否则调用方无法声明「幂等重放」,也无法在同键异载荷时返回 C4092。
+     * 当前 PromotionService 无发章入口(evaluateAndRecord 仅 2 入参),BadgeService.grantBadge
+     * 虽 4 入参但返回 boolean 而非 Result,无法满足。
+     */
+    @Test
+    void replayEntryMustAcceptIdempotencyKeyAndPayload() {
+        boolean hasReplayEntry = false;
+        for (Method m : PromotionService.class.getMethods()) {
+            String name = m.getName().toLowerCase();
+            boolean grantLike = name.contains("badge") || name.contains("grant")
+                    || name.contains("promote") || name.contains("evaluate") || name.contains("lecturer");
+            if (grantLike && Result.class.isAssignableFrom(m.getReturnType())
+                    && m.getParameterCount() >= 4) {
+                hasReplayEntry = true;
+                break;
+            }
+        }
+        assertTrue(hasReplayEntry,
+                "train.badge.lecturer 契约要求 PromotionService 暴露带 replay/key/payload 的发章入口"
+                        + "(Result 返回且至少 4 入参)以支持 replay=true;"
+                        + "当前仅有 evaluateAndRecord(Long,Long) 2 入参,无法表达幂等重放");
+    }
+
+    // ==================== 边界 1:同键异载荷 C4092 ====================
+
+    /**
+     * 同一档位键 lec_t2 已晋升发放,再次重放却携带不同载荷(另一规则/指标阈值):
+     * 必须返回 C4092 让调用方感知冲突,禁止静默按 200 复用既有档位。
+     */
+    @Test
+    void sameKeyDifferentPayloadReturnsC4092() {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(rule(RULE_ID, "T2", serveCountAtLeast(1)));
+        when(orderMapper.selectCount(any())).thenReturn(5L);
+        Result<Map<String, Object>> first = service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        when(ruleMapper.selectById(OTHER_RULE_ID)).thenReturn(rule(OTHER_RULE_ID, "T2",
+                "[{\"metric\":\"rating\",\"op\":\">=\",\"value\":300}]"));
+        Result<Map<String, Object>> second = service.evaluateAndRecord(USER_ID, OTHER_RULE_ID);
+
+        assertEquals(CODE_OK, first.getCode());
+        assertEquals(CODE_SAME_KEY_DIFF_PAYLOAD, second.getCode(),
+                "同一 lec_t2 档位键携带不同晋升载荷(规则/指标阈值)重放必须返回 C4092(4092) 冲突,"
+                        + "禁止静默按 200 复用既有档位");
+    }
+
+    // ==================== 边界 2:乐观锁冲突 C422 ====================
+
+    /** 用户徽章实体须有 version 字段支撑并发发章的乐观锁 C422。 */
+    @Test
+    void userBadgeEntityMustHaveVersionField() {
+        Field versionField = findField(TrainUserBadge.class, "version");
+        assertNotNull(versionField,
+                "train_user_badge 实体必须声明 version 字段以支撑并发发章冲突 C422("
+                        + CODE_VERSION_CONFLICT + ");当前实体无 version");
+    }
+
+    // ==================== 边界 3:不存在 C404 ====================
+
+    /** 晋升规则/档位配置不存在 → C404,而非笼统的 500。 */
+    @Test
+    void nonExistentPromotionRuleReturns404() {
+        when(ruleMapper.selectById(RULE_ID)).thenReturn(null);
+
+        Result<Map<String, Object>> r = service.evaluateAndRecord(USER_ID, RULE_ID);
+
+        assertEquals(CODE_NOT_FOUND, r.getCode(),
+                "晋升规则不存在时发章入口必须返回 C404(404),不得降级为笼统的 500");
+    }
+
+    // ==================== 边界 4:越权 C403 ====================
+
+    /** 非管理员触发周期评定批量晋升降发章 → C403,而非笼统的 500。 */
+    @Test
+    void nonAdminScanGrantReturns403() {
+        when(roleGuard.requireAdminRole(Boolean.FALSE)).thenReturn("需要管理员权限");
+
+        Result<Map<String, Object>> r = service.scanAndGrant(Boolean.FALSE);
+
+        assertEquals(CODE_FORBIDDEN, r.getCode(),
+                "非管理员触发批量晋升降发章必须返回 C403(403),不得降级为笼统的 500");
+    }
+
+    // ==================== helpers ====================
+
+    private static Field findField(Class<?> type, String name) {
+        Class<?> c = type;
+        while (c != null) {
+            try {
+                return c.getDeclaredField(name);
+            } catch (NoSuchFieldException ignored) {
+                c = c.getSuperclass();
+            }
+        }
+        return null;
+    }
+}