Files
lpt-be/src/test/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImplTest.java
T

486 lines
21 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.guo.learningprogresstracker.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.guo.learningprogresstracker.common.StudyTimePolicy;
import com.guo.learningprogresstracker.dto.ReportSections;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.guo.learningprogresstracker.entity.StudySessionsEntity;
import com.guo.learningprogresstracker.entity.TaskEntity;
import com.guo.learningprogresstracker.enums.StudySessionStateEnum;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper;
import com.guo.learningprogresstracker.mapper.StudyReportsMapper;
import com.guo.learningprogresstracker.mapper.StudySessionsMapper;
import com.guo.learningprogresstracker.service.StudyExpectationsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class StudySessionsServiceImplTest {
@Spy
@InjectMocks
private StudySessionsServiceImpl studySessionsService;
@Mock
private StudyReportsMapper studyReportsMapper;
@Mock
private StudyReportFragmentsMapper studyReportFragmentsMapper;
@Mock
private StudySessionsMapper studySessionsMapper;
@Mock
private StudyExpectationsService studyExpectationsService;
@Mock
private TasksServiceImpl tasksServiceImpl;
@Mock
private AiServiceClient aiServiceClient;
/** 时间口径用真实默认值,避免测试里出现 null 策略;需要改口径时换成自建实例即可 */
@Spy
private StudyTimePolicy studyTimePolicy = StudyTimePolicy.DEFAULT;
@BeforeEach
void setUp() {
// stub updateById,避免调用真实的 getBaseMapper()
doReturn(true).when(studySessionsService).updateById(any());
// stub 条件更新(结束会话抢占),默认视为抢占成功
doReturn(true).when(studySessionsService).update(any(StudySessionsEntity.class), any(Wrapper.class));
// stub removeById,避免调用真实的 getBaseMapper()
doReturn(true).when(studySessionsService).removeById(any(Serializable.class));
// 收敛路径直接使用 ServiceImpl 的 baseMapper 字段,必须显式注入(Mockito 不会填父类字段)
ReflectionTestUtils.setField(studySessionsService, "baseMapper", studySessionsMapper);
}
private StudySessionsEntity createSession(String state, int minutesAgo) {
StudySessionsEntity session = new StudySessionsEntity();
session.setSessionNum("SESSION_TEST");
session.setSessionState(state);
session.setStartTime(LocalDateTime.now().minusMinutes(minutesAgo));
session.setLastStartTime(LocalDateTime.now().minusMinutes(minutesAgo));
session.setEffectiveTime(0);
session.setActualTime(0);
return session;
}
private void mockGetOneOpt(StudySessionsEntity session) {
doReturn(Optional.of(session)).when(studySessionsService).getOneOpt(any(Wrapper.class));
}
/**
* 场景1:ONGOING 状态,有效时间 < 10分钟 → 返回提示消息
*/
@Test
void endedStudySession_ongoing_lessThan10Min_shouldReturnMessage() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertEquals("本次有效学习时间不足10分钟,不计入总学习时间", message);
assertEquals(0, session.getEffectiveTime(), "effectiveTime 应被清零");
assertEquals(StudySessionStateEnum.ENDED.name(), session.getSessionState());
verify(studyReportsMapper).insert(any(StudyReportsEntity.class));
}
/**
* 场景2:ONGOING 状态,有效时间 > 10分钟 → 返回 null(正常结束)
*/
@Test
void endedStudySession_ongoing_moreThan10Min_shouldReturnNull() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 15);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertNull(message, "有效时间超过10分钟不应返回提示");
assertTrue(session.getEffectiveTime() > 0, "effectiveTime 应保留");
assertEquals(StudySessionStateEnum.ENDED.name(), session.getSessionState());
}
/**
* 场景3:PAUSED 状态,有效时间 < 10分钟 → 返回 null(PAUSED 不触发提示)
*/
@Test
void endedStudySession_paused_lessThan10Min_shouldReturnNull() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.PAUSED.name(), 5);
session.setEffectiveTime(5 * 60);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertNull(message, "PAUSED 状态结束不返回提示(用户已主动暂停)");
assertEquals(0, session.getEffectiveTime(), "effectiveTime 仍应被实体层清零");
}
/**
* 场景4:PAUSED 状态,有效时间 > 10分钟 → 返回 null,effectiveTime 保留
*/
@Test
void endedStudySession_paused_moreThan10Min_shouldReturnNull() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.PAUSED.name(), 15);
session.setEffectiveTime(15 * 60);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertNull(message);
assertTrue(session.getEffectiveTime() > 0, "effectiveTime 应保留");
}
/**
* 场景5:无论是否触发清零,学习报告都应正常创建
*/
@Test
void endedStudySession_shouldAlwaysCreateReport() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 3);
mockGetOneOpt(session);
studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "测试报告内容"));
verify(studyReportsMapper).insert(argThat(report ->
"SESSION_TEST".equals(((StudyReportsEntity) report).getSessionNum())
&& "测试报告内容".equals(((StudyReportsEntity) report).getFreeSummary())
));
}
/**
* 场景6:ONGOING 状态,有效时间恰好 = 10分钟 → 有效时间保留(600 不 < 600)
*/
@Test
void endedStudySession_ongoing_exactly10Min_shouldReturnNull() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 10);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertNull(message, "有效时间等于10分钟应保留(阈值为 < 600)");
assertTrue(session.getEffectiveTime() >= 10 * 60, "effectiveTime 应保留");
}
/**
* 场景7:会话不存在 → 抛出异常
*/
@Test
void endedStudySession_sessionNotFound_shouldThrowException() {
doReturn(Optional.empty()).when(studySessionsService).getOneOpt(any(Wrapper.class));
assertThrows(Exception.class, () ->
studySessionsService.endedStudySession("NOT_EXIST", new ReportSections(null, null, "内容")));
}
/**
* 场景8:ONGOING 状态,有效时间极短(1分钟) → 返回提示消息
*/
@Test
void endedStudySession_ongoing_veryShortTime_shouldReturnMessage() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 1);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "学习内容"));
assertEquals("本次有效学习时间不足10分钟,不计入总学习时间", message);
assertEquals(0, session.getEffectiveTime());
}
/**
* 场景9:ONGOING 状态,刚开始就结束(effectiveTime ≈ 0) → 返回提示消息
*/
@Test
void endedStudySession_ongoing_immediatelyEnded_shouldReturnMessage() throws Exception {
StudySessionsEntity session = new StudySessionsEntity();
session.setSessionNum("SESSION_INSTANT");
session.setSessionState(StudySessionStateEnum.ONGOING.name());
session.setStartTime(LocalDateTime.now());
session.setLastStartTime(LocalDateTime.now());
session.setEffectiveTime(0);
session.setActualTime(0);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_INSTANT", new ReportSections(null, null, "内容"));
assertEquals("本次有效学习时间不足10分钟,不计入总学习时间", message);
assertEquals(0, session.getEffectiveTime());
}
/**
* 场景10:确认会话状态被持久化(条件更新:仅当仍未结束时写入)
*/
@Test
void endedStudySession_shouldCallUpdateWithNotEndedCondition() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
session.setId(10);
mockGetOneOpt(session);
studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "内容"));
verify(studySessionsService).update(eq(session), any(Wrapper.class));
}
// ============ 误操作结束(零数据关闭) ============
/**
* 场景11:确认语正确且未产生残片 → 删除预期与会话,零数据关闭
*/
@Test
void abortStudySession_success_shouldDeleteEverything() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
session.setId(1);
mockGetOneOpt(session);
doReturn(0L).when(studyReportFragmentsMapper).selectCount(any());
studySessionsService.abortStudySession("SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION);
verify(studyExpectationsService).deleteBySessionNum("SESSION_TEST");
verify(studySessionsService).removeById(1);
}
/**
* 场景12:确认语不正确 → 抛异常,不删除任何数据
*/
@Test
void abortStudySession_wrongConfirmation_shouldThrow() {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
mockGetOneOpt(session);
ErrorParameterException ex = assertThrows(ErrorParameterException.class, () ->
studySessionsService.abortStudySession("SESSION_TEST", "我不是确认语"));
assertEquals("确认语输入不正确,请核对后重新输入", ex.getMessage());
verify(studyExpectationsService, never()).deleteBySessionNum(any());
verify(studySessionsService, never()).removeById(any());
}
/**
* 场景13:确认语首尾空白应被忽略,仍视为正确
*/
@Test
void abortStudySession_confirmationWithSpaces_shouldSucceed() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.PAUSED.name(), 5);
session.setId(2);
mockGetOneOpt(session);
doReturn(0L).when(studyReportFragmentsMapper).selectCount(any());
studySessionsService.abortStudySession("SESSION_TEST",
" " + StudySessionsServiceImpl.MISOPERATION_CONFIRMATION + " ");
verify(studyExpectationsService).deleteBySessionNum("SESSION_TEST");
verify(studySessionsService).removeById(2);
}
/**
* 场景14:已产生学习残片 → 抛异常,不能误操作结束
*/
@Test
void abortStudySession_hasFragments_shouldThrow() {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
mockGetOneOpt(session);
doReturn(1L).when(studyReportFragmentsMapper).selectCount(any());
ErrorParameterException ex = assertThrows(ErrorParameterException.class, () ->
studySessionsService.abortStudySession("SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION));
assertEquals("这次学习已经产生了学习残片,不能按误操作结束了哦", ex.getMessage());
verify(studyExpectationsService, never()).deleteBySessionNum(any());
verify(studySessionsService, never()).removeById(any());
}
/**
* 场景15:会话已结束 → 抛异常
*/
@Test
void abortStudySession_endedSession_shouldThrow() {
StudySessionsEntity session = createSession(StudySessionStateEnum.ENDED.name(), 5);
mockGetOneOpt(session);
ErrorParameterException ex = assertThrows(ErrorParameterException.class, () ->
studySessionsService.abortStudySession("SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION));
assertEquals("这次学习会话已经结束,不能再误操作结束了", ex.getMessage());
verify(studySessionsService, never()).removeById(any());
}
/**
* 场景16:会话不存在 → 抛异常
*/
@Test
void abortStudySession_sessionNotFound_shouldThrow() {
doReturn(Optional.empty()).when(studySessionsService).getOneOpt(any(Wrapper.class));
assertThrows(ErrorParameterException.class, () ->
studySessionsService.abortStudySession("NOT_EXIST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION));
}
// ============ 会话-01:结算路径统一 ============
/**
* 场景17:ONGOING 且上一段开始于 3 小时前 → 结束时应截断为 25 分钟
*/
@Test
void endedStudySession_ongoingThreeHoursGap_shouldTruncateToOnePomodoro() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 180);
session.setId(20);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "内容"));
assertNull(message, "截断后 25 分钟 ≥ 10 分钟,不应提示时间不足");
assertEquals(25 * 60, session.getEffectiveTime(), "3 小时无人操作只应计入 25 分钟");
verify(studyReportsMapper).insert(any(StudyReportsEntity.class));
}
/**
* 场景18:ONGOING 且上一段开始于 3 小时前 → 暂停时同样应截断为 25 分钟
*/
@Test
void pauseStudySession_ongoingThreeHoursGap_shouldTruncateToOnePomodoro() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 180);
mockGetOneOpt(session);
studySessionsService.pauseStudySession("SESSION_TEST", null);
assertEquals(StudySessionStateEnum.PAUSED.name(), session.getSessionState());
assertEquals(25 * 60, session.getEffectiveTime(), "暂停路径也应按遗忘规则截断");
}
// ============ 会话-02:暂停会话不再弹出超时提示 ============
/**
* 场景19:PAUSED 且 end_time 已存在、last_start_time 很旧 → 不返回 systemMessage
*/
@Test
void startOrContinueStudySession_pausedStaleSession_shouldNotReturnSystemMessage() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.PAUSED.name(), 180);
session.setEndTime(session.getLastStartTime().plusMinutes(25));
session.setEffectiveTime(25 * 60);
mockGetOneOpt(session);
TaskEntity task = new TaskEntity();
task.setTaskNum("TASK_TEST");
task.setTaskName("测试任务");
doReturn(Optional.of(task)).when(tasksServiceImpl).getOneOpt(any(Wrapper.class));
var response = studySessionsService.startOrContinueStudySession("TASK_TEST");
assertNull(response.getSystemMessage(), "已暂停的会话不应再提示超时");
}
// ============ 会话-03:结束会话幂等 ============
/**
* 场景20:重复结束已 ENDED 的会话 → 不重复生成学习报告
*/
@Test
void endedStudySession_alreadyEnded_shouldNotInsertReport() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ENDED.name(), 5);
session.setEffectiveTime(5 * 60);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "内容"));
assertNull(message);
verify(studyReportsMapper, never()).insert(any(StudyReportsEntity.class));
verify(studySessionsService, never()).update(any(StudySessionsEntity.class), any(Wrapper.class));
}
/**
* 场景21:并发结束抢占失败(其他请求已先结束)→ 不重复生成学习报告
*/
@Test
void endedStudySession_concurrentClaimLost_shouldNotInsertReport() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 15);
session.setId(30);
mockGetOneOpt(session);
doReturn(false).when(studySessionsService).update(any(StudySessionsEntity.class), any(Wrapper.class));
String message = studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "内容"));
assertNull(message);
verify(studyReportsMapper, never()).insert(any(StudyReportsEntity.class));
}
// ============ 会话-04:悬挂会话收敛 ============
@Test
void convergeStaleSessionsOfCurrentUser_staleOngoing_shouldPauseTruncateAndMark() {
StudySessionsEntity stale = createSession(StudySessionStateEnum.ONGOING.name(), 180);
doReturn(List.of(stale)).when(studySessionsService).list(any(Wrapper.class));
when(studySessionsMapper.convergeStaleSession(any())).thenReturn(1);
int converged = studySessionsService.convergeStaleSessionsOfCurrentUser();
assertEquals(1, converged);
assertEquals(StudySessionStateEnum.PAUSED.name(), stale.getSessionState());
assertEquals(25 * 60, stale.getEffectiveTime(), "悬挂 3 小时只应计入一个番茄钟");
assertEquals(Boolean.TRUE, stale.getAutoConverged());
}
@Test
void convergeStaleSessionsOfCurrentUser_freshOngoing_shouldNotWrite() {
StudySessionsEntity fresh = createSession(StudySessionStateEnum.ONGOING.name(), 10);
doReturn(List.of(fresh)).when(studySessionsService).list(any(Wrapper.class));
int converged = studySessionsService.convergeStaleSessionsOfCurrentUser();
assertEquals(0, converged, "未超过硬兜底阈值不应收敛");
assertEquals(StudySessionStateEnum.ONGOING.name(), fresh.getSessionState());
verify(studySessionsMapper, never()).convergeStaleSession(any());
}
@Test
void convergeStaleSessionsOfCurrentUser_concurrentClaimLost_shouldCountZero() {
StudySessionsEntity stale = createSession(StudySessionStateEnum.ONGOING.name(), 180);
doReturn(List.of(stale)).when(studySessionsService).list(any(Wrapper.class));
// 条件更新未命中:说明已被其他请求收敛
when(studySessionsMapper.convergeStaleSession(any())).thenReturn(0);
assertEquals(0, studySessionsService.convergeStaleSessionsOfCurrentUser());
}
@Test
void scanAndConvergeStaleSessions_shouldUseCrossTenantScan() {
StudySessionsEntity stale = createSession(StudySessionStateEnum.ONGOING.name(), 200);
when(studySessionsMapper.selectForcePausableSessions(any(), anyInt())).thenReturn(List.of(stale));
when(studySessionsMapper.convergeStaleSession(any())).thenReturn(1);
int converged = studySessionsService.scanAndConvergeStaleSessions();
assertEquals(1, converged);
assertEquals(Boolean.TRUE, stale.getAutoConverged());
verify(studySessionsMapper).selectForcePausableSessions(any(), anyInt());
}
@Test
void getActiveSession_shouldRunLazyConvergenceFirst() {
when(studySessionsMapper.selectList(any())).thenReturn(List.of());
assertNull(studySessionsService.getActiveSession(null));
// 惰性收敛先按状态 + last_start_time 查一次悬挂会话
verify(studySessionsMapper, atLeastOnce()).selectList(any());
}
}