Kaynağa Gözat

test(train): train.hours.ingest 契约级 RED 单测(40/20/90 封顶/幂等/C4092/C422/C404/C403)

新增 TrainHoursIngestContractTest(8 例,7 红 1 基线绿):
- TC-1008 theory≤40h / practice≤20h / total≤90h 分列封顶,当前 accrueAccount 无条件累加未封顶
- 幂等重放 replay=true 同键去重(基线通过)
- 同键异载荷 C4092 / 乐观锁冲突 C422 / 不存在 C404 / 越权 C403 错误码契约
- 纯 Mockito,不启 Spring、不连 DB;src/main 零改动
liaoxg 8 saat önce
ebeveyn
işleme
2d8ea08f21

+ 243 - 0
train-backend/src/test/java/com/train/service/impl/TrainHoursIngestContractTest.java

@@ -0,0 +1,243 @@
+package com.train.service.impl;
+
+import com.train.common.Result;
+import com.train.entity.TrainCreditAccount;
+import com.train.entity.TrainCreditLedger;
+import com.train.mapper.TrainAttendanceMapper;
+import com.train.mapper.TrainCreditAccountMapper;
+import com.train.mapper.TrainCreditLedgerMapper;
+import com.train.service.CfcCreditSyncService;
+import com.train.service.CreditService;
+import com.train.service.RoleGuard;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.lang.reflect.Method;
+import java.time.Year;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code train.hours.ingest} 契约级单测(TDD-RED,S-train-8;TC-1008 / TC-3002 / TC-2007)。
+ *
+ * <p>需求锚点:docs/tdd/SRS.md「场景定义 §2 域一 T3-S2(Must)」——多来源(培训 / 实习 / 社区 /
+ * 家庭服务换算)学时入账,theory≤40 / practice≤20 / total≤90 分列正确,无重复入账,12-31 结算。</p>
+ *
+ * <p>本轮只写测试、不改任何 src/main 实现。纯 Mockito(不启 Spring、不连 DB)。被测面为学时入账链路
+ * {@link CreditServiceImpl#ledgerPending}(幂等入账)→ {@link CreditServiceImpl#applyEffective}(T+3 生效)
+ * → accrueAccount(分列物化),以及同一学时服务上负责错误语义的 object / disposeObjected。</p>
+ *
+ * <p>当前实现缺陷(RED 依据):accrueAccount 对 theory / practice / total 只做无条件累加,未做 40h/20h/90h
+ * 封顶;入账入口仅返回 boolean,无法表达同键异载荷 C4092;object / disposeObjected 全部走 Result.error 的
+ * 500,不区分 C422 / C404 / C403。</p>
+ *
+ * <p>契约错误码(Result.code):C4092=4092 同幂等键异载荷;C422=422 乐观锁冲突;C404=404 不存在;
+ * C403=403 越权。学时单位一律「分钟」整数:40h=2400、20h=1200、90h=5400。</p>
+ */
+class TrainHoursIngestContractTest {
+
+    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 int CAP_THEORY = 2400;    // 40h
+    private static final int CAP_PRACTICE = 1200;  // 20h
+    private static final int CAP_TOTAL = 5400;     // 90h
+
+    private static final Long USER = 990008L;
+    private static final int YEAR = Year.now().getValue();
+
+    private CreditServiceImpl service;
+    private TrainCreditAccountMapper accountMapper;
+    private TrainCreditLedgerMapper ledgerMapper;
+    private RoleGuard roleGuard;
+
+    @BeforeEach
+    void setUp() {
+        service = new CreditServiceImpl();
+        accountMapper = mock(TrainCreditAccountMapper.class);
+        ledgerMapper = mock(TrainCreditLedgerMapper.class);
+        roleGuard = mock(RoleGuard.class);
+
+        ReflectionTestUtils.setField(service, "trainCreditAccountMapper", accountMapper);
+        ReflectionTestUtils.setField(service, "trainCreditLedgerMapper", ledgerMapper);
+        ReflectionTestUtils.setField(service, "trainAttendanceMapper", mock(TrainAttendanceMapper.class));
+        ReflectionTestUtils.setField(service, "roleGuard", roleGuard);
+        ReflectionTestUtils.setField(service, "cfcCreditSyncService", mock(CfcCreditSyncService.class));
+        ReflectionTestUtils.setField(service, "effectiveDelayHours", 72);
+    }
+
+    private static TrainCreditAccount account(int theory, int practice, int total) {
+        TrainCreditAccount a = new TrainCreditAccount();
+        a.setId(8801L);
+        a.setUserId(USER);
+        a.setYear(YEAR);
+        a.setTheoryHours(theory);
+        a.setPracticeHours(practice);
+        a.setTotalHours(total);
+        a.setEffectiveHours(total);
+        a.setPendingHours(0);
+        a.setStatus("active");
+        return a;
+    }
+
+    private static TrainCreditLedger pendingLedger(long id, String category, int hours) {
+        TrainCreditLedger l = new TrainCreditLedger();
+        l.setId(id);
+        l.setUserId(USER);
+        l.setYear(YEAR);
+        l.setSourceType("training");
+        l.setSourceCategory(category);
+        l.setSourceId("src-" + id);
+        l.setHours(hours);
+        l.setStatus("pending");
+        l.setDeleted(0);
+        return l;
+    }
+
+    /** 取账户最后一次 updateById 的快照(accrueAccount 写回结果)。 */
+    private TrainCreditAccount lastUpdatedAccount() {
+        ArgumentCaptor<TrainCreditAccount> cap = ArgumentCaptor.forClass(TrainCreditAccount.class);
+        verify(accountMapper, atLeastOnce()).updateById(cap.capture());
+        List<TrainCreditAccount> all = cap.getAllValues();
+        return all.get(all.size() - 1);
+    }
+
+    private static int hoursOf(Integer v) {
+        return v == null ? 0 : v;
+    }
+
+    // ==================== 边界 0:幂等重放 replay=true(基线,当前已覆盖) ====================
+
+    /** 同幂等键 (userId, sourceType, sourceId) 重放:去重,只入账一次。 */
+    @Test
+    void replayTrueWithSameKeyDeduplicatesAndSkipsSecondInsert() {
+        // 首次 selectCount=0(键不存在);重放 selectCount=1(键已存在)
+        when(ledgerMapper.selectCount(any())).thenReturn(0L, 1L);
+
+        boolean first = service.ledgerPending(USER, "training", "S-1008", "theory", 480, "首次入账");
+        boolean replay = service.ledgerPending(USER, "training", "S-1008", "theory", 480, "重放 replay=true");
+
+        assertTrue(first, "首次入账应新增一条台账");
+        assertFalse(replay, "replay=true 命中同幂等键必须去重(返回 false 表示跳过重复入账)");
+        verify(ledgerMapper, times(1)).insert(any(TrainCreditLedger.class));
+    }
+
+    // ==================== TC-1008:40 / 20 / 90 分列封顶 ====================
+
+    /** 理论学时单笔 50h 入账:必须截断到 40h=2400 分钟。 */
+    @Test
+    void theoryHoursNeverExceedFortyHourCap() {
+        when(accountMapper.selectOne(any())).thenReturn(account(0, 0, 0));
+        TrainCreditLedger l = pendingLedger(8001L, "theory", 3000); // 50h,超 40h 上限
+        when(ledgerMapper.selectById(8001L)).thenReturn(l);
+
+        service.applyEffective(l);
+
+        int theory = hoursOf(lastUpdatedAccount().getTheoryHours());
+        assertTrue(theory <= CAP_THEORY,
+                "TC-1008 理论学时上限 40h=2400 分钟,实际入账 " + theory + " 分钟(50h 未被封顶)");
+    }
+
+    /** 实践学时单笔 25h 入账:必须截断到 20h=1200 分钟。 */
+    @Test
+    void practiceHoursNeverExceedTwentyHourCap() {
+        when(accountMapper.selectOne(any())).thenReturn(account(0, 0, 0));
+        TrainCreditLedger l = pendingLedger(8002L, "practice", 1500); // 25h,超 20h 上限
+        when(ledgerMapper.selectById(8002L)).thenReturn(l);
+
+        service.applyEffective(l);
+
+        int practice = hoursOf(lastUpdatedAccount().getPracticeHours());
+        assertTrue(practice <= CAP_PRACTICE,
+                "TC-1008 实践学时上限 20h=1200 分钟,实际入账 " + practice + " 分钟(25h 未被封顶)");
+    }
+
+    /** 其他来源单笔 100h 入账:总学时必须截断到 90h=5400 分钟。 */
+    @Test
+    void totalHoursNeverExceedNinetyHourCap() {
+        when(accountMapper.selectOne(any())).thenReturn(account(0, 0, 0));
+        TrainCreditLedger l = pendingLedger(8003L, "other", 6000); // 100h,超 90h 上限
+        when(ledgerMapper.selectById(8003L)).thenReturn(l);
+
+        service.applyEffective(l);
+
+        int total = hoursOf(lastUpdatedAccount().getTotalHours());
+        assertTrue(total <= CAP_TOTAL,
+                "TC-1008 总学时上限 90h=5400 分钟,实际入账 " + total + " 分钟(100h 未被封顶)");
+    }
+
+    // ==================== 边界 1:同键异载荷 C4092 ====================
+
+    /**
+     * 同一幂等键 (userId, sourceType, sourceId) 但载荷指纹不同(category/hours 变更):
+     * 契约要求入账入口返回 Result 并给出 C4092,禁止 boolean ledgerPending 静默吞掉冲突。
+     */
+    @Test
+    void sameKeyDifferentPayloadReturnsC4092() {
+        boolean hasResultIngest = false;
+        for (Method m : CreditService.class.getMethods()) {
+            if (m.getName().toLowerCase().contains("ingest")
+                    && Result.class.isAssignableFrom(m.getReturnType())) {
+                hasResultIngest = true;
+                break;
+            }
+        }
+        assertTrue(hasResultIngest,
+                "train.hours.ingest 契约要求 CreditService 暴露返回 Result 的入账入口:"
+                        + "同幂等键 (userId,sourceType,sourceId) 携带不同 category/hours 载荷时必须返回 "
+                        + "C4092(" + CODE_SAME_KEY_DIFF_PAYLOAD + ");当前仅有 boolean ledgerPending,无法表达冲突码");
+    }
+
+    // ==================== 边界 2:乐观锁冲突 C422 ====================
+
+    /** 台账 updateById 影响 0 行(并发丢失更新):必须 C422,不得按成功返回。 */
+    @Test
+    void optimisticLockConflictReturnsC422() {
+        TrainCreditLedger l = pendingLedger(8006L, "theory", 480);
+        when(ledgerMapper.selectById(8006L)).thenReturn(l);
+        when(ledgerMapper.updateById(any(TrainCreditLedger.class))).thenReturn(0);
+
+        Result<Void> r = service.object(USER, 8006L, "并发更新");
+
+        assertEquals(CODE_VERSION_CONFLICT, r.getCode(),
+                "学时台账更新影响 0 行(乐观锁冲突)必须返回 C422(422),不得静默按成功返回");
+    }
+
+    // ==================== 边界 3:不存在 C404 ====================
+
+    /** 目标台账不存在:必须 C404,而非笼统的 500。 */
+    @Test
+    void nonExistentLedgerReturnsC404() {
+        when(ledgerMapper.selectById(999999L)).thenReturn(null);
+
+        Result<Void> r = service.object(USER, 999999L, "不存在");
+
+        assertEquals(CODE_NOT_FOUND, r.getCode(), "学时台账不存在必须返回 C404(404)");
+    }
+
+    // ==================== 边界 4:越权 C403(适用时) ====================
+
+    /** 非管理员处置学时入账结果:必须 C403。 */
+    @Test
+    void unauthorizedDisposeReturnsC403() {
+        when(roleGuard.requireAdminRole(Boolean.FALSE)).thenReturn("需要管理员权限");
+
+        Result<Boolean> r = service.disposeObjected(Boolean.FALSE, USER, 8008L, Boolean.FALSE, null);
+
+        assertEquals(CODE_FORBIDDEN, r.getCode(), "非管理员处置学时入账结果必须返回 C403(403)");
+    }
+}