"""流程试跑有没有「按这份表单收敛成真实那一条路」,用几张合成画布钉住。 试跑(``service/simulator.py``)是设计器上「预测这一单会怎么走」的那套算法。它最容易 犯的错是把画布上所有能画的线都描成走过的绿线——条件分支、同名出口(待办上其实是一个 按钮)、被适用条件挡住的出口,只要有一条没收敛,设计者看到的预测就比真跑多一条路。 这里不连任何业务数据,直接拼几张最小画布,按当前表单断言: 1. 同名出口只走引擎会挑的那一条,换一份表单换一条; 2. 适用条件当前不成立的出口不进预测,还点得动的按钮照常铺开(那是人的选择); 3. 每条出口都被挡住=这一单卡死,要报 error 而不是硬走一条; 4. 条件当场算不出来(字段没填)必须留一条说明,不许静默走默认分支; 5. 整环自动跳过时照引擎的口径走第一条出口,并把「有人点就走另一条」说出来。 要连开发库(借一条流程当壳子拿它的表单口径,画布用传参覆盖),跑在 backend 目录下:: python3 scripts/check_simulate_paths.py """ from __future__ import annotations import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) from sqlalchemy import select # noqa: E402 from app import models # noqa: E402 from app.db import SessionLocal # noqa: E402 from app.service import personref, simulator # noqa: E402 #: 试跑用的流程级开关:三个去重全关,免得环节被自动跳过掩盖了要验的东西 FLAT = {"skipStarter": False, "dedup": "none", "dedupAhead": "none"} #: 处理人一律取发起人,找人这一步不在本脚本的关注范围 ME = [{"type": "creator", "data": []}] CASES: list[tuple[str, dict, list[dict], list[dict], str]] = [] def node(ident: str, name: str, kind: str = "manual", config: dict | None = None) -> dict: return { "id": ident, "type": kind, "name": name, "alias": name, "description": "", "form": "", "x": 0, "y": 0, "order_number": 0, "config": config if config is not None else ({"taskValues": ME} if kind == "manual" else {}), } def route(ident: str, src: str, name: str, dst: str, expression: str = "") -> dict: return { "id": ident, "name": name, "alias": name, "from_activity": src, "to_activity": dst, "decision": "", "expression": expression, "order_number": 0, } def case(title: str, data: dict, activities: list[dict], routes: list[dict], want: str) -> None: CASES.append((title, data, activities, routes, want)) # 1/2:同名出口是一个按钮,按条件挑一条;另一个按钮被适用条件挡住 same_name = [node("begin", "开始", "begin"), node("n1", "部门主管"), node("boss", "总经理"), node("end", "结束", "end")] same_routes = [ route("r0", "begin", "提交", "n1"), route("r1", "n1", "同意", "boss", "amount > 1000"), route("r2", "n1", "同意", "end"), route("r3", "boss", "同意", "end"), ] case("同名出口:条件成立时只走总经理", {"amount": 5000}, same_name, same_routes, "visits=boss,paths=1") case("同名出口:条件不成立时只走结束", {"amount": 10}, same_name, same_routes, "visits=,paths=1") two_buttons = [ node("begin", "开始", "begin"), node("n1", "部门主管"), node("boss", "总经理"), node("quick", "直报接收人"), node("end", "结束", "end"), ] two_routes = [ route("r0", "begin", "提交", "n1"), route("r1", "n1", "同意", "boss", "amount > 1000"), route("r2", "n1", "直报", "quick"), route("r3", "boss", "同意", "end"), route("r4", "quick", "同意", "end"), ] case("两个按钮都点得动:照常铺开两条路", {"amount": 5000}, two_buttons, two_routes, "visits=boss,quick,paths=2") case("两个按钮:同意被条件挡住就只剩直报", {"amount": 1}, two_buttons, two_routes, "visits=quick,paths=1") # 3:唯一出口被挡住=卡死 stuck = [node("begin", "开始", "begin"), node("n1", "部门主管"), node("end", "结束", "end")] stuck_routes = [route("r0", "begin", "提交", "n1"), route("r1", "n1", "同意", "end", "amount > 1000")] case("唯一出口不成立:报 error 且不硬走", {"amount": 1}, stuck, stuck_routes, "error=route_guard,paths=0") # 4:条件当场算不出来(字段没填)必须说话 choice = [node("begin", "开始", "begin"), node("c1", "判断", "choice"), node("x", "条件支路"), node("end", "结束", "end")] choice_routes = [ route("r0", "begin", "提交", "c1"), route("r1", "c1", "有大类", "x", "category == 'A'"), route("r2", "c1", "默认", "end"), route("r3", "x", "同意", "end"), ] case("分支条件算不出来:走默认但要留说明", {"amount": 1}, choice, choice_routes, "warn=expression,visits=,paths=1") case("分支条件成立:走条件支路", {"category": "A"}, choice, choice_routes, "visits=x,paths=1") def expectations(spec: str) -> dict[str, str]: out: dict[str, str] = {} for part in spec.split(","): key, _, value = part.partition("=") out[key] = value return out #: 试跑的问题清单是给人看的设计问题,不是 Python 异常原话。阈值那一步曾经把 #: ``definition.begin``(环节对象本身,不是它的 id)当成 activities 的键去查, #: 一句 unhashable type 就被报成「阈值规则会挡住这张单」,画布明明没问题却被判卡住。 CRASH_MARKS = ("unhashable", "has no attribute", "not subscriptable", "object is not", "Traceback") def crashes(result: dict) -> list[str]: """这一跑有没有把内部异常混进问题清单。""" out = [] for item in result["findings"]: message = str(item.get("message") or "") if any(mark in message for mark in CRASH_MARKS): out.append(f"[{item.get('level')}/{item.get('kind')}] {message}") return out def check(db, process_id: str, identity: str) -> int: """跑一遍全部用例,返回失败条数。""" failed = 0 for title, data, activities, routes, spec in CASES: result = simulator.simulate( db, process_id=process_id, data=data, starter_identity=identity, activities=activities, routes=routes, approval=FLAT, ) want = expectations(spec) visited = {step["activity"] for step in result["steps"]} problems: list[str] = [] if "visits" in want: for ident in [item for item in want["visits"].split(",") if item]: if ident not in visited: problems.append(f"应该走到 {ident}") if "paths" in want and len(result["endings"]) != int(want["paths"]): problems.append(f"路径数应为 {want['paths']},实际 {len(result['endings'])}") if "error" in want and not [f for f in result["findings"] if f["level"] == "error" and f["kind"] == want["error"]]: problems.append(f"应有 error 级发现(kind={want['error']})") if "warn" in want and not [f for f in result["findings"] if f["kind"] == want["warn"]]: problems.append(f"应有一条 kind={want['warn']} 的说明") for line in crashes(result): problems.append(f"问题清单里混进了内部异常:{line}") if problems: failed += 1 print(f" FAIL {title}:" + ";".join(problems)) else: print(f" ok {title}") # 5:整环自动跳过照引擎的第一条出口走,并说明有人点按钮会是另一条 result = simulator.simulate( db, process_id=process_id, data={"amount": 5000}, starter_identity=identity, activities=same_name, routes=same_routes, approval={**FLAT, "skipStarter": True}, ) skipped = [step for step in result["steps"] if step["state"] == "skipped"] notes = [f for f in result["findings"] if f.get("kind") == "skip_route"] if skipped and not notes: failed += 1 print(" FAIL 整环跳过:没说出「引擎照第一条出口走」这件事") else: print(" ok 整环跳过:照引擎的第一条出口走并说明差异") return failed def main() -> int: db = SessionLocal() try: process = db.execute(select(models.Process)).scalars().first() # 发起人交登录账号:库里认人只认账号(见 service/personref.py),身份 DN 已退役 person = db.execute( select(models.User) .where(models.User.status == models.UserStatus.ACTIVE, models.User.account != "") .order_by(models.User.id) ).scalars().first() if process is None or person is None: print("跳过:库里还没有流程或在职人员,先起一次后端种演示数据") return 0 print(f"流程试跑路径收敛自检(借 {process.name} 当壳子,画布全部用传参的)") failed = check(db, process.id, personref.ref_of(person)) except Exception as exc: # noqa: BLE001 - 连不上库不该把自检算成失败 print(f"跳过:跑不起来(多半是连不上数据库):{exc}") return 0 finally: db.close() print(("全部通过" if not failed else f"{failed} 条没通过") + f"(共 {len(CASES) + 1} 条)") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())