feat(flow): 草稿发布(incoming/outgoing剥除+id还原中文key+ProcessValidator校验门+disableSchemaValidation)+影响摘要

POST /models/{id}/deploy:剥除 bpmn-js 补的 incoming/outgoing 文本引用元素
(Flowable 从 sequenceFlow 自行推导,不剥则 restore 只还原属性位→落库脏 XML,T1.3 I-2)
→ BpmnIdSanitizer.restore 依 eip4IdMap 还原中文原 key(存量 D7 硬需求,新建流程无 idMap 跳过)
→ ProcessValidator 语义校验门(仅 ERROR 级阻断,返 422 {errors:[{activityId,problem,defaultDescription}]}
不部署;WARNING 放行)→ createDeployment().disableSchemaValidation()(只跳 XSD:bpmn-js 默认命名空间
与严格 XSD 已知不兼容,语义已在上一步)部署 → {status,deploymentId,processKey,newVersion}。

GET /models/{id}/impact:还原后解析 processKey → {processKey,currentVersion(最新已部署版本),
runningInstances(运行中实例数)},供同人确认弹窗展示。

控制器加 @Autowired(RepositoryService,RuntimeService) 构造(保留单参构造零改动既有 CRUD 单测)+
全参构造注入 mock ProcessValidator。发布/影响端点 8 单测(还原中文key+剥除无残留净化id+disableSchemaValidation
验证/ERROR 422 不部署/WARNING 放行/404/impact 计数),既有 17 单测零改动;全 reactor clean install 绿
(ArchitectureRulesTest 6/6)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-02 13:32:31 +08:00
parent 647f06836f
commit 6f180522f3
2 changed files with 395 additions and 1 deletions

View File

@@ -2,19 +2,27 @@ package com.eip4.flowservice.api;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.impl.util.io.StringStreamSource; import org.flowable.common.engine.impl.util.io.StringStreamSource;
import org.flowable.engine.RepositoryService; import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Model; import org.flowable.engine.repository.Model;
import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ProcessValidatorFactory;
import org.flowable.validation.ValidationError;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
@@ -27,6 +35,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -67,11 +76,42 @@ public class ProcessModelController {
/** DOCTYPE 门 prolog 扫描字节上限(BOM/XML 声明/注释/DOCTYPE 都在最前)。 */ /** DOCTYPE 门 prolog 扫描字节上限(BOM/XML 声明/注释/DOCTYPE 都在最前)。 */
private static final int PROLOG_SCAN_BYTES = 8192; private static final int PROLOG_SCAN_BYTES = 8192;
/**
* bpmn-js {@code saveXML} 补的 {@code <*:incoming>/<*:outgoing>} 文本引用元素(前缀可选:bpmn/bpmn2/默认)。
* 发布前整体剥除——Flowable 从 {@code sequenceFlow} 的 sourceRef/targetRef 自行推导入出边,这些元素冗余;
* 且它们把节点/流 id 存为<b>元素文本</b>(非属性),{@link BpmnIdSanitizer#restore} 只还原属性位不碰文本
* → 不剥则落库「属性=中文原 key、文本引用=净化 id」的脏 XML(T1.3 评审 I-2)。
*/
private static final Pattern FLOW_REF_ELEMENT = Pattern.compile(
"<(?:[\\w.-]+:)?(?:incoming|outgoing)>[^<]*</(?:[\\w.-]+:)?(?:incoming|outgoing)>");
private final RepositoryService repositoryService; private final RepositoryService repositoryService;
private final RuntimeService runtimeService;
private final ProcessValidator processValidator;
private final ObjectMapper objectMapper = new ObjectMapper(); private final ObjectMapper objectMapper = new ObjectMapper();
public ProcessModelController(RepositoryService repositoryService) { @Autowired
public ProcessModelController(RepositoryService repositoryService, RuntimeService runtimeService) {
this(repositoryService, runtimeService, new ProcessValidatorFactory().createDefaultProcessValidator());
}
/**
* 单参构造:既有草稿 CRUD 单测保留零改动地 {@code new ProcessModelController(repositoryService)}
* (那些用例不触发发布/影响路径,无需 RuntimeService/校验器)。
*/
ProcessModelController(RepositoryService repositoryService) {
this(repositoryService, null, new ProcessValidatorFactory().createDefaultProcessValidator());
}
/**
* 全参构造:发布/影响端点单测注入 <b>mock</b> {@link ProcessValidator}
* ({@code ProcessValidatorFactory} 产的默认校验器无法 mock,须构造注入以断言 ERROR-vs-WARNING 分支)。
*/
ProcessModelController(RepositoryService repositoryService, RuntimeService runtimeService,
ProcessValidator processValidator) {
this.repositoryService = repositoryService; this.repositoryService = repositoryService;
this.runtimeService = runtimeService;
this.processValidator = processValidator;
} }
@GetMapping("/models") @GetMapping("/models")
@@ -230,6 +270,155 @@ public class ProcessModelController {
return ResponseEntity.ok(resp); return ResponseEntity.ok(resp);
} }
@PostMapping("/models/{id}/deploy")
@Operation(summary = "发布草稿为流程定义",
description = "草稿不存在→404;还原 eip4IdMap 里的中文原 key(存量流程 D7 硬需求,新建流程无 idMap 跳过)+"
+ "剥除 bpmn-js 补的 incoming/outgoing 文本引用 → 引擎 ProcessValidator 语义校验(仅 ERROR 级阻断,"
+ "返 422 {errors:[{activityId,problem,defaultDescription}]} 不部署;WARNING 放行)→ "
+ "createDeployment().disableSchemaValidation()(只跳 XSD:bpmn-js 默认命名空间与严格 XSD 已知不兼容,"
+ "语义校验已在上一步)部署 → {status:0,deploymentId,processKey,newVersion}。")
public ResponseEntity<Map<String, Object>> deploy(@PathVariable String id) {
Model model = repositoryService.getModel(id);
if (model == null) {
return status(HttpStatus.NOT_FOUND, "草稿不存在: " + id);
}
byte[] source = repositoryService.getModelEditorSource(id);
if (source == null) {
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿源为空,无法发布: " + id);
}
Map<String, String> idMap = readIdMap(model.getMetaInfo());
String deployXml;
BpmnModel bpmnModel;
try {
deployXml = prepareDeployXml(new String(source, StandardCharsets.UTF_8), idMap);
// XXE 兜底:还原后 XML 再过字节级 DOCTYPE 守卫(与 parseGuard 同源防御);enableSafeBpmnXml 亦禁 DOCTYPE,双保险。
if (hasDoctypeInBytes(deployXml.getBytes(StandardCharsets.UTF_8))) {
log.warn("[流程发布] 拒绝: 还原后 XML 含 DOCTYPE 声明(XXE 防御) id={}", id);
return status(HttpStatus.UNPROCESSABLE_ENTITY, "BPMN 解析失败");
}
// validateSchema=false:bpmn-js 默认命名空间输出与严格 XSD 已知不兼容,语义交给下方 ProcessValidator;
// enableSafeBpmnXml=true:加固解析器关外部实体/DTD。
bpmnModel = new BpmnXMLConverter().convertToBpmnModel(new StringStreamSource(deployXml), false, true);
} catch (IllegalArgumentException e) {
// BpmnIdSanitizer.restore 的 fail-fast:idMap 非双射(metaInfo 损坏)——须炸不能静默还原成别的 key。
log.warn("[流程发布] id 还原失败(idMap 损坏) id={}: {}", id, e.toString());
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿 id 映射损坏,无法还原原 key");
} catch (Exception e) {
log.warn("[流程发布] BPMN 解析失败 id={}: {}", id, e.toString());
return status(HttpStatus.UNPROCESSABLE_ENTITY, "BPMN 解析失败");
}
// 引擎校验门:区分 ERROR/WARNING,只 ERROR 级阻断部署。
List<Map<String, Object>> blocking = new ArrayList<>();
for (ValidationError ve : processValidator.validate(bpmnModel)) {
if (ve.isWarning()) {
log.info("[流程发布] 校验告警(放行) id={} activityId={} problem={} desc={}",
id, ve.getActivityId(), ve.getProblem(), ve.getDefaultDescription());
continue;
}
Map<String, Object> err = new LinkedHashMap<>();
err.put("activityId", ve.getActivityId());
err.put("problem", ve.getProblem());
err.put("defaultDescription", ve.getDefaultDescription());
blocking.add(err);
}
if (!blocking.isEmpty()) {
log.warn("[流程发布] ProcessValidator 拒绝 id={} errorCount={}", id, blocking.size());
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", 1);
body.put("msg", "流程校验未通过");
body.put("errors", blocking);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(body);
}
// 部署资源名用中文原 key(仅 act_ge_bytearray 名,不决定 process key——后者取自 XML 的 <process id>)。
String resource = model.getKey() + ".bpmn20.xml";
var deployment = repositoryService.createDeployment()
.disableSchemaValidation()
.name(model.getName())
.addString(resource, deployXml)
.deploy();
var deployed = repositoryService.createProcessDefinitionQuery()
.deploymentId(deployment.getId()).singleResult();
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("deploymentId", deployment.getId());
resp.put("processKey", deployed != null ? deployed.getKey() : model.getKey());
resp.put("newVersion", deployed != null ? deployed.getVersion() : 0);
return ResponseEntity.ok(resp);
}
@GetMapping("/models/{id}/impact")
@Operation(summary = "发布影响摘要",
description = "草稿不存在→404;还原后解析 processKey → {processKey,currentVersion(该 key 最新已部署版本,"
+ "无则 0),runningInstances(该 key 运行中实例数)}。供同人确认弹窗展示「新版本/旧版本实例不受影响」。")
public ResponseEntity<Map<String, Object>> impact(@PathVariable String id) {
Model model = repositoryService.getModel(id);
if (model == null) {
return status(HttpStatus.NOT_FOUND, "草稿不存在: " + id);
}
byte[] source = repositoryService.getModelEditorSource(id);
if (source == null) {
return status(HttpStatus.UNPROCESSABLE_ENTITY, "草稿源为空: " + id);
}
Map<String, String> idMap = readIdMap(model.getMetaInfo());
String processKey;
try {
String deployXml = prepareDeployXml(new String(source, StandardCharsets.UTF_8), idMap);
BpmnModel bpmnModel = new BpmnXMLConverter()
.convertToBpmnModel(new StringStreamSource(deployXml), false, true);
var mainProcess = bpmnModel.getMainProcess();
processKey = mainProcess != null ? mainProcess.getId() : model.getKey();
} catch (Exception e) {
// 解析失败(半成品草稿)回退 model.key:影响摘要是只读参考,不该因草稿未完成而 500。
log.warn("[流程发布] 影响摘要解析失败,回退 model.key id={}: {}", id, e.toString());
processKey = model.getKey();
}
var latest = repositoryService.createProcessDefinitionQuery()
.processDefinitionKey(processKey).latestVersion().singleResult();
long runningInstances = runtimeService.createProcessInstanceQuery()
.processDefinitionKey(processKey).count();
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("processKey", processKey);
resp.put("currentVersion", latest != null ? latest.getVersion() : 0);
resp.put("runningInstances", runningInstances);
return ResponseEntity.ok(resp);
}
/**
* 发布/影响摘要前的 XML 规范化:①{@link #FLOW_REF_ELEMENT} 剥除 bpmn-js 补的 incoming/outgoing 文本引用元素;
* ②{@link BpmnIdSanitizer#restore} 依 {@code idMap} 把净化 id 还原为中文原 key(idMap 空=新建流程,原样返回)。
* restore 在剥除后跑:文本引用已消除,还原只作用于属性位,最终部署 XML 无残留净化 id。
* idMap 非双射时 restore fail-fast 抛 {@link IllegalArgumentException},由调用方转 422。
*/
private static String prepareDeployXml(String xml, Map<String, String> idMap) {
String stripped = FLOW_REF_ELEMENT.matcher(xml).replaceAll("");
return BpmnIdSanitizer.restore(stripped, idMap);
}
/**
* 从 metaInfo JSON 取 {@code eip4IdMap}(原→净化)。metaInfo 空 / 无该键(新建流程无净化)/ 解析失败
* 一律返回空 Map(发布走「无 idMap 跳过还原」分支,key 原样部署)。
*/
private Map<String, String> readIdMap(String metaInfo) {
if (metaInfo == null || metaInfo.isBlank()) {
return Map.of();
}
try {
Map<String, Object> meta = objectMapper.readValue(metaInfo, new TypeReference<Map<String, Object>>() {});
Object raw = meta.get("eip4IdMap");
if (!(raw instanceof Map<?, ?> m)) {
return Map.of();
}
Map<String, String> idMap = new LinkedHashMap<>();
for (Map.Entry<?, ?> e : m.entrySet()) {
idMap.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
return idMap;
} catch (Exception e) {
log.warn("[流程发布] metaInfo 解析失败,按无 idMap 处理: {}", e.toString());
return Map.of();
}
}
/** /**
* BPMN 解析守卫:过则返回 {@code null}(放行),坏 XML 返回 422 ResponseEntity({status:1,msg})。 * BPMN 解析守卫:过则返回 {@code null}(放行),坏 XML 返回 422 ResponseEntity({status:1,msg})。
* 就地 catch 一切异常,不让引擎 XMLException/FlowableException 逸出到全局 advice(那里映射成 400,语义不符)。 * 就地 catch 一切异常,不让引擎 XMLException/FlowableException 逸出到全局 advice(那里映射成 400,语义不符)。

View File

@@ -19,10 +19,16 @@ import java.util.Date;
import java.util.List; import java.util.List;
import org.flowable.engine.RepositoryService; import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentBuilder;
import org.flowable.engine.repository.Model; import org.flowable.engine.repository.Model;
import org.flowable.engine.repository.ModelQuery; import org.flowable.engine.repository.ModelQuery;
import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery; import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ValidationError;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -83,6 +89,23 @@ class ProcessModelControllerTest {
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\">" + "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\">"
+ "<process id=\"p1\"><startEvent id=\"s\"/></process></definitions>"; + "<process id=\"p1\"><startEvent id=\"s\"/></process></definitions>";
// 存量流程编辑器导出态(发布路径 fixture):process id + sequenceFlow id 原为中文,已被 sanitize 成净化 id
// (n1a2b3c / nflow1 / nflow2);bpmn-js saveXML 给流节点补了 <incoming>/<outgoing> 文本引用(内含净化 id)。
// metaInfo.eip4IdMap 记「中文原 id→净化 id」,发布时 restore 逆向还原。model.key=中文原 key「总包合同交底」。
private static final String DRAFT_SANITIZED_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" targetNamespace=\"http://eip4\">"
+ "<process id=\"n1a2b3c\" name=\"总包合同交底\" isExecutable=\"true\">"
+ "<startEvent id=\"start1\"><outgoing>nflow1</outgoing></startEvent>"
+ "<userTask id=\"taskA\" name=\"交底\"><incoming>nflow1</incoming><outgoing>nflow2</outgoing></userTask>"
+ "<endEvent id=\"end1\"><incoming>nflow2</incoming></endEvent>"
+ "<sequenceFlow id=\"nflow1\" sourceRef=\"start1\" targetRef=\"taskA\"/>"
+ "<sequenceFlow id=\"nflow2\" sourceRef=\"taskA\" targetRef=\"end1\"/>"
+ "</process></definitions>";
// 对应上面 fixture 的 metaInfo:eip4IdMap 三条(process + 两条 sequenceFlow) + sourceProcDefId + 中文 originalKey。
private static final String DRAFT_META_INFO = "{\"eip4IdMap\":{\"总包合同交底\":\"n1a2b3c\","
+ "\"流转1\":\"nflow1\",\"流转2\":\"nflow2\"},\"sourceProcDefId\":\"def-1\",\"originalKey\":\"总包合同交底\"}";
@BeforeEach @BeforeEach
void setUp() { void setUp() {
ProcessModelController controller = new ProcessModelController(repositoryService); ProcessModelController controller = new ProcessModelController(repositoryService);
@@ -406,6 +429,188 @@ class ProcessModelControllerTest {
verify(repositoryService, never()).newModel(); verify(repositoryService, never()).newModel();
} }
// ===== T3.1 发布(deploy)/ 影响摘要(impact) =====
/** 建带 mock ProcessValidator + RuntimeService 的控制器与 MockMvc(发布/影响端点专用,校验器须可 mock)。 */
private MockMvc deployMvc(RuntimeService runtimeService, ProcessValidator validator) {
return MockMvcBuilders.standaloneSetup(
new ProcessModelController(repositoryService, runtimeService, validator)).build();
}
@Test
void 发布_还原中文原key与剥除incoming_outgoing后部署XML无残留净化id且disableSchemaValidation() throws Exception {
Model m = Mockito.mock(Model.class);
when(m.getName()).thenReturn("总包合同交底");
when(m.getKey()).thenReturn("总包合同交底"); // 中文原 key(from-procdef 时存,发布资源名/还原目标)
when(m.getMetaInfo()).thenReturn(DRAFT_META_INFO);
when(repositoryService.getModel("m1")).thenReturn(m);
when(repositoryService.getModelEditorSource("m1"))
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
// 校验器无 ERROR → 放行部署。
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
when(validator.validate(any())).thenReturn(List.of());
// 部署链 mock:disableSchemaValidation().name().addString().deploy()。
DeploymentBuilder db = Mockito.mock(DeploymentBuilder.class);
when(repositoryService.createDeployment()).thenReturn(db);
when(db.disableSchemaValidation()).thenReturn(db);
when(db.name(any())).thenReturn(db);
when(db.addString(anyString(), anyString())).thenReturn(db);
Deployment dep = Mockito.mock(Deployment.class);
when(dep.getId()).thenReturn("dep-1");
when(db.deploy()).thenReturn(dep);
ProcessDefinition deployed = Mockito.mock(ProcessDefinition.class);
when(deployed.getKey()).thenReturn("总包合同交底");
when(deployed.getVersion()).thenReturn(2);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.deploymentId("dep-1")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(deployed);
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
localMvc.perform(post("/api/flow/models/m1/deploy"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value(0))
.andExpect(jsonPath("$.deploymentId").value("dep-1"))
.andExpect(jsonPath("$.processKey").value("总包合同交底"))
.andExpect(jsonPath("$.newVersion").value(2));
// disableSchemaValidation 必被调用(防有人回退成严格 XSD,咬 bpmn-js 默认命名空间输出→cvc-complex-type)。
verify(db).disableSchemaValidation();
// 捕获部署 XML:属性位还原为中文原 key/流 id,incoming/outgoing 文本引用剥除 → 全程无残留净化 id。
ArgumentCaptor<String> deployXml = ArgumentCaptor.forClass(String.class);
verify(db).addString(eq("总包合同交底.bpmn20.xml"), deployXml.capture());
String xml = deployXml.getValue();
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"总包合同交底\""), xml);
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"流转1\""), xml);
org.junit.jupiter.api.Assertions.assertTrue(xml.contains("id=\"流转2\""), xml);
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("n1a2b3c"), "残留净化 process id: " + xml);
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("nflow1"), "残留净化流 id(incoming/outgoing 未剥除): " + xml);
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("nflow2"), "残留净化流 id(incoming/outgoing 未剥除): " + xml);
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("<incoming>"), "incoming 元素未剥除: " + xml);
org.junit.jupiter.api.Assertions.assertFalse(xml.contains("<outgoing>"), "outgoing 元素未剥除: " + xml);
}
@Test
void 发布_ProcessValidator_ERROR级返422带明细且不部署() throws Exception {
Model m = Mockito.mock(Model.class);
// metaInfo 默认 null → 无 idMap(新建流程分支,不还原);getKey 在 ERROR 返回前不会被读,不 stub 免 strict-stub。
when(repositoryService.getModel("m1")).thenReturn(m);
when(repositoryService.getModelEditorSource("m1"))
.thenReturn(VALID_BPMN.getBytes(StandardCharsets.UTF_8));
ValidationError err = new ValidationError();
err.setActivityId("taskA");
err.setProblem("flowable-usertask-no-assignment");
err.setDefaultDescription("用户任务无办理人");
err.setWarning(false);
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
when(validator.validate(any())).thenReturn(List.of(err));
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
localMvc.perform(post("/api/flow/models/m1/deploy"))
.andExpect(status().isUnprocessableEntity())
.andExpect(jsonPath("$.status").value(1))
.andExpect(jsonPath("$.errors[0].activityId").value("taskA"))
.andExpect(jsonPath("$.errors[0].problem").value("flowable-usertask-no-assignment"))
.andExpect(jsonPath("$.errors[0].defaultDescription").value("用户任务无办理人"));
// ERROR 级校验失败 → 绝不部署。
verify(repositoryService, never()).createDeployment();
}
@Test
void 发布_ProcessValidator仅WARNING放行部署() throws Exception {
Model m = Mockito.mock(Model.class);
when(m.getName()).thenReturn("新流程");
when(m.getKey()).thenReturn("newproc");
when(repositoryService.getModel("m1")).thenReturn(m);
when(repositoryService.getModelEditorSource("m1"))
.thenReturn(VALID_BPMN.getBytes(StandardCharsets.UTF_8));
ValidationError warn = new ValidationError();
warn.setActivityId("taskA");
warn.setProblem("some-warning");
warn.setWarning(true);
ProcessValidator validator = Mockito.mock(ProcessValidator.class);
when(validator.validate(any())).thenReturn(List.of(warn));
DeploymentBuilder db = Mockito.mock(DeploymentBuilder.class);
when(repositoryService.createDeployment()).thenReturn(db);
when(db.disableSchemaValidation()).thenReturn(db);
when(db.name(any())).thenReturn(db);
when(db.addString(anyString(), anyString())).thenReturn(db);
Deployment dep = Mockito.mock(Deployment.class);
when(dep.getId()).thenReturn("dep-2");
when(db.deploy()).thenReturn(dep);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.deploymentId("dep-2")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(null); // 查不到也不炸:回退 model.key/0
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), validator);
localMvc.perform(post("/api/flow/models/m1/deploy"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value(0))
.andExpect(jsonPath("$.deploymentId").value("dep-2"))
.andExpect(jsonPath("$.processKey").value("newproc"))
.andExpect(jsonPath("$.newVersion").value(0));
// 仅 WARNING → 放行:部署照常发生。
verify(db).deploy();
}
@Test
void 发布_草稿不存在返404不部署() throws Exception {
when(repositoryService.getModel("nope")).thenReturn(null);
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
localMvc.perform(post("/api/flow/models/nope/deploy"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status").value(1));
verify(repositoryService, never()).createDeployment();
}
@Test
void 影响摘要_还原后解析processKey返当前版本与运行实例数() throws Exception {
Model m = Mockito.mock(Model.class);
// processKey 取自还原后 XML 的 <process id>(=总包合同交底),不读 model.getKey → 不 stub 免 strict-stub。
when(m.getMetaInfo()).thenReturn(DRAFT_META_INFO);
when(repositoryService.getModel("m1")).thenReturn(m);
when(repositoryService.getModelEditorSource("m1"))
.thenReturn(DRAFT_SANITIZED_XML.getBytes(StandardCharsets.UTF_8));
ProcessDefinition latest = Mockito.mock(ProcessDefinition.class);
when(latest.getVersion()).thenReturn(3);
when(repositoryService.createProcessDefinitionQuery()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.processDefinitionKey("总包合同交底")).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.latestVersion()).thenReturn(processDefinitionQuery);
when(processDefinitionQuery.singleResult()).thenReturn(latest);
RuntimeService runtimeService = Mockito.mock(RuntimeService.class);
ProcessInstanceQuery piq = Mockito.mock(ProcessInstanceQuery.class);
when(runtimeService.createProcessInstanceQuery()).thenReturn(piq);
when(piq.processDefinitionKey("总包合同交底")).thenReturn(piq);
when(piq.count()).thenReturn(5L);
MockMvc localMvc = deployMvc(runtimeService, Mockito.mock(ProcessValidator.class));
localMvc.perform(get("/api/flow/models/m1/impact"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.processKey").value("总包合同交底"))
.andExpect(jsonPath("$.currentVersion").value(3))
.andExpect(jsonPath("$.runningInstances").value(5));
}
@Test
void 影响摘要_草稿不存在返404() throws Exception {
when(repositoryService.getModel("nope")).thenReturn(null);
MockMvc localMvc = deployMvc(Mockito.mock(RuntimeService.class), Mockito.mock(ProcessValidator.class));
localMvc.perform(get("/api/flow/models/nope/impact"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status").value(1));
}
/** 把任意字符串编成 JSON 字符串字面量(转义引号/反斜杠/换行),用于拼请求体。 */ /** 把任意字符串编成 JSON 字符串字面量(转义引号/反斜杠/换行),用于拼请求体。 */
private static String jsonString(String s) { private static String jsonString(String s) {
StringBuilder sb = new StringBuilder("\""); StringBuilder sb = new StringBuilder("\"");