Junjie
2026-04-27 73a8fcbaaec22b972c7f52d9477271a246d17926
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
package com.zy.ai.service;
 
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.zy.ai.domain.autotune.AutoTuneApplyRequest;
import com.zy.ai.domain.autotune.AutoTuneApplyResult;
import com.zy.ai.domain.autotune.AutoTuneChangeCommand;
import com.zy.ai.entity.AiAutoTuneChange;
import com.zy.ai.entity.AiAutoTuneJob;
import com.zy.ai.service.impl.AutoTuneApplyServiceImpl;
import com.zy.asrs.entity.BasCrnp;
import com.zy.asrs.entity.BasDualCrnp;
import com.zy.asrs.entity.BasStation;
import com.zy.asrs.entity.StationFlowCapacity;
import com.zy.asrs.service.BasCrnpService;
import com.zy.asrs.service.BasDualCrnpService;
import com.zy.asrs.service.BasStationService;
import com.zy.asrs.service.StationFlowCapacityService;
import com.zy.system.entity.Config;
import com.zy.system.service.ConfigService;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
 
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class AutoTuneApplyServiceImplTest {
 
    private AutoTuneApplyServiceImpl service;
 
    @Mock
    private AiAutoTuneJobService aiAutoTuneJobService;
    @Mock
    private AiAutoTuneChangeService aiAutoTuneChangeService;
    @Mock
    private ConfigService configService;
    @Mock
    private BasStationService basStationService;
    @Mock
    private BasCrnpService basCrnpService;
    @Mock
    private BasDualCrnpService basDualCrnpService;
    @Mock
    private StationFlowCapacityService stationFlowCapacityService;
 
    @BeforeEach
    void setUp() {
        service = new AutoTuneApplyServiceImpl();
        ReflectionTestUtils.setField(service, "aiAutoTuneJobService", aiAutoTuneJobService);
        ReflectionTestUtils.setField(service, "aiAutoTuneChangeService", aiAutoTuneChangeService);
        ReflectionTestUtils.setField(service, "configService", configService);
        ReflectionTestUtils.setField(service, "basStationService", basStationService);
        ReflectionTestUtils.setField(service, "basCrnpService", basCrnpService);
        ReflectionTestUtils.setField(service, "basDualCrnpService", basDualCrnpService);
        ReflectionTestUtils.setField(service, "stationFlowCapacityService", stationFlowCapacityService);
 
        AtomicLong jobId = new AtomicLong(100);
        when(aiAutoTuneJobService.save(any(AiAutoTuneJob.class))).thenAnswer(invocation -> {
            AiAutoTuneJob job = invocation.getArgument(0);
            job.setId(jobId.incrementAndGet());
            return true;
        });
        when(aiAutoTuneJobService.updateById(any(AiAutoTuneJob.class))).thenReturn(true);
        when(aiAutoTuneChangeService.saveBatch(any(Collection.class))).thenReturn(true);
        when(aiAutoTuneChangeService.list(any(Wrapper.class))).thenReturn(Collections.emptyList());
        when(configService.getConfigValue(eq("aiAutoTuneIntervalMinutes"), any())).thenReturn("10");
        when(configService.saveConfigValue(any(), any())).thenReturn(true);
        when(basStationService.update(any(Wrapper.class))).thenReturn(true);
        when(basCrnpService.update(any(Wrapper.class))).thenReturn(true);
        when(basDualCrnpService.update(any(Wrapper.class))).thenReturn(true);
    }
 
    @Test
    void rejectNonWhitelistedKey() {
        AutoTuneApplyResult result = service.apply(request(true, command("sys_config", null, "badKey", "10")));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertFalse(result.getSuccess());
        assertEquals("rejected", changes.get(0).getResultStatus());
        assertTrue(changes.get(0).getRejectReason().contains("不支持的调参目标"));
        verify(configService, never()).saveConfigValue(any(), any());
    }
 
    @Test
    void rejectOutOfRangeInterval() {
        when(configService.getOne(any(Wrapper.class))).thenReturn(config("aiAutoTuneIntervalMinutes", "10"));
 
        AutoTuneApplyResult result = service.apply(request(true, command("sys_config", null, "aiAutoTuneIntervalMinutes", "100")));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertFalse(result.getSuccess());
        assertEquals("rejected", changes.get(0).getResultStatus());
        assertTrue(changes.get(0).getRejectReason().contains("5~60"));
    }
 
    @Test
    void rejectOverStepConveyorLimitChange() {
        when(configService.getOne(any(Wrapper.class))).thenReturn(config("conveyorStationTaskLimit", "10"));
 
        service.apply(request(true, command("sys_config", null, "conveyorStationTaskLimit", "16")));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertEquals("rejected", changes.get(0).getResultStatus());
        assertTrue(changes.get(0).getRejectReason().contains("步长不能超过 5"));
    }
 
    @Test
    void rejectStationOutTaskLimitAboveDirectionalBufferCapacity() {
        when(basStationService.getById(101)).thenReturn(station(101, 1));
        when(stationFlowCapacityService.getOne(any(Wrapper.class))).thenReturn(capacity(101, "OUT", 2));
 
        service.apply(request(true, command("station", "101", "outTaskLimit", "3")));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertEquals("rejected", changes.get(0).getResultStatus());
        assertTrue(changes.get(0).getRejectReason().contains("0~2"));
    }
 
    @Test
    void rejectCooldownHit() {
        when(configService.getOne(any(Wrapper.class))).thenReturn(config("conveyorStationTaskLimit", "10"));
        AiAutoTuneChange cooldownChange = new AiAutoTuneChange();
        cooldownChange.setResultStatus("success");
        cooldownChange.setCooldownExpireTime(new Date(System.currentTimeMillis() + 60_000L));
        when(aiAutoTuneChangeService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(cooldownChange));
 
        service.apply(request(true, command("sys_config", null, "conveyorStationTaskLimit", "15")));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertEquals("rejected", changes.get(0).getResultStatus());
        assertTrue(changes.get(0).getRejectReason().contains("冷却期"));
    }
 
    @Test
    void applyMixedBatchSuccessfully() {
        when(configService.getOne(any(Wrapper.class))).thenReturn(config("conveyorStationTaskLimit", "10"));
        when(basStationService.getById(101)).thenReturn(station(101, 1));
        when(stationFlowCapacityService.getOne(any(Wrapper.class))).thenReturn(capacity(101, "OUT", 2));
        when(basCrnpService.getById(1)).thenReturn(crn(1, 1, 1));
        when(basDualCrnpService.getById(2)).thenReturn(dualCrn(2, 1, 1));
 
        AutoTuneApplyResult result = service.apply(request(false,
                command("sys_config", null, "conveyorStationTaskLimit", "15"),
                command("station", "101", "outTaskLimit", "2"),
                command("crn", "1", "maxOutTask", "2"),
                command("dual_crn", "2", "maxInTask", "2")
        ));
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertTrue(result.getSuccess());
        assertEquals(4, changes.size());
        assertEquals(4, result.getSuccessCount());
        assertEquals(0, result.getRejectCount());
        assertTrue(changes.stream().allMatch(change -> "success".equals(change.getResultStatus())));
        verify(configService).saveConfigValue("conveyorStationTaskLimit", "15");
        verify(configService).refreshSystemConfigCache();
        verify(basStationService).update(any(Wrapper.class));
        verify(basCrnpService).update(any(Wrapper.class));
        verify(basDualCrnpService).update(any(Wrapper.class));
    }
 
    @Test
    void rollbackLastJobSuccessfully() {
        AiAutoTuneJob latestJob = new AiAutoTuneJob();
        latestJob.setId(10L);
        when(aiAutoTuneJobService.list(any(Wrapper.class))).thenReturn(Collections.singletonList(latestJob));
 
        AiAutoTuneChange configChange = successChange(10L, "sys_config", "", "conveyorStationTaskLimit", "10", "15");
        AiAutoTuneChange stationChange = successChange(10L, "station", "101", "outTaskLimit", "1", "2");
        when(aiAutoTuneChangeService.list(any(Wrapper.class))).thenReturn(List.of(configChange, stationChange));
        when(configService.getOne(any(Wrapper.class))).thenReturn(config("conveyorStationTaskLimit", "15"));
        when(basStationService.getById(101)).thenReturn(station(101, 2));
 
        AutoTuneApplyResult result = service.rollbackLastSuccessfulJob("manual rollback");
 
        List<AiAutoTuneChange> changes = savedChanges();
        assertTrue(result.getSuccess());
        assertEquals(2, changes.size());
        assertTrue(changes.stream().allMatch(change -> "success".equals(change.getResultStatus())));
        verify(configService).saveConfigValue("conveyorStationTaskLimit", "10");
        verify(configService).refreshSystemConfigCache();
        verify(basStationService).update(any(Wrapper.class));
    }
 
    private AutoTuneApplyRequest request(boolean dryRun, AutoTuneChangeCommand... commands) {
        AutoTuneApplyRequest request = new AutoTuneApplyRequest();
        request.setDryRun(dryRun);
        request.setReason("test");
        request.setTriggerType("manual");
        request.setChanges(List.of(commands));
        return request;
    }
 
    private AutoTuneChangeCommand command(String targetType, String targetId, String targetKey, String newValue) {
        AutoTuneChangeCommand command = new AutoTuneChangeCommand();
        command.setTargetType(targetType);
        command.setTargetId(targetId);
        command.setTargetKey(targetKey);
        command.setNewValue(newValue);
        return command;
    }
 
    private Config config(String code, String value) {
        Config config = new Config();
        config.setCode(code);
        config.setValue(value);
        config.setStatus((short) 1);
        return config;
    }
 
    private BasStation station(Integer stationId, Integer outTaskLimit) {
        BasStation station = new BasStation();
        station.setStationId(stationId);
        station.setOutTaskLimit(outTaskLimit);
        return station;
    }
 
    private BasCrnp crn(Integer crnNo, Integer maxOutTask, Integer maxInTask) {
        BasCrnp crnp = new BasCrnp();
        crnp.setCrnNo(crnNo);
        crnp.setMaxOutTask(maxOutTask);
        crnp.setMaxInTask(maxInTask);
        return crnp;
    }
 
    private BasDualCrnp dualCrn(Integer crnNo, Integer maxOutTask, Integer maxInTask) {
        BasDualCrnp dualCrnp = new BasDualCrnp();
        dualCrnp.setCrnNo(crnNo);
        dualCrnp.setMaxOutTask(maxOutTask);
        dualCrnp.setMaxInTask(maxInTask);
        return dualCrnp;
    }
 
    private StationFlowCapacity capacity(Integer stationId, String directionCode, Integer bufferCapacity) {
        StationFlowCapacity capacity = new StationFlowCapacity();
        capacity.setStationId(stationId);
        capacity.setDirectionCode(directionCode);
        capacity.setBufferCapacity(bufferCapacity);
        return capacity;
    }
 
    private AiAutoTuneChange successChange(Long jobId,
                                           String targetType,
                                           String targetId,
                                           String targetKey,
                                           String oldValue,
                                           String appliedValue) {
        AiAutoTuneChange change = new AiAutoTuneChange();
        change.setJobId(jobId);
        change.setTargetType(targetType);
        change.setTargetId(targetId);
        change.setTargetKey(targetKey);
        change.setOldValue(oldValue);
        change.setAppliedValue(appliedValue);
        change.setResultStatus("success");
        return change;
    }
 
    private List<AiAutoTuneChange> savedChanges() {
        ArgumentCaptor<Collection<AiAutoTuneChange>> captor = ArgumentCaptor.forClass(Collection.class);
        verify(aiAutoTuneChangeService).saveBatch(captor.capture());
        return new ArrayList<>(captor.getValue());
    }
}