fix(b82-01): 任务行部分字段落库改 update(null, wrapper),13 处部分实体 updateById 不再抹 failure_category
B82-01:failureCategory 标 FieldStrategy.ALWAYS(V186 让清错误分支的 null 真落库)的代价是任何 new 出来的部分实体走 updateById 都把该列无条件抹回 NULL。现网只读探针(2026-11-05,SSH 主机B)实证列全表零非空:近 7 天 194 条 FAILED 全空,9 条文案命中 CREDENTIAL/DELIVERY markers 的行列也是空。本笔只动调用点一边;注解半边由 TaskFailureCategoryMigrationV186Test 的 ALWAYS 钉守住。 写点转换(13 处 updateById,12 个条目,DedupeRunService 收尾一处两调用):convert/split/productrisk/queryasin/withdraw/similarasin/appearance-patent/pricetrack 显式两到四列;shopdatacrawl 快照+归属三列;deletebrand 终态分支 error_message 与分类同笔配对 TaskFailureLedger.categoryOf(护栏格1连线语义);dedupe FAILED 收尾同笔配对;similarasin 归属绑定(rustfs 回退)。Explore 初判 12 处漏了 withdraw/pricetrack 族——逐支验明全是 loadTaskForExecution 全实体(selectById/缓存血统),非抹列点,留痕不扩 scope;DELIVERY/CREDENTIAL 两族终态写点接 ledger 属后续批,不在本笔。 护栏 TaskFailureCategoryGuardrailTest 5→7:① ledger 对六组 markers 各出一条值非空断言(配对写恒 NULL 也绿那半堵上);② .updateById( 总量棘轮 173→160(本仓 ALWAYS 字段还有 PriceTrackLoopRun/ShopKey/SkipPriceAsin 四实体,棘轮按全量钉,新增写法必须登记复审)。测试适配:共享探针 UpdateWrapperProbe(getSqlSet 列序+MPGENVAL 精确取值+列名 snake 归一——单测 JVM 的 Lambda 列缓存可能被自动初始化成驼峰,不归一则快照取决于测试类执行顺序);4 份 golden 重钉 11 行(窄写面 status 不在写面渲染成 -);ShopDataCrawlOwnerColumnTest 假 DB 从只会 CAS 升级为按 SQL 语义应用 SET 段(whereEq 校验 id/status eq);SimilarAsinTaskServiceSubmitTest 归属断言改为录 SET 段断言零 owner_instance_id(touchJavaSideTaskActivity 本就合法走 update(null,wrapper),verify(never) 会误杀)。 门禁:受影响七支定向 50/0 失败/0 错误/3 skipped(既有 skip,零新增);mvn -o test 整量 5321/0 失败/0 错误/19 skipped BUILD SUCCESS(5:01,skip 数与在册基线逐字相同);后端无 lint/格式器如实跳过;未动 application.yml/路由/Flyway/env,门禁5不适用。
This commit is contained in:
+13
-7
@@ -178,13 +178,19 @@ class AppearancePatentCreateTaskSnapshotTest {
|
||||
+ " resultJson=" + task.getResultJson());
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenAnswer(invocation -> {
|
||||
FileTaskEntity task = invocation.getArgument(0);
|
||||
events.add("task.update id=" + task.getId()
|
||||
+ " resultJson.keys=" + jsonKeys(task.getResultJson())
|
||||
+ " resultJson=" + task.getResultJson());
|
||||
return 1;
|
||||
});
|
||||
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
// B82-01:任务行部分字段落库改走 update(null, wrapper),从 SET 段取值
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
|
||||
task.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
|
||||
task.setResultJson((String) com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper).get("result_json"));
|
||||
events.add("task.update id=" + task.getId()
|
||||
+ " resultJson.keys=" + jsonKeys(task.getResultJson())
|
||||
+ " resultJson=" + task.getResultJson());
|
||||
return 1;
|
||||
});
|
||||
when(fileResultMapper.insert(any(FileResultEntity.class))).thenAnswer(invocation -> {
|
||||
FileResultEntity row = invocation.getArgument(0);
|
||||
row.setId(7001L);
|
||||
|
||||
+10
-2
@@ -159,9 +159,17 @@ class DeleteBrandSnapshotTest {
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.taskUpdates.add(invocation.getArgument(0));
|
||||
// B82-01:部分字段落库走 update(null, wrapper)——按 SET 段重建探针实体再进快照
|
||||
// (status 不在 RUNNING 分支的写面里 ⇒ 渲染成 "-";FAILED 分支显式带 status/error_message)
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
|
||||
FileTaskEntity probe = new FileTaskEntity();
|
||||
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
|
||||
captured.taskUpdates.add(probe);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
|
||||
+10
-2
@@ -134,9 +134,17 @@ class PriceTrackSnapshotTest {
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.taskUpdates.add(invocation.getArgument(0));
|
||||
// B82-01:部分字段落库走 update(null, wrapper)——按 SET 段重建探针实体再进快照
|
||||
// (status 不在建单写面里 ⇒ 渲染成 "-")
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
|
||||
FileTaskEntity probe = new FileTaskEntity();
|
||||
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
|
||||
captured.taskUpdates.add(probe);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
|
||||
+16
-13
@@ -164,28 +164,31 @@ class ShopDataCrawlOwnerColumnTest {
|
||||
});
|
||||
lenient().when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenReturn(1);
|
||||
// 2026-09:陈旧扫描的 FAILED 写入改为条件更新(where id=? and status='RUNNING' 的 CAS),
|
||||
// 走的是 update(entity=null, wrapper)。这里按 wrapper 参数模拟 DB:只有仍为 RUNNING 的行才命中,
|
||||
// 命中后落回内存表(与真实 DB 语义一致,第二次扫描因终态不再命中)。
|
||||
// 注意用 isNull():Mockito 2+ 的 any(Class) 不匹配 null。
|
||||
// 走的是 update(entity=null, wrapper)。B82-01 后建单快照写(request_json/owner_instance_id/
|
||||
// result_json)也是同一形状——这里按 SQL 语义模拟假 DB:先校验 WHERE 段(id 必有;CAS 形状
|
||||
// 还有 eq(status,'RUNNING')),命中才把 SET 段逐列应用到内存行(与真实 DB 语义一致,
|
||||
// 第二次扫描因终态不再命中)。注意用 isNull():Mockito 2+ 的 any(Class) 不匹配 null。
|
||||
lenient().when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
|
||||
any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper =
|
||||
invocation.getArgument(1);
|
||||
java.util.Map<String, Object> params = extractParamValues(wrapper);
|
||||
java.util.Optional<Object> idValue = params.values().stream()
|
||||
.filter(value -> value instanceof Long)
|
||||
.findFirst();
|
||||
if (idValue.isEmpty()) {
|
||||
java.util.Map<String, Object> sets =
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper);
|
||||
java.util.Map<String, Object> where =
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.whereEq(wrapper);
|
||||
if (!(where.get("id") instanceof Long id)) {
|
||||
return 0;
|
||||
}
|
||||
FileTaskEntity stored = dbTask((Long) idValue.get());
|
||||
if (stored == null || !"RUNNING".equals(stored.getStatus())) {
|
||||
FileTaskEntity stored = dbTask(id);
|
||||
if (stored == null) {
|
||||
return 0;
|
||||
}
|
||||
stored.setStatus("FAILED");
|
||||
stored.setUpdatedAt(LocalDateTime.now());
|
||||
stored.setFinishedAt(LocalDateTime.now());
|
||||
Object eqStatus = where.get("status");
|
||||
if (eqStatus != null && !eqStatus.equals(stored.getStatus())) {
|
||||
return 0;
|
||||
}
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(stored, sets);
|
||||
return 1;
|
||||
});
|
||||
lenient().when(fileTaskMapper.selectById(anyLong())).thenReturn(null);
|
||||
|
||||
+10
-2
@@ -150,9 +150,17 @@ class ShopDataCrawlCreateTaskSnapshotTest {
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
events.add("task.update: " + renderTaskUpdate(invocation.<FileTaskEntity>getArgument(0)));
|
||||
// B82-01:任务行部分字段落库改走 update(null, wrapper)——从 SET 段重建探针实体,
|
||||
// 只带 request_json/owner_instance_id/result_json 三列(status/计数不在写面 ⇒ 渲染成 "-")
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
|
||||
FileTaskEntity probe = new FileTaskEntity();
|
||||
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
|
||||
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
|
||||
events.add("task.update: " + renderTaskUpdate(probe));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + resultInserts.size());
|
||||
|
||||
+16
-1
@@ -226,7 +226,10 @@ class SimilarAsinTaskServiceSubmitTest {
|
||||
configureNewChunkAndScope();
|
||||
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
|
||||
configureChunkStore(true);
|
||||
when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenReturn(0);
|
||||
// B82-01:owner 绑定失败的注入点改打 update(null, wrapper)——部分实体 updateById 已从写面退场
|
||||
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
|
||||
.thenReturn(0);
|
||||
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class,
|
||||
() -> service.submitResult(TASK_ID, request(false)));
|
||||
@@ -248,11 +251,23 @@ class SimilarAsinTaskServiceSubmitTest {
|
||||
configureChunkStore(true);
|
||||
when(transientPayloadStorageService.extractPointer(STORED_CHUNK_POINTER)).thenReturn(CHUNK_POINTER);
|
||||
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
|
||||
// B82-01:owner 绑定也改走 update(null, wrapper)——但活动心跳(touchJavaSideTaskActivity)
|
||||
// 本来就合法地走同一形状,所以不能 verify(never()).update;改成录下每一笔 SET 段,
|
||||
// 断言「没有任何一次写 owner_instance_id」=重复候选确实没被改绑归属。
|
||||
java.util.List<java.util.Map<String, Object>> updateSets = new java.util.ArrayList<>();
|
||||
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
updateSets.add(com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(invocation.getArgument(1)));
|
||||
return 1;
|
||||
});
|
||||
|
||||
service.submitResult(TASK_ID, request(false));
|
||||
|
||||
verify(taskChunkMapper, never()).insert(any(TaskChunkEntity.class));
|
||||
verify(fileTaskMapper, never()).updateById(any(FileTaskEntity.class));
|
||||
assertTrue(updateSets.stream().noneMatch(sets -> sets.containsKey("owner_instance_id")),
|
||||
"重复候选不得改写归属列(owner 绑定只许发生在新增 chunk 的路径上)");
|
||||
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(STORED_CHUNK_POINTER);
|
||||
}
|
||||
|
||||
|
||||
+9
-2
@@ -171,9 +171,16 @@ class SimilarAsinCreateTaskSnapshotTest {
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.events.add("task.update: " + renderTaskUpdate(invocation.getArgument(0)));
|
||||
// B82-01:任务行部分字段落库改走 update(null, wrapper)——从 SET 段重建探针实体,
|
||||
// moduleType/status 不在写面里 ⇒ 渲染成 "-",快照把「窄写」钉在脸上
|
||||
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
|
||||
FileTaskEntity probe = new FileTaskEntity();
|
||||
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
|
||||
probe.setResultJson((String) com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper).get("result_json"));
|
||||
captured.events.add("task.update: " + renderTaskUpdate(probe));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.events.add("result.insert: " + renderResultInsert(invocation.getArgument(0)));
|
||||
return 1;
|
||||
|
||||
+76
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -51,6 +52,20 @@ class TaskFailureCategoryGuardrailTest {
|
||||
/** 名单内在册写点数(AP 4 +相似ASIN 4 +采集 1);低于它=写点被挪走或改了写法。 */
|
||||
private static final int ENTITY_FACE_MIN_WRITE_SITES = 9;
|
||||
|
||||
/**
|
||||
* {@code .updateById(} 写法总量的在册棘轮(B82-01 收口时的换算值:改前 173,本笔把 12 处
|
||||
* 部分实体写点——13 处 {@code updateById} 调用,{@code DedupeRunService} 的收尾一处两调用——
|
||||
* 改成 {@code update(null, wrapper)} 后余 160)。
|
||||
*
|
||||
* <p>为什么钉总量而不是逐点名单:failure_category 只是本仓 {@code FieldStrategy.ALWAYS} 的
|
||||
* 五分之一({@code PriceTrackLoopRunEntity.active_task_id}、{@code ShopKeyEntity}×2、
|
||||
* {@code SkipPriceAsinEntity}×5 个最低价列都标了它)——任何实体上新增一处
|
||||
* {@code updateById},都值得先审一遍「实体里有没有 ALWAYS 字段、传进去的是不是新鲜实体」。
|
||||
* 部分字段落库的正本形状是 {@code update(null, wrapper)} 显式 {@code .set}
|
||||
* ({@code CollectDataService} 结果文件组装的条件更新)。
|
||||
*/
|
||||
private static final int REGISTERED_UPDATE_BY_ID_SITES = 160;
|
||||
|
||||
@Test
|
||||
void 任务失败文案写点必须同笔写分类列() {
|
||||
List<String> violations = new ArrayList<>();
|
||||
@@ -178,6 +193,67 @@ class TaskFailureCategoryGuardrailTest {
|
||||
assertThat(TaskRetryEligibility.category(null)).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* B82-01 抓出的判据缺口:上面两格只验「写文案的行旁边出现了写列的行」这条<b>连线</b>,
|
||||
* 配对写一个恒为 {@code null} 的值也照样绿——而这正是现网实况(2026-11-05 只读探针:
|
||||
* {@code failure_category} 全表非空 0、近 7 天 194 条 FAILED 全空,另有 9 条文案命中
|
||||
* CREDENTIAL/DELIVERY markers 的行列也是空)。连线格买到的是零免疫力。
|
||||
* 这里把「值本身非空」钉住:六组 markers(KEY 并入 BALANCE,共 5 个枚举值)各出一条样本,
|
||||
* {@link TaskFailureLedger#categoryOf} 必须给出对应的非空分类名。
|
||||
*/
|
||||
@Test
|
||||
void ledger_对六组markers各出一条非空分类() {
|
||||
// 停止文案取常量不抄字面量(与 STOPPED_MARKERS 同一条纪律:两处各写一遍,改一处就静默失效)
|
||||
assertThat(TaskFailureLedger.categoryOf(TaskResumeService.DUPLICATE_STOP_REASON))
|
||||
.as("STOPPED 组必须判得出:这是六组里最先判、语义唯一的一条")
|
||||
.isEqualTo(TaskRetryEligibility.Category.STOPPED.name());
|
||||
assertThat(TaskFailureLedger.categoryOf("已收到 73 个结果分片,但结果文件生成多次失败,任务已自动结束"))
|
||||
.isEqualTo(TaskRetryEligibility.Category.DELIVERY.name());
|
||||
assertThat(TaskFailureLedger.categoryOf("LLM 服务余额欠费(上游账户额度不足,非本行数据问题)"))
|
||||
.isEqualTo(TaskRetryEligibility.Category.BALANCE.name());
|
||||
assertThat(TaskFailureLedger.categoryOf("upstream error: invalid_api_key"))
|
||||
.as("KEY 组并入 BALANCE:密钥失效不许被误判成别的类,更不许判空")
|
||||
.isEqualTo(TaskRetryEligibility.Category.BALANCE.name());
|
||||
assertThat(TaskFailureLedger.categoryOf("对象存储出口不可达,无法写入结果"))
|
||||
.isEqualTo(TaskRetryEligibility.Category.SERVICE_DOWN.name());
|
||||
assertThat(TaskFailureLedger.categoryOf("aiprice 未登录且自动登录失败"))
|
||||
.isEqualTo(TaskRetryEligibility.Category.CREDENTIAL.name());
|
||||
// 反向:值域外的普通可重试文案必须判不出——写侧落 null=未登记,读侧逐字回落文案
|
||||
assertThat(TaskFailureLedger.categoryOf("第 3 行数据格式不合法")).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code .updateById(} 写法总量棘轮(B82-01 的另一半:抹列面)。
|
||||
*
|
||||
* <p>{@code failure_category} 标了 {@code updateStrategy = ALWAYS}(V186,让「清错误」分支的
|
||||
* null 真落库),代价是<b>任何</b>「{@code new} 出来的部分实体」走 {@code updateById} 都会把
|
||||
* 这一列连同 ALWAYS 家族的其它列无条件抹回 NULL——12 处这种写法本笔已全部改成
|
||||
* {@code update(null, wrapper)} 显式 {@code .set}。本格钉住改后的总量:再多出一处
|
||||
* {@code updateById} 就当场红,逼着先审「实体有没有 ALWAYS 字段、传的是不是新鲜实体」,
|
||||
* 审过再登记基线。只报违规清零不报总量漂移的护栏,会把复发藏进平均值(B82-02 同族教训)。
|
||||
*/
|
||||
@Test
|
||||
void 任务行updateById写法总量棘轮_新增必须登记() {
|
||||
int sites = 0;
|
||||
for (Path file : mainJavaFiles()) {
|
||||
for (String line : readLines(file)) {
|
||||
String stripped = line.trim();
|
||||
if (isComment(stripped)) {
|
||||
continue;
|
||||
}
|
||||
int idx = stripped.indexOf(".updateById(");
|
||||
while (idx >= 0) {
|
||||
sites++;
|
||||
idx = stripped.indexOf(".updateById(", idx + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(sites)
|
||||
.as("updateById 写法总量偏离在册棘轮 ⇒ 要么有新写法没登记(先审 ALWAYS 抹列风险),"
|
||||
+ "要么有在册写点被改掉(把基线改到新值并在注释里留痕)")
|
||||
.isEqualTo(REGISTERED_UPDATE_BY_ID_SITES);
|
||||
}
|
||||
|
||||
/** 配对行必须引用同一个表达式来源,防止「写了列但写的是另一句文案的分类」。 */
|
||||
private static boolean pairingIsForSameMessage(String messageLine, String categoryLine) {
|
||||
String messageExpr = expressionOf(messageLine, MESSAGE_SET);
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.nanri.aiimage.testutil;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 从 MyBatis-Plus 的 {@code update(null, wrapper)} 入参里取回「SET 了哪些列、各是什么值」(B82-01 收口配套)。
|
||||
*
|
||||
* <p>任务行的部分字段落库已统一改成 {@code update(null, wrapper)} 显式 {@code .set}——部分实体
|
||||
* {@code updateById} 会把 {@code FieldStrategy.ALWAYS} 的 {@code failure_category} 无条件抹回 NULL。
|
||||
* mock 侧的事件捕获与假 DB 因此要从 wrapper 里取证,而不是从实体字段上读。列名与值的配对来自
|
||||
* {@code getSqlSet()} 的拼写顺序(与 {@code .set()} 调用顺序一致),值按 {@code MPGENVALn}
|
||||
* 精确取键——不依赖 {@code paramNameValuePairs} 的迭代序(那是 HashMap)。
|
||||
*/
|
||||
public final class UpdateWrapperProbe {
|
||||
|
||||
private static final Pattern SET_ITEM =
|
||||
Pattern.compile("([a-zA-Z_]+)=#\\{ew\\.paramNameValuePairs\\.(MPGENVAL\\d+)}");
|
||||
|
||||
private static final Pattern WHERE_ITEM =
|
||||
Pattern.compile("([a-zA-Z_]+)\\s*=\\s*#\\{ew\\.paramNameValuePairs\\.([A-Za-z0-9]+)}");
|
||||
|
||||
private UpdateWrapperProbe() {
|
||||
}
|
||||
|
||||
private record SetItem(String column, Object value, String paramKey) {
|
||||
}
|
||||
|
||||
private static List<SetItem> setItems(Wrapper<?> wrapper) {
|
||||
List<SetItem> out = new ArrayList<>();
|
||||
String sqlSet = sqlSet(wrapper);
|
||||
if (sqlSet == null || sqlSet.isBlank()) {
|
||||
return out;
|
||||
}
|
||||
Map<String, Object> params = paramNameValuePairs(wrapper);
|
||||
Matcher matcher = SET_ITEM.matcher(sqlSet);
|
||||
while (matcher.find()) {
|
||||
String paramKey = matcher.group(2);
|
||||
out.add(new SetItem(matcher.group(1), params.get(paramKey), paramKey));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** {@code getSqlSet()} 与 {@code getParamNameValuePairs()} 都挂在 AbstractWrapper 上,不在 Wrapper 接口。 */
|
||||
private static String sqlSet(Wrapper<?> wrapper) {
|
||||
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
|
||||
return abstractWrapper.getSqlSet();
|
||||
}
|
||||
throw new IllegalArgumentException("update(null, x) 的第二参不是 AbstractWrapper:" + wrapper.getClass());
|
||||
}
|
||||
|
||||
/** {@code getParamNameValuePairs()} 挂在 {@link com.baomidou.mybatisplus.core.conditions.AbstractWrapper} 上。 */
|
||||
public static Map<String, Object> paramNameValuePairs(Wrapper<?> wrapper) {
|
||||
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
|
||||
return abstractWrapper.getParamNameValuePairs();
|
||||
}
|
||||
throw new IllegalArgumentException("update(null, x) 的第二参不是 AbstractWrapper:" + wrapper.getClass());
|
||||
}
|
||||
|
||||
/** SET 段的「列名 → 值」,顺序与 {@code .set()} 调用顺序一致;列名一律归一成 snake_case。 */
|
||||
public static Map<String, Object> setValues(Wrapper<?> wrapper) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (SetItem item : setItems(wrapper)) {
|
||||
out.put(snake(item.column()), item.value());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 列名归一成 snake_case。单测 JVM 里 FileTaskEntity 的 Lambda 列缓存可能被先行自动初始化成
|
||||
* 驼峰(无 GlobalConfig 的裸 MybatisConfiguration 下 underCamel=false),而生产 Spring 上下文
|
||||
* 恒为下划线——探针两种都得认,否则快照结果取决于测试类的执行顺序。
|
||||
*/
|
||||
private static String snake(String column) {
|
||||
StringBuilder out = new StringBuilder(column.length() + 4);
|
||||
for (int i = 0; i < column.length(); i++) {
|
||||
char c = column.charAt(i);
|
||||
if (Character.isUpperCase(c)) {
|
||||
out.append('_').append(Character.toLowerCase(c));
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* WHERE 段的「列名 → 值」(等值条件;列名归一 snake_case)。判据与仓内
|
||||
* {@code applyTaskScanFilter} 同款:直接读 {@code getSqlSegment()} 的拼写,
|
||||
* 不靠 paramNameValuePairs 的键册回溯(那是 HashMap,序不可依赖)。
|
||||
*/
|
||||
public static Map<String, Object> whereEq(Wrapper<?> wrapper) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
if (!(wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper)) {
|
||||
return out;
|
||||
}
|
||||
String segment = abstractWrapper.getSqlSegment();
|
||||
if (segment == null || segment.isBlank()) {
|
||||
return out;
|
||||
}
|
||||
Map<String, Object> params = abstractWrapper.getParamNameValuePairs();
|
||||
Matcher matcher = WHERE_ITEM.matcher(segment);
|
||||
while (matcher.find()) {
|
||||
out.put(snake(matcher.group(1)), params.get(matcher.group(2)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** WHERE 段 {@code eq(id, …)} 的值(没有 eq(id) 或值不是 Long 时返回 null)。 */
|
||||
public static Long eqId(Wrapper<?> wrapper) {
|
||||
Object value = whereEq(wrapper).get("id");
|
||||
return value instanceof Long longValue ? longValue : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 SET 段按列名应用到内存实体上(假 DB 用;只认 {@code biz_file_task} 的列名)。
|
||||
* 未知列当场炸而不是静默跳过——假 DB 不认识的列会让快照测试说谎。
|
||||
*/
|
||||
public static void apply(FileTaskEntity entity, Map<String, Object> sets) {
|
||||
for (Map.Entry<String, Object> entry : sets.entrySet()) {
|
||||
String column = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
switch (column) {
|
||||
case "task_no" -> entity.setTaskNo((String) value);
|
||||
case "module_type" -> entity.setModuleType((String) value);
|
||||
case "task_mode" -> entity.setTaskMode((String) value);
|
||||
case "collect_channel" -> entity.setCollectChannel((String) value);
|
||||
case "status" -> entity.setStatus((String) value);
|
||||
case "source_file_count" -> entity.setSourceFileCount((Integer) value);
|
||||
case "success_file_count" -> entity.setSuccessFileCount((Integer) value);
|
||||
case "failed_file_count" -> entity.setFailedFileCount((Integer) value);
|
||||
case "request_json" -> entity.setRequestJson((String) value);
|
||||
case "result_json" -> entity.setResultJson((String) value);
|
||||
case "error_message" -> entity.setErrorMessage((String) value);
|
||||
case "failure_category" -> entity.setFailureCategory((String) value);
|
||||
case "created_by" -> entity.setCreatedBy((String) value);
|
||||
case "user_id" -> entity.setUserId((Long) value);
|
||||
case "device_id" -> entity.setDeviceId((String) value);
|
||||
case "owner_instance_id" -> entity.setOwnerInstanceId((String) value);
|
||||
case "updated_at" -> entity.setUpdatedAt((LocalDateTime) value);
|
||||
case "finished_at" -> entity.setFinishedAt((LocalDateTime) value);
|
||||
case "created_at" -> entity.setCreatedAt((LocalDateTime) value);
|
||||
default -> throw new IllegalStateException("UpdateWrapperProbe 不认识的列:" + column
|
||||
+ "(假 DB 拒绝静默跳过——把它登记进 apply 的列册再继续)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user