yeg
6 天以前 a04222c873e5e55f48c8d33b5c0bc46fa524ac8d
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package com.battery.business.service.impl;
 
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.ruoyi.common.exception.ServiceException;
import com.battery.business.domain.TDetectionCabinet;
import com.battery.business.domain.vo.DiscoveredCabinetVo;
import com.battery.business.mapper.TDetectionCabinetMapper;
import com.battery.device.api.discovery.InMemoryDeviceDiscoveryCandidateStore;
import com.battery.device.api.discovery.DeviceDiscoveryCandidateStore.CabinetCandidate;
import com.battery.device.api.discovery.DeviceDiscoveryCandidateStore.ChannelCandidate;
import com.battery.device.api.model.ChannelIdentity;
import com.battery.device.api.model.DeviceWorkStatus;
 
/**
 * 检测柜业务层单元测试,验证字段规范化、状态限制及唯一性校验等关键规则。
 */
@ExtendWith(MockitoExtension.class)
class TDetectionCabinetServiceImplTest
{
    @Mock
    private TDetectionCabinetMapper detectionCabinetMapper;
 
    private TDetectionCabinetServiceImpl detectionCabinetService;
    private InMemoryDeviceDiscoveryCandidateStore candidateStore;
 
    private TDetectionCabinet detectionCabinet;
 
    /**
     * 初始化一条满足新增校验的检测柜 Mock 数据。
     */
    @BeforeEach
    void setUp()
    {
        candidateStore = new InMemoryDeviceDiscoveryCandidateStore();
        detectionCabinetService = new TDetectionCabinetServiceImpl(detectionCabinetMapper, candidateStore);
        candidateStore.recordCabinets(List.of(candidate("CABINET-001", true, DeviceWorkStatus.WORKING)));
        detectionCabinet = new TDetectionCabinet();
        detectionCabinet.setCabinetCode(" CABINET-001 ");
        detectionCabinet.setCabinetName(" 一号检测柜 ");
        detectionCabinet.setIpAddress(" 192.168.1.10 ");
        detectionCabinet.setMacAddress("aa-bb-cc-dd-ee-ff");
        detectionCabinet.setManufacturer(" 厂商 ");
        detectionCabinet.setModel(" 型号A ");
        detectionCabinet.setCapacity(new BigDecimal("120.50"));
        detectionCabinet.setChannelCount(8);
        detectionCabinet.setRemark(" 备注 ");
    }
 
    /**
     * 验证新增时会规范化基础字段并初始化运行状态。
     */
    @Test
    void insertDetectionCabinetShouldPromoteDiscoveredCandidate()
    {
        when(detectionCabinetMapper.insertDetectionCabinet(any(TDetectionCabinet.class))).thenAnswer(invocation -> {
            invocation.getArgument(0, TDetectionCabinet.class).setCabinetId(7L);
            return 1;
        });
 
        int rows = detectionCabinetService.insertDetectionCabinet(detectionCabinet);
 
        ArgumentCaptor<TDetectionCabinet> captor = ArgumentCaptor.forClass(TDetectionCabinet.class);
        verify(detectionCabinetMapper).insertDetectionCabinet(captor.capture());
        TDetectionCabinet savedCabinet = captor.getValue();
        assertEquals(1, rows);
        assertEquals(7L, savedCabinet.getCabinetId());
        assertEquals("CABINET-001", savedCabinet.getCabinetCode());
        assertEquals("一号检测柜", savedCabinet.getCabinetName());
        assertEquals("192.168.1.10", savedCabinet.getIpAddress());
        assertEquals("AA:BB:CC:DD:EE:FF", savedCabinet.getMacAddress());
        assertEquals(new BigDecimal("120.50"), savedCabinet.getCapacity());
        assertEquals("OFFLINE", savedCabinet.getOnlineStatus());
        assertEquals("0", savedCabinet.getStatus());
        assertTrue(savedCabinet.getRelatedTests().isEmpty());
    }
 
    /**
     * 验证设备选择查询不再从 MySQL 读取发现候选。
     */
    @Test
    void discoveredCabinetSqlShouldNotReadLegacyTestColumns() throws IOException
    {
        try (InputStream input = getClass().getResourceAsStream(
                "/mapper/battery/TDetectionCabinetMapper.xml"))
        {
            assertNotNull(input);
            String mapperXml = new String(input.readAllBytes(), StandardCharsets.UTF_8);
            assertFalse(mapperXml.contains("selectDiscoveredCabinetList"));
            assertFalse(mapperXml.contains("registration_status = 'DISCOVERED'"));
        }
    }
 
    /**
     * 验证删除正式检测柜只取消人工登记,不删除适配器持续维护的设备事实。
     */
    @Test
    void deleteDetectionCabinetSqlShouldReturnOnlineDeviceToDiscoveryPool() throws IOException
    {
        try (InputStream input = getClass().getResourceAsStream(
                "/mapper/battery/TDetectionCabinetMapper.xml"))
        {
            assertNotNull(input);
            String mapperXml = new String(input.readAllBytes(), StandardCharsets.UTF_8);
            int deleteStart = mapperXml.indexOf("<update id=\"deleteDetectionCabinetById\"");
            int deleteEnd = mapperXml.indexOf("</update>", deleteStart);
            String deleteSql = mapperXml.substring(deleteStart, deleteEnd);
 
            assertTrue(deleteSql.contains("set del_flag = cabinet_id"));
            assertTrue(deleteSql.contains("registration_status = 'REGISTERED'"));
        }
    }
 
    /**
     * 验证检测柜主列表保留操作校验所需派生状态,不读取数据库不存在的列。
     */
    @Test
    void detectionCabinetListSqlShouldDeriveOperationStateWithoutCurrentTest() throws IOException
    {
        try (InputStream input = getClass().getResourceAsStream(
                "/mapper/battery/TDetectionCabinetMapper.xml"))
        {
            assertNotNull(input);
            String mapperXml = new String(input.readAllBytes(), StandardCharsets.UTF_8);
            int selectStart = mapperXml.indexOf("<sql id=\"selectDetectionCabinetVo\"");
            int selectEnd = mapperXml.indexOf("</sql>", selectStart);
            String selectSql = mapperXml.substring(selectStart, selectEnd);
            assertFalse(selectSql.contains("online_status, test_status"));
            assertFalse(selectSql.contains("current_test, status"));
            assertTrue(selectSql.contains("as test_status"));
            assertFalse(selectSql.contains("current_test"));
            String activeTestSql = sqlFragment(mapperXml, "activeCabinetTestExists");
            assertTrue(activeTestSql.contains("t_test_channel_binding"));
            assertTrue(activeTestSql.contains("t_detection_channel"));
            assertTrue(activeTestSql.contains("test_fact.test_status"));
            assertFalse(activeTestSql.contains("t_test_battery"));
            assertFalse(activeTestSql.contains("battery_fact.cabinet_id"));
            int listStart = mapperXml.indexOf("<select id=\"selectDetectionCabinetList\"");
            int listEnd = mapperXml.indexOf("</select>", listStart);
            assertTrue(mapperXml.substring(listStart, listEnd).contains("registration_status = 'REGISTERED'"));
            int registerStart = mapperXml.indexOf("<insert id=\"insertDetectionCabinet\"");
            int registerEnd = mapperXml.indexOf("</insert>", registerStart);
            String registerSql = mapperXml.substring(registerStart, registerEnd);
            assertTrue(registerSql.contains("'REGISTERED'"));
            assertTrue(registerSql.contains("#{createBy}"));
        }
    }
 
    /** 验证旧登记记录缺少厂商身份时仍可按稳定设备编码同步并补齐身份。 */
    @Test
    void registeredObservationSqlShouldRepairLegacyVendorIdentity() throws IOException
    {
        try (InputStream input = getClass().getResourceAsStream(
                "/mapper/battery/TDetectionCabinetMapper.xml"))
        {
            assertNotNull(input);
            String mapperXml = new String(input.readAllBytes(), StandardCharsets.UTF_8);
            int start = mapperXml.indexOf("<update id=\"updateRegisteredCabinetObservation\"");
            int end = mapperXml.indexOf("</update>", start);
            String updateSql = mapperXml.substring(start, end);
 
            assertTrue(updateSql.contains("vendor_device_type = coalesce(vendor_device_type, #{devtype})"));
            assertTrue(updateSql.contains("cabinet_code = concat(#{adapterCode}, '-', #{devtype}, '-', #{devid})"));
        }
    }
 
    private String sqlFragment(String mapperXml, String id)
    {
        int start = mapperXml.indexOf("<sql id=\"" + id + "\"");
        int end = mapperXml.indexOf("</sql>", start);
        return mapperXml.substring(start, end);
    }
 
    /**
     * 通道显示号:来源自己报了叫法就用它(操作员拿它跟厂商软件对上),没报就回退到身份里的「单元-通道」。
     * 显示号只是展示,不参与通道身份。
     */
    @Test
    void channelDisplayNoPrefersTheSourceOwnLabelAndFallsBackToTheIdentity()
    {
        ChannelCandidate declared = new ChannelCandidate(new ChannelIdentity("j22", 0, 0, 1, 26), true,
                DeviceWorkStatus.UNKNOWN, java.time.Instant.now(), null, null, "27");
        assertEquals("27", TDetectionCabinetServiceImpl.channelDisplayNo(declared));
 
        ChannelCandidate blank = new ChannelCandidate(new ChannelIdentity("j22", 0, 0, 1, 26), true,
                DeviceWorkStatus.UNKNOWN, java.time.Instant.now(), null, null, "   ");
        assertEquals("1-26", TDetectionCabinetServiceImpl.channelDisplayNo(blank));
 
        ChannelCandidate absent = new ChannelCandidate(new ChannelIdentity("neware76", 21, 3, 1, 4), true,
                DeviceWorkStatus.UNKNOWN, java.time.Instant.now());
        assertEquals("1-4", TDetectionCabinetServiceImpl.channelDisplayNo(absent));
    }
 
    private CabinetCandidate candidate(String deviceCode, boolean online, DeviceWorkStatus workStatus)
    {
        java.time.Instant observedAt = java.time.Instant.now();
        List<ChannelCandidate> channels = java.util.stream.IntStream.rangeClosed(1, 8)
                .mapToObj(channelId -> new ChannelCandidate(
                        new ChannelIdentity("dev-sim", 22, 1, 1, channelId), online, workStatus, observedAt))
                .toList();
        return new CabinetCandidate("dev-sim", null, deviceCode, 22, 1, "192.168.1.10",
                "AA:BB:CC:DD:EE:FF", "一号模拟柜", "开发模拟器", "BTS Virtual Cabinet",
                channels, observedAt, observedAt.plusSeconds(60));
    }
 
    /**
     * 验证设备选择列表读取候选的设备事实,不推断系统测试关系。
     */
    @Test
    void selectDiscoveredCabinetListShouldMapPersistedCabinetFacts()
    {
        when(detectionCabinetMapper.selectRegisteredCabinetCodes()).thenReturn(List.of());
 
        List<DiscoveredCabinetVo> devices = detectionCabinetService.selectDiscoveredCabinetList();
 
        assertEquals(1, devices.size());
        assertEquals("CABINET-001", devices.get(0).getDeviceCode());
        assertEquals("192.168.1.10", devices.get(0).getIp());
        assertEquals("AA:BB:CC:DD:EE:FF", devices.get(0).getMac());
        assertEquals("在线", devices.get(0).getOnlineStatus());
        var fields = new com.fasterxml.jackson.databind.ObjectMapper().valueToTree(devices.get(0));
        assertFalse(fields.has("testStatus"));
        assertFalse(fields.has("currentTest"));
        assertEquals("一号模拟柜", devices.get(0).getName());
        assertEquals("开发模拟器", devices.get(0).getManufacturer());
        assertEquals("BTS Virtual Cabinet", devices.get(0).getModel());
        assertEquals(8, devices.get(0).getChannelCount());
    }
 
    @Test
    void offlineCabinetRemainsDiscoverableAndCanBeRegistered()
    {
        var store = new InMemoryDeviceDiscoveryCandidateStore();
        store.recordCabinets(List.of(candidate("CABINET-001", false, DeviceWorkStatus.UNOBSERVABLE)));
        var service = new TDetectionCabinetServiceImpl(detectionCabinetMapper, store);
        when(detectionCabinetMapper.selectRegisteredCabinetCodes()).thenReturn(List.of());
        var devices = service.selectDiscoveredCabinetList();
        assertEquals(1, devices.size());
        assertEquals("离线", devices.get(0).getOnlineStatus());
        when(detectionCabinetMapper.insertDetectionCabinet(any(TDetectionCabinet.class))).thenReturn(1);
        assertEquals(1, service.insertDetectionCabinet(detectionCabinet));
        assertEquals("OFFLINE", detectionCabinet.getOnlineStatus());
        when(detectionCabinetMapper.selectRegisteredCabinetCodes()).thenReturn(List.of("CABINET-001"));
        assertEquals(0, service.selectDiscoveredCabinetList().size());
    }
 
    /**
     * 验证重复设备编码会阻止新增且不会执行写库操作。
     */
    @Test
    void insertDetectionCabinetShouldRejectDuplicateCabinetCode()
    {
        TDetectionCabinet existing = new TDetectionCabinet();
        existing.setCabinetId(2L);
        existing.setRegistrationStatus("REGISTERED");
        when(detectionCabinetMapper.selectByCabinetCode("CABINET-001")).thenReturn(existing);
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> detectionCabinetService.insertDetectionCabinet(detectionCabinet));
 
        assertEquals("设备编码已存在", exception.getMessage());
        verify(detectionCabinetMapper, never()).insertDetectionCabinet(any(TDetectionCabinet.class));
    }
 
    @Test
    void insertDetectionCabinetShouldRequireDiscoveredCandidate()
    {
        detectionCabinetService = new TDetectionCabinetServiceImpl(detectionCabinetMapper,
                new InMemoryDeviceDiscoveryCandidateStore());
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> detectionCabinetService.insertDetectionCabinet(detectionCabinet));
 
        assertEquals("请先选择有效的发现候选设备", exception.getMessage());
        verify(detectionCabinetMapper, never()).insertDetectionCabinet(any());
    }
 
    @Test
    void insertDetectionCabinetShouldValidateAuthoritativeCandidateTopology()
    {
        detectionCabinet.setIpAddress("invalid-ip");
        detectionCabinet.setMacAddress("invalid-mac");
        detectionCabinet.setChannelCount(99);
        when(detectionCabinetMapper.insertDetectionCabinet(any(TDetectionCabinet.class))).thenAnswer(invocation -> {
            invocation.getArgument(0, TDetectionCabinet.class).setCabinetId(7L);
            return 1;
        });
 
        assertEquals(1, detectionCabinetService.insertDetectionCabinet(detectionCabinet));
 
        ArgumentCaptor<TDetectionCabinet> captor = ArgumentCaptor.forClass(TDetectionCabinet.class);
        verify(detectionCabinetMapper).insertDetectionCabinet(captor.capture());
        assertEquals("192.168.1.10", captor.getValue().getIpAddress());
        assertEquals("AA:BB:CC:DD:EE:FF", captor.getValue().getMacAddress());
        assertEquals(8, captor.getValue().getChannelCount());
    }
 
    /**
     * 验证测试中的检测柜不能被禁用。
     */
    @Test
    void updateDetectionCabinetStatusShouldRejectDisablingTestingCabinet()
    {
        TDetectionCabinet current = new TDetectionCabinet();
        current.setCabinetId(1L);
        current.setStatus("0");
        current.setTestStatus("1");
        when(detectionCabinetMapper.selectDetectionCabinetById(1L)).thenReturn(current);
 
        TDetectionCabinet statusCommand = new TDetectionCabinet();
        statusCommand.setCabinetId(1L);
        statusCommand.setStatus("1");
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> detectionCabinetService.updateDetectionCabinetStatus(statusCommand));
 
        assertEquals("检测柜正在测试,不能禁用", exception.getMessage());
        verify(detectionCabinetMapper, never()).updateDetectionCabinetStatus(any(TDetectionCabinet.class));
    }
 
    /**
     * 验证检测中的检测柜允许执行启用操作。
     */
    @Test
    void updateDetectionCabinetStatusShouldAllowEnablingTestingCabinet()
    {
        TDetectionCabinet current = new TDetectionCabinet();
        current.setCabinetId(1L);
        current.setStatus("1");
        current.setTestStatus("1");
        when(detectionCabinetMapper.selectDetectionCabinetById(1L)).thenReturn(current);
        when(detectionCabinetMapper.updateDetectionCabinetStatus(any(TDetectionCabinet.class))).thenReturn(1);
 
        TDetectionCabinet statusCommand = new TDetectionCabinet();
        statusCommand.setCabinetId(1L);
        statusCommand.setStatus("0");
 
        int rows = detectionCabinetService.updateDetectionCabinetStatus(statusCommand);
 
        assertEquals(1, rows);
        verify(detectionCabinetMapper).updateDetectionCabinetStatus(statusCommand);
    }
 
    /**
     * 验证重复提交相同状态时按幂等成功处理,不重复写库。
     */
    @Test
    void updateDetectionCabinetStatusShouldBeIdempotent()
    {
        TDetectionCabinet current = new TDetectionCabinet();
        current.setCabinetId(1L);
        current.setStatus("0");
        current.setTestStatus("0");
        when(detectionCabinetMapper.selectDetectionCabinetById(1L)).thenReturn(current);
 
        TDetectionCabinet statusCommand = new TDetectionCabinet();
        statusCommand.setCabinetId(1L);
        statusCommand.setStatus("0");
 
        int rows = detectionCabinetService.updateDetectionCabinetStatus(statusCommand);
 
        assertEquals(1, rows);
        verify(detectionCabinetMapper, never()).updateDetectionCabinetStatus(any(TDetectionCabinet.class));
    }
 
    /**
     * 验证批量删除会先检查所有检测柜,存在测试中记录时不删除任何数据。
     */
    @Test
    void deleteDetectionCabinetByIdsShouldRejectTestingCabinetBeforeDeleting()
    {
        TDetectionCabinet normal = new TDetectionCabinet();
        normal.setCabinetId(1L);
        normal.setTestStatus("0");
        TDetectionCabinet testing = new TDetectionCabinet();
        testing.setCabinetId(2L);
        testing.setTestStatus("1");
        when(detectionCabinetMapper.selectDetectionCabinetById(1L)).thenReturn(normal);
        when(detectionCabinetMapper.selectDetectionCabinetById(2L)).thenReturn(testing);
 
        ServiceException exception = assertThrows(ServiceException.class,
                () -> detectionCabinetService.deleteDetectionCabinetByIds(new Long[] { 1L, 2L }, "admin"));
 
        assertEquals("检测柜正在测试,不能删除", exception.getMessage());
        verify(detectionCabinetMapper, never()).deleteDetectionCabinetById(any(), any());
    }
 
    /**
     * 验证编辑时唯一性查询命中当前记录仍视为唯一。
     */
    @Test
    void checkUniqueShouldAllowCurrentCabinet()
    {
        TDetectionCabinet current = new TDetectionCabinet();
        current.setCabinetId(1L);
        current.setCabinetCode("CABINET-001");
        current.setMacAddress("AA:BB:CC:DD:EE:FF");
        when(detectionCabinetMapper.selectByCabinetCode("CABINET-001")).thenReturn(current);
        when(detectionCabinetMapper.selectByMacAddress("AA:BB:CC:DD:EE:FF")).thenReturn(current);
 
        assertTrue(detectionCabinetService.checkCabinetCodeUnique(current));
        assertTrue(detectionCabinetService.checkMacAddressUnique(current));
    }
}