test(phase-3): 3A 迁移前补建单段 golden——吃真服务入口,不再抄一遍管线

AppearancePatentCreateTaskSnapshotTest(8 例)+ appearancepatent/golden/create-task-snapshot.txt。
渲染的是建单的落库事件流水:task.insert → payload.store → task.update → result.insert → scope.insert。

为什么已有 parse-snapshot.txt 还要再补一支:那支锁的是解析本身,而且是在测试里
重跑管线(自建 ExcelParser + 自己抄一份 baseId/hydratePromptFields),一行库没碰、
真入口一次没进。3A 要换掉的恰恰是 parseAndCreateTask 里那几行落库,那份 golden
对这件事零保护——蓝图 §5 的规矩写得很直白:「照抄那种对迁移零保护(旧代码消灭了测试还绿)」。

钉住的三段本支特有形状:
- 建单全程无事务:载荷存储失败时任务头行已经 insert(最后一节只剩 task.insert 一行),
  这是副作用边界,不是 bug 登记——底座不提供任何事务语义,迁移时必须原样保住。
- 结果行 success 留 NULL(不是 0 也不是 ShopDataCrawl 的 -1)、rowCount 写的是接受行数,
  所以底座 newScopeRow 的这两列只能由本支显式交进去。
- resultJson 是索引不是数据(六个顶层键+一枚载荷指针),真载荷只留 ptr://。

顺手钉出一条反直觉读数:maxParseRows 是「截断」口径不是「拒绝」口径——单文件读到上限
行数时 aggregate 那格的上限判定根本不触发,整单照建(golden 末行 events=5 就是这条)。
不顺手改,只登记。

时钟与雪花 id 不进快照;长内容取 sha256 前 12 位当摘要。两次独立 JVM 复跑逐字节相同
(generator 那格在未设环境变量时如实 skip)。AppearancePatent*Test 264 例全绿。
This commit is contained in:
2026-10-19 09:24:59 +08:00
parent 3471a4429f
commit 7b7d22cbb4
2 changed files with 534 additions and 0 deletions
@@ -0,0 +1,505 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import cn.hutool.crypto.digest.DigestUtil;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.service.ResultDownloadResolver;
import com.nanri.aiimage.modules.appearancepatent.client.AppearancePatentLlmClient;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParseRequest;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSourceFileDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParseVo;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 外观专利**建单段**的现网行为快照——3A 迁移的护身符。
*
* <p><b>为什么还要再补一支。</b>{@code AppearancePatentSnapshotTest} 那份 golden 锁的是解析本身,
* 而且是在测试里<b>重跑一遍管线</b>(自建 {@code AppearancePatentExcelParser} + 自己抄了一份
* {@code baseId}/{@code hydratePromptFields}),一行库都没碰、真服务入口一次没进。它对
* 「{@code parseAndCreateTask} 落了几张表、按什么顺序落」零保护——而 3A 要改的正是这一段
* (底座 {@code newTaskHeader}/{@code insertTask}/{@code writeJson} 换掉的就是这几行)。
* 蓝图 §5 早就给这类快照立过规矩:「照抄那种对迁移零保护(旧代码消灭了测试还绿)」。
* 所以这一支吃<b>真服务入口</b>:{@code parseAndCreateTask(request, deviceId)} 一路走到底。
*
* <p><b>快照吃的是事件流水</b>({@code task.insert → payload.store → task.update →
* result.insert → scope.insert}),顺序换了就红。这支同时钉住三段本支特有的现网形状:
* <ol>
* <li>建单<b>全程无事务</b>:载荷存储失败时任务头行<b>已经 insert</b>
* ({@code caseParsedPayloadStorageDisabledLeavesTheTaskRow})。这不是 bug 登记,
* 是迁移时必须原样保住的副作用边界——底座不提供任何事务语义。</li>
* <li>结果行<b>不写 success</b>(留 NULL)、{@code rowCount} 写的是接受行数,
* 与 ShopDataCrawl 的 {@code RESULT_PENDING=-1} 是两种形状 ⇒ 底座
* {@code newScopeRow} 的这两列必须由本支显式交进去,不能被默认值替掉。</li>
* <li>{@code resultJson} 里那六样东西(aiPrompt/apiKey/sourceFileKeys/parsedPayloadRef/
* ownerInstanceId …)是<b>索引</b>不是数据,真正的载荷只留一枚指针。</li>
* </ol>
*
* <p><b>刻意不进快照的两样</b>:雪花 id({@code taskNo} 擦成 {@code <snowflake>})、
* 时钟({@code createdAt/updatedAt/lastChunkAt})。第二条有个必须说清的边界:本支建单时
* {@code createdAt} 与 {@code updatedAt} 各调一次 {@code LocalDateTime.now()}(现网 {@code :208-209}),
* 而底座 {@code newTaskHeader} 只取一次——这格差异<b>快照量不出来</b>,也不该由快照来判:
* Phase 2 的 javadoc 已把它作为「两列都只用于建单时刻、无人拿它们互相比较」的多数派写法登记在案。
*
* golden:src/test/resources/appearancepatent/golden/create-task-snapshot.txt
* 重新生成:{@code SHUFU_SNAPSHOT_WRITE=true mvn -o test -Dtest=AppearancePatentCreateTaskSnapshotTest}
* (用环境变量而不是 {@code -D}:pom 里 {@code <argLine>} 是显式配置,命令行覆盖不动它。
* 这条 golden 只许在改动本支<b>之前</b>生成一次,此后它就是是非源。)
*/
class AppearancePatentCreateTaskSnapshotTest {
private static final File GOLDEN_CREATE =
new File("src/test/resources/appearancepatent/golden/create-task-snapshot.txt");
private static final String MODULE_TYPE = "APPEARANCE_PATENT";
private static final String[] HEADERS = {"id", "asin", "国家", "价格", "seller sku", "图片链接", "标题", "卖家名称", "品牌"};
@BeforeAll
static void initializeMybatisMetadata() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new Configuration(), "");
TableInfoHelper.initTableInfo(assistant, FileTaskEntity.class);
TableInfoHelper.initTableInfo(assistant, FileResultEntity.class);
TableInfoHelper.initTableInfo(assistant, TaskScopeStateEntity.class);
}
/** Spring 注入的那只 ObjectMapper ≠ {@code new ObjectMapper()}:Boot 会挂上 jsr310(Phase 0 实测教训)。 */
private static ObjectMapper bootLikeObjectMapper() {
return JsonMapper.builder()
.addModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
// ------------------------------------------------------------------
// 被测服务的装配:参数顺序=Lombok @RequiredArgsConstructor 的字段声明顺序
// ------------------------------------------------------------------
private static final class Harness {
final List<String> events = new ArrayList<>();
final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
final FileResultMapper fileResultMapper = mock(FileResultMapper.class);
final TaskScopeStateMapper taskScopeStateMapper = mock(TaskScopeStateMapper.class);
final LocalFileStorageService localFileStorageService = mock(LocalFileStorageService.class);
final TransientPayloadStorageService transientPayloadStorageService = mock(TransientPayloadStorageService.class);
final AppearancePatentProperties properties = mock(AppearancePatentProperties.class);
final InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
boolean sharedWriteEnabled = true;
AppearancePatentTaskService service() {
lenient().when(properties.getMaxParseRows()).thenReturn(1000);
lenient().when(instanceMetadata.getInstanceId()).thenReturn("instance-A");
lenient().when(transientPayloadStorageService.isSharedWriteEnabled()).thenReturn(sharedWriteEnabled);
lenient().when(transientPayloadStorageService.storeParsedPayloadFast(
anyString(), anyLong(), anyString(), anyString(), anyBoolean()))
.thenAnswer(invocation -> {
String scopeHash = invocation.getArgument(2);
String content = invocation.getArgument(3);
events.add("payload.storeParsed module=" + invocation.getArgument(0)
+ " taskId=" + invocation.getArgument(1)
+ " scopeHash=" + shortHash(scopeHash)
+ " entry=latest encodeAsJson=" + invocation.getArgument(4)
+ " content.len=" + content.length()
+ " content.digest=" + digest12(content));
return "ptr://task-parsed/" + shortHash(scopeHash) + "/latest";
});
doAnswer(invocation -> {
FileTaskEntity task = invocation.getArgument(0);
task.setId(1001L);
events.add("task.insert taskNo=" + maskTaskNo(task.getTaskNo())
+ " moduleType=" + task.getModuleType()
+ " status=" + task.getStatus()
+ " taskMode=" + task.getTaskMode()
+ " sourceFileCount=" + task.getSourceFileCount()
+ " successFileCount=" + task.getSuccessFileCount()
+ " failedFileCount=" + task.getFailedFileCount()
+ " userId=" + task.getUserId()
+ " createdBy=" + task.getCreatedBy()
+ " deviceId=" + task.getDeviceId()
+ " requestJson.keys=" + jsonKeys(task.getRequestJson())
+ " requestJson.digest=" + digest12(String.valueOf(task.getRequestJson()))
+ " 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(fileResultMapper.insert(any(FileResultEntity.class))).thenAnswer(invocation -> {
FileResultEntity row = invocation.getArgument(0);
row.setId(7001L);
events.add("result.insert taskId=" + row.getTaskId()
+ " moduleType=" + row.getModuleType()
+ " sourceFilename=" + row.getSourceFilename()
+ " sourceFileUrl=" + row.getSourceFileUrl()
+ " rowCount=" + row.getRowCount()
+ " success=" + row.getSuccess()
+ " userId=" + row.getUserId());
return 1;
});
when(taskScopeStateMapper.insert(any(TaskScopeStateEntity.class))).thenAnswer(invocation -> {
TaskScopeStateEntity scope = invocation.getArgument(0);
events.add("scope.insert taskId=" + scope.getTaskId()
+ " moduleType=" + scope.getModuleType()
+ " scopeKey=" + scope.getScopeKey()
+ " scopeHash=" + shortHash(String.valueOf(scope.getScopeHash()))
+ " parsedPayloadJson=" + scope.getParsedPayloadJson()
+ " stateJson=" + scope.getStateJson()
+ " chunkTotal=" + scope.getChunkTotal()
+ " receivedChunkCount=" + scope.getReceivedChunkCount()
+ " completed=" + scope.getCompleted());
return 1;
});
return new AppearancePatentTaskService(
localFileStorageService,
mock(OssStorageService.class),
mock(ResultDownloadResolver.class),
mock(StorageProperties.class),
fileTaskMapper,
fileResultMapper,
taskScopeStateMapper,
mock(TaskChunkMapper.class),
bootLikeObjectMapper(),
mock(AppearancePatentLlmClient.class),
mock(AppearancePatentTaskCacheService.class),
properties,
mock(TaskFileJobService.class),
mock(TaskProgressSnapshotService.class),
mock(TaskHeartbeatPositionService.class),
transientPayloadStorageService,
null,
mock(DistributedJobLockService.class),
mock(TaskDistributedLockService.class),
instanceMetadata,
mock(TaskProgressLightAssembler.class),
mock(UserApiSecretService.class));
}
}
// ------------------------------------------------------------------
// 夹具
// ------------------------------------------------------------------
private static File workbook(String name, List<String[]> rows) throws Exception {
File file = File.createTempFile("appearance-patent-create-task-", ".xlsx");
file.deleteOnExit();
try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream out = new FileOutputStream(file)) {
Sheet sheet = wb.createSheet(name);
Row header = sheet.createRow(0);
for (int i = 0; i < HEADERS.length; i++) {
header.createCell(i).setCellValue(HEADERS[i]);
}
for (int r = 0; r < rows.size(); r++) {
Row row = sheet.createRow(r + 1);
for (int c = 0; c < rows.get(r).length; c++) {
row.createCell(c).setCellValue(rows.get(r)[c]);
}
}
wb.write(out);
}
return file;
}
/** 四行两块:{@code 2_1/2_2} 同块、缺 asin 的一行 dropped、全空行连 total 都不算。 */
private static File mixedWorkbook() throws Exception {
return workbook("Sheet1", List.of(
new String[]{"2_1", "B01A", "US", "19.90", "SKU-1", "http://img/a.jpg", "title a", "seller-A", "brand-A"},
new String[]{"2_2", "B01B", "DE", "29.90", "SKU-2", "http://img/b.jpg", "", "seller-B", "brand-B"},
new String[]{"3", "", "FR", "", "", "", "", "seller-C", "brand-C"},
new String[]{"", "", ""}));
}
private static File secondWorkbook() throws Exception {
return workbook("Sheet1", List.<String[]>of(
new String[]{"9", "B09A", "UK", "1.00", "SKU-9", "http://img/i.jpg", "title i", "seller-I", "brand-I"}));
}
private static File emptyRowsWorkbook() throws Exception {
return workbook("Sheet1", List.<String[]>of(new String[]{"", "B02A", "US", "", "", "", "", "seller", "brand"}));
}
private static AppearancePatentSourceFileDto source(String fileKey, String originalFilename) {
AppearancePatentSourceFileDto dto = new AppearancePatentSourceFileDto();
dto.setFileKey(fileKey);
dto.setOriginalFilename(originalFilename);
return dto;
}
private static AppearancePatentParseRequest request(Long userId, List<AppearancePatentSourceFileDto> files) {
AppearancePatentParseRequest request = new AppearancePatentParseRequest();
request.setUserId(userId);
request.setFiles(files);
request.setAiPrompt(" 请排查侵权风险 ");
request.setApiKey("sk-test-0001");
return request;
}
private static Harness harnessWithFiles(String fileKeyA, File fileA, String fileKeyB, File fileB) {
Harness harness = new Harness();
when(harness.localFileStorageService.findLocalSourceFile(fileKeyA)).thenReturn(fileA);
if (fileKeyB != null) {
when(harness.localFileStorageService.findLocalSourceFile(fileKeyB)).thenReturn(fileB);
}
return harness;
}
// ------------------------------------------------------------------
// 读数整形:只擦不稳定量,不改结构
// ------------------------------------------------------------------
private static String maskTaskNo(String taskNo) {
int idx = taskNo == null ? -1 : taskNo.lastIndexOf('-');
return idx < 0 ? String.valueOf(taskNo) : taskNo.substring(0, idx) + "-<snowflake>";
}
/** 长内容的<b>摘要</b>(sha256 前 12 位):golden 要灵敏于内容变化,又不变成一堵 JSON 墙。 */
private static String digest12(String value) {
return DigestUtil.sha256Hex(value).substring(0, 12);
}
/** 本来就已截断的读数(scopeHash 现网即取 sha256 全串,这里只留前 12 位当身份)。 */
private static String shortHash(String value) {
return value.length() <= 12 ? value : value.substring(0, 12);
}
/** JSON 只取顶层键序:内容哈希另记,golden 不变成一堵 JSON 墙。 */
private static String jsonKeys(String json) {
if (json == null || json.isBlank()) {
return "[]";
}
List<String> keys = new ArrayList<>();
Matcher matcher = Pattern.compile("\"([^\"]+)\"\\s*:").matcher(json);
while (matcher.find()) {
keys.add(matcher.group(1));
}
return keys.isEmpty() ? "[<scalar>]" : "[" + String.join(",", keys) + "]";
}
private static String describe(String label, Runnable action) {
try {
action.run();
return label + " -> 未抛异常";
} catch (Exception ex) {
return label + " -> " + ex.getClass().getSimpleName() + ": " + ex.getMessage();
}
}
// ------------------------------------------------------------------
// 各场景(golden 的每一节)
// ------------------------------------------------------------------
private static String caseSingleFile() throws Exception {
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
AppearancePatentParseVo vo = harness.service()
.parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "device-1");
return "== 单文件建单 ==\n"
+ String.join("\n", harness.events)
+ "\nvo: taskId=" + vo.getTaskId()
+ " sourceFilename=" + vo.getSourceFilename()
+ " sourceFileCount=" + vo.getSourceFileCount()
+ " totalRows=" + vo.getTotalRows()
+ " acceptedRows=" + vo.getAcceptedRows()
+ " droppedRows=" + vo.getDroppedRows()
+ " groupCount=" + vo.getGroupCount()
+ " aiPrompt=" + vo.getAiPrompt()
+ " items=" + vo.getItems().size()
+ " groups=" + vo.getGroups().size()
+ "\n";
}
private static String caseTwoFilesAggregate() throws Exception {
Harness harness = harnessWithFiles("uploads/a.xlsx", mixedWorkbook(), "uploads/b.xlsx", secondWorkbook());
AppearancePatentParseVo vo = harness.service().parseAndCreateTask(request(7L, List.of(
source("uploads/a.xlsx", "a.xlsx"), source("uploads/b.xlsx", "b.xlsx"))), null);
return "== 双文件聚合 ==\n"
+ String.join("\n", harness.events)
+ "\nvo: sourceFilename=" + vo.getSourceFilename()
+ " sourceFileCount=" + vo.getSourceFileCount()
+ " totalRows=" + vo.getTotalRows()
+ " acceptedRows=" + vo.getAcceptedRows()
+ " groupCount=" + vo.getGroupCount()
+ "\n";
}
private static String caseRejectionsTouchNoDatabase() throws Exception {
StringBuilder sb = new StringBuilder("== 建单被拒的六格:一次库都不碰 ==\n");
sb.append(describe("userId=null", () -> new Harness().service()
.parseAndCreateTask(request(null, List.of(source("uploads/x.xlsx", "x.xlsx"))), "d"))).append('\n');
sb.append(describe("files=空", () -> new Harness().service()
.parseAndCreateTask(request(7L, List.of()), "d"))).append('\n');
sb.append(describe("files=全 null 元素", () -> new Harness().service()
.parseAndCreateTask(request(7L, Arrays.asList(null, null)), "d"))).append('\n');
Harness noKey = new Harness();
sb.append(describe("fileKey=空白", () -> noKey.service()
.parseAndCreateTask(request(7L, List.of(source(" ", "x.xlsx"))), "d"))).append('\n');
Harness missing = new Harness();
when(missing.localFileStorageService.findLocalSourceFile("uploads/none.xlsx")).thenReturn(null);
sb.append(describe("源文件不存在", () -> missing.service()
.parseAndCreateTask(request(7L, List.of(source("uploads/none.xlsx", "none.xlsx"))), "d"))).append('\n');
Harness noRows = harnessWithFiles("uploads/empty.xlsx", emptyRowsWorkbook(), null, null);
sb.append(describe("未解析到有效行", () -> noRows.service()
.parseAndCreateTask(request(7L, List.of(source("uploads/empty.xlsx", "empty.xlsx"))), "d"))).append('\n');
Harness overLimit = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
when(overLimit.properties.getMaxParseRows()).thenReturn(1);
sb.append(describe("超过 maxParseRows", () -> overLimit.service()
.parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d"))).append('\n');
sb.append("events=")
.append(noRows.events.size() + noKey.events.size() + missing.events.size() + overLimit.events.size())
.append("(四格有夹具的场景也必须零落库)\n");
return sb.toString();
}
private static String caseParsedPayloadStorageDisabledLeavesTheTaskRow() throws Exception {
Harness harness = new Harness();
harness.sharedWriteEnabled = false;
when(harness.localFileStorageService.findLocalSourceFile("uploads/main.xlsx")).thenReturn(mixedWorkbook());
String outcome = describe("共享临时存储关闭", () -> harness.service()
.parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d"));
return "== 载荷存储失败时的副作用边界(本支建单无事务) ==\n"
+ String.join("\n", harness.events)
+ "\noutcome=" + outcome + "\n";
}
private static String renderAll() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(caseSingleFile());
sb.append('\n');
sb.append(caseTwoFilesAggregate());
sb.append('\n');
sb.append(caseRejectionsTouchNoDatabase());
sb.append('\n');
sb.append(caseParsedPayloadStorageDisabledLeavesTheTaskRow());
return sb.toString();
}
private static String read(File file) throws Exception {
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
}
// ------------------------------------------------------------------
// 用例
// ------------------------------------------------------------------
@Test
void 建单段落库流水与golden一致() throws Exception {
assertEquals(read(GOLDEN_CREATE), renderAll(), "建单段事件流水必须与 golden 逐字节相等");
}
@Test
void 结果行不写success且rowCount是接受行数() throws Exception {
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
harness.service().parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "device-1");
String resultEvent = harness.events.stream().filter(e -> e.startsWith("result.insert")).findFirst().orElse("");
assertTrue(resultEvent.contains(" success=null"), "本支结果行的 success 留 NULL,不是 0 也不是 -1:" + resultEvent);
assertTrue(resultEvent.contains(" rowCount=2"), "rowCount 记的是接受行数(4 行夹具去掉 dropped 与全空行):" + resultEvent);
}
@Test
void 头行先落库再有载荷指针() throws Exception {
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
harness.service().parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "device-1");
assertEquals(List.of("task.insert", "payload.storeParsed", "task.update", "result.insert", "scope.insert"),
harness.events.stream().map(e -> e.substring(0, e.indexOf(' '))).toList(),
"建单的副作用顺序:头行→载荷存储→回填索引→结果行→作用域行");
}
@Test
void 非法建单一次库都不碰() {
Harness harness = new Harness();
assertThrows(com.nanri.aiimage.common.exception.BusinessException.class,
() -> harness.service().parseAndCreateTask(request(null, List.of(source("k", "k.xlsx"))), "d"));
assertTrue(harness.events.isEmpty(), "user_id 不合法时不得有任何落库");
}
@Test
void golden文件已入库且非空() {
assertNotNull(GOLDEN_CREATE);
assertTrue(GOLDEN_CREATE.isFile(), "golden 必须入库: " + GOLDEN_CREATE.getAbsolutePath());
assertTrue(GOLDEN_CREATE.length() > 0, "golden 非空");
}
@Test
void 篡改golden必须判红() throws Exception {
String original = read(GOLDEN_CREATE);
assertTrue(original.contains("== 单文件建单 =="), "golden 内容合法");
try {
Files.writeString(GOLDEN_CREATE.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
AssertionError failure = null;
try {
assertEquals(read(GOLDEN_CREATE), renderAll(), "篡改后应与 golden 不一致");
} catch (AssertionError ex) {
failure = ex;
}
assertNotNull(failure, "篡改 golden 后断言必须失败,否则这支是恒绿的");
} finally {
Files.writeString(GOLDEN_CREATE.toPath(), original, StandardCharsets.UTF_8);
}
assertEquals(original, read(GOLDEN_CREATE), "恢复原始 golden");
}
@Test
void 同一夹具跑两次流水一致() throws Exception {
assertEquals(renderAll(), renderAll(), "快照必须可复现(雪花 id 与时钟已擦除)");
}
/** 生成 golden 用:{@code SHUFU_SNAPSHOT_WRITE=true} 时把当前流水写回文件。 */
@Test
@org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable(named = "SHUFU_SNAPSHOT_WRITE", matches = "true")
void 重新生成golden() throws Exception {
Files.writeString(GOLDEN_CREATE.toPath(), renderAll(), StandardCharsets.UTF_8);
}
}