From 8be3f2dbf1eedd5a6ef8d5ea8cab25969f5b3f99 Mon Sep 17 00:00:00 2001 From: zhanghao <774378400@qq.com> Date: Mon, 30 Nov 2026 16:01:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(testing):=20=E8=AF=95=E9=AA=8C=E8=BD=AE?= =?UTF-8?q?=E6=AC=A1=E5=8F=AF=E5=85=B3=E8=81=94=E5=85=B1=E4=BA=AB=E5=88=86?= =?UTF-8?q?=E6=9E=90=E5=8F=82=E6=95=B0=E5=BF=AB=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/testing-analysis-parameters-plan.md | 2 + ruoyi-testing/README.md | 21 ++++ .../ruoyi/testing/domain/TestingInput.java | 4 +- .../ruoyi/testing/mapper/TestingMapper.java | 4 +- .../ruoyi/testing/service/TestingService.java | 29 +++-- .../TestingAnalysisParameterRunTest.java | 101 ++++++++++++++++++ .../views/testing/components/TaskDetail.vue | 82 ++++++++++++-- .../testing-analysis-parameter-runs.spec.js | 60 +++++++++++ 8 files changed, 285 insertions(+), 18 deletions(-) create mode 100644 ruoyi-testing/src/test/java/com/ruoyi/testing/TestingAnalysisParameterRunTest.java create mode 100644 ruoyi-ui-vue3/tests/runtime/testing-analysis-parameter-runs.spec.js diff --git a/docs/testing-analysis-parameters-plan.md b/docs/testing-analysis-parameters-plan.md index 342a439..393b295 100644 --- a/docs/testing-analysis-parameters-plan.md +++ b/docs/testing-analysis-parameters-plan.md @@ -88,3 +88,5 @@ - Task 1:新 API 缺失的编译 RED 已观察;实现后 5 个规则/识别/HTTP 用例全部通过;既有标定后端 22、前端 11 用例基线通过。验证在隔离副本,不触发运行服务加载。 - Task 2:共享资料/Mapper/存储 API 缺失的 RED 已观察;实现后累计 17 个相关用例通过,覆盖真实 H2 DDL/分页/乐观锁、只读拒写、错模式、模型后资格撤销和共享存储命名空间。005 仅生成,未连接真实数据库执行。 - Task 3:页面缺失的 RED 已观察;实现后真实 Element Plus 的 8 项前端用例全部通过,覆盖 17/11 字段、独立保存、编辑版本及列表刷新、迟到响应、确认期间人工修改、只读和 Blob 释放。 +- Task 4:新增轮次 API 缺失和选择界面缺失的 RED 已观察;6 个轮次后端用例、3 个前端用例通过。空快照兼容测试曾发现通用转换保留 null,已在新字段局部改用空对象解析,随后 43 个后端相关用例及 22 个前端相关用例全部通过。 +- 全量前端入口已执行:`table-cell-policy.test.mjs` 仍有既有测试页面列角色规范失败;新分析参数页没有新增违规。继续运行运行时测试入口及构建,不扩大范围修改旧页面。 diff --git a/ruoyi-testing/README.md b/ruoyi-testing/README.md index b7a4a43..a751bca 100644 --- a/ruoyi-testing/README.md +++ b/ruoyi-testing/README.md @@ -128,3 +128,24 @@ testing: 标定识别最多两个并发请求、90 秒超时;小型裁剪图片仅为模型生成有界的最近邻放大副本,原图及摘要不变。 低分辨率数字识别仍需对照原图核对,所有数据允许手工修正;不补零、不生成单位矩阵、不计算 TCP、角度、转换误差或合格结论。 历史旧格式可只读查看,基于旧记录创建新版本时补充新表单参数和截图,不回写历史 JSON。 + +## 分析参数共享资料库 + +“分析参数”位于测试管理下,路径 `/testing/analysis-parameters`,作为独立共享资料库保存,不绑定项目、机器人或任务。 +具有 `testing:read` 的用户可以查看记录及原图,具有 `testing:write` 且可读取的用户可以新增、编辑、上传及识别;不增加删除、计算或自动判定功能。 + +现有数据库在启动新版后端前执行 `sql/005_analysis_parameters.sql`;请按环境流程先备份并核对目标库。 +脚本可重复执行,只增加 `tm_analysis_parameter_image`、`tm_analysis_parameter`、`tm_test_run.analysis_parameters_json` 及菜单和已有测试读取角色的页面授权,不修改历史值或给普通角色授予测试权限。 +全新安装的 `001_testing_management.sql` 已包含这些表、列及菜单。回退应用时保留新增结构和快照,不通过删除资料或列回退。 + +- 轨迹:10 项公共几何/P1 位姿参数及 7 项轨迹参数,共 17 项。 +- 位姿:10 项公共参数及测量停顿时间,共 11 项。 +- 固定读取 C6C7/C6C5/C6C2、P2..P5 顶点距离比例、P1 的 x/y/z/R/P/Y,以及对应模式的圆比例、时间、距离及速度参照段。顶部示意图/选择项、其他开关及未要求区域即使清晰可见也不读取。 +- 数字保存原始十进制字符串;速度参照段保留 `1/4` 等文本,不转换成小数。无法识别的值留空,支持对照原图手工补充,不套用样图数值或补零。 + +每条记录保存当前原图和参数。上传只接受真实 PNG/JPEG,沿用 50MB、四千万像素、私有 MinIO 和 SHA256 完整性检查;使用独立 `testing/analysis-parameters/` 目录,不能把项目证据变成全局共享图片。 +上传后识别当前图片,实际测量模式或参数标签不匹配时拒绝回填。识别只生成候选,已有人工输入替换前核对;换图、换模式或关闭表单会阻止旧响应回填。重新编辑通过版本号防止覆盖他人修改。 + +新建实际试验轮次时,“关联标定版本”继续只选择当前机器人的标定;新增“关联分析参数(可选)”从共享资料库选一条记录。 +创建时提交资料 ID 及所见版本,在项目事务内当前读并核对后冻结名称、模式、版本、参数及原图引用;资料之后修改不回写轮次。过期版本需清空关联、重新搜索选择或重新打开弹窗,其他表单内容保留。 +旧请求可省略参数关联,旧轮次仍显示为未关联;不强制任务类型对应某种参数模式,不将参数写入阈值,也不改变判定结果。 diff --git a/ruoyi-testing/src/main/java/com/ruoyi/testing/domain/TestingInput.java b/ruoyi-testing/src/main/java/com/ruoyi/testing/domain/TestingInput.java index 4859f29..4da94c4 100644 --- a/ruoyi-testing/src/main/java/com/ruoyi/testing/domain/TestingInput.java +++ b/ruoyi-testing/src/main/java/com/ruoyi/testing/domain/TestingInput.java @@ -20,8 +20,8 @@ public final class TestingInput { String description, long templateId, JsonNode configuration, Long version) { } /** 删除只接受列表中的任务版本;创建者和删除状态由认证会话及数据库决定。 */ public record DeleteTask(Long version) { } - /** 每轮显式绑定标定版本与实际试验时间,不以截图上传时间冒充测量时间。 */ - public record Run(String actualAt, String notes, List calibrationIds) { } + /** 每轮绑定具体标定及可选分析参数;参数 ID/版本必须成对,旧 JSON 省略时保持无关联。 */ + public record Run(String actualAt, String notes, List calibrationIds, Long analysisParameterId, Long analysisParameterVersion) { } /** 标定为追加记录;同名记录产生后续版本,已关联的版本永不覆盖。 */ public record Calibration(long robotId, String name, String kind, JsonNode data) { } /** 模板发布生成不可变版本;初始模板可以保留为 DRAFT 等待真实截图完善。 */ diff --git a/ruoyi-testing/src/main/java/com/ruoyi/testing/mapper/TestingMapper.java b/ruoyi-testing/src/main/java/com/ruoyi/testing/mapper/TestingMapper.java index 4ab2f2c..122ba83 100644 --- a/ruoyi-testing/src/main/java/com/ruoyi/testing/mapper/TestingMapper.java +++ b/ruoyi-testing/src/main/java/com/ruoyi/testing/mapper/TestingMapper.java @@ -132,8 +132,8 @@ public interface TestingMapper { @Select("SELECT * FROM tm_test_run WHERE id=#{id}") Map run(long id); /** 轮次编号在项目写锁内分配。 */ @Select("SELECT COALESCE(MAX(round_no),0)+1 FROM tm_test_run WHERE task_id=#{task}") int nextRound(long task); - /** 关联快照,机器人及标定变化不回写此行。 */ - @Insert("INSERT INTO tm_test_run(task_id,round_no,config_id,robot_snapshot_json,calibration_json,actual_at,notes,created_by) VALUES(#{task_id},#{round_no},#{config_id},#{robot_snapshot_json},#{calibration_json},#{actual_at},#{notes},#{created_by})") + /** 设备、标定和可选共享参数快照一起提交;资料后续变化不回写本轮,旧请求保存NULL。 */ + @Insert("INSERT INTO tm_test_run(task_id,round_no,config_id,robot_snapshot_json,calibration_json,analysis_parameters_json,actual_at,notes,created_by) VALUES(#{task_id},#{round_no},#{config_id},#{robot_snapshot_json},#{calibration_json},#{analysis_parameters_json},#{actual_at},#{notes},#{created_by})") @Options(useGeneratedKeys=true,keyProperty="id") int insertRun(Map row); /** 每个分支结果按版本展示,识别失败也不丢失历史。 */ @Select("SELECT * FROM tm_result_batch WHERE run_id=#{run} ORDER BY case_code,revision_no DESC") List> batches(long run); diff --git a/ruoyi-testing/src/main/java/com/ruoyi/testing/service/TestingService.java b/ruoyi-testing/src/main/java/com/ruoyi/testing/service/TestingService.java index ca1d16e..f057131 100644 --- a/ruoyi-testing/src/main/java/com/ruoyi/testing/service/TestingService.java +++ b/ruoyi-testing/src/main/java/com/ruoyi/testing/service/TestingService.java @@ -21,10 +21,11 @@ public class TestingService { private final TestingRules rules; private final TestingImageStorage images; private final TestingCalibrationService calibrations; + private final TestingAnalysisParameterService analysisParameters; - /** 注入独立测试域组件,业务不依赖项目协作的阶段或审批规则。 */ - public TestingService(TestingMapper db,TestingAccess access,TestingRules rules,TestingImageStorage images,TestingCalibrationService calibrations) { - this.db=db; this.access=access; this.rules=rules; this.images=images; this.calibrations=calibrations; + /** 注入测试域组件;共享参数只为新轮次提供快照,不改变项目协作、标定或判定规则。 */ + public TestingService(TestingMapper db,TestingAccess access,TestingRules rules,TestingImageStorage images,TestingCalibrationService calibrations,TestingAnalysisParameterService analysisParameters) { + this.db=db; this.access=access; this.rules=rules; this.images=images; this.calibrations=calibrations; this.analysisParameters=analysisParameters; } /** 返回当前账号权限,页面只用于显示入口,正式操作仍重新鉴权。 */ @@ -232,7 +233,12 @@ public class TestingService { db.insertCalibration(row); audit(project,"CREATE","CALIBRATION",id(row,"id"),null,row,""); return id(row,"id"); } - /** 新轮次只关联在用标定类型;已经冻结的历史关联保持原样,实际重测仍创建新轮次。 */ + /** + * 新轮次在同一事务中冻结设备、标定和可选分析参数,不从后续可变资料中还原历史。 + * @param taskId 当前任务,仍须具备实时项目写资格。 + * @param in 实际时间、标定及可选分析参数 ID/所见版本;不接受客户端提供的快照正文。 + * @return 新轮次主键;资料已被编辑、标定不属于本机或审计失败时整次创建回滚。 + */ @Transactional public long createRun(long taskId,TestingInput.Run in) { Map task=access.task(taskId,true), config=db.latestConfig(taskId); List> calibration=new ArrayList<>(); @@ -243,8 +249,15 @@ public class TestingService { if(!TestingCalibrationData.KINDS.contains(c.get("kind"))) throw bad("该标定类型已停用,不能关联新的试验轮次"); calibration.add(c); } + Map parameters=null; + if(in.analysisParameterId()!=null || in.analysisParameterVersion()!=null) { + if(in.analysisParameterId()==null || in.analysisParameterVersion()==null || in.analysisParameterId()<1 || in.analysisParameterVersion()<1) + throw bad("请选择有效的分析参数记录及版本,或清空关联"); + // 先项目锁后资料当前读,与资料编辑不会形成反向锁依赖;过期选择不能静默换成新版。 + parameters=analysisParameters.snapshot(in.analysisParameterId(),in.analysisParameterVersion()); + } Map robot=map("tested",db.robot(id(task,"robot_id")),"compared",task.get("compared_robot_id")==null?null:db.robot(id(task,"compared_robot_id"))); - Map row=map("task_id",taskId,"round_no",db.nextRound(taskId),"config_id",id(config,"id"),"robot_snapshot_json",write(robot),"calibration_json",write(calibration),"actual_at",actual(in.actualAt()),"notes",text(in.notes(),4000,false,"轮次说明"),"created_by",access.actor()); + Map row=map("task_id",taskId,"round_no",db.nextRound(taskId),"config_id",id(config,"id"),"robot_snapshot_json",write(robot),"calibration_json",write(calibration),"analysis_parameters_json",parameters==null?null:write(parameters),"actual_at",actual(in.actualAt()),"notes",text(in.notes(),4000,false,"轮次说明"),"created_by",access.actor()); db.insertRun(row); audit(id(task,"project_id"),"CREATE","RUN",id(row,"id"),null,row,""); return id(row,"id"); } @@ -527,9 +540,11 @@ public class TestingService { List> copy=new ArrayList<>(source.size()); for(Map row:source) copy.add(new LinkedHashMap<>(row)); return copy; } - /** 轮次快照面向项目成员可读,当前机器人编辑不修改已保存内容。 */ + /** 只解析轮次保存的快照,不查询可变资料;旧轮次空参数按未关联展示。 */ private Map publicRun(Map source) { - Map copy=new LinkedHashMap<>(source); jsonColumn(copy,"robot_snapshot_json","robotSnapshot"); jsonColumn(copy,"calibration_json","calibrations"); return copy; + Map copy=new LinkedHashMap<>(source); jsonColumn(copy,"robot_snapshot_json","robotSnapshot"); jsonColumn(copy,"calibration_json","calibrations"); + // 旧轮次没有选择参数时返回空对象;不改变通用转换器对其他历史字段保留 null 的约定。 + copy.put("analysisParameters",read(copy.remove("analysis_parameters_json"))); return copy; } /** 从已验证上下文取项目主键,不能信任客户端附带的项目编号。 */ diff --git a/ruoyi-testing/src/test/java/com/ruoyi/testing/TestingAnalysisParameterRunTest.java b/ruoyi-testing/src/test/java/com/ruoyi/testing/TestingAnalysisParameterRunTest.java new file mode 100644 index 0000000..790c0f7 --- /dev/null +++ b/ruoyi-testing/src/test/java/com/ruoyi/testing/TestingAnalysisParameterRunTest.java @@ -0,0 +1,101 @@ +package com.ruoyi.testing; + +import com.ruoyi.common.exception.ServiceException; +import com.ruoyi.testing.domain.TestingInput; +import com.ruoyi.testing.mapper.TestingMapper; +import com.ruoyi.testing.security.TestingAccess; +import com.ruoyi.testing.service.*; +import com.ruoyi.testing.storage.TestingImageStorage; +import static com.ruoyi.testing.support.TestingJson.*; +import java.nio.file.*; +import java.util.*; +import java.util.regex.Pattern; +import org.h2.jdbcx.JdbcDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.*; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentCaptor; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** 共享参数的选择只增加轮次快照,不弱化原有项目及机器人标定校验。 */ +class TestingAnalysisParameterRunTest { + private final TestingMapper db=mock(TestingMapper.class); + private final TestingAccess access=mock(TestingAccess.class); + private final TestingAnalysisParameterService parameters=mock(TestingAnalysisParameterService.class); + private TestingService service; + + /** 外部依赖使用明确身份,创建轮次及 JSON 冻结过程使用真实业务方法。 */ + @BeforeEach void setup() { + service=new TestingService(db,access,mock(TestingRules.class),mock(TestingImageStorage.class),mock(TestingCalibrationService.class),parameters); + var task=map("id",4L,"project_id",7L,"robot_id",9L,"compared_robot_id",null); when(access.task(eq(4L),anyBoolean())).thenReturn(task); + when(access.actor()).thenReturn(10L); when(db.latestConfig(4)).thenReturn(map("id",12L,"config_json","{}")); + when(db.nextRound(4)).thenReturn(2); when(db.insertRun(any())).thenAnswer(call->{((Map)call.getArgument(0)).put("id",77L);return 1;}); + when(db.robot(9)).thenReturn(map("id",9L,"project_id",7L,"name","机器人A")); + } + + /** 旧 JSON 不传新字段时保持无关联,不能为它猜测一个共享记录。 */ + @Test void oldRunRequestStillCreatesWithoutAnalysisParameters() throws Exception { + var request=JSON.treeToValue(read("{\"actualAt\":null,\"notes\":\"\",\"calibrationIds\":[]}"),TestingInput.Run.class); + assertNull(request.analysisParameterId()); assertEquals(77L,service.createRun(4,request)); + var captured=ArgumentCaptor.forClass(Map.class); verify(db).insertRun(captured.capture()); + assertNull(captured.getValue().get("analysis_parameters_json")); verifyNoInteractions(parameters); + } + + /** 选择时核对版本并写入独立快照,后续更改共享对象不会改变已序列化的轮次。 */ + @Test void selectedRecordIsFrozenWithNameModeVersionValuesAndImage() { + var snapshot=map("id",5L,"name","共享位姿","mode","POSE","version",3L,"imageId",88L,"values",read("{\"p1R\":\"-115.9060\"}")); + when(parameters.snapshot(5,3L)).thenReturn(snapshot); + assertEquals(77L,service.createRun(4,new TestingInput.Run(null,"本轮",List.of(),5L,3L))); + var captured=ArgumentCaptor.forClass(Map.class); verify(db).insertRun(captured.capture()); + var frozen=read(captured.getValue().get("analysis_parameters_json")); snapshot.put("name","后来修改的名字"); + assertEquals("共享位姿",frozen.path("name").asText()); assertEquals("-115.9060",frozen.at("/values/p1R").asText()); assertEquals(88L,frozen.path("imageId").asLong()); + var order=inOrder(access,parameters,db); order.verify(access).task(4,true); order.verify(parameters).snapshot(5,3L); order.verify(db).insertRun(any()); + } + + /** 参数版本变更或 ID/版本不成对时不允许半创建轮次,表单应刷新重选。 */ + @Test void changedOrIncompleteSelectionCannotCreateARun() { + when(parameters.snapshot(5,2L)).thenThrow(new ServiceException("数据已更新",409)); + assertThrows(ServiceException.class,()->service.createRun(4,new TestingInput.Run(null,"",List.of(),5L,2L))); + assertThrows(ServiceException.class,()->service.createRun(4,new TestingInput.Run(null,"",List.of(),5L,null))); + assertThrows(ServiceException.class,()->service.createRun(4,new TestingInput.Run(null,"",List.of(),null,3L))); + verify(db,never()).insertRun(any()); + } + + /** 原有标定继续绑定本项目当前机器人,不能因为共享参数加入就接受另一设备的标定。 */ + @Test void existingCalibrationRobotBoundaryRemainsEnforced() { + when(db.calibration(11)).thenReturn(map("id",11L,"project_id",7L,"robot_id",10L,"kind","POSE")); + assertThrows(ServiceException.class,()->service.createRun(4,new TestingInput.Run(null,"",List.of(11L),5L,3L))); + verifyNoInteractions(parameters); verify(db,never()).insertRun(any()); + } + + /** 旧轮次读取为空对象,有快照的轮次仅解析所存 JSON,不再查询可变资料库。 */ + @Test void runReadUsesStoredSnapshotAndSupportsLegacyNull() { + var run=map("id",77L,"task_id",4L,"config_id",12L,"robot_snapshot_json","{}","calibration_json","[]","analysis_parameters_json",null); + when(db.run(77)).thenReturn(run); when(db.config(12)).thenReturn(map("config_json","{}")); when(db.batches(77)).thenReturn(List.of()); + var old=(Map)service.run(77).get("run"); assertTrue(((com.fasterxml.jackson.databind.JsonNode)old.get("analysisParameters")).isEmpty()); + run.put("analysis_parameters_json","{\"id\":5,\"version\":3,\"mode\":\"POSE\",\"values\":{\"p1R\":\"-115.9060\"}}"); + var current=(Map)service.run(77).get("run"); + assertEquals("-115.9060",((com.fasterxml.jackson.databind.JsonNode)current.get("analysisParameters")).at("/values/p1R").asText()); verifyNoInteractions(parameters); + } + + /** 真实轮次 Mapper 同时保存 NULL 兼容值和参数 JSON,验证新增列并非只存在于请求对象。 */ + @Test void actualRunSqlPersistsOptionalSnapshot() throws Exception { + var source=new JdbcDataSource(); source.setURL("jdbc:h2:mem:analysis_run_"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE"); + try(var connection=source.getConnection()) { + var sql=connection.createStatement(); sql.execute("CREATE TABLE tm_task(id BIGINT PRIMARY KEY)"); sql.execute("CREATE TABLE tm_task_config_version(id BIGINT PRIMARY KEY)"); + sql.execute("INSERT INTO tm_task VALUES(4)"); sql.execute("INSERT INTO tm_task_config_version VALUES(12)"); + var match=Pattern.compile("CREATE TABLE IF NOT EXISTS tm_test_run \\(.*?\\) ENGINE=InnoDB[^;]*;",Pattern.DOTALL).matcher(Files.readString(Path.of("sql/001_testing_management.sql"))); + assertTrue(match.find()); sql.execute(match.group().replaceAll("\\) ENGINE=InnoDB[^;]*;", ");")); + var config=new Configuration(new Environment("test",new JdbcTransactionFactory(),source)); config.addMapper(TestingMapper.class); + try(var session=new SqlSessionFactoryBuilder().build(config).openSession(connection)) { + var mapper=session.getMapper(TestingMapper.class); var row=map("task_id",4L,"round_no",1,"config_id",12L,"robot_snapshot_json","{}","calibration_json","[]","analysis_parameters_json",null,"actual_at",null,"notes","","created_by",10L); + mapper.insertRun(row); assertNull(mapper.run(id(row,"id")).get("analysis_parameters_json")); + row.put("round_no",2); row.put("analysis_parameters_json","{\"id\":5,\"values\":{\"p1R\":\"-115.9060\"}}"); mapper.insertRun(row); + assertEquals("-115.9060",read(mapper.run(id(row,"id")).get("analysis_parameters_json")).at("/values/p1R").asText()); + } + } + } +} diff --git a/ruoyi-ui-vue3/src/views/testing/components/TaskDetail.vue b/ruoyi-ui-vue3/src/views/testing/components/TaskDetail.vue index 3702f81..10ac65a 100644 --- a/ruoyi-ui-vue3/src/views/testing/components/TaskDetail.vue +++ b/ruoyi-ui-vue3/src/views/testing/components/TaskDetail.vue @@ -8,17 +8,33 @@
试验轮次实际重测建新轮次,纠正识别或录入错误建修订。
-

建立后冻结当前机器人、模板、测试范围和阈值。改变配置请新建下一轮。

+ + + + + + + + +

建立后冻结机器人、标定、所选分析参数、模板和阈值。分析参数只留存快照,不参与判定。

+ +
diff --git a/ruoyi-ui-vue3/tests/runtime/testing-analysis-parameter-runs.spec.js b/ruoyi-ui-vue3/tests/runtime/testing-analysis-parameter-runs.spec.js new file mode 100644 index 0000000..c59bef6 --- /dev/null +++ b/ruoyi-ui-vue3/tests/runtime/testing-analysis-parameter-runs.spec.js @@ -0,0 +1,60 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { mount, flushPromises } from '@vue/test-utils' +import ElementPlus from 'element-plus' +import TaskDetail from '@/views/testing/components/TaskDetail.vue' + +const api = vi.hoisted(() => ({ testing: vi.fn(), push: vi.fn(), route: { query: {} }, conflict: false, runs: [] })) +vi.mock('@/views/testing/shared/api', () => api) +vi.mock('vue-router', () => ({ useRoute: () => api.route, useRouter: () => ({ push: api.push }), onBeforeRouteLeave: vi.fn(), onBeforeRouteUpdate: vi.fn() })) +const wrappers = [] + +/** 模拟真实任务、同机器人标定和跨项目共享参数,不访问业务数据库。 */ +beforeEach(() => { + vi.clearAllMocks(); api.runs = []; api.route.query = {}; api.conflict = false + api.testing.mockImplementation(async (path, method = 'get', body, params) => { + if (path === '/tasks/4' && method === 'get') return { task: { id: 4, project_id: 7, robot_id: 9, name: '测试任务A', type_code: 'PRE', description: '', owner_name: '测试人员' }, runs: api.runs, configuration: {} } + if (path === '/capabilities') return { write: true } + if (path === '/catalog') return { types: [{ code: 'PRE', name: '预实验' }], metrics: [], templates: [] } + if (path === '/projects/7') return { role: 'MANAGER', robots: [{ id: 9, name: '机器人A' }] } + if (path === '/projects/7/calibrations') return [{ id: 11, robot_id: 9, name: '本机姿态', kind: 'POSE', version: 2 }, { id: 12, robot_id: 10, name: '另一机器人', kind: 'POSE', version: 1 }] + if (path === '/analysis-parameters') return { items: params?.keyword ? [{ id: 6, name: '新搜索记录', mode: 'TRAJECTORY', version: 1 }] : [{ id: 5, name: '共享位姿', mode: 'POSE', version: 3 }], total: 1 } + if (path === '/tasks/4/runs' && method === 'post') { + if (api.conflict) throw new Error('数据已更新,请刷新后重试') + api.runs = [{ id: 77, round_no: 2 }]; return 77 + } + if (path === '/runs/77') return { run: { id: 77, robotSnapshot: {}, calibrations: [], analysisParameters: {} }, task: { id: 4 }, configuration: { cases: {}, schema: { fields: [] } }, batches: [] } + throw new Error(`Unexpected request: ${path}`) + }) +}) + +/** 清理真实弹窗浮层,避免后续测试看到上一轮表单。 */ +afterEach(() => { wrappers.splice(0).forEach(wrapper => wrapper.unmount()); document.body.innerHTML = '' }) + +/** 挂载真实轮次表单,隔离无关结果编辑组件及其网络请求。 */ +async function detail() { + const wrapper = mount(TaskDetail, { attachTo: document.body, props: { taskId: 4 }, global: { plugins: [ElementPlus], stubs: { TaskForm: true, ThresholdEditor: true, ResultEditor: true } } }) + wrappers.push(wrapper); await flushPromises(); await wrapper.vm.openRun(); await flushPromises(); return wrapper +} + +test('new run can select shared analysis parameters separately from robot calibration', async () => { + const wrapper = await detail(); expect(wrapper.vm.calibrations.map(row => row.id)).toEqual([11]) + expect(document.body.textContent).toContain('关联分析参数'); wrapper.vm.runForm.calibrationIds = [11] + wrapper.vm.selectAnalysisParameter(5); await wrapper.vm.createRun() + const sent = api.testing.mock.calls.find(call => call[0] === '/tasks/4/runs' && call[1] === 'post')[2] + expect(sent.calibrationIds).toEqual([11]); expect(sent.analysisParameterId).toBe(5); expect(sent.analysisParameterVersion).toBe(3) +}) + +test('run association is optional and remote search does not discard the selected version', async () => { + const wrapper = await detail(); wrapper.vm.selectAnalysisParameter(5); await wrapper.vm.searchAnalysisParameters('新搜索') + expect(wrapper.vm.runForm.analysisParameterVersion).toBe(3); wrapper.vm.selectAnalysisParameter(null) + await wrapper.vm.createRun() + const sent = api.testing.mock.calls.find(call => call[0] === '/tasks/4/runs' && call[1] === 'post')[2] + expect(sent.analysisParameterId).toBeNull(); expect(sent.analysisParameterVersion).toBeNull() +}) + +test('version conflict retains selected data and keeps the run dialog open', async () => { + const wrapper = await detail(); wrapper.vm.selectAnalysisParameter(5); wrapper.vm.runForm.notes = '本轮说明'; api.conflict = true + await wrapper.vm.createRun(); await flushPromises() + expect(wrapper.vm.runOpen).toBe(true); expect(wrapper.vm.runForm.notes).toBe('本轮说明'); expect(wrapper.vm.runForm.analysisParameterId).toBe(5) + expect(document.body.textContent).toContain('数据已更新') +})