2026-06-24 f4bd1f3c89d906131495a0aca5aaf82966378510
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
package cn.iocoder.yudao.module.iot.service.rule.scene.action;
 
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage;
import cn.iocoder.yudao.module.iot.dal.dataobject.alert.IotAlertConfigDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.rule.IotSceneRuleDO;
import cn.iocoder.yudao.module.iot.enums.alert.IotAlertReceiveTypeEnum;
import cn.iocoder.yudao.module.iot.enums.rule.IotSceneRuleActionTypeEnum;
import cn.iocoder.yudao.module.iot.service.alert.IotAlertConfigService;
import cn.iocoder.yudao.module.iot.service.alert.IotAlertRecordService;
import cn.iocoder.yudao.module.iot.service.device.IotDeviceService;
import cn.iocoder.yudao.module.system.api.mail.MailSendApi;
import cn.iocoder.yudao.module.system.api.mail.dto.MailSendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
 
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
 
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
/**
 * {@link IotAlertTriggerSceneRuleAction} 的单元测试
 *
 * @author 芋道源码
 */
public class IotAlertTriggerSceneRuleActionTest extends BaseMockitoUnitTest {
 
    @InjectMocks
    private IotAlertTriggerSceneRuleAction action;
 
    @Mock
    private IotAlertConfigService alertConfigService;
    @Mock
    private IotAlertRecordService alertRecordService;
    @Mock
    private IotDeviceService deviceService;
 
    @Mock
    private SmsSendApi smsSendApi;
    @Mock
    private MailSendApi mailSendApi;
    @Mock
    private NotifyMessageSendApi notifyMessageSendApi;
 
    @Test
    public void testGetType() {
        // 调用并断言
        assertEquals(IotSceneRuleActionTypeEnum.ALERT_TRIGGER, action.getType());
    }
 
    @Test
    public void testExecute_noAlertConfigs() throws Exception {
        // 准备参数
        IotDeviceMessage message = createDeviceMessage();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
 
        // mock 行为:返回空列表
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.emptyList());
 
        // 调用
        action.execute(message, rule, actionConfig);
 
        // 断言:不查设备、不创建记录、不发消息
        verify(deviceService, never()).getDeviceFromCache(anyLong());
        verify(alertRecordService, never()).createAlertRecord(any(), any(), any(), any());
        verify(smsSendApi, never()).sendSingleSmsToAdmin(any());
        verify(mailSendApi, never()).sendSingleMailToAdmin(any());
        verify(notifyMessageSendApi, never()).sendSingleMessageToAdmin(any());
    }
 
    @Test
    public void testExecute_deviceTrigger_sendAllChannels() throws Exception {
        // 准备参数
        Long userId = randomLongId();
        IotDeviceMessage message = createDeviceMessage();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
        IotAlertConfigDO config = randomPojo(IotAlertConfigDO.class, c -> {
            c.setReceiveUserIds(Collections.singletonList(userId));
            c.setReceiveTypes(Arrays.asList(
                    IotAlertReceiveTypeEnum.SMS.getType(),
                    IotAlertReceiveTypeEnum.MAIL.getType(),
                    IotAlertReceiveTypeEnum.NOTIFY.getType()));
        });
        IotDeviceDO device = randomPojo(IotDeviceDO.class);
 
        // mock 行为
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.singletonList(config));
        when(deviceService.getDeviceFromCache(message.getDeviceId())).thenReturn(device);
 
        // 调用(mockStatic 需包住整个调用链;buildTemplateParams 内有 DictFrameworkUtils 静态调用)
        try (MockedStatic<DictFrameworkUtils> dictMock = mockStatic(DictFrameworkUtils.class)) {
            dictMock.when(() -> DictFrameworkUtils.parseDictDataLabel(any(), any(Integer.class)))
                    .thenReturn("WARN");
            action.execute(message, rule, actionConfig);
        }
 
        // 断言:设备只查一次
        verify(deviceService, times(1)).getDeviceFromCache(message.getDeviceId());
        // 断言:告警记录创建一次,参数透传
        verify(alertRecordService, times(1))
                .createAlertRecord(eq(config), eq(rule.getId()), eq(message), eq(device));
        // 断言:三条通道各发一次,模板编号匹配
        ArgumentCaptor<SmsSendSingleToUserReqDTO> smsCaptor = ArgumentCaptor.forClass(SmsSendSingleToUserReqDTO.class);
        verify(smsSendApi, times(1)).sendSingleSmsToAdmin(smsCaptor.capture());
        assertEquals(userId, smsCaptor.getValue().getUserId());
        assertEquals(IotAlertReceiveTypeEnum.SMS.getTemplateCode(), smsCaptor.getValue().getTemplateCode());
        ArgumentCaptor<MailSendSingleToUserReqDTO> mailCaptor = ArgumentCaptor.forClass(MailSendSingleToUserReqDTO.class);
        verify(mailSendApi, times(1)).sendSingleMailToAdmin(mailCaptor.capture());
        assertEquals(IotAlertReceiveTypeEnum.MAIL.getTemplateCode(), mailCaptor.getValue().getTemplateCode());
        ArgumentCaptor<NotifySendSingleToUserReqDTO> notifyCaptor = ArgumentCaptor.forClass(NotifySendSingleToUserReqDTO.class);
        verify(notifyMessageSendApi, times(1)).sendSingleMessageToAdmin(notifyCaptor.capture());
        assertEquals(IotAlertReceiveTypeEnum.NOTIFY.getTemplateCode(), notifyCaptor.getValue().getTemplateCode());
    }
 
    @Test
    public void testExecute_timerTrigger_skipDeviceLookup() throws Exception {
        // 准备参数:定时触发,message 为 null
        Long userId = randomLongId();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
        IotAlertConfigDO config = randomPojo(IotAlertConfigDO.class, c -> {
            c.setReceiveUserIds(Collections.singletonList(userId));
            c.setReceiveTypes(Collections.singletonList(IotAlertReceiveTypeEnum.NOTIFY.getType()));
        });
 
        // mock 行为
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.singletonList(config));
 
        // 调用
        try (MockedStatic<DictFrameworkUtils> dictMock = mockStatic(DictFrameworkUtils.class)) {
            dictMock.when(() -> DictFrameworkUtils.parseDictDataLabel(any(), any(Integer.class)))
                    .thenReturn("INFO");
            action.execute(null, rule, actionConfig);
        }
 
        // 断言:跳过设备查询;message 与 device 都用 null 创建告警记录
        verify(deviceService, never()).getDeviceFromCache(anyLong());
        verify(alertRecordService, times(1))
                .createAlertRecord(eq(config), eq(rule.getId()), eq(null), eq(null));
        verify(notifyMessageSendApi, times(1)).sendSingleMessageToAdmin(any(NotifySendSingleToUserReqDTO.class));
    }
 
    @Test
    public void testExecute_emptyReceiveUsers_skipSend() throws Exception {
        // 准备参数:接收用户为空
        IotDeviceMessage message = createDeviceMessage();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
        IotAlertConfigDO config = randomPojo(IotAlertConfigDO.class, c -> {
            c.setReceiveUserIds(Collections.emptyList());
            c.setReceiveTypes(Collections.singletonList(IotAlertReceiveTypeEnum.SMS.getType()));
        });
        IotDeviceDO device = randomPojo(IotDeviceDO.class);
 
        // mock 行为
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.singletonList(config));
        when(deviceService.getDeviceFromCache(message.getDeviceId())).thenReturn(device);
 
        // 调用
        action.execute(message, rule, actionConfig);
 
        // 断言:告警记录仍然创建,但不发送任何消息
        verify(alertRecordService, times(1))
                .createAlertRecord(eq(config), eq(rule.getId()), eq(message), eq(device));
        verify(smsSendApi, never()).sendSingleSmsToAdmin(any());
    }
 
    @Test
    public void testExecute_unknownReceiveType_skipSend() throws Exception {
        // 准备参数:接收类型为未知值
        Long userId = randomLongId();
        IotDeviceMessage message = createDeviceMessage();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
        IotAlertConfigDO config = randomPojo(IotAlertConfigDO.class, c -> {
            c.setReceiveUserIds(Collections.singletonList(userId));
            c.setReceiveTypes(Collections.singletonList(99));
        });
        IotDeviceDO device = randomPojo(IotDeviceDO.class);
 
        // mock 行为
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.singletonList(config));
        when(deviceService.getDeviceFromCache(message.getDeviceId())).thenReturn(device);
 
        // 调用
        try (MockedStatic<DictFrameworkUtils> dictMock = mockStatic(DictFrameworkUtils.class)) {
            dictMock.when(() -> DictFrameworkUtils.parseDictDataLabel(any(), any(Integer.class)))
                    .thenReturn("WARN");
            action.execute(message, rule, actionConfig);
        }
 
        // 断言:未知类型不发送
        verify(smsSendApi, never()).sendSingleSmsToAdmin(any());
        verify(mailSendApi, never()).sendSingleMailToAdmin(any());
        verify(notifyMessageSendApi, never()).sendSingleMessageToAdmin(any());
    }
 
    @Test
    public void testExecute_smsFailure_doesNotBlockOthers() throws Exception {
        // 准备参数
        Long userId = randomLongId();
        IotDeviceMessage message = createDeviceMessage();
        IotSceneRuleDO rule = randomPojo(IotSceneRuleDO.class);
        IotSceneRuleDO.Action actionConfig = randomPojo(IotSceneRuleDO.Action.class);
        IotAlertConfigDO config = randomPojo(IotAlertConfigDO.class, c -> {
            c.setReceiveUserIds(Collections.singletonList(userId));
            c.setReceiveTypes(Arrays.asList(
                    IotAlertReceiveTypeEnum.SMS.getType(),
                    IotAlertReceiveTypeEnum.MAIL.getType()));
        });
        IotDeviceDO device = randomPojo(IotDeviceDO.class);
 
        // mock 行为:sms 抛异常
        when(alertConfigService.getAlertConfigListBySceneRuleIdAndStatus(rule.getId(), CommonStatusEnum.ENABLE.getStatus()))
                .thenReturn(Collections.singletonList(config));
        when(deviceService.getDeviceFromCache(message.getDeviceId())).thenReturn(device);
        when(smsSendApi.sendSingleSmsToAdmin(any())).thenThrow(new RuntimeException("sms 渠道异常"));
 
        // 调用
        try (MockedStatic<DictFrameworkUtils> dictMock = mockStatic(DictFrameworkUtils.class)) {
            dictMock.when(() -> DictFrameworkUtils.parseDictDataLabel(any(), any(Integer.class)))
                    .thenReturn("ERROR");
            action.execute(message, rule, actionConfig);
        }
 
        // 断言:sms 抛错时邮件依旧发送
        verify(smsSendApi, times(1)).sendSingleSmsToAdmin(any());
        verify(mailSendApi, times(1)).sendSingleMailToAdmin(any());
    }
 
    /**
     * 创建带 reportTime 的设备消息
     */
    private IotDeviceMessage createDeviceMessage() {
        IotDeviceMessage message = new IotDeviceMessage();
        message.setId(randomString());
        message.setDeviceId(randomLongId());
        message.setReportTime(LocalDateTime.now());
        return message;
    }
 
}