2026-06-30 24681c81c09022f584a57006f2534b5f74723414
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package cn.iocoder.yudao.module.im.service.rtc;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
import cn.iocoder.yudao.module.im.controller.admin.rtc.vo.ImRtcCallCreateReqVO;
import cn.iocoder.yudao.module.im.controller.admin.rtc.vo.ImRtcCallInviteReqVO;
import cn.iocoder.yudao.module.im.dal.dataobject.group.ImGroupMemberDO;
import cn.iocoder.yudao.module.im.dal.dataobject.rtc.ImRtcCallDO;
import cn.iocoder.yudao.module.im.dal.dataobject.rtc.ImRtcParticipantDO;
import cn.iocoder.yudao.module.im.dal.mysql.rtc.ImRtcCallMapper;
import cn.iocoder.yudao.module.im.dal.mysql.rtc.ImRtcParticipantMapper;
import cn.iocoder.yudao.module.im.dal.redis.rtc.ImRtcCallLockRedisDAO;
import cn.iocoder.yudao.module.im.enums.ImConversationTypeEnum;
import cn.iocoder.yudao.module.im.enums.rtc.ImRtcCallStatusEnum;
import cn.iocoder.yudao.module.im.enums.rtc.ImRtcParticipantRoleEnum;
import cn.iocoder.yudao.module.im.enums.rtc.ImRtcParticipantStatusEnum;
import cn.iocoder.yudao.module.im.framework.config.ImProperties;
import cn.iocoder.yudao.module.im.service.group.ImGroupMemberService;
import cn.iocoder.yudao.module.im.service.websocket.ImWebSocketService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.dao.DuplicateKeyException;
 
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
 
import static cn.iocoder.yudao.module.im.enums.ErrorCodeConstants.RTC_GROUP_INVITEE_OVER_LIMIT;
import static cn.iocoder.yudao.module.im.enums.ErrorCodeConstants.RTC_GROUP_INVITEE_REQUIRED;
import static cn.iocoder.yudao.module.im.enums.ErrorCodeConstants.RTC_SELF_BUSY;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
 
/**
 * {@link ImRtcCallServiceImpl} 的单元测试
 *
 * @author 芋道源码
 */
public class ImRtcCallServiceImplTest extends BaseMockitoUnitTest {
 
    @InjectMocks
    private ImRtcCallServiceImpl rtcCallService;
 
    @Mock
    private ImRtcParticipantMapper rtcParticipantMapper;
    @Mock
    private ImRtcCallMapper rtcCallMapper;
    @Mock
    private ImRtcCallLockRedisDAO rtcCallLockRedisDAO;
    @Mock
    private AdminUserApi adminUserApi;
    @Mock
    private ImWebSocketService webSocketService;
    @Mock
    private ImProperties imProperties;
    @Mock
    private ImGroupMemberService groupMemberService;
 
    // ========== timeoutInvitingParticipants ==========
 
    @Test
    public void testTimeoutInvitingParticipants_emptyCandidates_returnsZeroAndNoDownstream() {
        // 准备:无超时候选
        when(rtcParticipantMapper.selectListByStatusAndInviteTimeBefore(
                eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any(LocalDateTime.class)))
                .thenReturn(Collections.emptyList());
 
        // 调用
        int result = rtcCallService.timeoutInvitingParticipants(1);
 
        // 断言:返回 0;无候选时不应触发 user 预查 / call 查询 / 推送
        assertEquals(0, result);
        verifyNoInteractions(adminUserApi, rtcCallMapper, webSocketService);
    }
 
    @Test
    public void testTimeoutInvitingParticipants_thresholdConvertedToCutoff() {
        // 准备:阈值 5 分钟;mock 空候选避免触发后续逻辑
        when(rtcParticipantMapper.selectListByStatusAndInviteTimeBefore(any(), any(LocalDateTime.class)))
                .thenReturn(Collections.emptyList());
 
        // 调用
        LocalDateTime before = LocalDateTime.now();
        rtcCallService.timeoutInvitingParticipants(5);
 
        // 断言:cutoff = now - 5 分钟(允许 5 秒漂移)
        ArgumentCaptor<LocalDateTime> cutoffCaptor = ArgumentCaptor.forClass(LocalDateTime.class);
        verify(rtcParticipantMapper).selectListByStatusAndInviteTimeBefore(
                eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), cutoffCaptor.capture());
        LocalDateTime cutoff = cutoffCaptor.getValue();
        LocalDateTime expected = before.minusMinutes(5);
        assertTrue(Duration.between(cutoff, expected).abs().getSeconds() < 5,
                "cutoff 应当约等于 now - 5 min;实际:" + cutoff);
    }
 
    @Test
    public void testTimeoutInvitingParticipants_casAllFails_noPushNoEndSession() {
        // 准备:候选非空但每个 CAS 都失败(并发已变状态)
        ImRtcParticipantDO p = buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING);
        when(rtcParticipantMapper.selectListByStatusAndInviteTimeBefore(any(), any()))
                .thenReturn(ListUtil.of(p));
        when(adminUserApi.getUserMap(anySet())).thenReturn(MapUtil.of(100L, buildUser(100L)));
        when(rtcParticipantMapper.updateByIdAndStatus(eq(10L), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any()))
                .thenReturn(0);
 
        // 调用
        int result = rtcCallService.timeoutInvitingParticipants(1);
 
        // 断言:CAS 全失败时返回 0;不查 call、不推送
        assertEquals(0, result);
        verify(rtcCallMapper, never()).selectByRoom(any());
        verifyNoInteractions(webSocketService);
    }
 
    @Test
    public void testTimeoutInvitingParticipants_groupCall_pushesNoAnswerSkipsEndSession() {
        // 准备:群通话单候选 CAS 成功;shouldCloseGroupRoom 通过 selectListByRoom 多 JOINED 让其返 false,跳过 endSession
        ImRtcParticipantDO p = buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING);
        when(rtcParticipantMapper.selectListByStatusAndInviteTimeBefore(any(), any()))
                .thenReturn(ListUtil.of(p));
        when(adminUserApi.getUserMap(anySet())).thenReturn(MapUtil.of(100L, buildUser(100L)));
        when(rtcParticipantMapper.updateByIdAndStatus(eq(10L), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any()))
                .thenReturn(1);
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.GROUP, 999L);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(groupMemberService.getActiveGroupMemberUserIdsByGroupId(999L)).thenReturn(ListUtil.of(200L, 201L));
        // 房内 2 个 JOINED + 1 个 INVITING → shouldCloseGroupRoom 返 false
        when(rtcParticipantMapper.selectListByRoom("r1")).thenReturn(ListUtil.of(
                buildParticipant(20L, "r1", 200L, ImRtcParticipantStatusEnum.JOINED),
                buildParticipant(21L, "r1", 201L, ImRtcParticipantStatusEnum.JOINED),
                buildParticipant(22L, "r1", 202L, ImRtcParticipantStatusEnum.INVITING)
        ));
 
        // 调用
        int result = rtcCallService.timeoutInvitingParticipants(1);
 
        // 断言:成功 1 个;NO_ANSWER 信令推到主叫;不触发 endSession
        assertEquals(1, result);
        verify(webSocketService).sendNotificationAsync(eq(200L), anyInt(), anyInt(), any());
        verify(rtcCallMapper, never()).updateByIdAndStatusIn(any(), anyCollection(), any());
    }
 
    @Test
    public void testTimeoutInvitingParticipants_callMissing_silentSkip() {
        // 准备:CAS 成功后通话主表缺失(异常兜底场景)
        ImRtcParticipantDO p = buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING);
        when(rtcParticipantMapper.selectListByStatusAndInviteTimeBefore(any(), any()))
                .thenReturn(ListUtil.of(p));
        when(adminUserApi.getUserMap(anySet())).thenReturn(MapUtil.of(100L, buildUser(100L)));
        when(rtcParticipantMapper.updateByIdAndStatus(eq(10L), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any()))
                .thenReturn(1);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(null);
 
        // 调用
        int result = rtcCallService.timeoutInvitingParticipants(1);
 
        // 断言:CAS 已成功但 call 缺失视为部分失败返 0;不应推送
        assertEquals(0, result);
        verifyNoInteractions(webSocketService);
    }
 
    // ========== noAnswerCallCheck ==========
 
    @Test
    public void testNoAnswerCallCheck_authFails_silentNoOp() {
        // 准备:selectByRoomAndUserId 返 null 覆盖三种鉴权失败场景(非参与者 / 非法 room / null room)
        when(rtcParticipantMapper.selectByRoomAndUserId(any(), eq(100L))).thenReturn(null);
 
        // 调用
        rtcCallService.noAnswerCallCheck(100L, "r1");
        rtcCallService.noAnswerCallCheck(100L, "");
        rtcCallService.noAnswerCallCheck(100L, null);
 
        // 断言:仅鉴权查询了 3 次;不应进入后续超时扫描 / 推送
        verify(rtcParticipantMapper, times(3)).selectByRoomAndUserId(any(), eq(100L));
        verify(rtcParticipantMapper, never()).selectListByRoomAndStatusAndInviteTimeBefore(any(), any(), any());
        verifyNoInteractions(adminUserApi, webSocketService);
    }
 
    @Test
    public void testNoAnswerCallCheck_usesBackendThreshold_notFrontend() {
        // 准备:鉴权通过 + 后端配置阈值 2 分钟 + 无候选(避免触发推送)
        when(rtcParticipantMapper.selectByRoomAndUserId("r1", 100L))
                .thenReturn(buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING));
        ImProperties.Rtc rtcConfig = new ImProperties.Rtc();
        rtcConfig.setInviteTimeoutMinutes(2);
        when(imProperties.getRtc()).thenReturn(rtcConfig);
        when(rtcParticipantMapper.selectListByRoomAndStatusAndInviteTimeBefore(
                eq("r1"), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any(LocalDateTime.class)))
                .thenReturn(Collections.emptyList());
 
        // 调用
        LocalDateTime before = LocalDateTime.now();
        rtcCallService.noAnswerCallCheck(100L, "r1");
 
        // 断言:扫描时使用 cutoff = now - 2 分钟(后端配置),而非前端 60s
        ArgumentCaptor<LocalDateTime> cutoffCaptor = ArgumentCaptor.forClass(LocalDateTime.class);
        verify(rtcParticipantMapper).selectListByRoomAndStatusAndInviteTimeBefore(
                eq("r1"), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), cutoffCaptor.capture());
        LocalDateTime cutoff = cutoffCaptor.getValue();
        LocalDateTime expected = before.minusMinutes(2);
        assertTrue(Duration.between(cutoff, expected).abs().getSeconds() < 5,
                "cutoff 应当约等于 now - 2 min(后端配置);实际:" + cutoff);
    }
 
    @Test
    public void testNoAnswerCallCheck_groupCall_pushesNoAnswer() {
        // 准备:鉴权通过 + 单候选 CAS 成功 + 群通话不关房
        when(rtcParticipantMapper.selectByRoomAndUserId("r1", 100L))
                .thenReturn(buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING));
        ImProperties.Rtc rtcConfig = new ImProperties.Rtc();
        rtcConfig.setInviteTimeoutMinutes(1);
        when(imProperties.getRtc()).thenReturn(rtcConfig);
        ImRtcParticipantDO timeoutTarget = buildParticipant(11L, "r1", 101L, ImRtcParticipantStatusEnum.INVITING);
        when(rtcParticipantMapper.selectListByRoomAndStatusAndInviteTimeBefore(
                eq("r1"), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any()))
                .thenReturn(ListUtil.of(timeoutTarget));
        when(adminUserApi.getUserMap(anySet())).thenReturn(MapUtil.of(101L, buildUser(101L)));
        when(rtcParticipantMapper.updateByIdAndStatus(eq(11L), eq(ImRtcParticipantStatusEnum.INVITING.getStatus()), any()))
                .thenReturn(1);
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.GROUP, 999L);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(groupMemberService.getActiveGroupMemberUserIdsByGroupId(999L)).thenReturn(ListUtil.of(200L, 201L));
        // 让 shouldCloseGroupRoom 返 false
        when(rtcParticipantMapper.selectListByRoom("r1")).thenReturn(ListUtil.of(
                buildParticipant(20L, "r1", 200L, ImRtcParticipantStatusEnum.JOINED),
                buildParticipant(21L, "r1", 201L, ImRtcParticipantStatusEnum.JOINED)
        ));
 
        // 调用
        rtcCallService.noAnswerCallCheck(100L, "r1");
 
        // 断言:NO_ANSWER 信令推到主叫 200L;不触发 endSession
        verify(webSocketService).sendNotificationAsync(eq(200L), anyInt(), anyInt(), any());
        verify(rtcCallMapper, never()).updateByIdAndStatusIn(any(), anyCollection(), any());
    }
 
    // ========== createCall ==========
 
    @Test
    public void testCreateCall_groupOnlyInviteSelf_throwInviteeRequired() throws Exception {
        when(imProperties.getRtc()).thenReturn(new ImProperties.Rtc());
        when(rtcCallLockRedisDAO.lockGroup(eq(10L), any())).thenAnswer(invocation -> {
            @SuppressWarnings("unchecked")
            Callable<ImRtcCallDO> callable = invocation.getArgument(1);
            return callable.call();
        });
        ImRtcCallCreateReqVO reqVO = new ImRtcCallCreateReqVO();
        reqVO.setConversationType(ImConversationTypeEnum.GROUP.getType());
        reqVO.setGroupId(10L);
        reqVO.setInviteeIds(CollUtil.newHashSet(100L));
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> rtcCallService.createCall(100L, reqVO));
 
        assertEquals(RTC_GROUP_INVITEE_REQUIRED.getCode(), exception.getCode());
        verify(rtcParticipantMapper, never()).insertBatch(anyList());
    }
 
    // ========== acceptCall / joinCall 忙线校验 ==========
 
    @Test
    public void testAcceptCall_joinedOtherRoom_throwSelfBusy() {
        // 准备:当前通话仍在邀请中,但用户已加入另一个房间
        when(imProperties.getRtc()).thenReturn(new ImProperties.Rtc());
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.PRIVATE, null);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(rtcParticipantMapper.selectByRoomAndUserId("r1", 100L))
                .thenReturn(buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.INVITING));
        when(rtcParticipantMapper.selectLastOneByUserIdAndStatusInAndRoomNot(eq(100L), anyCollection(), eq("r1")))
                .thenReturn(buildParticipant(11L, "r2", 100L, ImRtcParticipantStatusEnum.JOINED));
 
        // 调用 + 断言:拒绝接听,不覆盖其它房间状态
        ServiceException exception = assertThrows(ServiceException.class,
                () -> rtcCallService.acceptCall(100L, "r1"));
        assertEquals(RTC_SELF_BUSY.getCode(), exception.getCode());
        verify(rtcParticipantMapper, never()).updateByIdAndStatus(eq(10L), any(), any());
    }
 
    @Test
    public void testJoinCall_joinedOtherRoom_throwSelfBusy() {
        // 准备:群通话活跃,用户已加入另一个房间
        when(imProperties.getRtc()).thenReturn(new ImProperties.Rtc());
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.GROUP, 999L);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(groupMemberService.validateMemberInGroup(999L, 100L)).thenReturn(new ImGroupMemberDO());
        when(rtcParticipantMapper.selectLastOneByUserIdAndStatusInAndRoomNot(eq(100L), anyCollection(), eq("r1")))
                .thenReturn(buildParticipant(11L, "r2", 100L, ImRtcParticipantStatusEnum.JOINED));
 
        // 调用 + 断言:拒绝加入,不写参与者状态
        ServiceException exception = assertThrows(ServiceException.class,
                () -> rtcCallService.joinCall(100L, "r1"));
        assertEquals(RTC_SELF_BUSY.getCode(), exception.getCode());
        verify(rtcParticipantMapper, never()).insert(any(ImRtcParticipantDO.class));
        verify(rtcParticipantMapper, never()).updateById(any(ImRtcParticipantDO.class));
    }
 
    @Test
    public void testJoinCall_insertDuplicateKey_reuseExistingParticipant() {
        // 准备:群通话活跃,首次查询无参与者,插入时命中唯一键
        when(imProperties.getRtc()).thenReturn(new ImProperties.Rtc());
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.GROUP, 999L);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(groupMemberService.validateMemberInGroup(999L, 100L)).thenReturn(new ImGroupMemberDO());
        when(rtcParticipantMapper.selectLastOneByUserIdAndStatusInAndRoomNot(eq(100L), anyCollection(), eq("r1")))
                .thenReturn(null);
        when(rtcParticipantMapper.selectByRoomAndUserId("r1", 100L))
                .thenReturn(null, buildParticipant(10L, "r1", 100L, ImRtcParticipantStatusEnum.JOINED));
        when(rtcParticipantMapper.insert(any(ImRtcParticipantDO.class))).thenThrow(new DuplicateKeyException("dup"));
 
        // 调用
        ImRtcCallDO result = rtcCallService.joinCall(100L, "r1");
 
        // 断言:不向上抛数据库异常
        assertSame(call, result);
        verify(rtcParticipantMapper, never()).updateById(any(ImRtcParticipantDO.class));
    }
 
    @Test
    public void testInviteCall_overLimit_throws() throws Exception {
        ImProperties.Rtc rtcConfig = new ImProperties.Rtc();
        rtcConfig.setGroupMaxParticipants(3);
        when(imProperties.getRtc()).thenReturn(rtcConfig);
        ImRtcCallDO call = buildCall("r1", 200L, ImConversationTypeEnum.GROUP, 999L);
        when(rtcCallMapper.selectByRoom("r1")).thenReturn(call);
        when(rtcParticipantMapper.selectByRoomAndUserId("r1", 200L))
                .thenReturn(buildParticipant(10L, "r1", 200L, ImRtcParticipantStatusEnum.JOINED));
        when(rtcCallLockRedisDAO.lockGroup(eq(999L), any())).thenAnswer(invocation -> {
            @SuppressWarnings("unchecked")
            Callable<Void> callable = invocation.getArgument(1);
            return callable.call();
        });
        when(rtcParticipantMapper.selectListByRoom("r1")).thenReturn(ListUtil.of(
                buildParticipant(10L, "r1", 200L, ImRtcParticipantStatusEnum.JOINED),
                buildParticipant(11L, "r1", 201L, ImRtcParticipantStatusEnum.JOINED),
                buildParticipant(12L, "r1", 202L, ImRtcParticipantStatusEnum.INVITING)
        ));
        ImRtcCallInviteReqVO reqVO = new ImRtcCallInviteReqVO();
        reqVO.setRoom("r1");
        reqVO.setInviteeIds(CollUtil.newHashSet(203L));
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> rtcCallService.inviteCall(200L, reqVO));
 
        assertEquals(RTC_GROUP_INVITEE_OVER_LIMIT.getCode(), exception.getCode());
        verify(rtcParticipantMapper, never()).insertBatch(anyList());
    }
 
    // ========== 测试数据构造 ==========
 
    private ImRtcParticipantDO buildParticipant(Long id, String room, Long userId, ImRtcParticipantStatusEnum status) {
        return new ImRtcParticipantDO()
                .setId(id)
                .setRoom(room)
                .setUserId(userId)
                .setRole(ImRtcParticipantRoleEnum.INVITEE.getRole())
                .setStatus(status.getStatus())
                .setInviteTime(LocalDateTime.now());
    }
 
    private ImRtcCallDO buildCall(String room, Long inviterUserId, ImConversationTypeEnum conversationType, Long groupId) {
        return new ImRtcCallDO()
                .setRoom(room)
                .setConversationType(conversationType.getType())
                .setMediaType(1)
                .setInviterUserId(inviterUserId)
                .setGroupId(groupId)
                .setStatus(ImRtcCallStatusEnum.RUNNING.getStatus())
                .setStartTime(LocalDateTime.now());
    }
 
    private AdminUserRespDTO buildUser(Long id) {
        AdminUserRespDTO user = new AdminUserRespDTO();
        user.setId(id);
        user.setNickname("user-" + id);
        return user;
    }
 
}